# Other players' avatars by id

Friends lists, lobbies and leaderboards show each player's own 360sona avatar. `sona_players` looks avatars up by id
through the routes the accounts server answers, keeps them in memory and in one cache file, asks again when they are
old, paces itself under the server's limits and falls back to the last known look, then to a placeholder, when the
network or the server is gone. It hands out manifests; the game adds them with `sona_avatar_add` like any other.

## Ids

| Id | Route (`{host}` default `https://360sona.com`) | What it is |
|---|---|---|
| `Your Gamertag`, `gt:Your Gamertag`, `Name#1234` | `GET {host}/sona/v1/gamertag/<gamertag>?client=<app>` | the avatar on an Xbox account ([the lookup API](../web-api.md#lookup)) |
| `a:<account id>/<slot>` | `GET {host}/sona/a/<account>/<slot>` | one of a 360sona account's twenty slots, only when its owner made it public |
| `w:<case key>` | `GET {host}/sona/w/<key>`, its version from `GET {host}/sona/wv/<key>` | the avatar on a display case |

Gamertags compare without case, as the server's cache does: `YOUR GAMERTAG` and `Your Gamertag` are one player; events give the id
as the game last watched it. Gamertags are checked as the server checks them (a letter or digit, then up to 15
letters, digits and spaces, then an optional `#` and up to four digits); a string that is not an id becomes
`SONA_PLAYER_NONE` at once, with no request. `client` is the app id the gamertag lookup knows (an app 360sona set up for
lookups, or an auto-approved developer app with lookups); left NULL it is the app id stamped into the
build. Without one, gamertags fail with `SONA_E_APP` and account and case ids still work. A 404 that says "No such
route." means the server does not know the client: every gamertag then fails with `SONA_E_APP`, once.

## A lobby

```c
sona_players_config pc;
sona_players *players;
sona_players_defaults(&pc);
pc.client = "your-app-id";
pc.cache_dir = "players-cache";         /* NULL: memory only */
sona_players_open(&pc, &players);

const char *lobby[] = { "Ember Lane", "Quiet Fox", "a:Kq3mPZx0aB1cD2eF3gH4i/2", "w:c4se-k3y" };
sona_players_watch(players, lobby, 4, 0);  /* returns at once; cached looks are there now */

/* every frame */
sona_players_update(players);
sona_player_event ev;
while (sona_players_poll(players, &ev)) {
  sona_player_look look;
  sona_players_look(players, ev.id, &look);  /* always a look to draw: the player's, or the placeholder */
  seat_show(seat_of(ev.id), look.manifest);   /* add the new avatar; remove the old one once the new is READY */
}
```

```cpp
sona_players_config pc;
sona_players *players = nullptr;
sona_players_defaults(&pc);
pc.client = "your-app-id";
pc.cache_dir = "players-cache";             // nullptr: memory only
sona_players_open(&pc, &players);

const char *lobby[] = { "Ember Lane", "Quiet Fox", "a:Kq3mPZx0aB1cD2eF3gH4i/2", "w:c4se-k3y" };
sona_players_watch(players, lobby, 4, 0);   // returns at once; cached looks are there now

// every frame
sona_players_update(players);
sona_player_event ev;
while (sona_players_poll(players, &ev)) {
  sona_player_look look;
  sona_players_look(players, ev.id, &look);    // always a look to draw: the player's, or the placeholder
  seat_show(seat_of(ev.id), look.manifest);    // add the new avatar; remove the old one once the new is READY
}
```

```csharp
using var players = new SonaPlayers(new SonaPlayersOptions { Client = "your-app-id", CacheDir = "players-cache" });   // null: memory only
players.Watch(new[] { "Ember Lane", "Quiet Fox", "a:Kq3mPZx0aB1cD2eF3gH4i/2", "w:c4se-k3y" });   // returns at once; cached looks are there now

// every frame
players.Update();
foreach (var ev in players.Poll())
    SeatShow(SeatOf(ev.Id), players.Look(ev.Id).Manifest);   // add the new avatar; remove the old one once the new is READY
```

```rust
let o = PlayersOptions { client: Some("your-app-id".into()), cache_dir: Some("players-cache".into()), ..Default::default() };   // None: memory only
let mut players = Players::open(&o)?;
players.watch(&["Ember Lane", "Quiet Fox", "a:Kq3mPZx0aB1cD2eF3gH4i/2", "w:c4se-k3y"], 0)?;   // returns at once; cached looks are there now

// every frame
players.update();
for ev in players.poll() {
    if let PlayerEvent::Look(id) = ev {
        let (look, _) = players.look(&id);
        seat_show(seat_of(&id), &look.manifest);   // add the new avatar; remove the old one once the new is READY
    }
}
```

```python
players = sona.Players(client="your-app-id", cache_dir="players-cache")   # None: memory only
players.watch(["Ember Lane", "Quiet Fox", "a:Kq3mPZx0aB1cD2eF3gH4i/2", "w:c4se-k3y"])   # returns at once

# every frame
players.update()
for ev in players.poll():
    seat_show(seat_of(ev.id), players.look(ev.id).manifest)   # add the new avatar; remove the old one once the new is READY
```

`sona_players_look` always fills `look.manifest`, so a seat never shows a hole: before the first answer, and for a
private or unknown player, it is the placeholder (`look.placeholder` is 1). `look.state` says which:

| State | Means | Drawn |
|---|---|---|
| `SONA_PLAYER_WAITING` | nothing known | the placeholder |
| `SONA_PLAYER_FRESH` | the server answered for this look within `refresh_s` | the look |
| `SONA_PLAYER_STALE` | the last known look: a check is due, or failed (`look.error` says why) | the look |
| `SONA_PLAYER_PRIVATE` | the owner keeps the avatar private on Xbox (403) | the placeholder |
| `SONA_PLAYER_NONE` | no such player, no avatar, a slot not shared, a deleted case, or not an id | the placeholder |

Events: `SONA_PLAYER_EVENT_LOOK` when a look arrives or changes (a refresh that brings the same bytes raises
nothing), `_GONE` when a look is no longer shown (private, deleted, not shared), `_FAILED` once when checks start
failing (offline `SONA_E_IO`, `SONA_E_LIMIT`, `SONA_E_GATE` for a server error, `SONA_E_CORRUPT` for a body that is
not a manifest, `SONA_E_APP`). The last known look stays through a failure.

The swap without a hole: keep the old avatar until the new one is `SONA_AVATAR_READY`, then remove the old one, as
`samples/players/players_lobby.c` does (`sona_headless_render` waits for READY there; a game checks
`sona_avatar_state_of` each frame).

## Refresh

A look is asked for again once it is `refresh_s` old (default 600 s, the lookup's own cache time, so asking sooner
would only get the server's cached copy). `sona_players_refresh` asks now, for some ids or every watched one (still
inside the limits below). Only watched ids are asked; `sona_players_unwatch` keeps their looks cached.

The version of a look is its SHA-256 (the first 16 bytes, as 32 hex digits in `look.version`). Each check of a
gamertag or a slot sends `If-None-Match: "<version>"`; a server that answers 304 costs no body, and one that answers
200 with the same bytes is "the same" all the same. A display
case is checked by `GET /wv/<key>`, which answers only when the case last changed; `GET /w/<key>` (which counts a
visit for the case's owner) is asked only when that changed.

## Limits and batching

The lookup allows 60 requests an hour per address, cache hits included, and the server's own budget is 600 an hour.
So by default the client sends at most `per_hour` = 60 requests in any rolling hour and `in_flight` = 4 at once, one
per distinct id however many times it is watched. A lobby of 64 new players fills in 60 now and 4 when the hour
allows (they show the placeholder meanwhile, and `look.next_check` says when).
Ids watched with a higher `priority` go first (say, the players on screen), then in the order they were first
watched. The server has no batch route, so a batch is this queue: `sona_players_watch` takes the whole list.

Failures back off: no network, a 5xx or a 429 pauses every request (defaults of 30 and 60 s, the longer for a 429, doubling to a cap of 15 minutes);
a body that is not a manifest backs off that id alone. `stats.paused_until` says until when.

## Offline and the cache file

With `cache_dir`, every look is kept in `<cache_dir>/players.cache` (made when missing, written at most every 2 s
and at close, as a whole new file renamed over the old). A new session reads it at open: looks checked within
`refresh_s` are fresh and not asked again, older ones are stale and asked when watched. Offline, the game draws the
last known looks; with none, the placeholder. A file that does not decode (damaged, cut short, another format) is
ignored and replaced. Two processes sharing one folder do not corrupt it, but the last to write wins.

## Privacy

- Only what the owner made public is asked for: an Xbox avatar the account shows (the server answers 403 for one kept
  private), a slot its owner shared, a display case. A look that turns private, unshared or deleted is dropped from
  memory and from the cache file at the next write.
- Only what the lookup returns is kept: the id, the name the answer gives (the gamertag's spelling or the slot's name),
  the 1000 manifest bytes, when it arrived and was last checked, and a case's version number. A display case's
  configuration (its profile, links, pet) is read past and never kept. Nothing about the player who asks is stored.
- `sona_players_forget` drops one id at once.

## Placeholder

`sona_players_placeholder` is the site's own mannequin: the stock body and head,
nothing worn, no hair, no face features, grey. `config.placeholder` replaces it with any manifest of the game's.
The animated silhouette for avatars still loading is a separate feature: [Loading placeholders](placeholder.md).

## Reference

| Call | Rules and results |
|---|---|
| `sona_players_defaults`, `sona_players_open`, `sona_players_close` | `size` must be set (defaults does); `SONA_E_UNSUPPORTED` without an HTTP layer; release builds take `https://` hosts and loopback `http://` only |
| `sona_players_watch(p, ids, n, priority)` | `SONA_E_ARGUMENT` when one id is not an id (the rest are watched), `SONA_E_LIMIT` past `max_players` |
| `sona_players_unwatch(p, ids, n)`, `sona_players_refresh(p, ids, n)` | `ids` NULL: every id |
| `sona_players_update(p)` | each frame, owner thread: answers, requests, the cache file |
| `sona_players_poll(p, &ev)` | 1 per event |
| `sona_players_look(p, id, &look)` | always filled; `SONA_E_NOT_FOUND` for an id never watched nor cached |
| `sona_players_forget`, `sona_players_stats_get`, `sona_players_placeholder` | `forget`: `SONA_E_NOT_FOUND` when the id had no look; the other two always succeed |

Config: `max_players` (2048 looks kept, in memory and on disk; watched ids are never dropped), `refresh_s` (600),
`per_hour` (60), `in_flight` (4, at most 16), `timeout_ms` (15000), `host`, `client`, `http` (NULL: the platform's
layer: WinHTTP, libcurl or NSURLSession), `cache_dir`, `placeholder`, `clock` (seconds since 1970, for tests),
`allocator`. Bindings: Python `sona.Players`, Rust `sona::Players`, C# `SonaPlayers`.
