/
index.js
191 lines (166 loc) · 6.05 KB
/
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
/**
* Created by Henrik Peinar on 01/04/16
*/
'use strict';
const express = require('express');
const fs = require('fs');
const r = require('rethinkdb');
const importer = require('../lib/importer');
const multipart = require('connect-multiparty');
const multipartMiddleware = multipart({
maxFieldsSize: '25MB'
});
const crypto = require('crypto');
const request = require('request');
const cors = require('cors');
const RateLimit = require('express-rate-limit');
const hri = require('human-readable-ids').hri;
const limiter = new RateLimit({
windowMs: 15*60*1000, // 15 minutes
max: 600, // limit each IP to 100 requests per windowMs
delayMs: 0 // disable delaying - full speed until the max limit is reached,
});
module.exports = function () {
let app = express.Router();
app.post('/import', [limiter, cors(), multipartMiddleware], function (req, res, next) {
if (!req.files || !req.files.file) {
res.status(500).json({message: 'Missing file'});
return;
}
importer(req.files.file.path).then(function (farmData) {
return save(farmData, req._conn).then(function (result) {
res.json({
id: result.id,
absolutePath: 'https://stardew.info/planner/'+ result.id
});
next();
}).catch(function (err) {
req.log.error(err, 'Failed to save farm, in catch');
res.sendStatus(500);
next();
});
}).catch(function (err) {
req.log.error(err);
res.status(500).json({message: 'Failed to import save file'});
next();
});
});
app.get('/:id', function (req, res, next) {
r.table('farms').get(req.params.id).run(req._conn)
.then(function (results) {
if (!results) {
return r.table('farms').getAll(req.params.id, {index: 'oldId'}).run(req._conn);
} else {
return results;
}
})
.then(function (farm) {
if (typeof farm.toArray === 'function') {
let data = farm.toArray();
return data;
} else {
return farm;
}
})
.then(function (farm) {
if (!farm.farmData && !farm.length) {
res.sendStatus(404);
return;
}
res.json((farm.farmData || farm[0].farmData));
next();
}).error(function (err) {
req.log.error(err, 'Failed to get farm');
res.sendStatus(404);
next();
});
});
app.post('/save', function (req, res, next) {
save(req.body, req._conn).then(function (result) {
res.json({id: result.id});
next();
}).catch(function (err) {
req.log.error(err, 'Failed to save farm, in catch');
res.sendStatus(500);
next();
});
});
app.post('/render', function (req, res, next) {
save(req.body, req._conn).then(function (result) {
// after saving, post it to upload.farm
request({
method: 'POST',
uri: 'http://upload.farm/api/v1/plan',
body: {
plan_json: req.body,
season: req.body.options.season || 'spring',
source_url: 'https://stardew.info/planner/'+ result.id
},
json: true
}, function (error, response, body) {
if (error) {
req.log.error(error, 'Failed to render in upload.farm');
res.status(500).json(body);
return next();
}
res.json(body);
next();
});
}).catch(function (err) {
req.log.error(err, 'Failed to save farm, in catch');
res.sendStatus(500);
next();
});
});
function save (farmData, conn) {
let hashedData = {
buildings: farmData.buildings,
tiles: farmData.tiles,
options: farmData.options
};
// generate unique hash but take the season out of it
let oldSeason = null;
if (hashedData.options.season) {
oldSeason = hashedData.options.season;
delete hashedData.options.season;
}
let uniqueHash = crypto.createHash('md5').update(JSON.stringify(hashedData)).digest("hex");
if (oldSeason) {
farmData.options.season = oldSeason;
}
return r.table('farms').getAll(uniqueHash, {index: 'md5'}).run(conn).then(farms => farms.toArray()).then(function (results) {
if (results.length) {
return Promise.resolve({id: results[0].id});
} else {
return uniqueId(conn).then(function (uniqueId) {
let farm = {
id: uniqueId,
md5: uniqueHash,
farmData: farmData
};
return r.table('farms').insert(farm).run(conn).then(function (result) {
if (result.inserted !== 1) {
throw new Error('Failed to insert farm')
}
return Promise.resolve({id: uniqueId});
})
});
}
}).error(function (err) {
throw new Error('Failed to save farm');
});
}
function uniqueId (conn) {
let readableId = hri.random();
return new Promise(function (resolve, reject) {
r.table('farms').get(readableId).run(conn).then(function (results) {
if (results) {
return uniqueId(conn);
} else {
resolve(readableId);
}
}).error(err => reject(err));
});
}
return app;
};