BlueGit

projects-timfalken-com meteors

Files

meteors / server / api.php

api.php

api.php 9.3 KiB Download Raw
1<?php
2declare(strict_types=1);
3require __DIR__ . '/lib/bootstrap.php';
4require __DIR__ . '/lib/Store.php';
5
6$action = $_GET['action'] ?? $_POST['action'] ?? '';
7if ($action === '') {
8 $body = readJsonBody();
9 $action = (string) ($body['action'] ?? '');
10} else {
11 $body = readJsonBody();
12}
13
14try {
15 $configured = authConfigured();
16 $local = localDev();
17 $user = currentUser();
18
19 if ($action === 'me' || $action === '') {
20 $view = ['lobby' => null, 'incoming' => [], 'shot_results' => [], 'shot_flights' => []];
21 $profile = [
22 'lifetime_points' => 0,
23 'locale' => null,
24 'locale_explicit' => false,
25 'last_planet' => null,
26 'blocks' => [],
27 'planets' => [],
28 ];
29 $authLocale = null;
30 if ($user) {
31 $store = Store::open();
32 $store->touchProfile($user['id'], $user['name'], $user['avatar'] ?? null);
33 $view = $store->viewFor($user['id']);
34 $profile = $store->profilePayload($user['id']);
35 $token = $_SESSION['token'] ?? null;
36 $authLocale = refreshAuthLocale(is_string($token) ? $token : null);
37 }
38 jsonOut([
39 'ok' => true,
40 'configured' => $configured,
41 'local' => $local,
42 'csrf' => csrfToken(),
43 'me' => $user,
44 'lobby' => $view['lobby'],
45 'incoming' => $view['incoming'],
46 'shot_results' => $view['shot_results'],
47 'shot_flights' => $view['shot_flights'] ?? [],
48 'miss_chance_default' => METEORS_DEFAULT_MISS,
49 'flight_duration' => METEORS_FLIGHT_DURATION,
50 'login_url' => 'auth.php',
51 'logout_url' => 'logout.php',
52 'lifetime_points' => $profile['lifetime_points'],
53 'locale' => $profile['locale'],
54 'locale_explicit' => !empty($profile['locale_explicit']),
55 'auth_locale' => $authLocale,
56 'last_planet' => $profile['last_planet'],
57 'blocks' => $profile['blocks'],
58 'planets' => $profile['planets'],
59 ]);
60 }
61
62 if ($action === 'leaderboard') {
63 $scope = (string) ($body['scope'] ?? $_GET['scope'] ?? 'global');
64 if ($scope !== 'friends') {
65 $scope = 'global';
66 }
67 $store = Store::open();
68 $viewer = $user['id'] ?? null;
69 $token = $_SESSION['token'] ?? null;
70 if ($scope === 'friends') {
71 if (!$user) {
72 jsonOut([
73 'ok' => true,
74 'scope' => 'friends',
75 'login_required' => true,
76 'players' => [],
77 'me' => null,
78 ]);
79 }
80 [$known, $friends, $friendsError] = leaderboardKnownIdentities($store, $user, $token);
81 if ($friendsError !== null && $friends === []) {
82 jsonFail('De vriendenlijst is nu niet beschikbaar.', 502);
83 }
84 jsonOut([
85 'ok' => true,
86 'scope' => 'friends',
87 'login_required' => false,
88 'players' => $store->applyIdentities(
89 $store->friendsLeaderboard($friends, 10, $viewer),
90 $known
91 ),
92 'me' => $viewer,
93 ]);
94 }
95 $players = $store->topPlayers(10, $viewer);
96 [$known] = leaderboardKnownIdentities($store, $user, $token, array_column($players, 'id'));
97 jsonOut([
98 'ok' => true,
99 'scope' => 'global',
100 'login_required' => false,
101 'players' => $store->applyIdentities($players, $known),
102 'me' => $viewer,
103 ]);
104 }
105
106 if ($action === 'test_login') {
107 if (!localDev()) {
108 jsonFail('Niet beschikbaar.', 403);
109 }
110 requireCsrf();
111 $who = (string) ($body['user'] ?? $_GET['user'] ?? '');
112 if (!in_array($who, ['test_user_1', 'test_user_2'], true)) {
113 jsonFail('Onbekende testgebruiker.');
114 }
115 loginUser('local:' . $who, $who);
116 jsonOut(['ok' => true, 'me' => currentUser(), 'csrf' => csrfToken()]);
117 }
118
119 if (!$user && $action !== 'me') {
120 jsonFail('Log in om verder te gaan.', 401);
121 }
122
123 requireCsrf();
124 $store = Store::open();
125 $userId = $user['id'];
126 $name = $user['name'];
127
128 switch ($action) {
129 case 'lobby_create':
130 $miss = isset($body['miss_chance']) ? (float) $body['miss_chance'] : METEORS_DEFAULT_MISS;
131 $planet = (string) ($body['planet_id'] ?? '');
132 $lobby = $store->createLobby($userId, $name, $miss, $planet);
133 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
134
135 case 'lobby_join':
136 $code = (string) ($body['code'] ?? '');
137 $planet = (string) ($body['planet_id'] ?? '');
138 $lobby = $store->joinLobby($userId, $name, $code, $planet);
139 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
140
141 case 'lobby_set_planet':
142 $planet = (string) ($body['planet_id'] ?? '');
143 $lobby = $store->setPlanet($userId, $planet);
144 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
145
146 case 'lobby_leave':
147 $store->leaveLobby($userId);
148 jsonOut(['ok' => true, 'lobby' => null, 'csrf' => csrfToken()]);
149
150 case 'lobby_ready':
151 $ready = (bool) ($body['ready'] ?? true);
152 $lobby = $store->setReady($userId, $ready);
153 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
154
155 case 'lobby_start':
156 $lobby = $store->startGame($userId);
157 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
158
159 case 'poll':
160 $snapshot = isset($body['snapshot']) && is_array($body['snapshot']) ? $body['snapshot'] : null;
161 $score = isset($body['score']) ? (int) $body['score'] : null;
162 $eliminated = !empty($body['eliminated']);
163 $outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];
164 $view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);
165 $profile = $store->profilePayload($userId);
166 $rawLobby = $store->lobbyForUser($userId);
167 $onlineAwarded = $rawLobby ? $store->onlineAwardedFor($userId, $rawLobby) : null;
168 jsonOut([
169 'ok' => true,
170 'csrf' => csrfToken(),
171 'me' => $user,
172 'lobby' => $view['lobby'],
173 'incoming' => $view['incoming'],
174 'shot_results' => $view['shot_results'],
175 'shot_flights' => $view['shot_flights'] ?? [],
176 'lifetime_points' => $profile['lifetime_points'],
177 'online_awarded' => $onlineAwarded,
178 'locale' => $profile['locale'],
179 'locale_explicit' => !empty($profile['locale_explicit']),
180 'auth_locale' => sessionAuthLocale(),
181 'last_planet' => $profile['last_planet'],
182 'blocks' => $profile['blocks'],
183 'planets' => $profile['planets'],
184 ]);
185
186 case 'play_begin':
187 $mode = (string) ($body['mode'] ?? 'solo');
188 $ses = $store->playBegin($userId, $mode);
189 jsonOut(['ok' => true, 'csrf' => csrfToken(), 'token' => $ses['token']]);
190
191 case 'play_finish':
192 $token = (string) ($body['token'] ?? '');
193 $score = isset($body['score']) ? (int) $body['score'] : 0;
194 $result = $store->playFinish($userId, $token, $score);
195 jsonOut([
196 'ok' => true,
197 'csrf' => csrfToken(),
198 'lifetime_points' => $result['lifetime_points'],
199 'awarded' => $result['awarded'],
200 'already' => $result['already'],
201 'blocks' => Blocks::present($result['lifetime_points']),
202 ]);
203
204 case 'planet_save':
205 $snap = $store->saveCustomPlanet($userId, is_array($body['planet'] ?? null) ? $body['planet'] : $body);
206 jsonOut([
207 'ok' => true,
208 'csrf' => csrfToken(),
209 'planet' => $snap,
210 'planets' => $store->listCustomPlanets($userId),
211 ]);
212
213 case 'planet_delete':
214 $store->deleteCustomPlanet($userId, (string) ($body['id'] ?? $body['planet_id'] ?? ''));
215 jsonOut([
216 'ok' => true,
217 'csrf' => csrfToken(),
218 'planets' => $store->listCustomPlanets($userId),
219 ]);
220
221 case 'set_last_planet':
222 $pid = $store->setLastPlanet($userId, (string) ($body['planet_id'] ?? ''));
223 jsonOut(['ok' => true, 'csrf' => csrfToken(), 'last_planet' => $pid]);
224
225 case 'set_locale':
226 $locale = $store->setLocale($userId, (string) ($body['locale'] ?? ''));
227 jsonOut(['ok' => true, 'csrf' => csrfToken(), 'locale' => $locale]);
228
229 default:
230 jsonFail('Onbekende actie.', 404);
231 }
232} catch (RuntimeException $e) {
233 jsonFail($e->getMessage(), 400);
234} catch (Throwable $e) {
235 jsonFail('Interne fout.', 500);
236}