607ab39e9c255cfab957f5c9776211b61251d40b
[vchess.git] / server / routes / games.js
1 let router = require("express").Router();
2 const UserModel = require("../models/User");
3 const ChallengeModel = require('../models/Challenge');
4 const GameModel = require('../models/Game');
5 const access = require("../utils/access");
6 const params = require("../config/parameters");
7
8 // From main hall, start game between players 0 and 1
9 router.post("/games", access.logged, access.ajax, (req,res) => {
10 const gameInfo = req.body.gameInfo;
11 const cid = req.body.cid;
12 if (
13 Array.isArray(gameInfo.players) &&
14 gameInfo.players.some(p => p.id == req.userId) &&
15 cid.toString().match(/^[0-9]+$/) &&
16 GameModel.checkGameInfo(gameInfo)
17 ) {
18 ChallengeModel.remove(cid);
19 GameModel.create(
20 gameInfo.vid, gameInfo.fen, gameInfo.cadence, gameInfo.players,
21 (err,ret) => {
22 const oppIdx = (gameInfo.players[0].id == req.userId ? 1 : 0);
23 const oppId = gameInfo.players[oppIdx].id;
24 UserModel.tryNotify(oppId,
25 "Game started: " + params.siteURL + "/#/game/" + ret.gid);
26 res.json({gameId: ret.gid});
27 }
28 );
29 }
30 });
31
32 router.get("/games", access.ajax, (req,res) => {
33 const gameId = req.query["gid"];
34 if (gameId)
35 {
36 if (gameId.match(/^[0-9]+$/))
37 {
38 GameModel.getOne(gameId, false, (err,game) => {
39 res.json({game: game});
40 });
41 }
42 }
43 else
44 {
45 // Get by (non-)user ID:
46 const userId = req.query["uid"];
47 if (userId.match(/^[0-9]+$/))
48 {
49 const excluded = !!req.query["excluded"];
50 GameModel.getByUser(userId, excluded, (err,games) => {
51 res.json({games: games});
52 });
53 }
54 }
55 });
56
57 // FEN update + score(Msg) + draw status / and new move + chats
58 router.put("/games", access.logged, access.ajax, (req,res) => {
59 const gid = req.body.gid;
60 const obj = req.body.newObj;
61 if (gid.toString().match(/^[0-9]+$/) && GameModel.checkGameUpdate(obj))
62 {
63 GameModel.getPlayers(gid, (err,players) => {
64 if (players.some(p => p.uid == req.userId))
65 {
66 GameModel.update(gid, obj, (err) => {
67 if (!err && (obj.move || obj.score))
68 {
69 // Notify opponent if he enabled notifications:
70 const oppid = players[0].uid == req.userId
71 ? players[1].uid
72 : players[0].uid;
73 const messagePrefix = obj.move
74 ? "New move in game: "
75 : "Game ended: ";
76 UserModel.tryNotify(oppid,
77 messagePrefix + params.siteURL + "/#/game/" + gid);
78 }
79 res.json(err || {});
80 });
81 }
82 });
83 }
84 });
85
86 // TODO: chats deletion here, but could/should be elsewhere.
87 // Moves update also could, although logical unit in a game.
88 router.delete("/chats", access.logged, access.ajax, (req,res) => {
89 const gid = req.query["gid"];
90 GameModel.getPlayers(gid, (err,players) => {
91 if (players.some(p => p.uid == req.userId))
92 {
93 GameModel.update(gid, {delchat: true}, (err) => {
94 res.json(err || {});
95 });
96 }
97 });
98 });
99
100 module.exports = router;