BlueGit

projects-timfalken-com microchess

Files

microchess / web / api.php

api.php

api.php 10.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 'links'=>query('SELECT * FROM links WHERE owner=?',[$u])->fetchAll(),
20 'games'=>query('SELECT * FROM games WHERE a=? OR b=?',[$u,$u])->fetchAll(),
21 'results'=>query('SELECT * FROM results WHERE a=? OR b=?',[$u,$u])->fetchAll()]);
22 }
23 if ($action!=='state') fail('Unknown action.',404);
24 $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();
25 foreach ($friends as &$f) {
26 $rows=query('SELECT winner FROM results WHERE (a=? AND b=?) OR (a=? AND b=?)',[$u,$f['id'],$f['id'],$u])->fetchAll();
27 $f['wins']=count(array_filter($rows,fn($r)=>$r['winner']===$u));$f['ties']=count(array_filter($rows,fn($r)=>$r['winner']===null));$f['losses']=count($rows)-$f['wins']-$f['ties'];
28 } unset($f);
29 $games=query('SELECT * FROM games WHERE (a=? AND exit_a=0) OR (b=? AND exit_b=0) ORDER BY id DESC',[$u,$u])->fetchAll();
30 $invite=null;
31 if (isset($_GET['invite'])) {
32 $l=query('SELECT l.*,u.name FROM links l JOIN users u ON u.id=l.owner WHERE token=?',[(string)$_GET['invite']])->fetch();
33 if (!$l || $l['used'] || $l['expires']<=time()) $invite=['error'=>'This invitation has expired or has already been accepted.'];
34 elseif ($l['owner']===$u) $invite=['error'=>'This is your invitation. Share the link with someone else.'];
35 else $invite=['kind'=>$l['kind'],'name'=>$l['name'],'token'=>$l['token']];
36 }
37 jsonOut(['user'=>profile($u),'csrf'=>$_SESSION['csrf'],'local'=>localDev(),'friends'=>$friends,'games'=>array_map(fn($g)=>gameView($g,$u),$games),'invite'=>$invite]);
38 }
39 if ($method!=='POST') fail('Method not allowed.',405);
40 if (!hash_equals($_SESSION['csrf']??'',$_SERVER['HTTP_X_CSRF_TOKEN']??'')) fail('Invalid session token. Reload the page.',403);
41 $in=json_decode(file_get_contents('php://input'),true,32,JSON_THROW_ON_ERROR);
42 if (!is_array($in)) throw new DomainException('Invalid request.');
43 $action=$in['action']??'';
44 if ($action==='switch_user') {
45 if (!localDev()) fail('Not available.',403);
46 if (!in_array($in['user']??'', ['test_user_1','test_user_2'],true)) throw new DomainException('Unknown test user.');
47 loginUser('local:'.$in['user'],$in['user']);jsonOut(['ok'=>true]);
48 }
49 if ($action==='logout') {
50 if (!localDev() && isset($_SESSION['token'])) authRequest('/api/logout',[],$_SESSION['token']);
51 $_SESSION=[];session_destroy();jsonOut(['ok'=>true]);
52 }
53 db()->exec('BEGIN IMMEDIATE');
54 $out=['ok'=>true];
55 if ($action==='set_avatar') {
56 $avatar=$in['avatar']??null;
57 if ($avatar===null) {
58 $avatars=avatarCatalog();
59 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']]);
60 }
61 else {
62 if (!is_string($avatar)||!in_array($avatar,array_column(avatarCatalog(),'id'),true)) throw new DomainException('Choose an avatar from the available pieces.');
63 query('INSERT INTO user_avatars(user_id,avatar) VALUES(?,?) ON CONFLICT(user_id) DO UPDATE SET avatar=excluded.avatar',[$u,$avatar]);
64 }
65 } elseif ($action==='create_link') {
66 $kind=$in['kind']??''; if (!in_array($kind,['friend','match'],true)) throw new DomainException('Invalid invitation type.');
67 $token=bin2hex(random_bytes(24));
68 query('INSERT INTO links(token,owner,kind,expires) VALUES(?,?,?,?)',[$token,$u,$kind,(new DateTimeImmutable())->modify('+1 month')->getTimestamp()]);
69 $out['url']=baseUrl().'/?invite='.$token;
70 } elseif ($action==='accept_link') {
71 $l=query('SELECT * FROM links WHERE token=?',[$in['token']??''])->fetch();
72 if (!$l || $l['used'] || $l['expires']<=time()) throw new DomainException('This invitation has expired or has already been accepted.');
73 if ($l['owner']===$u) throw new DomainException('You cannot accept your own invitation.');
74 if ($l['kind']==='friend') query('INSERT OR IGNORE INTO friends VALUES(?,?)',pair($u,$l['owner']));
75 else $out['game']=startGame($l['owner'],$u);
76 query('UPDATE links SET used=1 WHERE token=?',[$l['token']]);
77 } elseif ($action==='remove_friend' || $action==='challenge') {
78 $other=$in['friend']??'';$p=pair($u,$other);
79 if (!query('SELECT 1 FROM friends WHERE a=? AND b=?',$p)->fetchColumn()) throw new DomainException('This person is no longer in your friends list.');
80 if ($action==='remove_friend') query('DELETE FROM friends WHERE a=? AND b=?',$p);
81 else {
82 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.');
83 query("INSERT INTO games(a,b,status,created) VALUES(?,?,'pending',?)",[$u,$other,time()]);
84 }
85 } else {
86 $g=query('SELECT * FROM games WHERE id=?',[$in['game']??0])->fetch();
87 if (!$g || ($g['a']!==$u && $g['b']!==$u)) throw new DomainException('Game not found.');
88 $side=$g['a']===$u?'a':'b';$opSide=$side==='a'?'b':'a';$other=$g[$opSide];
89 if ($g['exit_'.$side]) throw new DomainException('You have left this game.');
90 if (!isset($in['version']) || $in['version']!==(int)$g['version']) throw new DomainException('The game has changed. Please try again.');
91 if ($action==='stop_inactive') {
92 if (($g['activity_at']??time())>time()-7*86400) throw new DomainException('This game has been active within the last week.');
93 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']]);
94 } elseif (in_array($action,['accept','reject'],true)) {
95 if ($g['status']!=='pending' || $g['b']!==$u) throw new DomainException('This invitation is no longer available.');
96 if ($action==='reject') query('DELETE FROM games WHERE id=?',[$g['id']]);
97 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']]);
98 } elseif ($action==='exit' || $action==='rematch') {
99 if ($g['status']!=='ended') throw new DomainException('The game has not ended.');
100 if ($action==='exit') query("UPDATE games SET exit_$side=1,rematch_$side=0,version=version+1 WHERE id=?",[$g['id']]);
101 else {
102 if ($g['exit_'.$opSide]) throw new DomainException('Your opponent has left this game.');
103 if ($g['rematch_'.$side]) throw new DomainException('Your rematch request is already waiting.');
104 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']]);
105 else query("UPDATE games SET rematch_$side=1,version=version+1 WHERE id=?",[$g['id']]);
106 }
107 } else {
108 if ($g['status']!=='active') throw new DomainException('This game is not active.');
109 $s=json_decode($g['state'],true);$color=$g['white']===$u?'w':'b';
110 if ($s['turn']!==$color) throw new DomainException('It is not your turn.');
111 if ($action==='move') {
112 if (!is_int($in['from']??null)||!is_int($in['to']??null)) throw new DomainException('Invalid squares.');
113 $s=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
114 $r=Chess::result($s);
115 if ($r) finishGame($g,$r['winner']===null?null:($r['winner']==='w'?$g['white']:($g['white']===$g['a']?$g['b']:$g['a'])),$r['reason'],$s);
116 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']]);
117 } elseif ($action==='claim_draw') {
118 $claim=$s;
119 if (isset($in['from'],$in['to'])) $claim=Chess::move($s,$in['from'],$in['to'],$in['promotion']??null);
120 if (!Chess::claimable($claim)) throw new DomainException('A draw cannot be claimed in this position.');
121 finishGame($g,null,$claim['halfmove']>=100?'50-move rule':'Threefold repetition',$s);
122 } elseif ($action==='offer_draw') {
123 if ($g['draw_offer']) throw new DomainException('A draw has already been offered.');
124 query('UPDATE games SET draw_offer=?,version=version+1 WHERE id=?',[$u,$g['id']]);
125 } elseif ($action==='accept_draw') {
126 if ($g['draw_offer']!==$other) throw new DomainException('There is no draw offer to accept.');
127 finishGame($g,null,'Draw by agreement',$s);
128 } elseif ($action==='resign') finishGame($g,$other,'Resignation',$s);
129 else throw new DomainException('Unknown action.');
130 }
131 }
132 db()->exec('COMMIT');jsonOut($out);
133} catch (Throwable $e) {
134 try {if (isset($action)) db()->exec('ROLLBACK');} catch (Throwable) {}
135 if ($e instanceof DomainException || $e instanceof JsonException) fail($e->getMessage(),409);
136 error_log((string)$e);fail('Something went wrong. Please try again.',500);
137}