-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1886 lines (1665 loc) · 61.4 KB
/
Copy pathserver.js
File metadata and controls
1886 lines (1665 loc) · 61.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
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 crypto = require( 'crypto' );
const sha1 = require( 'sha1' );
const restify = require( 'restify' );
const passport = require( 'passport' );
const alphanumSort = require( 'alphanum-sort' );
const Hashids = require( 'hashids/cjs' );
const Strategy = require( 'passport-http-bearer' ).Strategy;
const corsMiddleware = require( 'restify-cors-middleware2' );
const { Op } = require('sequelize');
const { LRUCache } = require( 'lru-cache' );
const models = require( './models' );
const LISTEN_PORT = process.env.PORT || 3000;
const JSON_INDENTATION = 4;
const SUCCESS_STATUS_CODE = 200;
const INTERNAL_SERVER_ERROR_STATUS_CODE = 500;
const MALFORMED_REQUEST_STATUS_CODE = 400;
const FORBIDDEN_STATUS_CODE = 403;
const NOT_FOUND_STATUS_CODE = 404;
const SERVICE_UNAVAILABLE_STATUS_CODE = 503;
const TOKEN_REFRESH_INTERVAL = 60 * 1000;
const TOKEN_LENGTH = 24;
const EXISTING_RESOURCE_STATUS_CODE = 409;
const ID_HASH_MIN_LENGTH = 8;
const MAX_POST_LIMIT = 1000;
const MAX_POST_OFFSET = 10000;
const DEFAULT_POST_LIMIT = 50;
const CACHE_TIMES = {
favicon: 2592000,
groups: 3600,
posts: 900,
services: 3600,
singlePost: 2592000,
singlePostHead: 600,
stats: 300,
};
const STATS_WINDOW_DAYS = 30;
const STATS_QUARTER_DAYS = 90;
const STATS_WEEK_DAYS = 7;
const SECONDS_PER_DAY = 86400;
const MILLISECONDS_PER_SECOND = 1000;
const hashids = new Hashids( '', ID_HASH_MIN_LENGTH, 'abcdefghijklmnopqrstuvwxyz' );
const server = restify.createServer( {
// eslint-disable-next-line no-sync
// certificate: fs.readFileSync( path.join( __dirname, './assets/fullchain.pem' ) ),
// eslint-disable-next-line no-sync
// key: fs.readFileSync( path.join( __dirname, './assets/privkey.pem' ) ),
name: 'Post tracker REST API',
} );
// Tokens live in the `tokens` DB table (name + scopes per token). They're
// cached in memory so auth doesn't hit the DB on every request; the cache is
// refreshed periodically and busted immediately when tokens are created/revoked.
const tokenScopes = new Map();
// Optional break-glass token: always authenticates with admin scope and is
// never stored in the DB, so an empty/unreachable tokens table can't lock
// everyone out (recovery / first boot).
const ROOT_API_TOKEN = process.env.ROOT_API_TOKEN;
// Transitional fallback for the pre-DB env-var token registry. A token that
// isn't in the DB (or the ROOT break-glass) is authorized against its old
// per-path/method permissions from API_TOKENS, exactly as before — so existing
// tokens keep working across the deploy with no service interruption. Once all
// tokens are seeded into the `tokens` table, remove API_TOKENS from the env and
// this fallback goes dormant.
const legacyTokenData = process.env.API_TOKENS ? JSON.parse( process.env.API_TOKENS ) : {};
const legacyAuthorize = function legacyAuthorize ( token, routePath, method ) {
const entry = legacyTokenData[ token ];
if ( !entry || !entry.paths || !entry.paths[ routePath ] ) {
return false;
}
return entry.paths[ routePath ].includes( method );
};
const loadTokens = async function loadTokens () {
const tokens = await models.Token.findAll( {
where: {
active: true,
},
} );
tokenScopes.clear();
tokens.forEach( ( tokenRow ) => {
tokenScopes.set( tokenRow.token, {
name: tokenRow.name,
scopes: tokenRow.scopes || [],
} );
} );
};
const lookupToken = function lookupToken ( token ) {
if ( ROOT_API_TOKEN && token === ROOT_API_TOKEN ) {
return {
name: 'root',
scopes: [ 'admin' ],
};
}
const found = tokenScopes.get( token );
if ( found ) {
return found;
}
// Not yet migrated to the DB — recognise it so passport authenticates it;
// requireScope/the GET /games check then fall back to its legacy per-path
// permissions instead of scopes.
if ( legacyTokenData[ token ] ) {
return {
legacy: true,
name: 'legacy',
scopes: [],
};
}
return false;
};
const generateToken = function generateToken () {
let token = '';
while ( token.length < TOKEN_LENGTH ) {
token += crypto.randomBytes( TOKEN_LENGTH ).toString( 'base64' ).replace( /[^a-zA-Z0-9]/g, '' );
}
return token.slice( 0, TOKEN_LENGTH );
};
const myCache = new LRUCache( {
max: 1000,
maxSize: 800 * 1024 * 1024,
sizeCalculation: ( value ) => {
return value.length;
},
ttl: CACHE_TIMES.posts * 1000,
} );
passport.use( new Strategy(
( token, authenticationCallback ) => {
const found = lookupToken( token );
if ( !found ) {
return authenticationCallback( null, false );
}
return authenticationCallback( null, {
legacy: found.legacy || false,
name: found.name,
scopes: found.scopes,
token: token,
} );
}
) );
// Route guard factory: authenticates the bearer token, then requires the token
// to carry the given scope (the `admin` scope satisfies any requirement).
const requireScope = function requireScope ( scope ) {
return [
passport.authenticate( 'bearer', {
session: false,
} ),
( request, response, next ) => {
const user = request.user || {};
// Legacy env-var tokens authorize against their old per-path map
// rather than scopes, preserving their exact prior access.
if ( user.legacy ) {
if ( legacyAuthorize( user.token, request.route.path, request.method ) ) {
return next();
}
} else {
const scopes = user.scopes || [];
if ( scopes.includes( 'admin' ) || scopes.includes( scope ) ) {
return next();
}
}
response.send( FORBIDDEN_STATUS_CODE, {
error: 'Insufficient scope',
required: scope,
} );
return false;
},
];
};
const cors = corsMiddleware( {
allowHeaders: [ 'authorization' ],
exposeHeaders: [ 'authorization' ],
origins: [ '*' ],
} );
const addHeader = ( request, response, next ) => {
response.setHeader( 'vary', 'accept-encoding' );
next();
};
const accessLog = ( request, response, next ) => {
const startNs = process.hrtime.bigint();
const clientIp = request.headers[ 'cf-connecting-ip' ]
|| ( request.headers[ 'x-forwarded-for' ] || '' ).split( ',' )[ 0 ].trim()
|| ( request.connection && request.connection.remoteAddress )
|| '-';
const userAgent = request.headers[ 'user-agent' ] || '-';
console.log( `[access:start] ${ new Date().toISOString() } ${ clientIp } "${ request.method } ${ request.url }" "${ userAgent }"` );
response.on( 'finish', () => {
const durationMs = Number( process.hrtime.bigint() - startNs ) / 1e6;
console.log( `[access] ${ new Date().toISOString() } ${ clientIp } "${ request.method } ${ request.url }" ${ response.statusCode } ${ durationMs.toFixed( 1 ) }ms "${ userAgent }"` );
} );
next();
};
server.pre( cors.preflight );
server.use( cors.actual );
server.use( restify.plugins.bodyParser() );
server.use( restify.plugins.queryParser() );
server.use( restify.plugins.gzipResponse() );
server.use( addHeader );
server.use( accessLog );
// Prime the token cache and keep it fresh so newly issued / revoked tokens
// propagate without a restart.
loadTokens().catch( ( loadError ) => {
console.error( 'Failed to load tokens', loadError );
} );
setInterval( () => {
loadTokens().catch( ( loadError ) => {
console.error( 'Failed to refresh tokens', loadError );
} );
}, TOKEN_REFRESH_INTERVAL );
const postsCache = new LRUCache( {
max: 50000,
ttl: CACHE_TIMES.singlePost * 1000,
} );
let allAccounts = [];
const CACHE_QUERY_KEYS = [
'search',
'services',
'groups',
'excludeService',
'limit',
'offset',
];
const getCacheKey = ( request ) => {
const params = new URLSearchParams();
for ( const key of CACHE_QUERY_KEYS ) {
const value = request.query[ key ];
if ( value === undefined || value === null || value === '' ) {
continue;
}
if ( Array.isArray( value ) ) {
params.append( key, value.join( ',' ) );
} else {
params.append( key, String( value ) );
}
}
params.sort();
const queryString = params.toString();
const base = `${ request.params.game }/posts`;
return queryString ? `${ base }?${ queryString }` : base;
};
const getAllAccounts = async () => {
const query = {
attributes: [
'id',
'identifier',
'service',
],
include: [
{
attributes: [
'group',
'name',
'nick',
'role',
'active',
],
include: [
{
attributes: [
'identifier',
],
model: models.Game,
},
],
model: models.Developer,
},
],
};
await models.Account.findAll( query )
.then( ( accountInstances ) => {
const newAccounts = [];
for ( let i = 0; i < accountInstances.length; i = i + 1 ) {
const account = accountInstances[ i ].get();
newAccounts.push(account);
}
allAccounts = newAccounts;
} )
.catch( ( findError ) => {
// Background refresh (startup + 60s interval). A transient DB pool
// timeout here must not reject (it would become an unhandled
// rejection); just log and keep the previously cached accounts.
console.error( `[warn] getAllAccounts refresh failed, keeping cached accounts: ${ findError.message }` );
} );
};
getAllAccounts();
setInterval(getAllAccounts, 60000);
const getAccountsForGame = async (gameIdentifier) => {
const gameAccounts = allAccounts.filter((account) => {
return account.developer.game.identifier === gameIdentifier;
});
return gameAccounts;
};
// Anything with a dot basically
const serveStatic = restify.plugins.serveStatic( {
default: 'index.json',
directory: './static',
} );
// restify's find-my-way router (v7+) dropped RegExp route paths, so this
// static-file catch-all is now a '/*' wildcard. find-my-way gives wildcards
// the lowest match precedence, so the API/:param routes still win and only
// otherwise-unmatched paths (asset requests) fall through to serveStatic.
server.get( '/*', ( request, response, next ) => {
try {
decodeURIComponent( request.path() );
} catch ( decodeError ) {
response.status( MALFORMED_REQUEST_STATUS_CODE );
response.end();
return next( false );
}
return serveStatic( request, response, next );
} );
server.get( '/', ( request, response, next ) => {
response.json( 'Wanna do cool stuff? Msg me wherever /u/Kokarn kokarn@gmail @oskarrisberg' );
} );
server.get( '/health', ( request, response, next ) => {
response.json( { status: 'ok' } );
} );
server.get( '/loaderio-7fa45b57bc0a2a51cd5159425752f4f2/', ( request, response, next ) => {
response.sendRaw( 'loaderio-7fa45b57bc0a2a51cd5159425752f4f2' );
} );
server.head( '/:game/posts', ( request, response, next ) => {
// Should add game checking
response.status( SUCCESS_STATUS_CODE );
response.end();
} );
server.head( '/', ( request, response, next ) => {
response.status( SUCCESS_STATUS_CODE );
response.end();
} );
server.get(
'/:game/posts',
// eslint-disable-next-line max-lines-per-function
async (request, response) => {
const cacheKey = getCacheKey(request);
const cachedValue = myCache.get(cacheKey);
if (cachedValue) {
console.log('Cache hit!');
response.json({
// eslint-disable-next-line id-blacklist
data: JSON.parse(cachedValue),
});
return true;
}
let gameAccounts = await getAccountsForGame(request.params.game);
const query = {
attributes: [
'id',
'timestamp',
'accountId',
],
where: {},
limit: DEFAULT_POST_LIMIT,
// Order by `timestamp + 0`, not `timestamp`. A plain
// `ORDER BY timestamp DESC ... LIMIT` lets MySQL walk the
// single-column posts_timestamp index backward and post-filter
// `accountId IN (...)`, betting it hits the LIMIT quickly. For a
// game whose posts aren't near the top of the global timeline
// (quiet/older games) that bet is catastrophic — it scans most of
// the table (csgo: 973k rows / ~147s measured). The `+ 0` denies
// that index for ordering, so MySQL instead ranges over accountId_2
// (this game's posts only) and filesorts the bounded set — csgo
// drops to ~140ms, and tiny games can no longer full-scan. Search
// (below) needs the same trick for its own reasons.
order: [
[
models.sequelize.literal( 'timestamp + 0' ),
'DESC',
],
],
};
response.cache( 'public', {
maxAge: CACHE_TIMES.posts,
} );
if ( request.query.search ) {
query.where = Object.assign(
{},
query.where,
{
[ Op.or ]: [
{
content: {
[ Op.like ]: `%${ request.query.search }%`,
},
},
// {
// '$account.developer.nick$': {
// [ Op.like ]: `%${ request.query.search }%`,
// },
// },
],
}
);
// Ordering already uses `timestamp + 0` (set on the base query
// above). That's also what a rare-term search needs: a
// leading-wildcard LIKE can't use an index, and ordering by the bare
// `timestamp` would make MySQL content-scan the whole table
// newest-first until it collects enough matches. Ranging over this
// game's accounts and filesorting that bounded set is far cheaper.
}
if ( request.query.services ) {
gameAccounts = gameAccounts.filter((gameAccount) => {
return request.query.services.includes(gameAccount.service);
});
}
if ( request.query.groups ) {
gameAccounts = gameAccounts.filter((gameAccount) => {
return request.query.groups.includes(gameAccount.developer.group);
});
}
if ( request.query.excludeService ) {
gameAccounts = gameAccounts.filter((gameAccount) => {
return !request.query.excludeService.includes(gameAccount.service);
});
}
if ( request.query.limit ) {
const newLimit = Number( request.query.limit );
if ( newLimit > 0 ) {
query.limit = Math.min( newLimit, MAX_POST_LIMIT );
}
}
if ( request.query.offset ) {
const postOffset = Number( request.query.offset );
if ( postOffset > MAX_POST_OFFSET ) {
response.status( MALFORMED_REQUEST_STATUS_CODE );
response.json( {
error: `offset must be <= ${ MAX_POST_OFFSET }`,
} );
return false;
}
if ( postOffset > 0 ) {
query.offset = postOffset;
}
}
query.where = Object.assign(
{},
query.where,
{
accountId: {
[Op.in]: gameAccounts.map((gameAccount) => {
return gameAccount.id;
}),
},
}
);
// Return the promise so restify awaits it. This handler is async, and
// restify finalizes the response when the async function resolves — an
// un-returned chain resolves immediately, so restify would send first
// and the later .then() would hit ERR_HTTP_HEADERS_SENT.
return models.Post.findAll( query )
.then( ( postInstances ) => {
const postIdList = [];
for ( let i = 0; i < postInstances.length; i = i + 1 ) {
const post = postInstances[ i ].get();
postIdList.push(post.id);
}
const postQuery = {
attributes: [
'content',
'id',
'section',
'timestamp',
'topic',
'topicUrl',
'url',
'urlHash',
],
include: [
{
attributes: [
'identifier',
'service',
],
include: [
{
attributes: [
'group',
'name',
'nick',
'role',
],
include: [
{
attributes: [],
model: models.Game,
},
],
model: models.Developer,
},
],
model: models.Account,
},
],
order: [
[
'timestamp',
'DESC',
],
],
where: {
id: {
[Op.in]: postIdList,
}
},
};
return models.Post.findAll(postQuery);
} )
.then( ( postInstances ) => {
const posts = [];
for ( let i = 0; i < postInstances.length; i = i + 1 ) {
const post = postInstances[ i ].get();
post.id = hashids.encode( post.id );
posts.push( post );
}
response.json( {
// eslint-disable-next-line id-blacklist
data: posts,
} );
if( posts.length > 0 ) {
myCache.set( cacheKey, JSON.stringify( posts ) );
}
} )
.catch( ( findError ) => {
// Don't rethrow: that hangs the request (no response) and logs a
// misleading [fatal]. A DB pool-acquire timeout is transient, so
// answer 503 and let the client retry.
console.error( `[warn] posts query failed: ${ findError.message }` );
response.status( SERVICE_UNAVAILABLE_STATUS_CODE );
response.json( {
error: 'Temporarily unable to load posts, please retry.',
} );
} );
}
);
server.get(
'/:game/posts/:id',
( request, response, next ) => {
const query = {
attributes: [
'content',
'id',
'timestamp',
'topic',
'topicUrl',
'url',
],
include: [
{
attributes: [
'identifier',
'service',
],
include: [
{
attributes: [
'group',
'name',
'nick',
'role',
],
include: [
{
attributes: [],
model: models.Game,
where: {
identifier: request.params.game,
},
},
],
model: models.Developer,
where: {},
},
],
model: models.Account,
where: {},
},
],
limit: 1,
order: [
[
'timestamp',
'DESC',
],
],
where: {},
};
response.cache( 'public', {
maxAge: CACHE_TIMES.singlePost,
} );
if ( Number( request.params.id ) ) {
query.where = Object.assign(
{},
query.where,
{
v1Id: request.params.id,
}
);
} else {
query.where = Object.assign(
{},
query.where,
{
id: hashids.decode( request.params.id ),
}
);
}
models.Post.findAll( query )
.then( ( postInstances ) => {
if ( postInstances && postInstances[ 0 ] ) {
const post = postInstances[ 0 ].get();
post.id = hashids.encode( post.id );
response.json( {
// eslint-disable-next-line id-blacklist
data: [ post ],
} );
} else {
response.status( NOT_FOUND_STATUS_CODE );
response.end();
}
} )
.catch( ( findError ) => {
// Transient DB pool-acquire timeout: answer 503 rather than
// rethrowing (which would hang the request and log [fatal]).
console.error( `[warn] single post query failed: ${ findError.message }` );
response.status( SERVICE_UNAVAILABLE_STATUS_CODE );
response.json( {
error: 'Temporarily unable to load post, please retry.',
} );
} );
}
);
server.get(
'/games',
( request, response, next ) => {
models.Game.findAll(
{
attributes: [
'id',
'identifier',
'name',
'shortName',
'hostname',
'config',
],
}
)
.then( ( fullGameData ) => {
const responseData = [];
let instantReponse = true;
for ( const game of fullGameData ) {
const config = {};
if ( game.config ) {
// Offline games (config.live falsy) stay in the public
// response — "offline" only stops indexing, not visibility.
if ( game.config.boxart ) {
config.boxart = game.config.boxart;
}
}
responseData.push( {
config,
hostname: game.hostname,
identifier: game.identifier,
name: game.name,
shortName: game.shortName,
} );
}
if ( request.header( 'Authorization' ) ) {
const tokenMatch = request.header( 'Authorization' ).match( /Bearer (.*)/ );
if ( tokenMatch ) {
instantReponse = false;
const matchedToken = lookupToken( tokenMatch[ 1 ] );
let isAuthed = false;
if ( matchedToken && matchedToken.legacy ) {
isAuthed = legacyAuthorize( tokenMatch[ 1 ], request.route.path, request.method );
} else if ( matchedToken ) {
isAuthed = matchedToken.scopes.includes( 'admin' )
|| matchedToken.scopes.includes( 'games:read' );
}
if ( isAuthed ) {
response.json( {
// eslint-disable-next-line id-blacklist
data: fullGameData,
} );
} else {
response.json( {
// eslint-disable-next-line id-blacklist
data: responseData,
} );
}
}
}
if ( instantReponse ) {
response.json( {
// eslint-disable-next-line id-blacklist
data: responseData,
} );
}
} )
.catch( ( queryError ) => {
console.log( queryError );
} );
}
);
server.get(
'/:game/accounts',
...requireScope( 'accounts:read' ),
async ( request, response ) => {
let gameAccounts = await getAccountsForGame(request.params.game);
if ( request.query.active && request.query.active.length > 0 ) {
gameAccounts = gameAccounts.filter((gameAccount) => {
return gameAccount.developer.active;
});
}
if ( request.query.excludeService ) {
gameAccounts = gameAccounts.filter((gameAccount) => {
return !request.query.excludeService.includes(gameAccount.service);
});
}
response.json({
data: gameAccounts.map((gameAccount) => {
return {
id: gameAccount.id,
identifier: gameAccount.identifier,
service: gameAccount.service,
};
}),
});
}
);
server.get(
'/:game/developers',
...requireScope( 'developers:read' ),
( request, response, next ) => {
const query = {
include: [
{
attributes: [],
model: models.Game,
where: {
identifier: request.params.game,
},
},
{
model: models.Account,
},
],
model: models.Developer,
where: {},
};
models.Developer.findAll( query )
.then( ( developers ) => {
response.json( {
// eslint-disable-next-line id-blacklist
data: developers,
} );
} )
.catch( ( queryError ) => {
console.log( queryError );
} );
}
);
server.get(
'/:game/hashes',
...requireScope( 'hashes:read' ),
( request, response, next ) => {
const query = {
attributes: [
'urlHash',
],
include: [
{
attributes: [],
include: [
{
attributes: [],
include: [
{
attributes: [],
model: models.Game,
where: {
identifier: request.params.game,
},
},
],
model: models.Developer,
where: {},
},
],
model: models.Account,
where: {},
},
],
where: {},
};
models.Post.findAll( query )
.then( ( posts ) => {
const urls = [];
posts.forEach( ( post ) => {
urls.push( post.urlHash );
} );
response.json( {
// eslint-disable-next-line id-blacklist
data: urls,
} );
} )
.catch( ( queryError ) => {
console.log( queryError );
} );
}
);
server.get(
'/:game/services',
( request, response, next ) => {
const query = {
attributes: [],
include: [
{
attributes: [
'service',
],
include: [
{
attributes: [],
include: [
{
attributes: [],
model: models.Game,
where: {
identifier: request.params.game,
},
},
],
model: models.Developer,
where: {},
},
],
model: models.Account,
where: {},
},
],
raw: true,
where: {},
};
response.cache( 'public', {
maxAge: CACHE_TIMES.services,
} );
models.Post.findAll( query )
.then( ( serviceObjects ) => {
const services = [];
serviceObjects.forEach( ( currentObject ) => {
if ( services.includes( currentObject[ 'account.service' ] ) ) {
return true;
}
services.push( currentObject[ 'account.service' ] );
} );
response.json( {
// eslint-disable-next-line id-blacklist
data: alphanumSort(
services,
{
insensitive: true,
}
),
} );
} )
.catch( ( queryError ) => {
console.log( queryError );
} );
}
);
server.get(
'/:game/groups',
( request, response, next ) => {
const query = {
attributes: [
'group',
],
include: [
{
attributes: [],
model: models.Game,
where: {
identifier: request.params.game,