Merge feature/t1249-leaderboard-names: resolve leaderboard names from the auth friends list (t1249)
@@ -19,8 +19,11 @@ Live (na de eerste deploy): https://projects.timfalken.com/meteors/
19
19
**Ranglijst** (t1247): de top 10 op het puntentotaal van je profiel
20
20
(het getal waar het puntenscherm naartoe telt). Een tweede tab toont
21
21
alleen mensen op je vriendenlijst van
22
[auth.timfalken.com](https://auth.timfalken.com). Gasten zien de
23
wereldwijde top 10; de vriendentab vraagt hen in te loggen. Sta je
22
[auth.timfalken.com](https://auth.timfalken.com). Namen en avatars
23
komen uit die vriendenlijst (en uit je eigen login) en worden
24
gecached, zodat ook gasten ze later zien. Ontbreekt die info, dan
25
blijft de oude terugval (het cijfer uit het account-id). Gasten zien
26
de wereldwijde top 10; de vriendentab vraagt hen in te loggen. Sta je
24
27
zelf in de lijst, dan is je rij gemarkeerd, met avatar en naam.
25
28
Hieronder de regels van het veld zelf.
26
29
2. Elke seconde valt er een blokje van één van vijf kleuren in een willekeurige kolom.
@@ -19,8 +19,11 @@ Live (na de eerste deploy): https://projects.timfalken.com/meteors/19
**Ranglijst** (t1247): de top 10 op het puntentotaal van je profiel19
**Ranglijst** (t1247): de top 10 op het puntentotaal van je profiel20
(het getal waar het puntenscherm naartoe telt). Een tweede tab toont20
(het getal waar het puntenscherm naartoe telt). Een tweede tab toont21
alleen mensen op je vriendenlijst van21
alleen mensen op je vriendenlijst van22
[auth.timfalken.com](https://auth.timfalken.com). Gasten zien de22
[auth.timfalken.com](https://auth.timfalken.com). Namen en avatars23
wereldwijde top 10; de vriendentab vraagt hen in te loggen. Sta je23
komen uit die vriendenlijst (en uit je eigen login) en worden24
gecached, zodat ook gasten ze later zien. Ontbreekt die info, dan25
blijft de oude terugval (het cijfer uit het account-id). Gasten zien26
de wereldwijde top 10; de vriendentab vraagt hen in te loggen. Sta je24
zelf in de lijst, dan is je rij gemarkeerd, met avatar en naam.27
zelf in de lijst, dan is je rij gemarkeerd, met avatar en naam.25
Hieronder de regels van het veld zelf.28
Hieronder de regels van het veld zelf.26
2. Elke seconde valt er een blokje van één van vijf kleuren in een willekeurige kolom.29
2. Elke seconde valt er een blokje van één van vijf kleuren in een willekeurige kolom.@@ -1431,3 +1431,35 @@ getest kan worden. Op productie bestaat die koppeling niet.
1431
1431
1432
1432
Tests: `server/tests/run.php` (t1247), `test/leaderboard.test.js`;
1433
1433
Playwright `test/t1247-leaderboard-playwright.py URL TAG`.
1434
1435
## t1249 — Namen en avatars van auth.timfalken.com
1436
1437
Auth heeft **geen** publieke lookup van gebruikersnaam per id. Wel:
1438
`GET /api/friends` (bearer-token van de kijker) levert `id`, `username`
1439
en `avatar_url`; `GET /api/me` hetzelfde voor jezelf; `GET /avatar/{id}`
1440
is publiek maar geeft alleen de foto (geen naam), en 404 zonder foto.
1441
Aan auth.timfalken.com is niets veranderd.
1442
1443
**Aanpak in Meteors.** Als je ingelogd de ranglijst (wereldwijd of
1444
vrienden) opent, haalt de server je vriendenlijst op met jouw token.
1445
Die namen/avatars, plus die van jezelf, worden over de getoonde rijen
1446
gelegd en teruggeschreven op bestaande profielen (`rememberIdentities`).
1447
Een fallback-naam zoals “3” voor `auth:3` telt niet als echte naam.
1448
Vrienden die Meteors nooit hebben gespeeld krijgen geen nieuw profiel
1449
(ze blijven dus van de wereldwijde top 10 af).
1450
1451
**Cache.** De vriendenlijst per kijker staat in `friends_cache` en
1452
wordt 10 minuten hergebruikt (`Store::FRIENDS_CACHE_TTL`). Faalt auth,
1453
dan mag een verlopen cache nog worden gebruikt. Een gast ziet echte
1454
namen zodra een eerdere ingelogde kijker (die die mensen als vriend
1455
heeft, of de spelers zelf) ze heeft laten backfillen; anders blijft
1456
de id-terugval.
1457
1458
**Voorstel (niet gebouwd).** Een kleine auth-API, bijvoorbeeld
1459
`GET /api/users/{id}` of `GET /api/profiles?ids=1,2,3` (publiek of
1460
met client credentials), die alleen `{id, username, avatar_url}`
1461
teruggeeft, zou ook gasten en niet-vrienden op de wereldwijde lijst
1462
van echte namen kunnen voorzien. Dat vereist een wijziging op
1463
auth.timfalken.com; die is hier niet gedaan.
1464
1465
Tests: `server/tests/run.php` (t1249).
@@ -1431,3 +1431,35 @@ getest kan worden. Op productie bestaat die koppeling niet.1431
1431
1432
Tests: `server/tests/run.php` (t1247), `test/leaderboard.test.js`;1432
Tests: `server/tests/run.php` (t1247), `test/leaderboard.test.js`;1433
Playwright `test/t1247-leaderboard-playwright.py URL TAG`.1433
Playwright `test/t1247-leaderboard-playwright.py URL TAG`.1434
1435
## t1249 — Namen en avatars van auth.timfalken.com1436
1437
Auth heeft **geen** publieke lookup van gebruikersnaam per id. Wel:1438
`GET /api/friends` (bearer-token van de kijker) levert `id`, `username`1439
en `avatar_url`; `GET /api/me` hetzelfde voor jezelf; `GET /avatar/{id}`1440
is publiek maar geeft alleen de foto (geen naam), en 404 zonder foto.1441
Aan auth.timfalken.com is niets veranderd.1442
1443
**Aanpak in Meteors.** Als je ingelogd de ranglijst (wereldwijd of1444
vrienden) opent, haalt de server je vriendenlijst op met jouw token.1445
Die namen/avatars, plus die van jezelf, worden over de getoonde rijen1446
gelegd en teruggeschreven op bestaande profielen (`rememberIdentities`).1447
Een fallback-naam zoals “3” voor `auth:3` telt niet als echte naam.1448
Vrienden die Meteors nooit hebben gespeeld krijgen geen nieuw profiel1449
(ze blijven dus van de wereldwijde top 10 af).1450
1451
**Cache.** De vriendenlijst per kijker staat in `friends_cache` en1452
wordt 10 minuten hergebruikt (`Store::FRIENDS_CACHE_TTL`). Faalt auth,1453
dan mag een verlopen cache nog worden gebruikt. Een gast ziet echte1454
namen zodra een eerdere ingelogde kijker (die die mensen als vriend1455
heeft, of de spelers zelf) ze heeft laten backfillen; anders blijft1456
de id-terugval.1457
1458
**Voorstel (niet gebouwd).** Een kleine auth-API, bijvoorbeeld1459
`GET /api/users/{id}` of `GET /api/profiles?ids=1,2,3` (publiek of1460
met client credentials), die alleen `{id, username, avatar_url}`1461
teruggeeft, zou ook gasten en niet-vrienden op de wereldwijde lijst1462
van echte namen kunnen voorzien. Dat vereist een wijziging op1463
auth.timfalken.com; die is hier niet gedaan.1464
1465
Tests: `server/tests/run.php` (t1249).@@ -60,6 +60,8 @@ try {
60
60
}
61
61
$store = Store::open();
62
62
$viewer = $user['id'] ?? null;
63
$token = $_SESSION['token'] ?? null;
64
[$known, $friends, $friendsError] = leaderboardKnownIdentities($store, $user, $token);
63
65
if ($scope === 'friends') {
64
66
if (!$user) {
65
67
jsonOut([
@@ -70,22 +72,17 @@ try {
70
72
'me' => null,
71
73
]);
72
74
}
73
$friends = [];
74
$token = $_SESSION['token'] ?? null;
75
if (is_string($token) && $token !== '') {
76
try {
77
$friends = parseAuthFriends(authRequest('/api/friends', null, $token));
78
} catch (Throwable $e) {
79
jsonFail('De vriendenlijst is nu niet beschikbaar.', 502);
80
}
81
} elseif (localDev()) {
82
$friends = localTestFriends($user['id']);
75
if ($friendsError !== null && $friends === []) {
76
jsonFail('De vriendenlijst is nu niet beschikbaar.', 502);
83
77
}
84
78
jsonOut([
85
79
'ok' => true,
86
80
'scope' => 'friends',
87
81
'login_required' => false,
88
'players' => $store->friendsLeaderboard($friends, 10, $viewer),
82
'players' => $store->applyIdentities(
83
$store->friendsLeaderboard($friends, 10, $viewer),
84
$known
85
),
89
86
'me' => $viewer,
90
87
]);
91
88
}
@@ -93,7 +90,7 @@ try {
93
90
'ok' => true,
94
91
'scope' => 'global',
95
92
'login_required' => false,
96
'players' => $store->topPlayers(10, $viewer),
93
'players' => $store->applyIdentities($store->topPlayers(10, $viewer), $known),
97
94
'me' => $viewer,
98
95
]);
99
96
}
@@ -60,6 +60,8 @@ try {60
}60
}61
$store = Store::open();61
$store = Store::open();62
$viewer = $user['id'] ?? null;62
$viewer = $user['id'] ?? null;63
$token = $_SESSION['token'] ?? null;64
[$known, $friends, $friendsError] = leaderboardKnownIdentities($store, $user, $token);63
if ($scope === 'friends') {65
if ($scope === 'friends') {64
if (!$user) {66
if (!$user) {65
jsonOut([67
jsonOut([@@ -70,22 +72,17 @@ try {70
'me' => null,72
'me' => null,71
]);73
]);72
}74
}73
$friends = [];75
if ($friendsError !== null && $friends === []) {74
$token = $_SESSION['token'] ?? null;76
jsonFail('De vriendenlijst is nu niet beschikbaar.', 502);75
if (is_string($token) && $token !== '') {76
try {77
$friends = parseAuthFriends(authRequest('/api/friends', null, $token));78
} catch (Throwable $e) {79
jsonFail('De vriendenlijst is nu niet beschikbaar.', 502);80
}81
} elseif (localDev()) {82
$friends = localTestFriends($user['id']);83
}77
}84
jsonOut([78
jsonOut([85
'ok' => true,79
'ok' => true,86
'scope' => 'friends',80
'scope' => 'friends',87
'login_required' => false,81
'login_required' => false,88
'players' => $store->friendsLeaderboard($friends, 10, $viewer),82
'players' => $store->applyIdentities(83
$store->friendsLeaderboard($friends, 10, $viewer),84
$known85
),89
'me' => $viewer,86
'me' => $viewer,90
]);87
]);91
}88
}@@ -93,7 +90,7 @@ try {93
'ok' => true,90
'ok' => true,94
'scope' => 'global',91
'scope' => 'global',95
'login_required' => false,92
'login_required' => false,96
'players' => $store->topPlayers(10, $viewer),93
'players' => $store->applyIdentities($store->topPlayers(10, $viewer), $known),97
'me' => $viewer,94
'me' => $viewer,98
]);95
]);99
}96
}@@ -118,6 +118,13 @@ SQL);
118
118
$this->ensureColumn('profiles', 'last_planet', 'TEXT');
119
119
$this->ensureColumn('profiles', 'name', 'TEXT');
120
120
$this->ensureColumn('profiles', 'avatar', 'TEXT');
121
$this->pdo->exec(<<<'SQL'
122
CREATE TABLE IF NOT EXISTS friends_cache (
123
viewer_id TEXT PRIMARY KEY,
124
payload TEXT NOT NULL,
125
fetched INTEGER NOT NULL
126
);
127
SQL);
121
128
}
122
129
123
130
private function ensureColumn(string $table, string $column, string $ddl): void
@@ -854,7 +861,8 @@ SQL);
854
861
$args = [$this->now()];
855
862
if ($name !== null) {
856
863
$name = trim($name);
857
if ($name !== '' && mb_strlen($name) <= 64 && !preg_match('/[\x00-\x1F]/', $name)) {
864
if ($name !== '' && !isPlaceholderName($userId, $name)
865
&& mb_strlen($name) <= 64 && !preg_match('/[\x00-\x1F]/', $name)) {
858
866
$sets[] = 'name = ?';
859
867
$args[] = $name;
860
868
}
@@ -923,13 +931,16 @@ SQL);
923
931
$row = $found[$id] ?? null;
924
932
$fallbackName = isset($f['name']) && is_string($f['name']) ? $f['name'] : '';
925
933
$fallbackAvatar = isset($f['avatar']) && is_string($f['avatar']) ? $f['avatar'] : null;
934
$storedName = $row !== null ? trim((string) ($row['name'] ?? '')) : '';
935
if (isPlaceholderName($id, $storedName)) {
936
$storedName = '';
937
}
938
$storedAvatar = $row !== null ? ($row['avatar'] ?? '') : '';
926
939
$rows[] = [
927
940
'user_id' => $id,
928
941
'lifetime_points' => $row !== null ? (int) $row['lifetime_points'] : 0,
929
'name' => ($row['name'] ?? '') !== '' && $row !== null ? $row['name'] : $fallbackName,
930
'avatar' => ($row['avatar'] ?? '') !== '' && $row !== null
931
? $row['avatar']
932
: $fallbackAvatar,
942
'name' => $storedName !== '' ? $storedName : $fallbackName,
943
'avatar' => $storedAvatar !== '' ? $storedAvatar : $fallbackAvatar,
933
944
];
934
945
}
935
946
$list = $this->presentLeaderboard($rows, $viewerId);
@@ -978,12 +989,149 @@ SQL);
978
989
return $list;
979
990
}
980
991
992
/**
993
* Overlay names/avatars from auth (friends list, the viewer, or an
994
* earlier backfill) onto an already presented leaderboard. Placeholder
995
* names such as "3" for auth:3 are replaced. Ties are re-sorted.
996
*
997
* @param list<array{rank:int,id:string,name:string,avatar:?string,points:int,you:bool}> $players
998
* @param array<string,array{id?:string,name?:string,avatar?:?string}> $known
999
* @return list<array{rank:int,id:string,name:string,avatar:?string,points:int,you:bool}>
1000
*/
1001
public function applyIdentities(array $players, array $known): array
1002
{
1003
foreach ($players as &$p) {
1004
$id = (string) ($p['id'] ?? '');
1005
$k = $known[$id] ?? null;
1006
if (!is_array($k)) {
1007
continue;
1008
}
1009
$knownName = isset($k['name']) && is_string($k['name']) ? trim($k['name']) : '';
1010
if ($knownName !== '' && !isPlaceholderName($id, $knownName)
1011
&& isPlaceholderName($id, (string) ($p['name'] ?? ''))) {
1012
$p['name'] = $knownName;
1013
}
1014
$knownAvatar = safeAvatarUrl($k['avatar'] ?? null);
1015
if ($knownAvatar !== null && empty($p['avatar'])) {
1016
$p['avatar'] = $knownAvatar;
1017
}
1018
}
1019
unset($p);
1020
usort($players, static function (array $a, array $b): int {
1021
$pc = $b['points'] <=> $a['points'];
1022
if ($pc !== 0) {
1023
return $pc;
1024
}
1025
$nc = strcasecmp((string) $a['name'], (string) $b['name']);
1026
if ($nc !== 0) {
1027
return $nc;
1028
}
1029
return strcmp((string) $a['id'], (string) $b['id']);
1030
});
1031
foreach ($players as $i => &$p) {
1032
$p['rank'] = $i + 1;
1033
}
1034
unset($p);
1035
return $players;
1036
}
1037
1038
/**
1039
* Write known auth names/avatars onto existing Meteors profiles.
1040
* Does not create profiles (friends who never played stay off the
1041
* global board). Placeholder names are not stored.
1042
*
1043
* @param list<array{id?:string,name?:string,avatar?:?string}> $identities
1044
*/
1045
public function rememberIdentities(array $identities): int
1046
{
1047
$changed = 0;
1048
foreach ($identities as $item) {
1049
if (!is_array($item) || !isset($item['id']) || !is_string($item['id']) || $item['id'] === '') {
1050
continue;
1051
}
1052
$userId = $item['id'];
1053
$name = isset($item['name']) && is_string($item['name']) ? trim($item['name']) : '';
1054
if ($name !== '' && isPlaceholderName($userId, $name)) {
1055
$name = '';
1056
}
1057
$avatar = safeAvatarUrl($item['avatar'] ?? null);
1058
if ($name === '' && $avatar === null) {
1059
continue;
1060
}
1061
$stmt = $this->pdo->prepare('SELECT name, avatar FROM profiles WHERE user_id = ?');
1062
$stmt->execute([$userId]);
1063
$row = $stmt->fetch();
1064
if (!$row) {
1065
continue;
1066
}
1067
$sets = ['updated = ?'];
1068
$args = [$this->now()];
1069
$storedName = trim((string) ($row['name'] ?? ''));
1070
if ($name !== '' && ($storedName === '' || isPlaceholderName($userId, $storedName) || $storedName !== $name)) {
1071
$sets[] = 'name = ?';
1072
$args[] = $name;
1073
}
1074
$storedAvatar = $row['avatar'] ?? null;
1075
if ($avatar !== null && $avatar !== $storedAvatar) {
1076
$sets[] = 'avatar = ?';
1077
$args[] = $avatar;
1078
}
1079
if (count($sets) === 1) {
1080
continue;
1081
}
1082
$args[] = $userId;
1083
$this->pdo->prepare(
1084
'UPDATE profiles SET ' . implode(', ', $sets) . ' WHERE user_id = ?'
1085
)->execute($args);
1086
$changed++;
1087
}
1088
return $changed;
1089
}
1090
1091
/**
1092
* Cached GET /api/friends payload for a viewer, or null if missing/stale.
1093
*
1094
* @return list<array{id:string,name:string,avatar:?string}>|null
1095
*/
1096
public function readFriendsCache(string $viewerId, ?int $now = null, bool $allowStale = false): ?array
1097
{
1098
$stmt = $this->pdo->prepare('SELECT payload, fetched FROM friends_cache WHERE viewer_id = ?');
1099
$stmt->execute([$viewerId]);
1100
$row = $stmt->fetch();
1101
if (!$row) {
1102
return null;
1103
}
1104
$now = $now ?? $this->now();
1105
$fetched = (int) $row['fetched'];
1106
if (!$allowStale && ($now - $fetched) > self::FRIENDS_CACHE_TTL) {
1107
return null;
1108
}
1109
$data = json_decode((string) $row['payload'], true);
1110
return is_array($data) ? $data : null;
1111
}
1112
1113
/** @param list<array{id:string,name:string,avatar:?string}> $friends */
1114
public function writeFriendsCache(string $viewerId, array $friends, ?int $fetchedAt = null): void
1115
{
1116
$this->pdo->prepare(
1117
'INSERT INTO friends_cache (viewer_id, payload, fetched) VALUES (?,?,?)
1118
ON CONFLICT(viewer_id) DO UPDATE SET payload = excluded.payload, fetched = excluded.fetched'
1119
)->execute([
1120
$viewerId,
1121
json_encode(array_values($friends), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
1122
$fetchedAt ?? $this->now(),
1123
]);
1124
}
1125
981
1126
public function locale(string $userId): ?string
982
1127
{
983
1128
$v = $this->ensureProfile($userId)['locale'] ?? null;
984
1129
return is_string($v) && $v !== '' ? $v : null;
985
1130
}
986
1131
1132
/** Seconds to reuse a viewer's auth friends list before refetching. */
1133
public const FRIENDS_CACHE_TTL = 600;
1134
987
1135
/** @var list<string> */
988
1136
public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
989
1137
@@ -118,6 +118,13 @@ SQL);118
$this->ensureColumn('profiles', 'last_planet', 'TEXT');118
$this->ensureColumn('profiles', 'last_planet', 'TEXT');119
$this->ensureColumn('profiles', 'name', 'TEXT');119
$this->ensureColumn('profiles', 'name', 'TEXT');120
$this->ensureColumn('profiles', 'avatar', 'TEXT');120
$this->ensureColumn('profiles', 'avatar', 'TEXT');121
$this->pdo->exec(<<<'SQL'122
CREATE TABLE IF NOT EXISTS friends_cache (123
viewer_id TEXT PRIMARY KEY,124
payload TEXT NOT NULL,125
fetched INTEGER NOT NULL126
);127
SQL);121
}128
}122
129
123
private function ensureColumn(string $table, string $column, string $ddl): void130
private function ensureColumn(string $table, string $column, string $ddl): void@@ -854,7 +861,8 @@ SQL);854
$args = [$this->now()];861
$args = [$this->now()];855
if ($name !== null) {862
if ($name !== null) {856
$name = trim($name);863
$name = trim($name);857
if ($name !== '' && mb_strlen($name) <= 64 && !preg_match('/[\x00-\x1F]/', $name)) {864
if ($name !== '' && !isPlaceholderName($userId, $name)865
&& mb_strlen($name) <= 64 && !preg_match('/[\x00-\x1F]/', $name)) {858
$sets[] = 'name = ?';866
$sets[] = 'name = ?';859
$args[] = $name;867
$args[] = $name;860
}868
}@@ -923,13 +931,16 @@ SQL);923
$row = $found[$id] ?? null;931
$row = $found[$id] ?? null;924
$fallbackName = isset($f['name']) && is_string($f['name']) ? $f['name'] : '';932
$fallbackName = isset($f['name']) && is_string($f['name']) ? $f['name'] : '';925
$fallbackAvatar = isset($f['avatar']) && is_string($f['avatar']) ? $f['avatar'] : null;933
$fallbackAvatar = isset($f['avatar']) && is_string($f['avatar']) ? $f['avatar'] : null;934
$storedName = $row !== null ? trim((string) ($row['name'] ?? '')) : '';935
if (isPlaceholderName($id, $storedName)) {936
$storedName = '';937
}938
$storedAvatar = $row !== null ? ($row['avatar'] ?? '') : '';926
$rows[] = [939
$rows[] = [927
'user_id' => $id,940
'user_id' => $id,928
'lifetime_points' => $row !== null ? (int) $row['lifetime_points'] : 0,941
'lifetime_points' => $row !== null ? (int) $row['lifetime_points'] : 0,929
'name' => ($row['name'] ?? '') !== '' && $row !== null ? $row['name'] : $fallbackName,942
'name' => $storedName !== '' ? $storedName : $fallbackName,930
'avatar' => ($row['avatar'] ?? '') !== '' && $row !== null943
'avatar' => $storedAvatar !== '' ? $storedAvatar : $fallbackAvatar,931
? $row['avatar']932
: $fallbackAvatar,933
];944
];934
}945
}935
$list = $this->presentLeaderboard($rows, $viewerId);946
$list = $this->presentLeaderboard($rows, $viewerId);@@ -978,12 +989,149 @@ SQL);978
return $list;989
return $list;979
}990
}980
991
992
/**993
* Overlay names/avatars from auth (friends list, the viewer, or an994
* earlier backfill) onto an already presented leaderboard. Placeholder995
* names such as "3" for auth:3 are replaced. Ties are re-sorted.996
*997
* @param list<array{rank:int,id:string,name:string,avatar:?string,points:int,you:bool}> $players998
* @param array<string,array{id?:string,name?:string,avatar?:?string}> $known999
* @return list<array{rank:int,id:string,name:string,avatar:?string,points:int,you:bool}>1000
*/1001
public function applyIdentities(array $players, array $known): array1002
{1003
foreach ($players as &$p) {1004
$id = (string) ($p['id'] ?? '');1005
$k = $known[$id] ?? null;1006
if (!is_array($k)) {1007
continue;1008
}1009
$knownName = isset($k['name']) && is_string($k['name']) ? trim($k['name']) : '';1010
if ($knownName !== '' && !isPlaceholderName($id, $knownName)1011
&& isPlaceholderName($id, (string) ($p['name'] ?? ''))) {1012
$p['name'] = $knownName;1013
}1014
$knownAvatar = safeAvatarUrl($k['avatar'] ?? null);1015
if ($knownAvatar !== null && empty($p['avatar'])) {1016
$p['avatar'] = $knownAvatar;1017
}1018
}1019
unset($p);1020
usort($players, static function (array $a, array $b): int {1021
$pc = $b['points'] <=> $a['points'];1022
if ($pc !== 0) {1023
return $pc;1024
}1025
$nc = strcasecmp((string) $a['name'], (string) $b['name']);1026
if ($nc !== 0) {1027
return $nc;1028
}1029
return strcmp((string) $a['id'], (string) $b['id']);1030
});1031
foreach ($players as $i => &$p) {1032
$p['rank'] = $i + 1;1033
}1034
unset($p);1035
return $players;1036
}1037
1038
/**1039
* Write known auth names/avatars onto existing Meteors profiles.1040
* Does not create profiles (friends who never played stay off the1041
* global board). Placeholder names are not stored.1042
*1043
* @param list<array{id?:string,name?:string,avatar?:?string}> $identities1044
*/1045
public function rememberIdentities(array $identities): int1046
{1047
$changed = 0;1048
foreach ($identities as $item) {1049
if (!is_array($item) || !isset($item['id']) || !is_string($item['id']) || $item['id'] === '') {1050
continue;1051
}1052
$userId = $item['id'];1053
$name = isset($item['name']) && is_string($item['name']) ? trim($item['name']) : '';1054
if ($name !== '' && isPlaceholderName($userId, $name)) {1055
$name = '';1056
}1057
$avatar = safeAvatarUrl($item['avatar'] ?? null);1058
if ($name === '' && $avatar === null) {1059
continue;1060
}1061
$stmt = $this->pdo->prepare('SELECT name, avatar FROM profiles WHERE user_id = ?');1062
$stmt->execute([$userId]);1063
$row = $stmt->fetch();1064
if (!$row) {1065
continue;1066
}1067
$sets = ['updated = ?'];1068
$args = [$this->now()];1069
$storedName = trim((string) ($row['name'] ?? ''));1070
if ($name !== '' && ($storedName === '' || isPlaceholderName($userId, $storedName) || $storedName !== $name)) {1071
$sets[] = 'name = ?';1072
$args[] = $name;1073
}1074
$storedAvatar = $row['avatar'] ?? null;1075
if ($avatar !== null && $avatar !== $storedAvatar) {1076
$sets[] = 'avatar = ?';1077
$args[] = $avatar;1078
}1079
if (count($sets) === 1) {1080
continue;1081
}1082
$args[] = $userId;1083
$this->pdo->prepare(1084
'UPDATE profiles SET ' . implode(', ', $sets) . ' WHERE user_id = ?'1085
)->execute($args);1086
$changed++;1087
}1088
return $changed;1089
}1090
1091
/**1092
* Cached GET /api/friends payload for a viewer, or null if missing/stale.1093
*1094
* @return list<array{id:string,name:string,avatar:?string}>|null1095
*/1096
public function readFriendsCache(string $viewerId, ?int $now = null, bool $allowStale = false): ?array1097
{1098
$stmt = $this->pdo->prepare('SELECT payload, fetched FROM friends_cache WHERE viewer_id = ?');1099
$stmt->execute([$viewerId]);1100
$row = $stmt->fetch();1101
if (!$row) {1102
return null;1103
}1104
$now = $now ?? $this->now();1105
$fetched = (int) $row['fetched'];1106
if (!$allowStale && ($now - $fetched) > self::FRIENDS_CACHE_TTL) {1107
return null;1108
}1109
$data = json_decode((string) $row['payload'], true);1110
return is_array($data) ? $data : null;1111
}1112
1113
/** @param list<array{id:string,name:string,avatar:?string}> $friends */1114
public function writeFriendsCache(string $viewerId, array $friends, ?int $fetchedAt = null): void1115
{1116
$this->pdo->prepare(1117
'INSERT INTO friends_cache (viewer_id, payload, fetched) VALUES (?,?,?)1118
ON CONFLICT(viewer_id) DO UPDATE SET payload = excluded.payload, fetched = excluded.fetched'1119
)->execute([1120
$viewerId,1121
json_encode(array_values($friends), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),1122
$fetchedAt ?? $this->now(),1123
]);1124
}1125
981
public function locale(string $userId): ?string1126
public function locale(string $userId): ?string982
{1127
{983
$v = $this->ensureProfile($userId)['locale'] ?? null;1128
$v = $this->ensureProfile($userId)['locale'] ?? null;984
return is_string($v) && $v !== '' ? $v : null;1129
return is_string($v) && $v !== '' ? $v : null;985
}1130
}986
1131
1132
/** Seconds to reuse a viewer's auth friends list before refetching. */1133
public const FRIENDS_CACHE_TTL = 600;1134
987
/** @var list<string> */1135
/** @var list<string> */988
public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];1136
public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];989
1137
@@ -184,6 +184,23 @@ function safeAvatarUrl($url): ?string
184
184
return null;
185
185
}
186
186
187
/**
188
* True when $name is missing or only the numeric auth id (e.g. user
189
* auth:3 shown as "3"). Local test usernames like test_user_1 are real.
190
*/
191
function isPlaceholderName(string $userId, ?string $name): bool
192
{
193
$name = trim((string) $name);
194
if ($name === '' || strcasecmp($name, 'Player') === 0) {
195
return true;
196
}
197
if (str_starts_with($userId, 'auth:')) {
198
$num = substr($userId, 5);
199
return $name === $num || $name === $userId;
200
}
201
return false;
202
}
203
187
204
function authAvatarUrl(array $profile): ?string
188
205
{
189
206
foreach (['avatar_url', 'avatar', 'picture'] as $k) {
@@ -243,6 +260,70 @@ function localTestFriends(string $userId): array
243
260
return [];
244
261
}
245
262
263
/**
264
* Friends of the current viewer from the auth cache, or a fresh
265
* GET /api/friends call. Local testers get the built-in pair.
266
*
267
* @return array{0: list<array{id:string,name:string,avatar:?string}, 1: ?string} friends, error
268
*/
269
function fetchViewerFriends(Store $store, array $user, $token): array
270
{
271
$id = (string) ($user['id'] ?? '');
272
if ($id === '') {
273
return [[], null];
274
}
275
if (is_string($token) && $token !== '') {
276
$cached = $store->readFriendsCache($id);
277
if ($cached !== null) {
278
return [$cached, null];
279
}
280
try {
281
$friends = parseAuthFriends(authRequest('/api/friends', null, $token));
282
$store->writeFriendsCache($id, $friends);
283
return [$friends, null];
284
} catch (Throwable $e) {
285
$stale = $store->readFriendsCache($id, null, true);
286
if ($stale !== null) {
287
return [$stale, null];
288
}
289
return [[], $e->getMessage()];
290
}
291
}
292
if (localDev()) {
293
return [localTestFriends($id), null];
294
}
295
return [[], null];
296
}
297
298
/**
299
* Viewer's own identity plus friends from auth, keyed by Meteors user id.
300
* Also backfills existing profiles so later (guest) requests can show
301
* the same names without another auth call.
302
*
303
* @return array{0: array<string,array{id:string,name:string,avatar:?string}>, 1: list<array{id:string,name:string,avatar:?string}>, 2: ?string}
304
*/
305
function leaderboardKnownIdentities(Store $store, ?array $user, $token): array
306
{
307
$known = [];
308
$friends = [];
309
$error = null;
310
if ($user && isset($user['id'], $user['name'])) {
311
$known[$user['id']] = [
312
'id' => $user['id'],
313
'name' => (string) $user['name'],
314
'avatar' => $user['avatar'] ?? null,
315
];
316
[$friends, $error] = fetchViewerFriends($store, $user, $token);
317
foreach ($friends as $f) {
318
if (isset($f['id']) && is_string($f['id'])) {
319
$known[$f['id']] = $f;
320
}
321
}
322
$store->rememberIdentities(array_values($known));
323
}
324
return [$known, $friends, $error];
325
}
326
246
327
/** @return array{0:string,1:string,2:?string} id, name, avatar */
247
328
function authIdentity(array $profile): array
248
329
{
@@ -184,6 +184,23 @@ function safeAvatarUrl($url): ?string184
return null;184
return null;185
}185
}186
186
187
/**188
* True when $name is missing or only the numeric auth id (e.g. user189
* auth:3 shown as "3"). Local test usernames like test_user_1 are real.190
*/191
function isPlaceholderName(string $userId, ?string $name): bool192
{193
$name = trim((string) $name);194
if ($name === '' || strcasecmp($name, 'Player') === 0) {195
return true;196
}197
if (str_starts_with($userId, 'auth:')) {198
$num = substr($userId, 5);199
return $name === $num || $name === $userId;200
}201
return false;202
}203
187
function authAvatarUrl(array $profile): ?string204
function authAvatarUrl(array $profile): ?string188
{205
{189
foreach (['avatar_url', 'avatar', 'picture'] as $k) {206
foreach (['avatar_url', 'avatar', 'picture'] as $k) {@@ -243,6 +260,70 @@ function localTestFriends(string $userId): array243
return [];260
return [];244
}261
}245
262
263
/**264
* Friends of the current viewer from the auth cache, or a fresh265
* GET /api/friends call. Local testers get the built-in pair.266
*267
* @return array{0: list<array{id:string,name:string,avatar:?string}, 1: ?string} friends, error268
*/269
function fetchViewerFriends(Store $store, array $user, $token): array270
{271
$id = (string) ($user['id'] ?? '');272
if ($id === '') {273
return [[], null];274
}275
if (is_string($token) && $token !== '') {276
$cached = $store->readFriendsCache($id);277
if ($cached !== null) {278
return [$cached, null];279
}280
try {281
$friends = parseAuthFriends(authRequest('/api/friends', null, $token));282
$store->writeFriendsCache($id, $friends);283
return [$friends, null];284
} catch (Throwable $e) {285
$stale = $store->readFriendsCache($id, null, true);286
if ($stale !== null) {287
return [$stale, null];288
}289
return [[], $e->getMessage()];290
}291
}292
if (localDev()) {293
return [localTestFriends($id), null];294
}295
return [[], null];296
}297
298
/**299
* Viewer's own identity plus friends from auth, keyed by Meteors user id.300
* Also backfills existing profiles so later (guest) requests can show301
* the same names without another auth call.302
*303
* @return array{0: array<string,array{id:string,name:string,avatar:?string}>, 1: list<array{id:string,name:string,avatar:?string}>, 2: ?string}304
*/305
function leaderboardKnownIdentities(Store $store, ?array $user, $token): array306
{307
$known = [];308
$friends = [];309
$error = null;310
if ($user && isset($user['id'], $user['name'])) {311
$known[$user['id']] = [312
'id' => $user['id'],313
'name' => (string) $user['name'],314
'avatar' => $user['avatar'] ?? null,315
];316
[$friends, $error] = fetchViewerFriends($store, $user, $token);317
foreach ($friends as $f) {318
if (isset($f['id']) && is_string($f['id'])) {319
$known[$f['id']] = $f;320
}321
}322
$store->rememberIdentities(array_values($known));323
}324
return [$known, $friends, $error];325
}326
246
/** @return array{0:string,1:string,2:?string} id, name, avatar */327
/** @return array{0:string,1:string,2:?string} id, name, avatar */247
function authIdentity(array $profile): array328
function authIdentity(array $profile): array248
{329
{@@ -642,9 +642,79 @@ expect($fl[2]['avatar'] === 'https://auth.timfalken.com/avatar/3001', 'avatar fr
642
642
expect($fl[0]['you'] === false, 'you are not flagged on the friends list unless you are on it');
643
643
expect($lb->friendsLeaderboard([], 10, 'auth:1012') === [], 'empty friend list → empty board');
644
644
645
echo "Leaderboard names from auth (t1249)\n";
646
expect(isPlaceholderName('auth:3', '3') === true, 'name equal to the auth id is a placeholder');
647
expect(isPlaceholderName('auth:3', 'auth:3') === true, 'raw user id is a placeholder');
648
expect(isPlaceholderName('auth:3', '') === true, 'empty name is a placeholder');
649
expect(isPlaceholderName('auth:3', 'Ada') === false, 'a real username is not a placeholder');
650
expect(isPlaceholderName('local:test_user_1', 'test_user_1') === false, 'local test names are real');
651
652
// Existing profile with no stored name, like the live fallback "1" / "3".
653
$lb->awardPoints('auth:3', 40, 'lb-t1249-ada', 'solo');
654
$before = $lb->topPlayers(10, null);
655
$adaRow = null;
656
foreach ($before as $row) {
657
if ($row['id'] === 'auth:3') { $adaRow = $row; }
658
}
659
expect($adaRow && $adaRow['name'] === '3', 'without auth data the display name falls back to the id (' . ($adaRow['name'] ?? '?') . ')');
660
661
$known = [
662
'auth:3' => ['id' => 'auth:3', 'name' => 'Ada', 'avatar' => 'https://auth.timfalken.com/avatar/3?v=2'],
663
'auth:1012' => ['id' => 'auth:1012', 'name' => 'From Friends', 'avatar' => null],
664
];
665
$filled = $lb->applyIdentities($before, $known);
666
$adaFilled = null;
667
foreach ($filled as $row) {
668
if ($row['id'] === 'auth:3') { $adaFilled = $row; }
669
}
670
expect($adaFilled && $adaFilled['name'] === 'Ada', 'applyIdentities replaces the placeholder with the friends-list name');
671
expect($adaFilled && $adaFilled['avatar'] === 'https://auth.timfalken.com/avatar/3?v=2', 'applyIdentities fills the avatar from auth');
672
673
$n = $lb->rememberIdentities(array_values($known));
674
expect($n >= 1, 'rememberIdentities backfills existing profiles (changed ' . $n . ')');
675
$after = $lb->topPlayers(50, null);
676
$adaStored = null;
677
foreach ($after as $row) {
678
if ($row['id'] === 'auth:3') { $adaStored = $row; }
679
}
680
expect($adaStored && $adaStored['name'] === 'Ada', 'later reads (including guests) use the backfilled name');
681
expect($adaStored && $adaStored['avatar'] === 'https://auth.timfalken.com/avatar/3?v=2', 'backfilled avatar is stored');
682
683
// Does not create a profile for a friend who never played.
684
$beforeCount = $lb->topPlayers(50);
685
$lb->rememberIdentities([['id' => 'auth:9999', 'name' => 'Ghost', 'avatar' => null]]);
686
$afterCount = $lb->topPlayers(50);
687
expect(count($afterCount) === count($beforeCount), 'rememberIdentities does not invent profiles for friends who never played');
688
$ghost = false;
689
foreach ($afterCount as $row) {
690
if ($row['id'] === 'auth:9999') { $ghost = true; }
691
}
692
expect($ghost === false, 'the never-played friend is not on the global board');
693
694
// A leftover placeholder in the store loses to the friends-list name.
695
$pdoLb = new PDO('sqlite:' . $lbDir . '/meteors.sqlite');
696
$pdoLb->exec("UPDATE profiles SET name = '3' WHERE user_id = 'auth:3'");
697
$fl = $lb->friendsLeaderboard([
698
['id' => 'auth:3', 'name' => 'Ada', 'avatar' => 'https://auth.timfalken.com/avatar/3?v=9'],
699
], 10, 'auth:1012');
700
expect($fl && $fl[0]['name'] === 'Ada', 'friends tab prefers the auth name over a stored placeholder');
701
702
// Friends cache: fresh hit, stale miss, stale allowed on failure path.
703
$lb->writeFriendsCache('auth:7', [
704
['id' => 'auth:3', 'name' => 'Ada', 'avatar' => null],
705
], 1000);
706
$hit = $lb->readFriendsCache('auth:7', 1000 + 30);
707
expect($hit && $hit[0]['name'] === 'Ada', 'fresh friends cache is reused');
708
$miss = $lb->readFriendsCache('auth:7', 1000 + Store::FRIENDS_CACHE_TTL + 1);
709
expect($miss === null, 'stale friends cache is not reused by default');
710
$stale = $lb->readFriendsCache('auth:7', 1000 + Store::FRIENDS_CACHE_TTL + 1, true);
711
expect($stale && $stale[0]['id'] === 'auth:3', 'stale cache can be used when auth is unavailable');
712
645
713
$apiSrc = (string) file_get_contents(dirname(__DIR__) . '/api.php');
646
714
expect(strpos($apiSrc, "action === 'leaderboard'") !== false, 'api.php has a leaderboard action');
647
expect(strpos($apiSrc, "authRequest('/api/friends'") !== false, 'friends tab uses GET /api/friends on auth.timfalken.com');
715
expect(strpos($apiSrc, 'leaderboardKnownIdentities(') !== false, 'leaderboard resolves names via cached auth friends');
716
$bootSrc = (string) file_get_contents(dirname(__DIR__) . '/lib/bootstrap.php');
717
expect(strpos($bootSrc, "authRequest('/api/friends'") !== false, 'friends are fetched from GET /api/friends on auth.timfalken.com');
648
718
649
719
echo "\nConfig helpers\n";
650
720
@@ -642,9 +642,79 @@ expect($fl[2]['avatar'] === 'https://auth.timfalken.com/avatar/3001', 'avatar fr642
expect($fl[0]['you'] === false, 'you are not flagged on the friends list unless you are on it');642
expect($fl[0]['you'] === false, 'you are not flagged on the friends list unless you are on it');643
expect($lb->friendsLeaderboard([], 10, 'auth:1012') === [], 'empty friend list → empty board');643
expect($lb->friendsLeaderboard([], 10, 'auth:1012') === [], 'empty friend list → empty board');644
644
645
echo "Leaderboard names from auth (t1249)\n";646
expect(isPlaceholderName('auth:3', '3') === true, 'name equal to the auth id is a placeholder');647
expect(isPlaceholderName('auth:3', 'auth:3') === true, 'raw user id is a placeholder');648
expect(isPlaceholderName('auth:3', '') === true, 'empty name is a placeholder');649
expect(isPlaceholderName('auth:3', 'Ada') === false, 'a real username is not a placeholder');650
expect(isPlaceholderName('local:test_user_1', 'test_user_1') === false, 'local test names are real');651
652
// Existing profile with no stored name, like the live fallback "1" / "3".653
$lb->awardPoints('auth:3', 40, 'lb-t1249-ada', 'solo');654
$before = $lb->topPlayers(10, null);655
$adaRow = null;656
foreach ($before as $row) {657
if ($row['id'] === 'auth:3') { $adaRow = $row; }658
}659
expect($adaRow && $adaRow['name'] === '3', 'without auth data the display name falls back to the id (' . ($adaRow['name'] ?? '?') . ')');660
661
$known = [662
'auth:3' => ['id' => 'auth:3', 'name' => 'Ada', 'avatar' => 'https://auth.timfalken.com/avatar/3?v=2'],663
'auth:1012' => ['id' => 'auth:1012', 'name' => 'From Friends', 'avatar' => null],664
];665
$filled = $lb->applyIdentities($before, $known);666
$adaFilled = null;667
foreach ($filled as $row) {668
if ($row['id'] === 'auth:3') { $adaFilled = $row; }669
}670
expect($adaFilled && $adaFilled['name'] === 'Ada', 'applyIdentities replaces the placeholder with the friends-list name');671
expect($adaFilled && $adaFilled['avatar'] === 'https://auth.timfalken.com/avatar/3?v=2', 'applyIdentities fills the avatar from auth');672
673
$n = $lb->rememberIdentities(array_values($known));674
expect($n >= 1, 'rememberIdentities backfills existing profiles (changed ' . $n . ')');675
$after = $lb->topPlayers(50, null);676
$adaStored = null;677
foreach ($after as $row) {678
if ($row['id'] === 'auth:3') { $adaStored = $row; }679
}680
expect($adaStored && $adaStored['name'] === 'Ada', 'later reads (including guests) use the backfilled name');681
expect($adaStored && $adaStored['avatar'] === 'https://auth.timfalken.com/avatar/3?v=2', 'backfilled avatar is stored');682
683
// Does not create a profile for a friend who never played.684
$beforeCount = $lb->topPlayers(50);685
$lb->rememberIdentities([['id' => 'auth:9999', 'name' => 'Ghost', 'avatar' => null]]);686
$afterCount = $lb->topPlayers(50);687
expect(count($afterCount) === count($beforeCount), 'rememberIdentities does not invent profiles for friends who never played');688
$ghost = false;689
foreach ($afterCount as $row) {690
if ($row['id'] === 'auth:9999') { $ghost = true; }691
}692
expect($ghost === false, 'the never-played friend is not on the global board');693
694
// A leftover placeholder in the store loses to the friends-list name.695
$pdoLb = new PDO('sqlite:' . $lbDir . '/meteors.sqlite');696
$pdoLb->exec("UPDATE profiles SET name = '3' WHERE user_id = 'auth:3'");697
$fl = $lb->friendsLeaderboard([698
['id' => 'auth:3', 'name' => 'Ada', 'avatar' => 'https://auth.timfalken.com/avatar/3?v=9'],699
], 10, 'auth:1012');700
expect($fl && $fl[0]['name'] === 'Ada', 'friends tab prefers the auth name over a stored placeholder');701
702
// Friends cache: fresh hit, stale miss, stale allowed on failure path.703
$lb->writeFriendsCache('auth:7', [704
['id' => 'auth:3', 'name' => 'Ada', 'avatar' => null],705
], 1000);706
$hit = $lb->readFriendsCache('auth:7', 1000 + 30);707
expect($hit && $hit[0]['name'] === 'Ada', 'fresh friends cache is reused');708
$miss = $lb->readFriendsCache('auth:7', 1000 + Store::FRIENDS_CACHE_TTL + 1);709
expect($miss === null, 'stale friends cache is not reused by default');710
$stale = $lb->readFriendsCache('auth:7', 1000 + Store::FRIENDS_CACHE_TTL + 1, true);711
expect($stale && $stale[0]['id'] === 'auth:3', 'stale cache can be used when auth is unavailable');712
645
$apiSrc = (string) file_get_contents(dirname(__DIR__) . '/api.php');713
$apiSrc = (string) file_get_contents(dirname(__DIR__) . '/api.php');646
expect(strpos($apiSrc, "action === 'leaderboard'") !== false, 'api.php has a leaderboard action');714
expect(strpos($apiSrc, "action === 'leaderboard'") !== false, 'api.php has a leaderboard action');647
expect(strpos($apiSrc, "authRequest('/api/friends'") !== false, 'friends tab uses GET /api/friends on auth.timfalken.com');715
expect(strpos($apiSrc, 'leaderboardKnownIdentities(') !== false, 'leaderboard resolves names via cached auth friends');716
$bootSrc = (string) file_get_contents(dirname(__DIR__) . '/lib/bootstrap.php');717
expect(strpos($bootSrc, "authRequest('/api/friends'") !== false, 'friends are fetched from GET /api/friends on auth.timfalken.com');648
718
649
echo "\nConfig helpers\n";719
echo "\nConfig helpers\n";650
720