-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
2822 lines (2554 loc) · 104 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
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const http = require('http');
const decompress = require('decompress');
const redis = require('redis');
const acme = require('acme-client');
const https = require('https');
const url = require('url');
const archiver = require('archiver');
const fs = require('fs');
const querystring = require('querystring');
const crypto = require('crypto');
const util = require('util');
const { parse } = require('querystring');
const multiparty = require('multiparty');
const { fork } = require('child_process');
const path = require('path');
const WebSocket = require('ws');
const process = require('process');
const { getUserHash } = require('homegames-common');
const { v4: uuidv4 } = require('uuid');
const { Binary, MongoClient } = require('mongodb');
const amqp = require('amqplib/callback_api');
const geoip = require('geoip-lite');
const CERT_DOMAIN = process.env.CERT_DOMAIN || 'homegames.link';
const JOB_QUEUE_NAME = process.env.JOB_QUEUE_NAME || 'homegames-jobs';
const SourceType = {
GITHUB: 'GITHUB'
};
const poolData = {
UserPoolId: process.env.COGNITO_USER_POOL_ID
};
const _CENTROIDS = fs.readFileSync('centroids.json');
const CENTROIDS = JSON.parse(_CENTROIDS);
const CERTS_ENABLED = process.env.CERTS_ENABLED || false;
const DB_TYPE = process.env.DB_TYPE || 'local';
const AWS_ROUTE_53_HOSTED_ZONE_ID = process.env.AWS_ROUTE_53_HOSTED_ZONE_ID;
const QUEUE_HOST = process.env.QUEUE_HOST || 'localhost';
const SALT_ROUNDS = process.env.SALT_ROUNDS || 10;
const HASH_ITERATIONS = process.env.HASH_ITERATIONS || 100000;
const HASH_KEY_LENGTH = process.env.HASH_KEY_LENGTH || 64;
const HASH_DIGEST = process.env.HASH_DIGEST || 'sha512';
const ELASTICSEARCH_HOST = process.env.ELASTICSEARCH_HOST;
const ELASTICSEARCH_PORT = process.env.ELASTICSEARCH_PORT;
const ELASTICSEARCH_GAME_INDEX = process.env.ELASTICSEARCH_GAME_INDEX;
const ELASTICSEARCH_DEVELOPER_INDEX = process.env.ELASTICSEARCH_DEVELOPER_INDEX;
const DB_HOST = process.env.DB_HOST;
const DB_PORT = process.env.DB_PORT;
const DB_USERNAME = process.env.DB_USERNAME || '';
const DB_PASSWORD = process.env.DB_PASSWORD || '';
const DB_NAME = process.env.DB_NAME || 'homegames';
const JWT_SECRET = process.env.JWT_SECRET || 'hello world!';
// mongo, local (in memory)
const AUTH_TYPE = process.env.AUTH_TYPE || 'mongo';
const verifyToken = (token) => new Promise((resolve, reject) => {
const bearerPrefix = 'Bearer ';
if (!token || !token.startsWith(bearerPrefix)) {
reject('Invalid token');
} else {
const tokenValue = token.substring(bearerPrefix.length);
const tokenPieces = tokenValue.split('.');
if (tokenPieces.length !== 3) {
reject('Invalid token structure');
} else {
const tokenHeader = tokenPieces[0];
const tokenPayload = tokenPieces[1];
const tokenSignature = tokenPieces[2];
const payload = base64UrlDecode(tokenPayload);
const validSignature = getSignature(tokenHeader, tokenPayload);
if (!payload.iat || payload.iat + (15 * 60 * 1000) <= Date.now()) {
reject('Expired token');
} else {
if (validSignature == tokenSignature) {
resolve(payload);
} else {
reject('Invalid token');
}
}
}
}
});
const hashValue = (val) => {
return crypto.createHash('sha256').update(val).digest('hex');
}
const hashPassword = (password, salt) => new Promise((resolve, reject) => {
crypto.pbkdf2(password, salt, HASH_ITERATIONS, HASH_KEY_LENGTH, HASH_DIGEST, (error, hashedPassword) => {
if (error) {
reject(error);
} else {
resolve(hashedPassword);
}
});
});
const base64UrlDecode = (str) => {
const decoded = Buffer.from(str, 'base64url');
return JSON.parse(decoded);
};
const base64UrlEncode = (obj) => {
const stringified = JSON.stringify(obj);
return Buffer.from(stringified).toString('base64url');
};
const getSignature = (encodedHeader, encodedPayload) => {
const data = `${encodedHeader}.${encodedPayload}`;
return crypto.createHmac('sha256', JWT_SECRET).update(data).digest('base64url');
};
const downloadZip = (url) =>
new Promise((resolve, reject) => {
const outDir = `/tmp/${Date.now()}`;
fs.mkdirSync(outDir);
const zipPath = `${outDir}/data.zip`;
const zipWriteStream = fs.createWriteStream(zipPath);
zipWriteStream.on('close', () => {
resolve({
zipPath
});
});
https.get(url, (res) => {
res.pipe(zipWriteStream);
zipWriteStream.on('finish', () => {
zipWriteStream.close();
});
}).on('error', (err) => {
console.error(err);
reject(err);
});
});
const downloadFromGithub = (owner, repo, commit = '') =>
new Promise((resolve, reject) => {
const commitString = commit ? "/" + commit : "";
const thing = `https://codeload.github.com/${owner}/${repo}/zip${commitString}`;
downloadZip(thing).then(resolve).catch(reject);
});
const getMongoClient = () => {
const uri = DB_USERNAME ? `mongodb://${DB_USERNAME}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}` : `mongodb://${DB_HOST}:${DB_PORT}/${DB_NAME}`;
const params = {};
if (DB_USERNAME) {
params.auth = {
username: DB_USERNAME,
password: DB_PASSWORD
};
params.authSource = 'admin';
}
return new MongoClient(uri, params);
};
const getMongoAsset = (assetId) => new Promise((resolve, reject) => {
const client = getMongoClient();
client.connect().then(() => {
const db = client.db(DB_NAME);
const assetCollection = db.collection('assets');
assetCollection.findOne({ assetId }).then(resolve).catch(reject);
}).catch(reject);
});
const createSupportMessage = (body, sourceIp) => new Promise((resolve, reject) => {
const ipHash = hashValue(sourceIp);
getMongoCollection('supportMessages').then((collection) => {
const now = Date.now();
const oneDayAgo = now - (24 * 60 * 60 * 1000);
collection.find({ ipHash, 'status': 'PENDING', created: { '$gte': oneDayAgo } }).toArray().then((results) => {
// if we have 3 pending messages from this ip in the last 24 hours, reject
if (results.length >= 3) {
reject({ type: 'TOO_MANY_MESSAGES', message: 'Too many messages from this IP'});
} else {
const id = generateId();
collection.insertOne({ id, created: now, ipHash, 'status': 'PENDING', message: body.message, email: body.email || null }).then(() => {
resolve();
}).catch(reject);
}
}).catch(reject);
}).catch(reject);
});
const createBlogPost = (userId, blogPayload) => new Promise((resolve, reject) => {
const client = getMongoClient();
client.connect().then(() => {
const db = client.db(DB_NAME);
const blogCollection = db.collection('blog');
blogCollection.insertOne({ id: generateId(), publishedBy: userId, created: Date.now(), title: blogPayload.title || '', content: blogPayload.content }).then(resolve).catch(reject);
}).catch(reject);
});
const getBlogPost = (id) => new Promise((resolve, reject) => {
getMongoCollection('blog').then(collection => {
collection.findOne({ id }).then(post => {
if (!post) {
reject('Not found');
} else {
resolve(mapBlogPost(post, true));
}
});
}).catch(reject);
});
const listBlogPosts = (limit, offset, sort, query, includeMostRecent) => new Promise((resolve, reject) => {
getMongoCollection('blog').then(collection => {
let dbQuery = {};
if (query) {
dbQuery = {
'$and': [
{
'$or': [
{ title: { '$regex': query, $options: 'i' } },
{ content: { '$regex': query, $options: 'i' } }
]
}
]
};
}
collection.countDocuments(dbQuery).then((count) => {
collection.find(dbQuery).limit(Number(limit)).skip(Number(offset)).sort({ created: -1 }).toArray().then(posts => {
if (!!includeMostRecent) {
const mostRecent = posts.length ? mapBlogPost(posts[0], true) : null;
resolve({ posts: posts.map(p => mapBlogPost(p, false)), count, mostRecent });
} else {
resolve({ posts: posts.map(p => mapBlogPost(p, false)), count });
}
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
const getMongoDocument = (assetId) => new Promise((resolve, reject) => {
const client = getMongoClient();
client.connect().then(() => {
const db = client.db(DB_NAME);
const documentCollection = db.collection('documents');
documentCollection.findOne({ assetId }).then(resolve).catch(reject);
}).catch(reject);
});
const getUserRecord = (userId) => new Promise((resolve, reject) => {
getMongoCollection('users').then(collection => {
collection.findOne({ userId }).then(resolve).catch(reject);
}).catch(reject);
});
const login = (request) => new Promise((resolve, reject) => {
const { username, password } = request;
const client = getMongoClient();
client.connect().then(() => {
const db = client.db(DB_NAME);
const collection = db.collection('users');
collection.findOne({ userId: username }).then((usernameResponse) => {
if (usernameResponse == null) {
reject('user doesnt exist');
} else {
const passwordSalt = usernameResponse.passwordSalt;//.toString('hex');
hashPassword(password, passwordSalt).then((passwordHash) => {
if (usernameResponse.passwordHash.toString('hex') === passwordHash.toString('hex')) {
resolve({
username,
token: generateJwt(username),
isAdmin: usernameResponse.isAdmin || false,
created: usernameResponse.created
});
} else {
reject('incorrect username or password');
}
//collection.insertOne({ username, passwordHash, passwordSalt }).then(() => {
// const token = generateJwt(username);
// resolve({
// username,
// token
// });
//});
}).catch(reject);
}
}).catch(reject);
}).catch(reject);
});
const generateJwt = (userId) => {
const jwtHeader = {
alg: 'HS256',
typ: 'JWT'
};
const payload = { userId, iat: Date.now() };
const encodedHeader = base64UrlEncode(jwtHeader);
const encodedPayload = base64UrlEncode(payload);
const encodedSignature = getSignature(encodedHeader, encodedPayload);
return `${encodedHeader}.${encodedPayload}.${encodedSignature}`;
};
const mongoSignup = (userId, password) => new Promise((resolve, reject) => {
const client = getMongoClient();
client.connect().then(() => {
const db = client.db(DB_NAME);
const collection = db.collection('users');
collection.findOne({ userId }).then((userResponse) => {
if (userResponse == null) {
const passwordSalt = crypto.randomBytes(16).toString('hex');
hashPassword(password, passwordSalt).then((passwordHash) => {
collection.insertOne({ userId, passwordHash, passwordSalt, created: Date.now() }).then(() => {
const token = generateJwt(userId);
resolve({
userId,
token
});
});
});
} else {
reject('username already exists');
}
});
}).catch(reject);
});
const signup = (request) => new Promise((resolve, reject) => {
const { username, password } = request;
if (!username || !password) {
reject('signup requires username & password');
} else {
if (AUTH_TYPE === 'mongo') {
mongoSignup(username, password).then(resolve).catch((err) => {
reject(err);
});
}
}
});
const submitContentRequest = (request, ip) => new Promise((resolve, reject) => {
const requestId = uuidv4();
// todo: i dont like storing these. maybe store in redis with short (< 1 hour) ttl if we need to store ip (if we have lots of users)
getMongoCollection('contentRequests').then((collection) => {
const now = Date.now();
const messageBody = JSON.stringify({ requestId, created: now, type: request.type, model: request.model, prompt: request.prompt });
collection.insertOne({ requestId, created: now }).then(() => {
createContentRequest(messageBody).then(() => {
resolve(requestId);
}).catch(reject);
});
}).catch(reject);
});
const deleteDnsRecord = (name) => new Promise((resolve, reject) => {
getDnsRecord(name).then((value) => {
const deleteDnsParams = {
ChangeBatch: {
Changes: [
{
Action: 'DELETE',
ResourceRecordSet: {
Name: name,//dnsChallengeRecord.Name,
Type: 'TXT',
TTL: 300,
ResourceRecords: [
{
Value: value,//dnsChallengeRecord.Value
}
]
// TTL: 300,
// Type: dnsChallengeRecord.Type
}
}
]
},
HostedZoneId: AWS_ROUTE_53_HOSTED_ZONE_ID
};
const route53 = new aws.Route53Client();
route53.changeResourceRecordSets(deleteDnsParams, (err, data) => {
const deleteParams = {
Id: data.ChangeInfo.Id
};
route53.waitFor('resourceRecordSetsChanged', deleteParams, (err, data) => {
if (data.ChangeInfo.Status === 'INSYNC') {
resolve();
}
});
});
}).catch(reject);
});
const createDnsRecord = (name, value) => new Promise((resolve, reject) => {
const dnsParams = {
ChangeBatch: {
Changes: [
{
Action: 'CREATE',
ResourceRecordSet: {
Name: name,
ResourceRecords: [
{
Value: '"' + value + '"'
}
],
TTL: 300,
Type: 'TXT'
}
}
]
},
HostedZoneId: AWS_ROUTE_53_HOSTED_ZONE_ID
};
const route53 = new aws.Route53();
route53.changeResourceRecordSets(dnsParams, (err, data) => {
if (err) {
reject(err);
} else {
const params = {
Id: data.ChangeInfo.Id
};
route53.waitFor('resourceRecordSetsChanged', params, (err, data) => {
if (data.ChangeInfo.Status === 'INSYNC') {
resolve();
}
});
}
});
});
const challengeCreateFn = async(authz, challenge, keyAuthorization) => {
if (challenge.type === 'dns-01') {
console.log('creating!!');
await createDnsRecord(`_acme-challenge.${authz.identifier.value}`, keyAuthorization);
}
};
const challengeRemoveFn = async(authz, challenge, keyAuthorization) => {
if (challenge.type === 'dns-01') {
console.log('removing!!');
await deleteDnsRecord(`_acme-challenge.${authz.identifier.value}`);
}
};
const generateSocketId = () => {
return uuidv4();
};
const uploadMongo = (developerId, assetId, filePath, fileName, fileSize, fileType) => new Promise((resolve, reject) => {
const client = getMongoClient();
client.connect().then(() => {
const db = client.db(DB_NAME);
const collection = db.collection('assets');
collection.findOne({ assetId }).then(asset => {
const documentCollection = db.collection('documents');
documentCollection.insertOne({ developerId, assetId, data: new Binary(fs.readFileSync(filePath)), fileSize, fileType }).then(() => resolve(assetId)).catch(reject);
}).catch(reject);
}).catch(reject);
});
const logSuccess = (funcName) => {
console.error(`function ${funcName} succeeded`);
};
const logFailure = (funcName) => {
console.error(`function ${funcName} failed`);
};
const getProfileInfo = (userId) => new Promise((resolve, reject) => {
getMongoProfileInfo(userId).then(resolve).catch(reject);
});
const getMongoProfileInfo = (userId) => new Promise((resolve, reject) => {
const client = getMongoClient();
client.connect().then(() => {
const db = client.db(DB_NAME);
const collection = db.collection('users');
console.log('for ' + userId);
collection.findOne({ userId }).then((userResponse) => {
console.log('found user');
console.log(userResponse);
const { userId, created, image, description } = userResponse;
resolve({
username: userId,
created,
image,
description
});
});
}).catch(reject);
});
const elasticDeleteGame = (gameId) => new Promise((resolve, reject) => {
const options = {
hostname: ELASTICSEARCH_HOST,
port: ELASTICSEARCH_PORT,
path: `/games/_doc/${gameId}`,
method: 'DELETE',
headers: {}
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
const parsed = JSON.parse(data);
resolve();
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
reject();
});
req.write('');
req.end();
});
const updateGameSearch = (gameData) => new Promise((resolve, reject) => {
console.log("STRINGIFYING");
console.log(gameData);
const body = JSON.stringify(gameData);
const options = {
hostname: ELASTICSEARCH_HOST,
port: ELASTICSEARCH_PORT,
path: `/games/_doc/${gameData.gameId}`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
},
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
const parsed = JSON.parse(data);
resolve();
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
reject();
});
req.write(body);
req.end();
});
const createGame = (developerId, thumbnailAssetId, fields, files) => new Promise((resolve, reject) => {
console.log('creating game with thumbnail asset ' + thumbnailAssetId);
getMongoCollection('games').then(collection => {
const gameId = generateId();
const gameData = {
gameId,
description: fields?.description?.[0] || '',
name: fields?.name?.[0] || '',
developerId,
created: Date.now()
};
const beforeMongoInsertsId = Object.assign({}, gameData);
collection.insertOne(gameData).then(() => {
resolve(beforeMongoInsertsId);
updateGameSearch(beforeMongoInsertsId).catch((err) => {
console.error("Failed to update game search");
console.error(err);
});
createGameImagePublishRequest(developerId, thumbnailAssetId, gameId).catch((err) => {
console.error('Failed to create game image request');
console.error(err);
});
}).catch(reject);
});
});
const createGameImagePublishRequest = (userId, assetId, gameId) => new Promise((resolve, reject) => {
console.log('connecting to thing!');
amqp.connect(`amqp://${QUEUE_HOST}`, (err, conn) => {
console.log('cocnocncnetc!');
console.log(err);
if (err) {
reject(err);
} else {
conn.createChannel((err1, channel) => {
if (err1) {
reject(err1);
} else {
console.log('created channel');
channel.assertQueue(JOB_QUEUE_NAME, {
durable: true
});
channel.sendToQueue(JOB_QUEUE_NAME, Buffer.from(JSON.stringify({ type: 'GAME_IMAGE_APPROVAL_REQUEST', userId, assetId, gameId })), { persistent: true });
console.log('sent message');
resolve();
}
});
}
});
});
const createContentRequest = (req) => new Promise((resolve, reject) => {
amqp.connect(`amqp://${QUEUE_HOST}`, (err, conn) => {
if (err) {
reject(err);
} else {
conn.createChannel((err1, channel) => {
if (err1) {
reject(err1);
} else {
console.log('created channel');
channel.assertQueue(JOB_QUEUE_NAME, {
durable: true
});
channel.sendToQueue(JOB_QUEUE_NAME, Buffer.from(JSON.stringify({ type: 'CONTENT_REQUEST', data: req })), { persistent: true });
console.log('sent message');
resolve();
}
});
}
});
});
const updateProfileInfo = (userId, { description, image }) => new Promise((resolve, reject) => {
updateMongoProfileInfo(userId, { description, image }).then(resolve).catch(reject);
});
const getMongoCollection = (collectionName) => new Promise((resolve, reject) => {
const client = getMongoClient();
client.connect().then(() => {
const db = client.db(DB_NAME);
const collection = db.collection(collectionName);
resolve(collection);
}).catch(reject);
});
const createProfileImageTask = (userId, assetId) => new Promise((resolve, reject) => {
amqp.connect(`amqp://${QUEUE_HOST}`, (err, conn) => {
if (err) {
reject(err);
} else {
conn.createChannel((err1, channel) => {
if (err1) {
reject(err1);
} else {
console.log('created channel');
channel.assertQueue(JOB_QUEUE_NAME, {
durable: true
});
channel.sendToQueue(JOB_QUEUE_NAME, Buffer.from(JSON.stringify({ type: 'PROFILE_IMAGE_APPROVAL_REQUEST', userId, assetId })), { persistent: true });
console.log('sent message');
resolve();
}
});
}
});
});
const updateMongoProfileInfo = (userId, { description, image }) => new Promise((resolve, reject) => {
getMongoCollection('users').then(users => {
users.findOne({ userId }).then((foundUser) => {
if (!foundUser) {
reject('User not found');
} else {
if (image) {
createProfileImageTask(userId, image).catch(err => {
console.error(err);
});
}
if (description && foundUser.description != description) {
users.updateOne({ userId }, { "$set": { description } }).catch(reject).then(resolve);
} else {
resolve();
}
resolve();
}
}).catch(reject);
}).catch(reject);
});
const getPublishRequest = (requestId) => new Promise((resolve, reject) => {
console.log('looking for ' + requestId);
getMongoCollection('publishRequests').then((collection) => {
collection.findOne({ requestId }).then((result) => {
if (!result) {
reject('not found');
} else {
resolve(result);
}
}).catch(reject);
}).catch(reject);
});
const updatePublishRequestState = (requestId, gameId, sourceInfoHash, newStatus) => new Promise((resolve, reject) => {
getMongoCollection('publishRequests').then((publishRequests) => {
publishRequests.updateOne({ requestId }, { "$set": { status: newStatus } }).catch(reject).then(() => {
resolve();
}).catch(reject);
}).catch(reject);
});
// 50 MB max
const MAX_SIZE = 50 * 1024 * 1024;
const getHash = (input) => {
return crypto.createHash('md5').update(input).digest('hex');
};
const generateId = () => getHash(uuidv4());
const getReqBody = (req, cb) => {
let earlyReturn = false;
let _body = '';
req.on('error', (err) => {
console.log('request error ' + err);
cb && cb(null, err);
});
req.on('data', chunk => {
if (!earlyReturn && _body.length > (1000 * 1000)) {
earlyReturn = true;
cb && cb(null, 'too large');
} else if (!earlyReturn) {
_body += chunk.toString();
}
});
req.on('end', () => {
if (!earlyReturn) {
cb && cb(_body);
}
});
};
const getGame = (gameId) => new Promise((resolve, reject) => {
getMongoCollection('games').then(collection => {
collection.findOne({ gameId }).then(game => {
if (!game) {
reject('Game not found');
} else {
resolve({
id: game.gameId,
description: game.description,
name: game.name,
created: game.created,
developerId: game.developerId,
thumbnail: game.thumbnail
});
}
}).catch(reject);
}).catch(reject);
});
const updateGameIndex = (gameId) => new Promise((resolve, reject) => {
getGame(gameId).then(gameData => {
console.log('need to post to elasticsearch');
console.log(gameData);
const gameBody = {
id: gameData.id,
description: gameData.description,
name: gameData.name,
created: gameData.created,
developerId: gameData.developerId,
thumbnail: gameData.thumbnail
};
elasticSearchPost('/games/_doc/' + gameId, gameBody).then(() => {
resolve();
}).catch(reject);
}).catch(reject);
});
const updateGame = (gameId, updateParams) => new Promise((resolve, reject) => {
if (!updateParams.description && !updateParams.published_state) {
console.log('missing update params');
console.log(updateParams);
resolve();
} else {
if (updateParams.description) {
getMongoCollection('games').then((games) => {
games.updateOne({ gameId }, { "$set": { description: updateParams.description } }).catch(reject).then(() => {
// dumb
games.findOne({ gameId }).then((game) => {
const gameResult = {
id: game.gameId,
description: game.description,
created: game.description,
thumbnail: game.thumbnail,
developerId: game.developerId,
name: game.name
};
console.log(game);
console.log("fdsfds");
resolve(gameResult);
}).catch(reject);
});
}).catch(reject);
}
//if (updateParams.published_state) {
// attributeUpdates.published_state = {
// Action: 'PUT',
// Value: {
// S: updateParams.published_state
// }
// };
//}
}
});
const listAssets = (developerId, query, limit = 10, offset = 0) => new Promise((resolve, reject) => {
getMongoCollection('assets').then(collection => {
let dbQuery = { developerId };
if (query) {
dbQuery = {
'$and': [
{ developerId },
{
'$or': [
{ name: { '$regex': query, $options: 'i' } },
{ description: { '$regex': query, $options: 'i' } },
{ assetId: { '$regex': query, $options: 'i' } }
]
}
]
};
}
collection.countDocuments(dbQuery).then((count) => {
console.log('dsjfjsdfdsf');
collection.find(dbQuery).limit(Number(limit)).skip(Number(offset)).sort({ created: -1 }).toArray().then(assets => {
resolve({ assets, count });
}).catch(reject);
}).catch(reject);
}).catch(reject);
});
const createAssetRecord = (developerId, assetId, size, name, metadata, description) => new Promise((resolve, reject) => {
createMongoAssetRecord(developerId, assetId, size, name, metadata, description).then(resolve).catch(reject);
});
const createMongoAssetRecord = (developerId, assetId, size, name, metadata, description) => new Promise((resolve, reject) => {
getMongoCollection('assets').then(assetCollection => {
assetCollection.insertOne({ created: Date.now(), developerId, assetId, size, name, metadata, description }).then(() => resolve({assetId})).catch(reject);
});
});
const DEFAULT_GAME_ORDER = {
'game_name': {
order: 'asc'
}
};
const adminListPendingPublishRequests = () => new Promise((resolve, reject) => {
getMongoCollection('publishRequests').then((collection) => {
collection.find({ status: 'PENDING_PUBLISH_APPROVAL' }).toArray().then((results) => {
resolve({ requests: results });
}).catch(reject);
}).catch(reject);
});
const adminAcknowledgeMessage = (messageId) => new Promise((resolve, reject) => {
getMongoCollection('supportMessages').then((collection) => {
collection.findOne({ id: messageId }).then(supportMessage => {
console.log('found message');
console.log(supportMessage);
if (supportMessage) {
collection.updateOne({ id: messageId }, { "$set": { 'status': 'ACKNOWLEDGED' } }).then(resolve).catch(reject);
}
}).catch(reject);
}).catch(reject);
});
const adminListSupportMessages = (page, limit) => new Promise((resolve, reject) => {
const actualLimit = limit || 10;
const skip = ( page - 1 ) * actualLimit;
getMongoCollection('supportMessages').then((collection) => {
collection.find({ status: 'PENDING' }).skip(skip).limit(actualLimit).toArray().then((results) => {
resolve({ requests: results });
}).catch(reject);
}).catch(reject);
});
const adminListFailedPublishRequests = () => new Promise((resolve, reject) => {
getMongoCollection('publishRequests').then((collection) => {
collection.find({ status: 'FAILED' }).toArray().then((results) => {
resolve({ requests: results });
}).catch(reject);
}).catch(reject);
});
const listPublishRequests = (gameId) => new Promise((resolve, reject) => {
getMongoCollection('publishRequests').then(collection => {
collection.find({ gameId }).limit(100).toArray().then((requests) => {
resolve(requests.map(r => {
return {
id: r.requestId,
'status': r['status'],
'assetId': r['assetId'],
created: r.created,
adminMessage: r.adminMessage,
gameVersionId: r.versionId
}
}));
}).catch(reject);
}).catch(reject);
});
const listGamesForAuthor = (params) => new Promise((resolve, reject) => {
mongoListGamesForAuthor(params).then(resolve).catch(reject);
});
const listPublicGamesForAuthor = (params) => new Promise((resolve, reject) => {
console.log('fiufiufiufi elastic');
console.log(params);
const offset = params.offset|| 0;
const limit = params.limit || 10;
const ting = {
from: offset,
size: limit,
query: {
'multi_match': {
query: params.author,
fields: ['developerId']
}
}
};
console.log('this is ting');
console.log(JSON.stringify(ting));
elasticSearchPost('/games/_search', ting).then((results) => {
console.log("search results!');');");
console.log(results);
const totalResults = results.hits.total.value;
const pageCount = Math.ceil(totalResults / limit);
resolve({
total: totalResults,
games: results.hits.hits.map(h => mapElasticSearchGame(h)),
pageCount
})
}).catch(reject);
});
const mongoListGamesForAuthor = ({ author, page, limit }) => new Promise((resolve, reject) => {
console.log("gonna list games");
getMongoCollection('games').then(collection => {
const actualLimit = limit || 10;
const skip = ( page - 1 ) * actualLimit;
collection.find({ developerId: author }).limit(actualLimit).skip(skip).toArray().then(results => {//{ developerId: author }).then(results => {//.skip(skip).limit(actualLimit).then(results => {
resolve(results.map(r => {
return {