-
Notifications
You must be signed in to change notification settings - Fork 0
/
loadpgn.js
84 lines (72 loc) · 2.2 KB
/
loadpgn.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
if (process.argv.length < 3) {
console.log('Usage: node ' + process.argv[1] + ' FILENAME');
process.exit(1);
}
const fs = require('fs')
var path = require('path');
var moment = require('moment');
var mongodb = require('mongodb');
var filename = process.argv[2];
var games = {}
var index = 0
var gen_room = function (factor){
return Math.random().toString(36).substring(2, factor) + Math.random().toString(36).substring(2, factor)
}
mongodb.MongoClient.connect(process.env.MONGO_URL, {useNewUrlParser: true }, function(err, database) {
if(err) throw err
const db = database.db(process.env.MONGO_URL.split('/').reverse()[0])
fs.readFile(filename, 'utf8', function(err, data) {
if (err) throw err;
console.log('OK: ' + filename);
var parts = data.split(/\s\r\n\r\n/).reverse()
parts.forEach((part,index) => {
if(index%2===0){
const re = /\[(.*?)\]/g;
let current;
var game = {}
while (current = re.exec(part)) {
var m = current.pop()
var parts2 = m.split(' ')
var k = parts2[0].toLowerCase()
delete parts2[0]
var v = parts2.join(' ').split('"').join('').trim()
game[k] = v;
}
var parts3 = part.split(/\r\n\r\n/)
game.pgn = parts3[parts3.length-1]
game.room = gen_room(8)
games[Object.keys(games).length] = game
}
})
setInterval(() => {
if(index <= Object.keys(games).length){
var game = games[index]
index++
if(game){
db.collection('games').findOneAndUpdate(
{
event:game.event,
white:game.white,
site:game.site,
black:game.black,
result:game.result
},
{
"$set": game
},{
upsert: true,
'new': true,
returnOriginal:true
}).then(function(doc){
console.log('OK game loaded ' + index)
if(doc && doc.value){
console.log(doc.value.white+' vs '+doc.value.black + ' (' + doc.value.date + ')');
}
})
} else {
console.log("ERR game load fail " + index)
}
}
},5000)
});
});