-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
1344 lines (1222 loc) · 39.3 KB
/
index.ts
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
// TODO: review ACLs
const t0 = Date.now();
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as request from 'request-promise';
import * as express from 'express';
import {
ImageMetadata,
Upsert,
extractImageMetadata,
UploadRequest,
FsPath,
HierarchyNode,
autoId,
CodeReferral,
Relawan,
isValidImageId,
SUM_KEY,
APP_SCOPED_PREFIX_URL,
MAX_REFERRALS,
MAX_NUM_UPLOADS,
USER_ROLE,
isValidUserId,
ChangeLog,
SumMap,
RelawanPhotos,
UpsertProfile,
TpsData,
ApproveRequest,
toChildren,
FORM_TYPE,
IS_PLANO,
PublicProfile,
ProblemRequest,
MAX_URL_LENGTH,
MAX_REASON_LENGTH,
MAX_REPORT_ERRORS,
canGenerateCustomCode,
QuotaSegments,
QuotaSpecs,
isValidHalaman,
computeAction,
KPU_SCAN_UID,
BAWASLU_UID,
LaporKpuRequest,
MAX_LAPOR_KPU,
isSuperAdmin,
BOT_UID,
LOCK_DOWN
} from 'shared';
const t1 = Date.now();
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'https://kawal-c1.firebaseio.com'
});
const auth = admin.auth();
const fsdb = admin.firestore();
const t2 = Date.now();
const delay = (ms: number) => new Promise(_ => setTimeout(_, ms));
function getServingUrl(objectName: string, ithRetry = 0, maxRetry = 10) {
const domain = 'kawal-c1.appspot.com';
const path = encodeURIComponent(`${domain}/${objectName}`);
return request(`https://${domain}/gsu?path=${path}`, { timeout: 5000 })
.then(res => {
if (!res.startsWith('http')) {
throw new Error('gsu failed: ' + path);
}
return res;
})
.catch(async e => {
if (ithRetry >= maxRetry) {
console.error(`${e.message}; path = ${path}, #${ithRetry}/${maxRetry}`);
throw e;
}
if (ithRetry * 2 >= maxRetry) {
console.log(`gsu retry ${ithRetry}: ${e.message}`);
}
await delay(ithRetry * 1000);
return getServingUrl(objectName, ithRetry + 1, maxRetry);
});
}
// Creates a serving url for the uploaded images.
exports.handlePhotoUpload = functions.storage
.object()
.onFinalize(async object => {
const paths = object.name.split('/');
// object.name = uploads/{kelurahanId}/{tpsNo}/{userId}/{imageId}
const [dir, kelurahanId, tpsNo, userId, imageId] = paths;
if (dir !== 'uploads') {
return null;
}
// Exit if this is triggered on a file that is not an image.
if (!object.contentType.startsWith('image/')) {
console.warn(`Not an image: ${object.name}`);
return null;
}
if (LOCK_DOWN) {
console.warn(`On LOCK_DOWN: ${object.name}`);
return null;
}
const m = {} as ImageMetadata;
m.u = userId;
m.k = parseInt(kelurahanId, 10);
m.t = parseInt(tpsNo, 10);
if (isNaN(m.k) || isNaN(m.t)) {
throw new Error(`Invalid lokasi ${object.name}`);
}
m.v = await getServingUrl(object.name);
m.a = Date.now();
await fsdb.doc(FsPath.imageMetadata(imageId)).set(m);
});
/**
* Validates Firebase ID Tokens passed in the authorization HTTP header.
* Adds the decoded ID Token content to the request object.
*/
function validateToken() {
return (req, res: express.Response, next) => {
if (req.query.abracadabra) {
return next();
}
const a = req.headers.authorization;
if (!a || !a.startsWith('Bearer ')) {
return res.status(403).json({ error: 'Unauthorized' });
}
return auth
.verifyIdToken(a.substring(7))
.then(user => {
req.user = user;
next();
})
.catch(() => res.status(403).json({ error: 'Invalid token' }));
};
}
function lockDownCheck() {
return async (req, res, next) => {
const user = req.user as admin.auth.DecodedIdToken;
if (LOCK_DOWN) {
console.log('path', req.path);
if (!req.path.startsWith('/api/c/')) {
console.warn(`LOCK_DOWN ${user.uid} ${req.path}`);
return res.json({ error: 'LOCK_DOWN mode' });
}
}
next();
};
}
function rateLimitRequests() {
const quota: { [uid: string]: QuotaSegments } = {};
const quotaSpecs = new QuotaSpecs('api');
return (req, res, next) => {
if (!req.query.abracadabra) {
const user = req.user as admin.auth.DecodedIdToken;
if (
user.uid !== KPU_SCAN_UID &&
user.uid !== BAWASLU_UID &&
user.uid !== BOT_UID
) {
quota[user.uid] = quota[user.uid] || {};
if (!quotaSpecs.request(quota[user.uid], Date.now())) {
console.warn(`User ${user.uid} is rate-limited: ${req.url}`);
res.status(403).json({ error: 'Rate-limited' });
return null;
}
}
}
next();
};
}
const app = express();
const bodyParser = require('body-parser');
app.use(require('cors')({ origin: true }));
app.use(require('helmet')());
app.use(validateToken());
app.use(lockDownCheck());
app.use(rateLimitRequests());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((err, req, res, next) => {
if (err !== null) {
const user = req.user as admin.auth.DecodedIdToken;
if (err.status === 400 && err.name === 'SyntaxError' && err.body) {
const b = err.body.slice(0, 100).toString();
console.error(`Error ${user.uid} ${req.method + ' ' + req.url} : ${b}`);
} else {
console.error(`Error ${user.uid} ${req.method + ' ' + req.url}`);
}
res.json({ error: 'invalid request' });
} else {
next();
}
});
let fallbackUntilTs = 0;
let privateFailCount = 0;
async function getHierarchyNode(
cid: number,
uid: string
): Promise<HierarchyNode> {
const ts = Date.now();
const isPublic = uid.startsWith('public');
const level = isPublic || privateFailCount < 10 ? 'debug' : 'error';
if (!LOCK_DOWN && (fallbackUntilTs < ts || (!isPublic && privateFailCount < 10))) {
try {
const host = '35.193.104.134:8080';
const options = { timeout: isPublic ? 1500 : 3000, json: true };
const ret = await request(`http://${host}/api/c/${cid}`, options);
privateFailCount = 0;
return ret;
} catch (e) {
console[level](`fail c/${cid}: ${e.message}, uid ${uid}`);
fallbackUntilTs = ts + 15 * 1000;
if (!isPublic) {
privateFailCount++;
}
}
}
// Fallback to hierarchy with stale cache sum.
let snap = await fsdb.doc(FsPath.hieCache(cid)).get();
let c = snap.data() as HierarchyNode;
if (c) {
if (!LOCK_DOWN) console[level](`Cache hie for ${cid}, uid ${uid}`);
} else {
// Fallback to static hierarchy, without sum.
snap = await fsdb.doc(FsPath.hie(cid)).get();
c = snap.data() as HierarchyNode;
console[level](`Static hie for ${cid}, uid ${uid}`);
}
if (c) {
c.children = toChildren(c);
c.data = c.data || {};
delete c.child;
} else {
c = {} as HierarchyNode;
}
return c;
}
type Cache12 = { ts: number; h: HierarchyNode };
const cache_12: { [cid: string]: Cache12 } = {};
app.get('/api/c/:id', async (req: any, res) => {
const cid = +req.params.id;
if (isNaN(cid) || cid >= 1e6) {
return res.json({});
}
// res.set('Cache-Control', 'public, max-age=300, s-maxage=600');
const c = cache_12[cid];
const ts = Date.now();
if (c) {
if (c.h.depth < 1 && ts - c.ts < 60 * 1000) return res.json(c.h);
if (c.h.depth < 2 && ts - c.ts < 30 * 1000) return res.json(c.h);
if (ts - c.ts < 15 * 1000) return res.json(c.h);
}
const user = req.user as admin.auth.DecodedIdToken;
const uid = (user && user.uid) || 'public';
const h = await getHierarchyNode(cid, uid + ' from API');
if (h.depth <= 2 && user && user.uid) {
cache_12[cid] = { ts, h };
}
return res.json(h);
});
/** Fetches image metadata from Firestore, wait until it's populated. */
function populateServingUrl() {
return async (req, res, next) => {
const user = req.user as admin.auth.DecodedIdToken;
const b = req.body as UploadRequest;
const p: UploadRequest = (req.parsedBody = {
imageId: b.imageId,
kelId: +b.kelId,
tpsNo: +b.tpsNo,
meta: extractImageMetadata(b.meta),
ts: Date.now(),
url: null, // Populated below.
kelName: '', // Will be populated in the next middleware.
c1: null, // Will be populated on approved
sum: null // Will be populated on approved
});
if (!isValidImageId(p.imageId)) {
console.warn(`Metadata invalid ${p.imageId}, ${user.uid}`);
return res.json({ error: 'Invalid imageId' });
}
const maxRetry = 15;
for (let i = 1; i <= maxRetry; i++) {
const meta = (await fsdb
.doc(FsPath.imageMetadata(p.imageId))
.get()).data() as ImageMetadata;
if (meta && meta.v) {
p.url = meta.v;
return next();
}
await delay(i * 1000);
}
console.warn(`Metadata missing ${p.imageId}, ${user.uid}`);
return res.json({ error: 'Metadata does not exists' });
};
}
function populateKelName() {
const cache = {};
return async (req, res, next) => {
const user = req.user as admin.auth.DecodedIdToken;
const p = req.parsedBody as {
kelId: number;
tpsNo: number;
kelName: string;
};
if (!p.kelId || typeof p.tpsNo !== 'number') {
console.warn(`KelName ${p.kelId} ${p.tpsNo}, ${user.uid}`);
return res.json({ error: 'missing parameters' });
}
let mem = cache[p.kelId];
if (!mem) {
try {
const c = await getHierarchyNode(p.kelId, user.uid);
if (!c || !c.name) {
console.warn(`Children missing ${p.kelId}, ${user.uid}`);
return res.json({ error: 'kelId does not exists' });
}
mem = cache[p.kelId] = { name: c.name, hasTpsNo: {} };
(c.children || []).forEach(t => (mem.hasTpsNo[t[0]] = true));
} catch (e) {
console.warn(`Error ${e.message}, ${user.uid}`);
return res.json({ error: 'Server error please retry in 1 minute' });
}
}
p.kelName = mem.name;
if (user.uid === BAWASLU_UID) {
if (p.tpsNo !== 0) {
return res.json({ error: 'tpsNo must be zero' });
}
} else if (!mem.hasTpsNo[p.tpsNo]) {
// @ts-ignore
if (p.tpsNo !== 0 || p.c1.type !== FORM_TYPE.OTHERS) {
if (p.tpsNo) {
console.warn(`TPS missing ${p.kelId} ${p.tpsNo}, ${user.uid}`);
}
return res.json({ error: 'tpsNo does not exists' });
}
}
next();
};
}
async function uploadPhotoWithRetry(p: UploadRequest, req) {
for (let i = 1; ; i++) {
try {
return await uploadPhoto(p, req);
} catch (e) {
if (e.message.toLowerCase().indexOf('please try again') && i <= 3) {
await delay(i * 1000);
continue;
}
const user = req.user as admin.auth.DecodedIdToken;
console.error(`Error Upload Photo ${user.uid}`, p, e);
return e.message;
}
}
}
async function uploadPhoto(p: UploadRequest, req) {
const user = req.user as admin.auth.DecodedIdToken;
const ts = p.ts;
const rRef = fsdb.doc(FsPath.relawan(user.uid));
const pRef = fsdb.doc(FsPath.relawanPhoto(user.uid));
const tRef = fsdb.doc(FsPath.tps(p.kelId, p.tpsNo));
return await fsdb.runTransaction(async t => {
const r = (await t.get(rRef)).data() as Relawan;
if (!r || !r.profile || r.profile.uid !== user.uid) {
return 'Uploader not found';
}
let photo: RelawanPhotos = null;
if (user.uid !== KPU_SCAN_UID && user.uid !== BAWASLU_UID) {
photo = await getRelawanPhotos(t, pRef, user.uid);
photo.profile = r.profile;
photo.uploadCount = (photo.uploadCount || 0) + 1;
const maxNumUploads = photo.maxUploadCount || MAX_NUM_UPLOADS;
if (photo.uploadCount <= maxNumUploads) {
photo.uploads.unshift(p);
}
const pu = photo.uploads;
photo.nTps = new Set(pu.map(up => up.kelId + '-' + up.tpsNo)).size;
photo.nKel = new Set(pu.map(up => up.kelId)).size;
}
const ua = req.headers['user-agent'];
const ip = getIp(req);
const uploader = { ...r.profile, ts, ua, ip } as UpsertProfile;
let tps = (await t.get(tRef)).data() as TpsData;
tps = tps || { images: {}, imgCount: 0, laporKpu: false };
tps.images[p.imageId] = {
uploader,
reviewer: null,
reports: null,
c1: null,
sum: {} as SumMap,
url: p.url,
meta: p.meta
};
tps.imgCount++;
const action = computeAction(tps, p.tpsNo);
const upsert = { request: p, uploader, done: 0, action } as Upsert;
const imageRef = fsdb.doc(FsPath.upserts(p.imageId));
if ((await t.get(imageRef)).exists) return true;
t.create(imageRef, upsert);
if (photo) {
t.set(pRef, photo);
}
t.set(tRef, tps);
return true;
});
}
app.post(
'/api/upload',
[populateServingUrl(), populateKelName()],
async (req: any, res) => {
const user = req.user as admin.auth.DecodedIdToken;
const p = req.parsedBody as UploadRequest;
const ok = await uploadPhotoWithRetry(p, req);
if (ok !== true) {
console.error(`Upload failed ${user.uid}: ${ok}`, p);
return res.json({ error: ok });
}
return res.json({ ok: true });
}
);
function getIp(req: express.Request) {
const ip = req.headers['fastly-client-ip'];
return typeof ip === 'string' ? ip : JSON.stringify(ip);
}
function populateApprove() {
return async (req, res, next) => {
const user = req.user as admin.auth.DecodedIdToken;
const b = req.parsedBody as ApproveRequest;
const a = {
kelId: b.kelId,
tpsNo: b.tpsNo,
kelName: b.kelName
} as ApproveRequest;
if (!b || !isValidImageId(b.imageId)) {
console.warn(`Invalid imageId ${b.imageId} for user ${user.uid}`, b);
return res.json({ error: 'Invalid imageId' });
}
a.imageId = b.imageId;
if (!b.c1 || !FORM_TYPE[b.c1.type]) {
console.warn(`Invalid form ${JSON.stringify(b.c1)} for ${user.uid}`, b);
return res.json({ error: 'Invalid form' });
}
if (
b.c1.type !== FORM_TYPE.MALICIOUS &&
b.c1.type !== FORM_TYPE.OTHERS &&
b.c1.type !== FORM_TYPE.PEMANDANGAN
) {
if (!IS_PLANO[b.c1.plano]) {
console.warn(`Invalid plano ${JSON.stringify(b.c1)} for ${user.uid}`);
return res.json({ error: 'Invalid form' });
}
}
if (b.c1.halaman !== '0' && !isValidHalaman(b.c1)) {
console.warn(`Invalid halaman ${b.c1.halaman} for ${user.uid}`);
return res.json({ error: 'Invalid halaman' });
}
a.c1 = { type: b.c1.type, plano: b.c1.plano, halaman: b.c1.halaman };
if (!b || !b.sum) {
console.warn(`No sum ${user.uid}`);
return res.json({ error: 'No sum' });
}
a.sum = {} as SumMap;
for (const key in b.sum) {
if (!SUM_KEY[key]) {
console.error(`Sum key invalid ${user.uid}`, b);
return res.json({ error: 'Invalid sum key' });
}
const sum = b.sum[key];
if (typeof sum !== 'number' || sum < 0 || sum > 4000) {
console.error(`Sum ${sum} out of range ${user.uid}`, b);
return res.json({ error: 'Invalid sum range' });
}
a.sum[key] = sum;
}
req.parsedBody = a;
next();
};
}
async function approveWithRetry(a: ApproveRequest, ua, ip, ts, user) {
for (let i = 1; ; i++) {
try {
return await approve(a, ua, ip, ts, user);
} catch (e) {
if (e.message.toLowerCase().indexOf('please try again') && i <= 3) {
await delay(i * 1000);
continue;
}
console.error(`Error Approve ${user.uid}`, a, e);
return e.message;
}
}
}
async function approve(a: ApproveRequest, ua, ip, ts, user) {
const uRef = fsdb.doc(FsPath.upserts(a.imageId));
const rRef = fsdb.doc(FsPath.relawan(user.uid));
const rpRef = fsdb.doc(FsPath.relawanPhoto(user.uid));
return await fsdb.runTransaction(async t => {
const r = (await t.get(rRef)).data() as Relawan;
if (!r || r.profile.role < USER_ROLE.MODERATOR) return 'Not Authorized';
const rp = await getRelawanPhotos(t, rpRef, user.uid);
rp.profile = r.profile;
rp.reviewCount = (rp.reviewCount || 0) + 1;
const u = (await t.get(uRef)).data() as Upsert;
if (!u) return 'No Upsert';
if (r.profile.role < USER_ROLE.ADMIN && u.reviewer)
return 'Already approved';
const self = u.uploader.uid === user.uid;
const pRef = self ? null : fsdb.doc(FsPath.relawanPhoto(u.uploader.uid));
const urp = self ? rp : ((await t.get(pRef)).data() as RelawanPhotos);
if (!urp) return 'No relawan photo';
const photo = urp.uploads.find(p => p.imageId === a.imageId);
// if (
// !photo &&
// urp.profile.uid !== KPU_SCAN_UID &&
// urp.profile.uid !== BAWASLU_UID
// )
// return `No photo for ${a.imageId}`;
const tRef = fsdb.doc(FsPath.tps(u.request.kelId, u.request.tpsNo));
const tps = (await t.get(tRef)).data() as TpsData;
if (!tps) return 'No TPS';
const img = tps.images[a.imageId];
if (!img) return 'No Image';
const asum = JSON.parse(JSON.stringify(a.sum));
for (const key of Object.keys(img.sum || {})) {
if (!a.sum.hasOwnProperty(key)) {
a.sum[key] = 0;
}
}
img.c1 = a.c1;
img.sum = a.sum;
img.sum.pending = 0;
u.reviewer = img.reviewer = { ...r.profile, ts, ua, ip };
u.action = computeAction(tps, u.request.tpsNo);
// @ts-ignore
u.done = admin.firestore.FieldValue.increment(-1);
img.sum = asum;
if (photo) {
photo.c1 = img.c1;
photo.sum = img.sum;
if (pRef) {
t.update(pRef, urp);
}
}
t.set(rpRef, rp);
t.update(uRef, u);
t.update(tRef, tps);
return true;
});
}
app.post(
'/api/approve',
[
(req, res, next) => {
const b = req.body as ApproveRequest;
const p: ApproveRequest = {
kelId: +b.kelId,
kelName: '',
tpsNo: +b.tpsNo,
imageId: b.imageId,
sum: b.sum,
c1: b.c1
};
req.parsedBody = p;
next();
},
populateKelName(),
populateApprove()
],
async (req: any, res) => {
const user = req.user as admin.auth.DecodedIdToken;
const a = req.parsedBody as ApproveRequest;
const ua = req.headers['user-agent'];
const ip = getIp(req);
const uRef = fsdb.doc(FsPath.upserts(a.imageId));
const upsert = (await uRef.get()).data() as Upsert;
if (!upsert) {
console.warn(`No upsert ${user.uid} : ${a.imageId}`);
return res.json({ error: 'No upsert' });
}
if (a.c1.type === FORM_TYPE.MALICIOUS) {
const tuid = upsert.uploader.uid;
console.log(`Mal ${a.imageId} ${tuid}, a = ${user.uid}`);
const okBan = await changeRole(user.uid, tuid, USER_ROLE.BANNED, true);
if (okBan !== true) console.error(`Ban failed ${okBan}`);
} else if (
upsert.request.kelId !== a.kelId ||
upsert.request.tpsNo !== a.tpsNo
) {
if (a.c1.type === FORM_TYPE.OTHERS) {
if (upsert.request.tpsNo === 0) {
console.debug(`Tolong OTHERS kan foto bawaslu di TPS 0 ${user.uid}`);
return res.json({ error: `Tolong OTHERS kan foto bawaslu di TPS 0` });
}
console.debug(`Tolong refresh browser kamu ${user.uid}`);
return res.json({ error: `Tolong refresh browser kamu` });
}
// Moving photo to another TPS is like make a copy then set the old to OTHERS.
const copy: UploadRequest = {
imageId: upsert.request.imageId + '-' + a.kelId + '-' + a.tpsNo,
kelId: a.kelId,
kelName: a.kelName,
tpsNo: a.tpsNo,
meta: upsert.request.meta,
url: upsert.request.url,
ts: Date.now(),
c1: null,
sum: null
};
const oku = await uploadPhotoWithRetry(copy, req);
if (oku !== true) {
console.debug(`Error move copy ${user.uid} : ${oku}`);
return res.json({ error: oku });
}
const apr: ApproveRequest = {
kelId: a.kelId,
kelName: a.kelName,
tpsNo: a.tpsNo,
imageId: copy.imageId,
sum: a.sum,
c1: a.c1
};
const oka = await approveWithRetry(apr, ua, ip, Date.now(), user);
if (oka !== true) {
console.debug(`Error move approve ${user.uid} : ${oka}`);
return res.json({ error: oka });
}
a.c1.type = FORM_TYPE.OTHERS;
a.sum = {} as SumMap;
}
const ok = await approveWithRetry(a, ua, ip, Date.now(), user);
if (ok !== true) {
if (!ok.startsWith('Already')) {
console.warn(`Error approve ${user.uid} : ${ok}`);
}
return res.json({ error: ok });
}
return res.json({ ok: true });
}
);
async function getRelawanPhotos(t, rpRef, uid): Promise<RelawanPhotos> {
const rp = (await t.get(rpRef)).data() as RelawanPhotos;
if (rp) return rp;
const rRef = fsdb.doc(FsPath.relawan(uid));
const r = (await t.get(rRef)).data() as Relawan;
return {
profile: r.profile,
uploads: [],
uploadCount: 0,
maxUploadCount: 0,
reports: [],
reportCount: 0,
maxReportCount: 0,
reviewCount: 0,
laporKpus: [],
laporKpuCount: 0,
maxLaporKpuCount: 0,
nTps: 0,
nKel: 0
};
}
app.post(
'/api/problem',
[
(req, res, next) => {
const user = req.user as admin.auth.DecodedIdToken;
const b = req.body as ProblemRequest;
const p: ProblemRequest = (req.parsedBody = {
kelId: +b.kelId,
kelName: '',
tpsNo: +b.tpsNo,
url: b.url,
reason: b.reason,
ts: Date.now()
});
if (typeof p.url !== 'string' || p.url.length > MAX_URL_LENGTH) {
console.warn(`URL problem ${user.uid} ${p.kelId} ${p.tpsNo}`);
return res.json({ error: 'invalid URL' });
}
if (typeof p.reason !== 'string' || p.reason.length > MAX_REASON_LENGTH) {
console.warn(`Reason problem ${user.uid} ${p.kelId} ${p.tpsNo}`);
return res.json({ error: 'invalid reason' });
}
next();
},
populateKelName()
],
async (req: any, res) => {
const user = req.user as admin.auth.DecodedIdToken;
const p = req.parsedBody as ProblemRequest;
const ts = Date.now();
const ip = getIp(req);
const ua = req.headers['user-agent'];
const tRef = fsdb.doc(FsPath.tps(p.kelId, p.tpsNo));
const rpRef = fsdb.doc(FsPath.relawanPhoto(user.uid));
const ok = await fsdb
.runTransaction(async t => {
const tps = (await t.get(tRef)).data() as TpsData;
const imageId = Object.keys(tps.images).find(
i => tps.images[i].url === p.url
);
if (!imageId) return 'invalid URL';
const uRef = fsdb.doc(FsPath.upserts(imageId));
const u = (await t.get(uRef)).data() as Upsert;
if (!u) return 'imageId not found';
const rp = await getRelawanPhotos(t, rpRef, user.uid);
rp.reports = rp.reports || [];
rp.reportCount = (rp.reportCount || 0) + 1;
const maxReports = rp.maxReportCount || MAX_REPORT_ERRORS;
if (rp.reportCount < maxReports) {
rp.reports.unshift(p);
}
const reporter: UpsertProfile = { ...rp.profile, ts, ua, ip };
const img = tps.images[imageId];
img.reports = img.reports || {};
if (
Object.keys(img.reports)
.map(tt => img.reports[tt])
.find(
r =>
r.reporter.role >= USER_ROLE.ADMIN && r.reason.startsWith('OK:')
)
) {
return 'Foto ini sudah dicek oleh admin dan tidak ditemukan kesalahan.';
}
img.reports[ts] = { reporter, reason: p.reason };
img.sum.error = 1;
if (rp.profile.role >= USER_ROLE.ADMIN && p.reason.startsWith('OK:')) {
img.sum.error = 0;
}
u.reporter = reporter;
u.action = computeAction(tps, p.tpsNo);
// @ts-ignore
u.done = admin.firestore.FieldValue.increment(-1);
if (u.action.sum.janggal && img.sum.error) {
return 'Kamu tidak perlu melaporkan kesalahan di TPS yang sudah ditandai janggal.';
}
t.update(tRef, tps);
t.update(uRef, u);
t.set(rpRef, rp);
return true;
})
.catch(e => {
console.error(`DB lapor ${user.uid}`, e);
return `Database error`;
});
if (ok !== true) {
console.error(`Report ${user.uid} : ${ok}`);
return res.json({ error: ok });
}
return res.json({ ok: true });
}
);
app.post(
'/api/laporKpu',
[
(req, res, next) => {
const b = req.body as LaporKpuRequest;
req.parsedBody = {
kelId: +b.kelId,
kelName: '',
tpsNo: +b.tpsNo,
ts: Date.now()
} as LaporKpuRequest;
next();
},
populateKelName()
],
async (req: any, res) => {
const user = req.user as admin.auth.DecodedIdToken;
const p = req.parsedBody as LaporKpuRequest;
const ip = getIp(req);
const ua = req.headers['user-agent'];
const tRef = fsdb.doc(FsPath.tps(p.kelId, p.tpsNo));
const rpRef = fsdb.doc(FsPath.relawanPhoto(user.uid));
const ok = await fsdb
.runTransaction(async t => {
const tps = (await t.get(tRef)).data() as TpsData;
const imageId = Object.keys(tps.images).find(i => {
const c1 = tps.images[i].c1;
return c1 && c1.type === FORM_TYPE.PPWP && c1.halaman === '2';
});
if (!imageId) return 'no janggal image';
const uRef = fsdb.doc(FsPath.upserts(imageId));
const u = (await t.get(uRef)).data() as Upsert;
if (!u) return 'imageId not found';
const rp = await getRelawanPhotos(t, rpRef, user.uid);
rp.laporKpus = rp.laporKpus || [];
rp.laporKpuCount = (rp.laporKpuCount || 0) + 1;
const maxLaporKpu = rp.maxLaporKpuCount || MAX_LAPOR_KPU;
if (rp.laporKpuCount < maxLaporKpu) {
rp.laporKpus.unshift(p);
}
tps.laporKpu = true;
u.reporter = { ...rp.profile, ts: p.ts, ua, ip };
u.action = computeAction(tps, p.tpsNo);
// @ts-ignore
u.done = admin.firestore.FieldValue.increment(-1);
if (!u.action.sum.janggal) {
return 'Kamu tidak bisa lapor ke KPU untuk TPS yang tidak janggal';
}
t.update(tRef, tps);
t.update(uRef, u);
t.set(rpRef, rp);
return true;
})
.catch(e => {
console.error(`DB lapor kpu ${user.uid}`, e, p);
return `Database error`;
});
if (ok !== true) {
console.error(`Lapor KPU ${user.uid} : ${ok}`, p);
return res.json({ error: ok });
}
return res.json({ ok: true });
}
);
app.post('/api/register/login', async (req: any, res) => {
const user = req.user as admin.auth.DecodedIdToken;
if (user.uid !== user.user_id) {
console.error(`UID differs ${user.uid} !== ${user.user_id}`);
return res.json({ error: 'System error' });
}
const token = req.body.token;
try {
let link = '';
let pic = '';
if (token) {
if (!token.match(/^[a-zA-Z0-9]+$/)) {
console.error(`Invalid token ${user.uid} ${token}`);
return res.json({ error: 'Invalid token' });
}
const url = `https://graph.facebook.com/me?fields=link,picture.type(large)&access_token=${token}`;
const me = await request(url, { timeout: 5000, json: true });
if (!me || me.error) {
console.error(`Me ${user.uid} : ${token} : ${JSON.stringify(me)}`);
return res.json({ error: 'Invalid token' });
}
const p = APP_SCOPED_PREFIX_URL;
if (!me.link || !me.link.startsWith(p)) {
if (me.link && me.link.length > 0) {
console.error(`Invalid login ${user.uid} link: ${link}`);
}
} else {
link = me.link.substring(p.length);
if (!link.match(/^[a-zA-Z0-9]+\/$/)) {
console.error(`Invalid login ${user.uid} shorten link: ${link}`);
link = '';
}
}
pic = me.picture && me.picture.data && me.picture.data.url;
}
let code = '';
const rRef = fsdb.doc(FsPath.relawan(user.uid));
const ok = await fsdb.runTransaction(async t => {
const r = (await t.get(rRef)).data() as Relawan;
if (r) {
if (!r.theCode && r.depth > 0) {
r.theCode = code = await generateCode(t);
const newCode: CodeReferral = {
issuer: r.profile,
issuedTs: Date.now(),
depth: r.depth + 1,
name: 'Netizen',
claimer: null,
claimedTs: null,
agg: 0,
bulk: true
};
t.create(fsdb.doc(FsPath.codeReferral(code)), newCode);
}
if (!r.profile.link && link) {
// @ts-ignore
r.profile.noLink = 'y';
r.profile.link = link;
}
if (pic) {
r.profile.pic = pic;
}
// @ts-ignore
r.lastTs = Date.now();
t.update(rRef, r);
} else {
const profile: PublicProfile = {
uid: user.user_id,
link,
email: user.email || '',
name: user.name,
pic: pic || user.picture,
role: 0,
dr4: 0,
loginTs: Date.now()
};
t.create(rRef, { lowerCaseName: user.name.toLowerCase(), profile });
}
return true;
});
if (ok !== true) {
console.error(`login failed ${user.uid} : ${ok}`);
return res.json({ error: ok });
}
return res.json({ ok: true, code });
} catch (e) {
console.error(`login error ${user.uid} : ${e.message} : token: ${token}`);
return res.json({ error: `Login failed` });
}
});
async function generateCode(t) {
let code;
for (let i = 0; ; i++) {
code = autoId(10);
if (!(await t.get(fsdb.doc(FsPath.codeReferral(code)))).data()) break;
console.error(`Exists auto id ${code}`);
if (i > 10) return 'no_id';
}
return code;
}
async function addGeneratedCode(r: Relawan, nama, t, code, bulk = null) {