Convert all remaining tabs by 2spaces
[vchess.git] / server / routes / games.js
1 var router = require("express").Router();
2 var UserModel = require("../models/User");
3 var ChallengeModel = require('../models/Challenge');
4 var GameModel = require('../models/Game');
5 var VariantModel = require('../models/Variant');
6 var access = require("../utils/access");
7 var params = require("../config/parameters");
8
9 // From main hall, start game between players 0 and 1
10 router.post("/games", access.logged, access.ajax, (req,res) => {
11 const gameInfo = req.body.gameInfo;
12 if (!Array.isArray(gameInfo.players) ||
13 !gameInfo.players.some(p => p.id == req.userId))
14 {
15 return res.json({errmsg: "Cannot start someone else's game"});
16 }
17 const cid = req.body.cid;
18 // Check all entries of gameInfo + cid:
19 let error = GameModel.checkGameInfo(gameInfo);
20 if (!error)
21 {
22 if (!cid.toString().match(/^[0-9]+$/))
23 error = "Wrong challenge ID";
24 }
25 if (!!error)
26 return res.json({errmsg:error});
27 ChallengeModel.remove(cid);
28 GameModel.create(
29 gameInfo.vid, gameInfo.fen, gameInfo.timeControl, gameInfo.players,
30 (err,ret) => {
31 access.checkRequest(res, err, ret, "Cannot create game", () => {
32 const oppIdx = (gameInfo.players[0].id == req.userId ? 1 : 0);
33 const oppId = gameInfo.players[oppIdx].id;
34 UserModel.tryNotify(oppId,
35 "New game: " + params.siteURL + "/game/" + ret.gid);
36 res.json({gameId: ret.gid});
37 });
38 }
39 );
40 });
41
42 router.get("/games", access.ajax, (req,res) => {
43 const gameId = req.query["gid"];
44 if (!!gameId)
45 {
46 GameModel.getOne(gameId, (err,game) => {
47 access.checkRequest(res, err, game, "Game not found", () => {
48 res.json({game: game});
49 });
50 });
51 }
52 else
53 {
54 // Get by (non-)user ID:
55 const userId = req.query["uid"];
56 const excluded = !!req.query["excluded"];
57 GameModel.getByUser(userId, excluded, (err,games) => {
58 if (!!err)
59 return res.json({errmsg: err.errmsg || err.toString()});
60 res.json({games: games});
61 });
62 }
63 });
64
65 // New move + fen update + score, potentially
66 // TODO: if newmove fail, takeback in GUI
67 router.put("/games", access.logged, access.ajax, (req,res) => {
68 const gid = req.body.gid;
69 let error = "";
70 if (!gid.toString().match(/^[0-9]+$/))
71 error = "Wrong game ID";
72 const obj = req.body.newObj;
73 error = GameModel.checkGameUpdate(obj);
74 if (!!error)
75 return res.json({errmsg: error});
76 GameModel.update(gid, obj, (err) => {
77 if (!!err)
78 return res.json(err);
79 // Notify opponent if he enabled notifications:
80 GameModel.getPlayers(gid, (err2,players) => {
81 if (!!err2)
82 return res.json(err);
83 const oppid = (players[0].id == req.userId ? players[1].id : players[0].id);
84 UserModel.tryNotify(oppid,
85 "New move in game: " + params.siteURL + "/game/" + gid);
86 });
87 res.json({});
88 });
89 });
90
91 module.exports = router;