-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
475 lines (418 loc) · 12.4 KB
/
server.js
File metadata and controls
475 lines (418 loc) · 12.4 KB
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// server.js
// where your node app starts
// init project
const Gifsicle = require('gifsicle-stream');
const request = require('request');
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const base64 = require('base-64');
const toStream = require('buffer-to-stream');
const gifhelper = require('./gifhelper.js');
const githelper = require('./githelper.js');
const app = express();
let jsonParser = bodyParser.json({
limit: '50mb'
});
const winston = require('winston');
const logger = winston.createLogger({
format: winston.format.simple(),
transports: [
new winston.transports.Console()
]
});
module.exports.localBuild = true;
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'https://discordapp.com');
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();
});
app.use(express.static('public'));
app.use('/newemote', require('./discord.js'));
app.set('view engine', 'pug');
app.get('/test', (req, res) => {
res.render('test');
});
app.get("/", (request, response) => {
response.sendStatus(200);
});
/* Commit Emote */
const fileInfo = {
emoteBasePath: 'emotes/images/',
emoteDescription: ' added an emote.',
jsonPath: 'emotes/emotes.json',
jsonDescription: 'Update JSON',
jsonEncode: true
};
app.post('/commit', jsonParser, function (req, res) {
if (!isBodyValid(req.body, 'newemote')) {
logger.log('warn', 'Received invalid commit request', req.body);
return res.sendStatus(400);
}
githelper.getFile(fileInfo.jsonPath)
.then((emoteList) => {
logger.log('info', 'Got emote list');
let file = processData(req.body, JSON.parse(emoteList));
if (file.err) {
logger.log('warn', 'Failed to process data', file.err);
res.end(file.err.toString());
} else {
logger.log('info', 'Processed emote data');
commitEmote(file, req.body.username)
.then(() => {
logger.log('info', 'Emote added');
res.end('ok');
}).catch(err => {
logger.log('warn', 'Failed to add emote', err);
res.end(err.toString());
});
};
}).catch(err => {
logger.log('warn', 'Failed to get emote list', err);
res.end(err.toString());
});
});
function commitEmote(file, username) {
return new Promise((resolve, reject) => {
let filesToWrite = [];
filesToWrite.push({
filename: file.filename,
content: file.content,
description: username + fileInfo.emoteDescription
});
filesToWrite.push({
filename: fileInfo.jsonPath,
content: file.jsonContent,
description: fileInfo.jsonDescription,
encode: fileInfo.jsonEncode
});
githelper.writeFiles(filesToWrite).then(resolve()).catch(err => reject(err));
});
}
function processData(data, emotes) {
let file = data.file;
if (checkNameExists(file.emoteName, emotes)) {
return {
err: "Emote name already exists!"
};
}
let emoteNumber = Object.keys(emotes).length + 1;
emotes[emoteNumber] = file.emoteName + file.extension;
let newJson = JSON.stringify(emotes);
if (newJson === undefined) {
return {
err: "A problem occurred while adding your emote, please check your file."
};
}
return {
filename: fileInfo.emoteBasePath + emoteNumber + file.extension,
content: base64.encode(file.content),
width: file.width,
jsonContent: newJson,
};
}
function checkNameExists(emoteName, existingNames) {
for (let key in existingNames) {
if (existingNames.hasOwnProperty(key)) {
let emote = existingNames[key].split('.');
if (emote[0] === emoteName) {
return key + "." + emote[1];
}
}
}
return false;
}
/* Modify Emote */
app.post('/modifygif', jsonParser, (req, res) => {
if (!isBodyValid(req.body, 'modify')) {
logger.log('warn', 'Received invalid modify request', req.body);
return res.sendStatus(400);
}
let data = req.body;
data.commands = getCommands(data.options);
logger.log('info', 'Processed request commands', data.commands);
processCommands(data)
.then(buffer => {
logger.log('info', 'Processed modified emote', {
length: buffer.length
});
res.status(200);
res.send(buffer.toString('base64'));
}).catch(err => {
logger.log('warn', 'Failed to modify emote ', err);
res.status(400);
res.send(err);
});
});
function getCommands(options) {
let normal = [];
let special = [];
let priority = [];
let command = {};
options.forEach((option) => {
command = {};
switch (option[0]) {
case 'resize':
command.name = '--scale';
command.param = option[1];
let split = command.param.toString().split('x');
let shouldProcessAfter = false;
split.forEach(axis => {
if (axis > 1) shouldProcessAfter = true;
});
if (shouldProcessAfter) {
normal.push(command);
} else {
priority.push(command);
}
break;
case 'reverse':
command.name = '#-1-0';
normal.push(command);
break;
case 'rotate':
command.name = '--rotate-' + option[1];
command.param = '#0-';
normal.push(command);
break;
case 'flip':
command.name = '--flip-horizontal';
normal.push(command);
break;
case 'flap':
command.name = '--flip-vertical';
normal.push(command);
break;
case 'speed':
command.name = '-d' + Math.max(2, parseInt(option[1]));
normal.push(command);
break;
case 'hyperspeed':
command.name = 'hyperspeed';
normal.push(command);
break;
case 'wiggle':
let size = 2;
if (option[1]) {
let sizeName = option[1];
if (sizeName === 'big') size = 4;
else if (sizeName === 'bigger') size = 6;
else if (sizeName === 'huge') size = 10;
}
command.name = option[0];
command.param = size;
special.push(command);
break;
case 'rain':
command.name = option[0];
command.param = option[1] === 'glitter' ? 1 : 0;
special.push(command);
break;
case 'spin':
case 'spinrev':
case 'shake':
case 'rainbow':
case 'infinite':
case 'slide':
case 'sliderev':
let speed = 8;
if (option[1]) {
let speedName = option[1];
if (speedName === 'fast') speed = 6;
else if (speedName === 'faster') speed = 4;
else if (speedName === 'hyper') speed = 2;
}
command.name = option[0];
command.param = speed;
special.push(command);
break;
}
});
return {
priority,
special,
normal
};
}
function processCommands(data) {
return new Promise(async (resolve, reject) => {
let fileType = data.url.endsWith('gif') ? 'gif' : 'png';
let buffer = data.url;
let size;
try {
if (fileType === 'gif') {
// Priority commands (namely resizing) must be done before unoptimizing or it will cause glitches
if (data.commands.priority.length > 0) {
buffer = await modifyGif(buffer, data.commands.priority);
}
buffer = await modifyGif(buffer, [{
name: '--unoptimize'
}]);
}
if (fileType === 'png') {
let scaleIndex = getCommandIndexByProperty(data.commands.priority, 'name', '--scale');
if (typeof scaleIndex !== 'undefined') {
size = data.commands.priority[scaleIndex].param;
}
}
if (data.commands.special.length > 0) {
buffer = await processSpecialCommands({
data: buffer,
commands: data.commands.special,
fileType,
size
});
}
if (data.commands.normal.length > 0) {
buffer = await processNormalCommands(buffer, data.commands.normal);
}
buffer = await modifyGif(buffer, [{
name: '--optimize'
}]);
resolve(buffer);
} catch (err) {
reject(err);
}
});
}
function modifyGif(data, options) {
return new Promise((resolve, reject) => {
let gifsicleParams = [];
options.forEach((option) => {
gifsicleParams.push(option.name);
if (option.param) {
gifsicleParams.push(option.param);
}
});
let gifProcessor = new Gifsicle(gifsicleParams);
let readStream;
if (Buffer.isBuffer(data)) readStream = toStream(data);
else {
readStream = request(data, (err) => {
if (err) reject(err);
});
}
let buffers = [];
readStream
.pipe(gifProcessor)
.on('data', (chunk) => buffers.push(chunk))
.on('error', (err) => reject(err))
.on('end', () => resolve(Buffer.concat(buffers)));
});
}
function processSpecialCommands(options) {
return new Promise((mainResolve, mainReject) => {
let commands = options.commands;
if (commands.length > 0) {
let currentBuffer = options.data;
logger.log('info', 'Commands count: ' + commands.length);
for (let i = 0, p = Promise.resolve(); i < commands.length; i++) {
p = p.then(_ => new Promise((resolve, reject) => {
processSpecialCommand({
name: commands[i].name,
value: parseInt(commands[i].param),
buffer: currentBuffer,
type: i === 0 ? options.fileType : 'gif',
size: options.size || 1,
isResized: i > 0
}).then(buffer => {
currentBuffer = buffer;
if (i === commands.length - 1) {
mainResolve(currentBuffer);
} else resolve();
}).catch(err => reject(err));
})).catch(err => mainReject(err));
}
} else mainResolve(options.data);
});
}
function processSpecialCommand(command) {
return new Promise((resolve, reject) => {
logger.log('info', 'Command name: ' + command.name);
switch (command.name) {
case 'spin':
case 'spinrev':
gifhelper.spinEmote(command).then(resolve).catch(reject);
break;
case 'shake':
gifhelper.shakeEmote(command).then(resolve).catch(reject);
break;
case 'rainbow':
gifhelper.rainbowEmote(command).then(resolve).catch(reject);
break;
case 'wiggle':
gifhelper.wiggleEmote(command).then(resolve).catch(reject);
break;
case 'infinite':
gifhelper.infiniteEmote(command).then(resolve).catch(reject);
break;
case 'slide':
case 'sliderev':
gifhelper.slideEmote(command).then(resolve).catch(reject);
break;
case 'rain':
gifhelper.rainEmote(command).then(resolve).catch(reject);
break;
default:
resolve(command.buffer);
break;
};
});
}
function processNormalCommands(data, commands) {
return new Promise((resolve, reject) => {
modifyGif(data, [{
name: '-I'
}])
.then((info) => {
commands.unshift({
name: '-U'
});
let hyperspeedIndex = getCommandIndexByProperty(commands, 'name', 'hyperspeed');
if (typeof hyperspeedIndex !== 'undefined') {
commands.splice(hyperspeedIndex, 1);
commands = removeEveryOtherFrame(2, commands, info);
}
modifyGif(data, commands)
.then(resolve).catch(reject);
}).catch(reject);
});
}
function getCommandIndexByProperty(commands, property, name) {
for (let i = 0; i < commands.length; i++) {
if (commands[i][property] === name) return i;
}
}
function removeEveryOtherFrame(n, commands, data) {
commands.push({
name: '-d2'
});
let frameCount = data.toString('utf8').split('image #').length - 1;
if (frameCount <= 4) return commands;
commands.push({
name: '--delete'
});
for (let i = 1; i < frameCount; i += n) {
commands.push({
name: '#' + i
});
}
return commands;
}
function isBodyValid(body, type) {
if (type === 'modify') {
return !!(body && body.url && body.options && Array.isArray(body.options));
} else if (type === 'newemote') {
return !!(body && body.username && body.file.emoteName && body.file.extension && body.file.content && body.file.width);
}
}
// listen for requests :)
if (this.localBuild) {
app.listen(8080);
} else {
app.listen(process.env.PORT);
setInterval(() => {
http.get(`http://${process.env.PROJECT_DOMAIN}.glitch.me/`);
}, 280000);
}