Commit | Line | Data |
---|---|---|
298c42e6 BA |
1 | let router = require("express").Router(); |
2 | const sqlite3 = require('sqlite3'); | |
3 | const DbPath = __dirname.replace("/routes", "/db/vchess.sqlite"); | |
4 | const db = new sqlite3.Database(DbPath); | |
5 | const sanitizeHtml = require('sanitize-html'); | |
6 | const MaxNbProblems = 20; | |
7 | ||
8 | // Fetch N previous or next problems (AJAX) | |
9 | router.get("/problems/:variant([a-zA-Z0-9]+)", (req,res) => { | |
10 | if (!req.xhr) | |
11 | return res.json({errmsg: "Unauthorized access"}); | |
12 | const vname = req.params["variant"]; | |
13 | const directionStr = (req.query.direction == "forward" ? ">" : "<"); | |
14 | const lastDt = req.query.last_dt; | |
15 | if (!lastDt.match(/[0-9]+/)) | |
16 | return res.json({errmsg: "Bad timestamp"}); | |
17 | db.serialize(function() { | |
18 | const query = "SELECT * FROM Problems " + | |
19 | "WHERE variant='" + vname + "' " + | |
20 | " AND added " + directionStr + " " + lastDt + " " + | |
21 | "ORDER BY added " + (directionStr=="<" ? "DESC " : "") + | |
22 | "LIMIT " + MaxNbProblems; | |
23 | db.all(query, (err,problems) => { | |
24 | if (!!err) | |
25 | return res.json(err); | |
26 | return res.json({problems: problems}); | |
27 | }); | |
28 | }); | |
29 | }); | |
30 | ||
31 | // Upload a problem (AJAX) | |
32 | router.post("/problems/:variant([a-zA-Z0-9]+)", (req,res) => { | |
33 | if (!req.xhr) | |
34 | return res.json({errmsg: "Unauthorized access"}); | |
35 | const vname = req.params["variant"]; | |
36 | const timestamp = Date.now(); | |
37 | // Sanitize them | |
38 | const fen = req.body["fen"]; | |
39 | if (!fen.match(/^[a-zA-Z0-9, /-]*$/)) | |
40 | return res.json({errmsg: "Bad characters in FEN string"}); | |
41 | const instructions = sanitizeHtml(req.body["instructions"]).trim(); | |
42 | const solution = sanitizeHtml(req.body["solution"]).trim(); | |
43 | if (instructions.length == 0) | |
44 | return res.json({errmsg: "Empty instructions"}); | |
45 | if (solution.length == 0) | |
46 | return res.json({errmsg: "Empty solution"}); | |
47 | db.serialize(function() { | |
48 | let stmt = db.prepare("INSERT INTO Problems " + | |
49 | "(added,variant,fen,instructions,solution) VALUES (?,?,?,?,?)"); | |
50 | stmt.run(timestamp, vname, fen, instructions, solution); | |
51 | stmt.finalize(); | |
52 | }); | |
53 | res.json({}); | |
54 | }); | |
55 | ||
56 | // TODO: edit, delete a problem | |
57 | ||
58 | module.exports = router; |