BlueGit

projects-timfalken-com microchess

Files

microchess / web / api.php

api.php

api.php 13.3 KiB Download Raw
1<?php
2require __DIR__.'/lib/bootstrap.php';
3try {
4 $u=user();
5 if (!localDev() && time()-($_SESSION['validated']??0)>60) {
6 try {
7 authRequest('/api/me',null,$_SESSION['token']);
8 if ($_SESSION['expires']-time()<900) { $extended=authRequest('/api/session/extend',[],$_SESSION['token']);$_SESSION['expires']=time()+(int)$extended['expires_in']; }
9 $_SESSION['validated']=time();
10 } catch (Throwable $e) {unset($_SESSION['user']);fail('Please sign in again.',401);}
11 }
12 $method=$_SERVER['REQUEST_METHOD'];
13 if ($method==='GET') {
14 $action=$_GET['action']??'state';
15 if ($action==='export') {
16 header('Content-Disposition: attachment; filename="microchess-data.json"');
17 jsonOut(['exported_at'=>gmdate('c'),'profile'=>profile($u),
18 'friends'=>query('SELECT * FROM friends WHERE a=? OR b=?',[$u,$u])->fetchAll(),
19 'friend_requests'=>query('SELECT * FROM friend_requests WHERE a=? OR b=?',[$u,$u])->fetchAll(),
20 'links'=>query('SELECT * FROM links WHERE owner=?',[$u])->fetchAll(),
21 'matchmaking'=>query('SELECT * FROM matchmaking WHERE user_id=?',[$u])->fetchAll(),
22 'rating_changes'=>query('SELECT c.* FROM rating_changes c JOIN results r ON r.id=c.result_id WHERE r.a=? OR r.b=?',[$u,$u])->fetchAll(),
23 'games'=>query('SELECT * FROM games WHERE a=? OR b=?',[$u,$u])->fetchAll(),
24 'results'=>query('SELECT * FROM results WHERE a=? OR b=?',[$u,$u])->fetchAll()]);
25 }
26 if ($action!=='state') fail('Unknown action.',404);
27 if ((int)query('SELECT checked FROM matchmaking_clock WHERE id=1')->fetchColumn()<=time()-60) {
28 db()->exec('BEGIN IMMEDIATE');
29 matchPlayers();
30 db()->exec('COMMIT');
31 }
32 $friends=query('SELECT u.*,av.avatar FROM friends f JOIN users u ON u.id=CASE WHEN f.a=? THEN f.b ELSE f.a END LEFT JOIN user_avatars av ON av.user_id=u.id WHERE f.a=? OR f.b=? ORDER BY u.name',[$u,$u,$u])->fetchAll();
33 foreach ($friends as &$f) {
34 $f['rating']=(int)profile($f['id'])['rating'];
35 $f+=rivalry($u,$f['id']);
36 } unset($f);
37 $requests=query('SELECT u.id,u.name,av.avatar,r.sender FROM friend_requests r JOIN users u ON u.id=CASE WHEN r.a=? THEN r.b ELSE r.a END LEFT JOIN user_avatars av ON av.user_id=u.id WHERE r.a=? OR r.b=? ORDER BY r.created,u.id',[$u,$u,$u])->fetchAll();
38 foreach ($requests as &$request) {$request['incoming']=$request['sender']!==$u;unset($request['sender']);} unset($request);
39 $games=query('SELECT * FROM games WHERE (a=? AND exit_a=0) OR (b=? AND exit_b=0) ORDER BY id DESC',[$u,$u])->fetchAll();
40 $invite=null;
41 if (isset($_GET['invite'])) {
42 $l=query('SELECT l.*,u.name FROM links l JOIN users u ON u.id=l.owner WHERE token=?',[(string)$_GET['invite']])->fetch();
43 if (!$l || $l['used'] || $l['expires']<=time()) $invite=['error'=>'This invitation has expired or has already been accepted.'];
44 elseif ($l['owner']===$u) $invite=['error'=>'This is your invitation. Share the link with someone else.'];
45 else $invite=['kind'=>$l['kind'],'name'=>$l['name'],'token'=>$l['token']];
46 }
47 $joined=query('SELECT joined FROM matchmaking WHERE user_id=?',[$u])->fetchColumn();
48 jsonOut(['user'=>profile($u),'csrf'=>$_SESSION['csrf'],'local'=>localDev(),'friends'=>$friends,'friendRequests'=>$requests,'games'=>array_map(fn($g)=>gameView($g,$u),$games),'invite'=>$invite,'matchmaking'=>$joined===false?null:['status'=>(int)$joined<=time()-86400?'expired':'searching']]);
49 }
50 if ($method!=='POST') fail('Method not allowed.',405);
51 if (!hash_equals($_SESSION['csrf']??'',$_SERVER['HTTP_X_CSRF_TOKEN']??'')) fail('Invalid session token. Reload the page.',403);
52 $in=json_decode(file_get_contents('php://input'),true,32,JSON_THROW_ON_ERROR);
53 if (!is_array($in)) throw new DomainException('Invalid request.');
54 $action=$in['action']??'';
55 if ($action==='switch_user') {
56 if (!localDev()) fail('Not available.',403);
57 if (!in_array($in['user']??'', ['test_user_1','test_user_2'],true)) throw new DomainException('Unknown test user.');
58 loginUser('local:'.$in['user'],$in['user']);jsonOut(['ok'=>true]);
59 }
60 if ($action==='logout') {
61 if (!localDev() && isset($_SESSION['token'])) authRequest('/api/logout',[],$_SESSION['token']);
62 $_SESSION=[];session_destroy();jsonOut(['ok'=>true]);
63 }
64 db()->exec('BEGIN IMMEDIATE');
65 $out=['ok'=>true];
66 if (in_array($action,['send_friend_request','accept_friend_request','reject_friend_request'],true)) {
67 $other=$in['friend']??null;
68 if (!is_string($other) || $other===$u) throw new DomainException('Choose another player.');
69 $p=pair($u,$other);
70 if ($action==='send_friend_request') {
71 if (!query('SELECT 1 FROM games WHERE (a=? AND b=?) OR (a=? AND b=?)',[$u,$other,$other,$u])->fetchColumn()) throw new DomainException('Player not found.');
72 if (query('SELECT 1 FROM friends WHERE a=? AND b=?',$p)->fetchColumn()) throw new DomainException('You are already friends.');
73 $sender=query('SELECT sender FROM friend_requests WHERE a=? AND b=?',$p)->fetchColumn();
74 if ($sender!==false && $sender!==$u) throw new DomainException('This player has already sent you a friend request.');
75 query('INSERT OR IGNORE INTO friend_requests(a,b,sender,created) VALUES(?,?,?,?)',[$p[0],$p[1],$u,time()]);
76 } else {
77 if (query('SELECT sender FROM friend_requests WHERE a=? AND b=?',$p)->fetchColumn()!==$other) throw new DomainException('This friend request is no longer available.');
78 if ($action==='accept_friend_request') befriend($u,$other);
79 else query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);
80 }
81 } elseif ($action==='join_matchmaking') {
82 query('INSERT INTO matchmaking(user_id,joined) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET joined=excluded.joined WHERE matchmaking.joined<=?',[$u,time(),time()-86400]);
83 matchPlayers(true);
84 } elseif ($action==='cancel_matchmaking') {
85 query('DELETE FROM matchmaking WHERE user_id=?',[$u]);
86 } elseif ($action==='set_avatar') {
87 $avatar=$in['avatar']??null;
88 if ($avatar===null) {
89 $avatars=avatarCatalog();
90 query('INSERT INTO user_avatars(user_id,avatar) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET avatar=excluded.avatar',[$u,$avatars[random_int(0,count($avatars)-1)]['id']]);
91 }
92 else {
93 if (!is_string($avatar)||!in_array($avatar,array_column(avatarCatalog(),'id'),true)) throw new DomainException('Choose an avatar from the available pieces.');
94 query('INSERT INTO user_avatars(user_id,avatar) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET avatar=excluded.avatar',[$u,$avatar]);
95 }
96 } elseif ($action==='create_link') {
97 $kind=$in['kind']??''; if (!in_array($kind,['friend','match'],true)) throw new DomainException('Invalid invitation type.');
98 $token=bin2hex(random_bytes(24));
99 query('INSERT INTO links(token,owner,kind,expires) VALUES(?,?,?,?)',[$token,$u,$kind,(new DateTimeImmutable())->modify('+1 month')->getTimestamp()]);
100 $out['url']=baseUrl().'/?invite='.$token;
101 } elseif ($action==='accept_link') {
102 $l=query('SELECT * FROM links WHERE token=?',[$in['token']??''])->fetch();
103 if (!$l || $l['used'] || $l['expires']<=time()) throw new DomainException('This invitation has expired or has already been accepted.');
104 if ($l['owner']===$u) throw new DomainException('You cannot accept your own invitation.');
105 if ($l['kind']==='friend') befriend($u,$l['owner']);
106 else $out['game']=startGame($l['owner'],$u);
107 query('UPDATE links SET used=1 WHERE token=?',[$l['token']]);
108 } elseif ($action==='remove_friend' || $action==='challenge') {
109 $other=$in['friend']??'';$p=pair($u,$other);
110 if (!query('SELECT 1 FROM friends WHERE a=? AND b=?',$p)->fetchColumn()) throw new DomainException('This person is no longer in your friends list.');
111 if ($action==='remove_friend') query('DELETE FROM friends WHERE a=? AND b=?',$p);
112 else {
113 if (query("SELECT 1 FROM games WHERE status='pending' AND ((a=? AND b=?) OR (a=? AND b=?))",[$u,$other,$other,$u])->fetchColumn()) throw new DomainException('There is already an invitation waiting.');
114 query("INSERT INTO games(a,b,status,created) VALUES(?,?,'pending',?)",[$u,$other,time()]);
115 }
116 } else {
117 $g=query('SELECT * FROM games WHERE id=?',[$in['game']??0])->fetch();
118 if (!$g || ($g['a']!==$u && $g['b']!==$u)) throw new DomainException('Game not found.');
119 $side=$g['a']===$u?'a':'b';$opSide=$side==='a'?'b':'a';$other=$g[$opSide];
120 if ($g['exit_'.$side]) throw new DomainException('You have left this game.');
121 if (!isset($in['version']) || $in['version']!==(int)$g['version']) throw new DomainException('The game has changed. Please try again.');
122 if ($action==='stop_inactive') {
123 if (($g['activity_at']??time())>time()-7*86400) throw new DomainException('This game has been active within the last week.');
124 query("UPDATE games SET exit_a=1,exit_b=1,rematch_a=0,rematch_b=0,status=CASE WHEN status='ended' THEN status ELSE 'stopped' END,version=version+1 WHERE id=?",[$g['id']]);
125 } elseif (in_array($action,['accept','reject'],true)) {
126 if ($g['status']!=='pending' || $g['b']!==$u) throw new DomainException('This invitation is no longer available.');
127 if ($action==='reject') query('DELETE FROM games WHERE id=?',[$g['id']]);
128 else query("UPDATE games SET status='active',white=?,state=?,version=version+1 WHERE id=?",[random_int(0,1)?$g['a']:$g['b'],json_encode(Chess::initial()),$g['id']]);
129 } elseif ($action==='exit' || $action==='rematch') {
130 if ($g['status']!=='ended') throw new DomainException('The game has not ended.');
131 if ($action==='exit') query("UPDATE games SET exit_$side=1,rematch_$side=0,version=version+1 WHERE id=?",[$g['id']]);
132 else {
133 if ($g['exit_'.$opSide]) throw new DomainException('Your opponent has left this game.');
134 if ($g['rematch_'.$side]) throw new DomainException('Your rematch request is already waiting.');
135 if ($g['rematch_'.$opSide]) query("UPDATE games SET status='active',white=?,state=?,winner=NULL,reason=NULL,rematch_a=0,rematch_b=0,draw_offer=NULL,version=version+1 WHERE id=?",[$g['white']===$g['a']?$g['b']:$g['a'],json_encode(Chess::initial()),$g['id']]);
136 else query("UPDATE games SET rematch_$side=1,version=version+1 WHERE id=?",[$g['id']]);
137 }
138 } else {
139 if ($g['status']!=='active') throw new DomainException('This game is not active.');
140 $s=json_decode($g['state'],true);$color=$g['white']===$u?'w':'b';
141 if ($s['turn']!==$color) throw new DomainException('It is not your turn.');
142 if ($action==='move') {
143 if (!is_int($in['from']??null)||!is_int($in['to']??null)) throw new DomainException('Invalid squares.');
144 $before=$s;
145 $s=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
146 $feedbackStates=[$before,$s];
147 $r=Chess::result($s);
148 if ($r) finishGame($g,$r['winner']===null?null:($r['winner']==='w'?$g['white']:($g['white']===$g['a']?$g['b']:$g['a'])),$r['reason'],$s);
149 else query('UPDATE games SET state=?,draw_offer=CASE WHEN draw_offer=? THEN draw_offer ELSE NULL END,version=version+1 WHERE id=?',[json_encode($s),$u,$g['id']]);
150 } elseif ($action==='claim_draw') {
151 $claim=$s;
152 if (isset($in['from'],$in['to'])) $claim=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
153 if (!Chess::claimable($claim)) throw new DomainException('A draw cannot be claimed in this position.');
154 finishGame($g,null,$claim['halfmove']>=100?'50-move rule':'Threefold repetition',$s);
155 } elseif ($action==='offer_draw') {
156 if ($g['draw_offer']) throw new DomainException('A draw has already been offered.');
157 query('UPDATE games SET draw_offer=?,version=version+1 WHERE id=?',[$u,$g['id']]);
158 } elseif ($action==='accept_draw') {
159 if ($g['draw_offer']!==$other) throw new DomainException('There is no draw offer to accept.');
160 finishGame($g,null,'Draw by agreement',$s);
161 } elseif ($action==='resign') finishGame($g,$other,'Resignation',$s);
162 else throw new DomainException('Unknown action.');
163 }
164 }
165 db()->exec('COMMIT');
166 if (isset($feedbackStates)) {
167 // Release game/session writes before optional computation. Analysis can never undo a saved move.
168 session_write_close();
169 $out['feedback']=null;
170 try {$out['feedback']=(new MoveFeedback())->rate(...$feedbackStates);}
171 catch (Throwable $e) {error_log('Move feedback unavailable: '.$e->getMessage());}
172 }
173 jsonOut($out);
174} catch (Throwable $e) {
175 try {if (isset($action)) db()->exec('ROLLBACK');} catch (Throwable) {}
176 if ($e instanceof DomainException || $e instanceof JsonException) fail($e->getMessage(),409);
177 error_log((string)$e);fail('Something went wrong. Please try again.',500);
178}