@Fhillis/

plat online

Nodejs

A little platforming game with score submission

fork
loading
Files
  • index.js
  • public
  • views
  • README.md
  • package-lock.json
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
require('dotenv').config()
const express = require('express');
const path = require('path');
const fs = require('fs');
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const csrf = require("csurf");
const pug = require('pug');
const webhook = require("webhook-discord");
const Gists = require('gists');
const gists = new Gists({
  username: process.env.GIST_USERNAME, 
  password: process.env.GIST_PASSWORD
});

const scores = {};


const app = express();

// attatch pug to app
app.set('view engine', 'pug');

//set public views public
app.use(express.static(path.join(__dirname,'public')));

//parse cookies
app.use(cookieParser());

//sanitize input
app.use(require('sanitize').middleware);

// setup route middlewares
var csrfProtection = csrf({ cookie: true });
var parseForm = bodyParser.urlencoded({ extended: false });

app.get('/', async function(req, res){
  
  const isDirectory = source => fs.lstatSync(source).isDirectory()
  const getDirectories = source =>
  fs.readdirSync(source).map(name => path.join(source, name)).filter(isDirectory)

  var dirs = getDirectories(path.join(__dirname,'public','levels'));

  for (var d in dirs) {
    var dir = dirs[d];
    dir = dir.split(path.sep)
    dir = dir[dir.length-1];
    var score
    if (scores[dir] === undefined) {
      score = [];
    } else if (scores[dir][0]) {
      score = scores[dir][0][0];
    } else {
      score = [];
    }
    dirs[d] = [dir, score]
  }

  res.render('index',{levels: dirs})

})

app.get('/play/:level', csrfProtection, async function(req, res){
  res.render('plat',{level: req.params.level, token: req.csrfToken()})
})

app.post('/submit', parseForm, csrfProtection, async function(req, res){
  if(req.body.score && req.body.name && req.body.level && req.body.date && req.body.input && req.headers.referer.indexOf("plat") !== -1 && req.headers.referer.indexOf(encodeURIComponent(req.body.level)) !== -1) {
    var message = ""
    var name = req.bodyString("name");
    var score = req.bodyString("score");
    var level = req.bodyString("level");
    var date = req.bodyString("date");
    var input = req.body.input;

    var clean = fs.existsSync(path.join(__dirname,"public","levels",level));

    var acceptable = "1234567890-qwertyuiopasdfghjkl()zxcvbnm.:-_QWERTYUIO PLKJHGFDSAZXCVBNM";
    var tester = name.split("");
    for (var i in tester) {
      if (acceptable.indexOf(tester[i]) === -1) clean = false; message="name";
    }
    tester = level.split("");
    for (var i in tester) {
      if (acceptable.indexOf(tester[i]) === -1) clean = false; message="level";
    }
    if (isNaN(score)) clean = false; message="score";

    if (clean) {
      submitGist(level,score+";"+name+";"+date+";"+input).catch(console.error)
      scores[level].push([score,name,date,input])
      scores[level].sort(compare);
      res.redirect("/scores/"+level);
      var Hook = new webhook.Webhook(process.env.WEBHOOK_URL);
      var msg = new webhook.MessageBuilder();
      msg.setName("Scorekeeper");
      msg.setColor("#FF00FF");
      msg.addField("New score on "+level, name+" got "+score+" on "+level);
      Hook.send(msg);
    } else {
      console.log(message, name, score, level)
      res.redirect("/");
    }
  } else {
    res.redirect("/");
  }
})

app.get("/scores/:level/json", 
  async function(req,res) {
    if (scores[req.params.level]) {
      res.send(scores[req.params.level]);
    } else {
      res.send([]);
    }
  }
)

app.get("/scores/:level/", 
  async function(req,res) {
    if (scores[req.params.level]) {
      res.render("scores",{"level": req.params.level, "scores": scores[req.params.level]});
    } else {
      res.render("scores",{"level": req.params.level, "scores": []});
    }
  }
)

async function start() {

  app.listen(3000);

  await updateScores();

  console.log("started")
}

async function updateScores() {
  const isDirectory = source => fs.lstatSync(source).isDirectory()
  const getDirectories = source =>
  fs.readdirSync(source).map(name => path.join(source, name)).filter(isDirectory)

  var dirs = getDirectories(path.join(__dirname,'public','levels'));

  for (var d in dirs) {
    var dir = dirs[d];
    dir = dir.split(path.sep)
    dir = dir[dir.length-1];
    scores[dir] = await getGist(dir).catch(console.error);
  }
}

// function to submit score to gist
async function submitGist(level,value) {
  var data = await gists.get(process.env.GIST_ID).catch(console.error);
  data = data.body.files[level+".csv"]
  if (data) {
    data = data.content;
  } else {
    data = ""
  }
  var options = {files:{}};
  options.files[level+".csv"] = {content: data+"\n"+value};
  data = await gists.patch("/gists/"+process.env.GIST_ID, options).catch(console.error);
  data = data.body.files[level+".csv"].content;
  data = data.split(`\n`);
  for (var n in data) {
    data[n] = data[n].split(';');
  }
  
  data.sort(compare);
  return data
}
// function to get scores from gist
async function getGist(level) {
  var data = await gists.get(process.env.GIST_ID).catch(console.error);
  data = data.body.files[level+".csv"]
  if (data) {data = data.content;}
  else {return []}
  data = data.split(`\n`);
  for (var n in data) {
    data[n] = data[n].split(';');
    data[n][0] = data[n][0].replace(/\s/g, '');
  }
  data.shift()
  data.sort(compare);
  return data;
}


function compare(a,b) {
  if (a[3] && b[3]) {
    if (a[0].length > b[0].length) {
      return -1;
    }
    if (a[0].length < b[0].length) {
      return 1;
    }
    if (a[0] > b[0]) {
      return -1;
    }
    if (a[0] < b[0]) {
      return 1;
    }
    if (a[2] < b[2]) {
      return -1;
    }
    if (a[2] > b[2]) {
      return 1;
    }
    return 0;
  } else {
    return 1
  }
}

start()