-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
277 lines (240 loc) · 8.06 KB
/
server.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import { loggerMiddleware, getLetterSet, scoreWords, getValidWords, loadDictionary } from './utils.js';
import express from 'express';
import { CronJob } from 'cron';
import path from 'path';
import { v4 as uuidv4 } from 'uuid';
import nedb from 'nedb';
import cookieParser from 'cookie-parser';
import { appendFileSync } from 'fs';
const app = express();
const PORT = 3000;
const MIN_VALID_WORDS = 20;
const PANGRAM_BONUS = 7;
const dictionary = loadDictionary('dictionary.txt');
const BANNED_LETTERS = []
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(loggerMiddleware);
app.set('view engine', 'pug');
app.set('views', path.join(path.resolve(), 'views'))
console.log(`Starting server...`);
console.log(`creating database interfaces...`);
var leaderboardDB = new nedb({
filename: path.join(path.resolve(), 'leaderboard.db'),
autoload: true
});
leaderboardDB.ensureIndex({ fieldName: 'userId', unique: true });
var puzzleDB = new nedb({
filename: path.join(path.resolve(), 'puzzle.db'),
autoload: true
});
var puzzle = {
letters: [],
validWords: []
};
var yesterday = {
winner: {},
answers: [],
letters: []
};
const createNewPuzzle = (puzzleDB, dictionary) => {
console.log(`Creating new puzzle...`);
// reset today and yesterday
today = new Date();
today.setHours(0, 0, 0, 0);
console.log(`todays date: ${today}`);
let letters = getLetterSet(dictionary, MIN_VALID_WORDS, BANNED_LETTERS);
let validWords = getValidWords(letters, dictionary);
console.log(`New puzzle created: ${letters}`);
puzzleDB.insert({ date: today, letters: letters });
return { letters, validWords }
}
const getYesterdaysWinner = (leaderboardDB) => {
let today = new Date();
let yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
yesterday.setHours(0, 0, 0, 0);
today.setHours(0, 0, 0, 0);
// find yesterdaysWinner:
return new Promise((resolve, reject) => {
leaderboardDB.find({ date: { $gt: yesterday, $lt: today } }).sort({ score: -1, date: 1 }).exec((err, docs) => {
if (err) {
reject(err);
}
if (docs[0] != undefined) {
console.log(`found yesterdays winner: ${docs[0].nickname}`);
resolve({ nickname: docs[0].nickname, score: docs[0].score });
} else {
console.log(`found no winner for yesterday.`);
resolve({ nickname: "", score: 0 });
}
});
});
};
const getYesterdaysAnswers = (puzzleDB) => {
let today = new Date();
let yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
yesterday.setHours(0, 0, 0, 0);
today.setHours(0, 0, 0, 0);
// find yesterdaysAnswers:
return new Promise((resolve, reject) => {
puzzleDB.findOne({ date: { $gte: yesterday, $lt: today } }, (err, doc) => {
if (err) {
reject(err);
}
let answers = [];
let letters = [];
if (doc) {
answers = getValidWords(doc.letters, dictionary);
letters = doc.letters;
console.log(`found yesterdays puzzle: ${letters} (${answers.length} words)`);
} else {
console.log('could not find yesterdays puzzle');
}
resolve({ answers: answers, letters: letters });
});
});
}
function createNewUser(leaderboardDB, words, score) {
let userId = uuidv4().slice(0, 8);
leaderboardDB.insert({
date: new Date(),
userId: userId,
nickname: 'anonymous user',
words: words,
score: score
});
console.log('creating user: ' + userId)
return userId
}
// look for a puzzle with todays date in puzzleDB.
let today = new Date();
today.setHours(0, 0, 0, 0);
puzzleDB.findOne({ date: { $gte: today } }, (err, doc) => {
if (doc) {
console.log(`Found puzzle created today: ${doc.letters}`);
puzzle.letters = doc.letters;
puzzle.validWords = getValidWords(doc.letters, dictionary);
} else {
puzzle = createNewPuzzle(puzzleDB, dictionary);
}
});
// get winner from yesterday
getYesterdaysWinner(leaderboardDB)
.then(res => {
yesterday.winner = res;
})
.catch(err => {
console.log(err);
});
// get answers and letters from yesterday
getYesterdaysAnswers(puzzleDB)
.then(res => {
yesterday.answers = res.answers;
yesterday.letters = res.letters;
})
.catch(err => {
console.log(err);
});
// set up cron job to run at midnight to make new puzzle
var job = new CronJob('0 0 * * *', () => {
puzzle = createNewPuzzle(puzzleDB, dictionary);
// get winner from yesterday
getYesterdaysWinner(leaderboardDB)
.then(res => {
yesterday.winner = res;
})
.catch(err => {
console.log(err);
});
// get answers and letters from yesterday
getYesterdaysAnswers(puzzleDB)
.then(res => {
yesterday.answers = res.answers;
yesterday.letters = res.letters;
})
.catch(err => {
console.log(err);
});
}, null, true, 'America/Los_Angeles');
job.start();
// routes=====================================//
app.get('/', (req, res) => {
res.render('index', {
letters: JSON.stringify(puzzle.letters),
validWords: JSON.stringify(puzzle.validWords),
pangramBonus: PANGRAM_BONUS
})
});
app.post('/update', (req, res) => {
let words = req.cookies.words ? JSON.parse(req.cookies.words) : [];
let score = scoreWords(puzzle.letters, words, puzzle.validWords);
if (!req.cookies.userId) {
let userId = createNewUser(leaderboardDB, words, score);
res.cookie('userId', userId, { expires: new Date(2147483647 * 1000), sameSite: 'lax' });
res.send({ score: score });
} else {
leaderboardDB.update({ userId: req.cookies.userId }, { $set: { date: new Date(), words: words, score: score } }, {}, () => {
res.send({ score: score });
});
}
});
app.get('/leaderboard', (req, res) => {
let thisUsersId = req.cookies.userId ? req.cookies.userId : "";
leaderboardDB.find({ date: { $gt: new Date(new Date().setHours(0, 0, 0, 0)) } }).sort({ score: -1, date: 1 }).exec((err, docs) => {
res.render('leaderboard', {
yesterdaysWinner: yesterday.winner,
userId: thisUsersId,
leaderboard: docs,
showNickForm: (thisUsersId.length > 0)
})
})
});
app.post('/leaderboard', (req, res) => {
let nick = req.body.username.replace(/[\/\\#,+()~%.'":*?<>{}]/g, '').slice(0, 25);
leaderboardDB.update({ userId: req.cookies.userId }, { $set: { nickname: nick } }, {}, () => {
res.redirect('/leaderboard');
});
});
app.get('/yesterday', (req, res) => {
res.render('yesterday', {
words: JSON.stringify(yesterday.answers),
letters: JSON.stringify(yesterday.letters)
});
});
app.get('/missing', (req, res) => {
res.render('missing', {
submitted: false,
error: false
});
})
app.post('/missing', (req, res) => {
if (/([a-zA-Z]+ ?)/.test(req.body.word)) {
console.log(`missing word(s) submitted: ${req.body.word}`);
req.body.word.split(' ').forEach((suggested) => {
let hit = dictionary.find((w) => {
return w === suggested.toUpperCase();
});
if (hit === undefined) {
console.log(`word reported missing and might be: ${suggested}`);
appendFileSync('suggestions.txt', `${suggested}\n`.toUpperCase());
} else {
console.log(`word reported missing but its not: ${suggested}`);
}
})
res.render('missing', {
submitted: true,
error: false
});
} else {
res.render('missing', {
submitted: false,
error: true,
});
}
})
app.listen(PORT, () => {
console.log(`listening on port ${PORT}`);
});