-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserver.js
6137 lines (5476 loc) · 281 KB
/
server.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
/*
tagaway - v0.1.0
Written by Altocode (https://altocode.nl) and released into the public domain.
Please refer to readme.md to read the annotated source (some parts are annotated already, but not the whole file yet).
*/
// *** SETUP ***
var CONFIG = require ('./config.js');
var SECRET = require ('./secret.js');
var ENV = process.argv [2] === 'local' ? undefined : process.argv [2];
var mode = process.argv [3];
var crypto = require ('crypto');
var fs = require ('fs');
var Path = require ('path');
var os = require ('os');
var https = require ('https');
Error.stackTraceLimit = Infinity;
var dale = require ('dale');
var teishi = require ('teishi');
var lith = require ('lith');
var cicek = require ('cicek');
var redis = require ('redis').createClient ({db: CONFIG.redisdb});
var redmin = require ('redmin');
redmin.redis = redis;
var giz = require ('giz');
var hitit = require ('hitit');
var a = require ('./assets/astack.js');
var uuid = require ('uuid').v4;
var mailer = require ('nodemailer').createTransport (require ('nodemailer-ses-transport') (SECRET.ses));
var hash = require ('murmurhash').v3;
var mime = require ('mime');
var archiver = require ('archiver');
var jwt = require ('jsonwebtoken');
var type = teishi.type, clog = console.log, eq = teishi.eq, last = teishi.last, inc = teishi.inc, reply = cicek.reply, stop = function (rs, rules) {
return teishi.stop (rules, function (error) {
reply (rs, 400, {error: error});
}, true);
}, astop = function (rs, path) {
a.stop (path, function (s, error) {
reply (rs, 500, {error: error});
});
}, mexec = function (s, multi) {
multi.exec (function (error, data) {
if (error) return s.next (null, error);
s.next (data);
});
}
var debug = function () {clog.apply (null, ['DEBUG'].concat (dale.go (arguments, function (v) {return v})))};
// *** GIZ ***
giz.redis = redis;
giz.config.expires = 7 * 24 * 60 * 60;
// TODO: add this to giz
giz.loginOAuth = function (user, callback) {
require ('bcryptjs').genSalt (20, function (error, result) {
if (error) return callback (error);
giz.db.set ('session', result, user, function (error) {
callback (error, result);
});
});
}
// *** REDIS EXTENSIONS ***
redis.keyscan = function (s, match, cursor, keys) {
if (! cursor) cursor = 0;
if (! keys) keys = {};
redis.scan (cursor, 'MATCH', match, function (error, result) {
if (error) return s.next (null, error);
cursor = result [0];
dale.go (result [1], function (key) {
keys [key] = true;
});
if (cursor !== '0') return redis.keyscan (s, match, cursor, keys);
s.next (dale.keys (keys));
});
}
var Redis = function (s, action) {
redis [action].apply (redis, [].slice.call (arguments, 2).concat (function (error, data) {
if (error) s.next (null, error);
else s.next (data);
}));
}
// *** NOTIFICATIONS ***
var aclog = {
initialize: function (logProcessingFunction) {
aclog.send = function (log, CB) {
CB = CB || clog;
var freshCookie;
var login = function (cb) {
freshCookie = true;
hitit.one ({}, {
host: SECRET.aclog.host,
https: SECRET.aclog.https,
method: 'post',
path: SECRET.aclog.basepath + '/auth/login',
body: {username: SECRET.aclog.username, password: SECRET.aclog.password, timezone: new Date ().getTimezoneOffset ()}
}, function (error, data) {
if (error) return CB (error);
aclog.cookie = data.headers ['set-cookie'] [0];
aclog.csrf = data.body.csrf;
cb ();
});
}
var send = function () {
if (type (log) !== 'object') return CB ({error: 'Log must be an object but instead is of type ' + type (log), log: log});
hitit.one ({}, {
host: SECRET.aclog.host,
https: SECRET.aclog.https,
method: 'post',
path: SECRET.aclog.basepath + '/data',
headers: {cookie: aclog.cookie},
body: {csrf: aclog.csrf, log: logProcessingFunction ? logProcessingFunction (log) : log}
}, function (error) {
if (error && error.code === 403 && ! freshCookie) return login (send);
if (error) return CB (error);
CB ();
});
}
if (! aclog.cookie) login (send);
else send ();
}
}
}
aclog.initialize (function (log) {
log = dale.obj (log, function (v, k) {
var sv = type (v) === 'string' ? v : JSON.stringify (v);
var length = (sv || '').length;
if (length > 5000) v = sv.slice (0, 2500) + ' [' + (length - 5000) + ' CHARACTERS OMITTED' + '] ' + sv.slice (-2500);
return [k, v];
});
log.application = 'tagaway';
log.environment = ENV;
return log;
});
var notify = function (s, message) {
if (! ENV || ! SECRET.aclog.username) {
clog (new Date ().toISOString (), message);
return s.next ();
}
aclog.send (message, function (error) {
if (error) return s.next (null, error);
else s.next ();
});
}
// *** ON UNCAUGHT EXCEPTION, REPORT AND CLOSE SERVER ***
var server;
process.on ('uncaughtException', function (error, origin) {
a.seq ([
[notify, {priority: 'critical', type: 'server error', error: error, stack: error.stack, origin: origin}],
function (s) {
process.exit (1);
}
]);
});
// *** SENDMAIL ***
var sendmail = function (s, o) {
o.from1 = o.from1 || CONFIG.email.name;
o.from2 = o.from2 || CONFIG.email.address;
var parameters = {
from: o.from1 + ' <' + o.from2 + '>',
to: o.to1 + ' <' + o.to2 + '>',
replyTo: o.from2,
subject: o.subject,
html: lith.g (o.message),
};
if (! ENV) {
clog (new Date ().toISOString (), 'sendmail', parameters);
return s.next ();
}
mailer.sendMail (parameters, function (error) {
if (error) notify (s, {priority: 'critical', type: 'mailer error', error: error, options: o});
else s.next ();
});
}
// *** KABOOT ***
var k = function (s) {
var command = [].slice.call (arguments, 1);
var output = {stdout: '', stderr: '', command: command};
var options = {};
var commands = dale.fil (command.slice (1), undefined, function (command) {
if (type (command) !== 'object' || ! command.env) return command;
options.env = command.env;
});
var proc = require ('child_process').spawn (command [0], commands, options);
var wait = 3;
var done = function () {
if (--wait > 0) return;
if (output.code === 0) s.next (output);
else s.next (0, output);
}
dale.go (['stdout', 'stderr'], function (v) {
proc [v].on ('data', function (chunk) {
output [v] += chunk;
});
proc [v].on ('end', done);
});
proc.on ('error', function (error) {
output.err += error + ' ' + error.stack;
done ();
});
proc.on ('exit', function (code, signal) {
output.code = code;
output.signal = signal;
done ();
});
}
// *** S3 ***
var s3 = new (require ('aws-sdk')).S3 ({
apiVersion: '2006-03-01',
sslEnabled: true,
credentials: {accessKeyId: SECRET.s3.accessKeyId, secretAccessKey: SECRET.s3.secretAccessKey},
params: {Bucket: SECRET.s3.piv.bucketName},
region: SECRET.s3.region
});
// *** HELPERS ***
var H = {};
// Adapted from https://www.regular-expressions.info/email.html
H.email = /^(?=[A-Z0-9][A-Z0-9@._%+-]{5,253}$)[A-Z0-9._%+-]{1,64}@(?:(?=[A-Z0-9-]{1,63}\.)[A-Z0-9]+(?:-[A-Z0-9]+)*\.){1,8}[A-Z]{2,63}$/i
H.trim = function (string) {
return string.replace (/^\s+|\s+$/g, '').replace (/\s+/g, ' ');
}
H.log = function (s, username, ev) {
ev.t = Date.now ();
Redis (s, 'lpush', 'ulog:' + username, teishi.str (ev));
}
H.hash = function (string) {
return hash (string) + '';
}
H.isDateTag = function (tag) {
return !! tag.match (/^d::/);
}
H.isGeoTag = function (tag) {
return !! tag.match (/^g::/);
}
H.isUserTag = function (tag) {
tag = H.trim (tag);
return tag.length > 0 && ! tag.match (/^[a-z]::/);
}
H.shuffleArray = function (array) {
if (array.length === 0) return array;
dale.go (dale.times (array.length - 1, array.length - 1, -1), function (k) {
var randomIndex = Math.floor (Math.random () * (k + 1));
var temp = array [k];
array [k] = array [randomIndex];
array [randomIndex] = temp;
});
return array;
}
H.getGeotags = function (s, lat, lon) {
var countryCodes = {'AF':'Afghanistan','AX':'Åland Islands','AL':'Albania','DZ':'Algeria','AS':'American Samoa','AD':'Andorra','AO':'Angola','AI':'Anguilla','AQ':'Antarctica','AG':'Antigua and Barbuda','AR':'Argentina','AM':'Armenia','AW':'Aruba','AU':'Australia','AT':'Austria','AZ':'Azerbaijan','BS':'Bahamas','BH':'Bahrain','BD':'Bangladesh','BB':'Barbados','BY':'Belarus','BE':'Belgium','BZ':'Belize','BJ':'Benin','BM':'Bermuda','BT':'Bhutan','BO':'Bolivia, Plurinational State of','BQ':'Bonaire, Sint Eustatius and Saba','BA':'Bosnia and Herzegovina','BW':'Botswana','BV':'Bouvet Island','BR':'Brazil','IO':'British Indian Ocean Territory','BN':'Brunei Darussalam','BG':'Bulgaria','BF':'Burkina Faso','BI':'Burundi','KH':'Cambodia','CM':'Cameroon','CA':'Canada','CV':'Cape Verde','KY':'Cayman Islands','CF':'Central African Republic','TD':'Chad','CL':'Chile','CN':'China','CX':'Christmas Island','CC':'Cocos (Keeling) Islands','CO':'Colombia','KM':'Comoros','CG':'Congo','CD':'Congo, the Democratic Republic of the','CK':'Cook Islands','CR':'Costa Rica','CI':'Côte d\'Ivoire','HR':'Croatia','CU':'Cuba','CW':'Curaçao','CY':'Cyprus','CZ':'Czech Republic','DK':'Denmark','DJ':'Djibouti','DM':'Dominica','DO':'Dominican Republic','EC':'Ecuador','EG':'Egypt','SV':'El Salvador','GQ':'Equatorial Guinea','ER':'Eritrea','EE':'Estonia','ET':'Ethiopia','FK':'Falkland Islands (Malvinas)','FO':'Faroe Islands','FJ':'Fiji','FI':'Finland','FR':'France','GF':'French Guiana','PF':'French Polynesia','TF':'French Southern Territories','GA':'Gabon','GM':'Gambia','GE':'Georgia','DE':'Germany','GH':'Ghana','GI':'Gibraltar','GR':'Greece','GL':'Greenland','GD':'Grenada','GP':'Guadeloupe','GU':'Guam','GT':'Guatemala','GG':'Guernsey','GN':'Guinea','GW':'Guinea-Bissau','GY':'Guyana','HT':'Haiti','HM':'Heard Island and McDonald Islands','VA':'Holy See (Vatican City State)','HN':'Honduras','HK':'Hong Kong','HU':'Hungary','IS':'Iceland','IN':'India','ID':'Indonesia','IR':'Iran, Islamic Republic of','IQ':'Iraq','IE':'Ireland','IM':'Isle of Man','IL':'Israel','IT':'Italy','JM':'Jamaica','JP':'Japan','JE':'Jersey','JO':'Jordan','KZ':'Kazakhstan','KE':'Kenya','KI':'Kiribati','KP':'Korea, Democratic People\'s Republic of','KR':'Korea, Republic of','KW':'Kuwait','KG':'Kyrgyzstan','LA':'Lao People\'s Democratic Republic','LV':'Latvia','LB':'Lebanon','LS':'Lesotho','LR':'Liberia','LY':'Libya','LI':'Liechtenstein','LT':'Lithuania','LU':'Luxembourg','MO':'Macao','MK':'Macedonia, the Former Yugoslav Republic of','MG':'Madagascar','MW':'Malawi','MY':'Malaysia','MV':'Maldives','ML':'Mali','MT':'Malta','MH':'Marshall Islands','MQ':'Martinique','MR':'Mauritania','MU':'Mauritius','YT':'Mayotte','MX':'Mexico','FM':'Micronesia, Federated States of','MD':'Moldova, Republic of','MC':'Monaco','MN':'Mongolia','ME':'Montenegro','MS':'Montserrat','MA':'Morocco','MZ':'Mozambique','MM':'Myanmar','NA':'Namibia','NR':'Nauru','NP':'Nepal','NL':'Netherlands','NC':'New Caledonia','NZ':'New Zealand','NI':'Nicaragua','NE':'Niger','NG':'Nigeria','NU':'Niue','NF':'Norfolk Island','MP':'Northern Mariana Islands','NO':'Norway','OM':'Oman','PK':'Pakistan','PW':'Palau','PS':'Palestine, State of','PA':'Panama','PG':'Papua New Guinea','PY':'Paraguay','PE':'Peru','PH':'Philippines','PN':'Pitcairn','PL':'Poland','PT':'Portugal','PR':'Puerto Rico','QA':'Qatar','RE':'Réunion','RO':'Romania','RU':'Russian Federation','RW':'Rwanda','BL':'Saint Barthélemy','SH':'Saint Helena, Ascension and Tristan da Cunha','KN':'Saint Kitts and Nevis','LC':'Saint Lucia','MF':'Saint Martin (French part)','PM':'Saint Pierre and Miquelon','VC':'Saint Vincent and the Grenadines','WS':'Samoa','SM':'San Marino','ST':'Sao Tome and Principe','SA':'Saudi Arabia','SN':'Senegal','RS':'Serbia','SC':'Seychelles','SL':'Sierra Leone','SG':'Singapore','SX':'Sint Maarten (Dutch part)','SK':'Slovakia','SI':'Slovenia','SB':'Solomon Islands','SO':'Somalia','ZA':'South Africa','GS':'South Georgia and the South Sandwich Islands','SS':'South Sudan','ES':'Spain','LK':'Sri Lanka','SD':'Sudan','SR':'Suriname','SJ':'Svalbard and Jan Mayen','SZ':'Swaziland','SE':'Sweden','CH':'Switzerland','SY':'Syrian Arab Republic','TW':'Taiwan, Province of China','TJ':'Tajikistan','TZ':'Tanzania, United Republic of','TH':'Thailand','TL':'Timor-Leste','TG':'Togo','TK':'Tokelau','TO':'Tonga','TT':'Trinidad and Tobago','TN':'Tunisia','TR':'Turkey','TM':'Turkmenistan','TC':'Turks and Caicos Islands','TV':'Tuvalu','UG':'Uganda','UA':'Ukraine','AE':'United Arab Emirates','GB':'United Kingdom','US':'United States','UM':'United States Minor Outlying Islands','UY':'Uruguay','UZ':'Uzbekistan','VU':'Vanuatu','VE':'Venezuela, Bolivarian Republic of','VN':'Viet Nam','VG':'Virgin Islands, British','VI':'Virgin Islands, U.S.','WF':'Wallis and Futuna','EH':'Western Sahara','YE':'Yemen','ZM':'Zambia','ZW':'Zimbabwe'};
redis.georadius ('geo', lon, lat, 15, 'km', 'count', 100, 'asc', function (error, data) {
if (error) return s.next (null, error);
if (! data.length) return s.next ([]);
var biggestPop = 0, geotags = [];
dale.go (data, function (item) {
item = item.split (':');
var pop = parseInt (item [1]);
if (pop <= biggestPop) return;
biggestPop = pop;
geotags = ['g::' + item [0], 'g::' + item [2]];
});
s.next (geotags);
});
}
// General policy on async helpers: unless a specific error is caught, leave it to the calling context to decide whether to put an error handler or not.
// Note: this is not a recursive mkdir, if you want to make folder /a/b/c, both /a and /a/b must exist!
H.mkdirif = function (s, path) {
a.stop (s, [k, 'test', '-d', path], function (s) {
// TODO: check error code
a.seq (s, [k, 'mkdir', path]);
});
}
H.unlink = function (s, path, checkExistence) {
if (! checkExistence) return a.seq (s, [a.make (fs.unlink), path]);
a.seq (s, [
[function (s) {
fs.stat (path, function (error) {
if (! error) return s.next (true);
if (error.code === 'ENOENT') return s.next (false);
s.next (undefined, error);
});
}],
function (s) {
if (s.last === true) a.make (fs.unlink) (s, path);
else s.next ();
}
]);
}
H.thumbPic = function (s, invalidHandler, piv, path, heic_path) {
var max = Math.max (piv.dimw, piv.dimh);
// If we have a gif, we only make a small thumbnail, since we'll show the full gif when opening the piv.
if (piv.format === 'gif') s.thumbS = uuid ();
else if (piv.format !== 'jpeg' || piv.deg) {
// If piv is not a jpeg, we need to create a jpeg thumbnail to show in the browser.
// Also, if piv has rotation metadata, we need to create a thumbnail with no rotation metadata, to have a thumbnail with no metadata and thus avoid some browsers doing double rotation (one done by the metadata, another one by our interpretation of it).
s.thumbS = uuid ();
// If piv has a dimension larger than CONFIG.thumbSizes.S, we'll also need a config.thumbSizes.M thumbnail.
if (max > CONFIG.thumbSizes.S) s.thumbM = uuid ();
}
else {
if (max > CONFIG.thumbSizes.S) s.thumbS = uuid ();
if (max > CONFIG.thumbSizes.M) s.thumbM = uuid ();
}
var multiframeFormat = inc (['gif', 'tiff', 'webp'], piv.format);
a.seq (s, dale.go (['S', 'M'], function (size) {
if (! s ['thumb' + size]) return [];
// In the case of thumbnails done for stripping rotation metadata or non jpeg/png formats, we don't go over 100% if the piv is smaller than the desired thumbnail size.
var percentage = Math.min (Math.round (CONFIG.thumbSizes [size] / max * 100), 100);
var targetFormat = 'jpeg';
if (piv.format === 'gif' && size === 'M') targetFormat = 'gif';
return [
[invalidHandler, [k, 'convert', (heic_path || path) + (multiframeFormat ? '[0]' : ''), '-quality', 90, '-thumbnail', percentage + '%', Path.join (Path.dirname (path), s ['thumb' + size] + '.' + targetFormat)]],
[a.make (fs.rename), Path.join (Path.dirname (path), s ['thumb' + size] + '.' + targetFormat), Path.join (Path.dirname (path), s ['thumb' + size])],
[a.make (fs.stat), Path.join (Path.dirname (path), s ['thumb' + size])],
function (s) {
s ['bythumb' + size] = s.last.size;
s.next ();
}
];
}));
}
H.thumbVid = function (s, invalidHandler, piv, path) {
var askance = piv.deg === 90 || piv.deg === -90;
var max = Math.max (piv.dimw, piv.dimh);
s.thumbS = uuid ();
// If video has a dimension larger than CONFIG.thumbSizes.S, we'll also need a CONFIG.thumbSizes.M thumbnail.
if (max > CONFIG.thumbSizes.S) s.thumbM = uuid ();
a.seq (s, dale.go (['S', 'M'], function (size) {
if (! s ['thumb' + size]) return [];
// In the case of thumbnails done for very small videos, do not go over 100%.
var percentage = Math.min (Math.round (CONFIG.thumbSizes [size] / max * 100), 100);
var width = Math.round (piv.dimw * percentage / 100);
var height = Math.round (piv.dimh * percentage / 100);
return [
// If picture is askance, switch width and height, otherwise the thumbnail will be deformed.
[invalidHandler, [k, 'ffmpeg', '-i', path, '-vframes', '1', '-an', '-s', (askance ? height : width) + 'x' + (askance ? width : height), Path.join (Path.dirname (path), s ['thumb' + size] + '.jpg')]],
[a.make (fs.rename), Path.join (Path.dirname (path), s ['thumb' + size] + '.jpg'), Path.join (Path.dirname (path), s ['thumb' + size])],
[a.make (fs.stat), Path.join (Path.dirname (path), s ['thumb' + size])],
function (s) {
s ['bythumb' + size] = s.last.size;
s.next ();
}
];
}));
}
H.encrypt = function (path, cb) {
// https://github.com/luke-park/SecureCompatibleEncryptionExamples/blob/master/JavaScript/SCEE-Node.js
fs.readFile (path, function (error, file) {
if (error) return cb (error);
var nonce = crypto.randomBytes (CONFIG.crypto.nonceLength);
var cipher = crypto.createCipheriv (CONFIG.crypto.algorithm, SECRET.crypto.password, nonce);
var ciphertext = Buffer.concat ([cipher.update (file), cipher.final ()]);
cb (null, Buffer.concat ([nonce, ciphertext, cipher.getAuthTag ()]));
});
}
H.decrypt = function (data) {
var nonce = data.slice (0, CONFIG.crypto.nonceLength);
var ciphertext = data.slice (CONFIG.crypto.nonceLength, data.length - CONFIG.crypto.tagLength);
var tag = data.slice (- CONFIG.crypto.tagLength);
var cipher = crypto.createDecipheriv (CONFIG.crypto.algorithm, SECRET.crypto.password, nonce);
cipher.setAuthTag (tag);
return Buffer.concat ([cipher.update (ciphertext), cipher.final ()]);
}
H.s3put = function (s, key, path) {
a.stop (s, [
[a.make (H.encrypt), path],
function (s) {
s.time = Date.now ();
s.next ();
},
[a.get, a.make (s3.upload, s3), {Key: key, Body: '@last'}],
function (s) {
H.stat.w (s, 'max', 'ms-s3put', Date.now () - s.time);
},
[a.make (s3.headObject, s3), {Key: key}],
]);
}
H.s3get = function (s, key) {
s3.getObject ({Key: key}, function (error, data) {
if (error) return s.next (null, error);
s.next (H.decrypt (data.Body));
});
}
H.s3del = function (s, keys) {
var counter = 0, t = Date.now ();
if (type (keys) === 'string') keys = [keys];
if (keys.length === 0) return s.next ();
var batch = function () {
s3.deleteObjects ({Delete: {Objects: dale.go (keys.slice (counter * 1000, (counter + 1) * 1000), function (key) {
return {Key: key}
})}}, function (error) {
if (error) return s.next (null, error);
if (++counter === Math.ceil (keys.length / 1000)) {
H.stat.w (s, 'max', 'ms-s3del', Date.now () - t);
}
else batch ();
});
}
batch ();
}
H.s3list = function (s, prefix) {
var output = [];
var fetch = function (marker) {
s3.listObjects ({Prefix: prefix, Marker: marker}, function (error, data) {
if (error) return s.next (null, error);
output = output.concat (data.Contents);
delete data.Contents;
if (! data.IsTruncated) return s.next (dale.go (output, function (v) {return {key: v.Key, size: v.Size}}));
fetch (output [output.length - 1].Key);
});
}
fetch ();
}
H.s3queue = function (s, op, username, key, path) {
a.seq (s, [
[Redis, 'rpush', 's3:queue', JSON.stringify ({op: op, username: username, key: key, path: path, t: Date.now ()})],
function (s) {
if (s.error) return notify (s, {priority: 'critical', type: 'redis error s3queue', error: s.error});
// We call the next function.
s.next ();
// We trigger s3exec.
H.s3exec ();
}
]);
}
// Up to 3600 simultaneous operations (actually, per second, but simultaneous will do, since it's more conservative and easier to measure). But it's conservative only if the greatest share of operations are over one second in length.
// We only do 50 simultaneous operations for the sake of the network card of the server.
// https://docs.aws.amazon.com/AmazonS3/latest/dev/optimizing-performance.html
// Queue items are processed in order with regards to the *start* of it, not the whole thing (otherwise, we would wait for each to be done - for implementing this, we can set LIMIT to 1).
H.s3exec = function () {
// If there's no items on the queue, or if we're over the maximum: do nothing.
// Otherwise, increment s3:proc and LPOP the first element of the queue
redis.eval ('if redis.call ("llen", "s3:queue") == 0 then return nil end if (tonumber (redis.call ("get", "s3:proc")) or 0) >= 50 then return nil end redis.call ("incr", "s3:proc"); return redis.call ("lpop", "s3:queue")', 0, function (error, next) {
if (error) return notify (a.creat (), {priority: 'critical', type: 'redis error s3exec', error: error});
if (! next) return;
next = JSON.parse (next);
/* Possible valid sequences
- delete -> put? No, because put would be started before delete, otherwise it would be a genuine 404.
- put uploading -> delete: let the put delete the file it just uploaded.
- put ready -> delete: delete is in charge of deleting the file.
*/
var actions;
if (next.op === 'put') actions = [
[Redis, 'hset', 's3:files', next.key, 'true'],
[a.set, 'upload', [H.s3put, next.key, next.path]],
[Redis, 'hexists', 's3:files', next.key],
function (s) {
// If a delete operation removed the file while we were uploading it, we delete it from S3. No need to update the stats.
if (! s.last) return a.seq (s, [H.s3del, next.key]);
var bys3 = s.upload.ContentLength;
a.seq (s, [
// update S3 & the stats
[Redis, 'hset', 's3:files', next.key, bys3],
[H.stat.w, [
['flow', 'bys3', bys3],
['flow', 'bys3-' + next.username, bys3],
]]
]);
}
];
if (next.op === 'del') actions = [
[Redis, 'hget', 's3:files', next.key],
function (s) {
// File is being uploaded or shouldn't be uploaded because it's invalid, just remove entry.
if (s.last === 'true') return Redis (s, 'hdel', 's3:files', next.key);
// File has already been uploaded.
var bys3 = parseInt (s.last);
a.seq (s, [
[H.s3del, next.key],
[Redis, 'hdel', 's3:files', next.key],
[H.stat.w, [
['flow', 'bys3', - bys3],
['flow', 'bys3-' + next.username, - bys3],
]],
]);
}
];
a.stop ([
actions,
[Redis, 'decr', 's3:proc'],
H.s3exec
], function (s, error) {
if (error) notify (s, {priority: 'critical', type: 's3exec error', error: error, operation: next});
redis.decr ('s3:proc', function (error) {
if (error) return notify (a.creat (), {priority: 'critical', type: 'redis error s3exec', error: error});
H.s3exec ();
});
});
});
}
H.pad = function (v) {return v < 10 ? '0' + v : v}
H.deletePiv = function (s, id, username) {
a.stop (s, [
[function (s) {
var multi = redis.multi ();
multi.hgetall ('piv:' + id);
multi.smembers ('pivt:' + id);
multi.smembers ('sho:' + username);
mexec (s, multi);
}],
function (s) {
s.piv = s.last [0];
s.tags = s.last [1];
s.sho = s.last [2];
if (! s.piv || username !== s.piv.owner) return s.next (0, 'nf');
H.s3queue (s, 'del', username, Path.join (H.hash (username), id));
},
function (s) {
var thumbs = [];
if (s.piv.thumbS) thumbs.push (s.piv.thumbS);
if (s.piv.thumbM) thumbs.push (s.piv.thumbM);
a.fork (s, thumbs, function (v) {
return [H.unlink, Path.join (CONFIG.basepath, H.hash (username), v)];
});
},
[H.unlink, Path.join (CONFIG.basepath, H.hash (username), id)],
function (s) {
if (! s.piv.vid || s.piv.vid === '1' || s.piv.vid.match (/^pending/) || s.piv.vid.match (/^error/)) return s.next ();
// Delete mp4 version of non-mp4 video
H.unlink (s, Path.join (CONFIG.basepath, H.hash (username), s.piv.vid));
},
[a.set, 'sharedHashes', [H.getSharedHashes, username]],
function (s) {
var multi = redis.multi ();
multi.del ('piv:' + s.piv.id);
multi.del ('pivt:' + s.piv.id);
if (s.piv.thumbS) multi.del ('thu:' + s.piv.thumbS);
if (s.piv.thumbM) multi.del ('thu:' + s.piv.thumbM);
multi.hdel ('hash:' + s.piv.owner, s.piv.hash);
multi.hdel ('hashorig:' + s.piv.owner, s.piv.originalHash);
multi.sadd ('hashdel:' + s.piv.owner, s.piv.hash);
multi.sadd ('hashorigdel:' + s.piv.owner, s.piv.originalHash);
multi.srem ('hashid:' + s.piv.hash, s.piv.id);
if (s.piv.providerHash) {
var providerHash = s.piv.providerHash.split (':');
multi.srem ('hash:' + s.piv.owner + ':' + providerHash [0], providerHash [1]);
multi.sadd ('hashdel:' + s.piv.owner + ':' + providerHash [0], providerHash [1]);
}
// If the piv is deleted and the user has another piv shared with them that has the same hash, we will create hashtag and taghash entries (hashtag:USERNAME:HASH and taghash:USERNAME:TAG)
if (inc (s.sharedHashes, s.piv.hash)) dale.go (s.tags, function (tag) {
if (! H.isUserTag (tag)) return;
multi.sadd ('hashtag:' + username + ':' + s.piv.hash, tag)
multi.sadd ('taghash:' + username + ':' + tag, s.piv.hash);
});
dale.go (s.tags.concat (['a::', 'u::', 'o::', 'v::']), function (tag) {
multi.srem ('tag:' + s.piv.owner + ':' + tag, s.piv.id);
});
multi.del ('querycache:' + username);
mexec (s, multi);
},
[a.get, H.tagCleanup, username, '@tags', [id], '@sho'],
function (s) {
H.stat.w (s, [
// The minus sign coerces the strings into numbers.
['flow', 'byfs', - s.piv.byfs - (s.piv.bythumbS || 0) - (s.piv.bythumbM || 0) - (s.piv.bymp4 || 0)],
['flow', 'byfs-' + username, - s.piv.byfs - (s.piv.bythumbS || 0) - (s.piv.bythumbM || 0) - (s.piv.bymp4 || 0)],
['flow', s.piv.vid ? 'vids' : 'pics', -1],
['flow', 'format-' + s.piv.format, -1],
s.piv.bythumbS ? ['flow', 'thumbS', -1] : [],
s.piv.bythumbM ? ['flow', 'thumbM', -1] : [],
]);
}
]);
}
// If it returns false, piv does not exist or user has no access; otherwise, returns the piv itself.
H.hasAccess = function (S, username, pivId, channelId) {
a.stop ([
[function (s) {
if (! channelId) return s.next ();
Redis (s, 'lrange', 'channel:' + username + ':' + channelId, 0, -1);
}],
function (s) {
if (! channelId) return s.next ();
if (! s.last) return S.next (false);
var pivInChannel = dale.stop (s.last, true, function (v) {
return v.piv === pivId;
});
s.next ();
},
[Redis, 'hgetall', 'piv:' + pivId],
function (s) {
if (! s.last) return S.next (false);
s.piv = s.last;
if (s.piv.owner === username) return S.next (s.piv);
if (channelId) return S.next (s.piv); // If we're here, we did the check that the piv is in the channel and therefore accessible, so we also send it back.
Redis (s, 'smembers', 'pivt:' + pivId);
},
function (s) {
if (s.last.length === 0) return S.next (false);
var multi = redis.multi ();
dale.go (s.last, function (tag) {
multi.sismember ('shm:' + username, s.piv.owner + ':' + tag);
});
mexec (s, multi);
},
function (s) {
S.next (dale.stop (s.last, true, function (v) {
return !! v
}) ? s.piv : false);
}
], function (s, error) {
S.next (undefined, error);
});
}
// Returns an output of the shape: {isVid: UNDEFINED|true, mimetype: STRING, dimw: INT, dimh: INT, format: STRING, deg: UNDEFINED|90|180|-90, dates: {...}, date: INTEGER, dateSource: STRING, loc: UNDEFINED|[INT, INT]}
// If onlyLocation flag is passed, output will only have the `loc` field.
H.getMetadata = function (s, path, onlyLocation, lastModified, name) {
var output = {};
a.seq (s, [
[k, 'exiftool', path],
function (s) {
dale.stop (s.last.stdout.split ('\n'), true, function (line) {
if (! line.match (/^GPS Position\s+:/)) return;
var originalLine = line;
line = (line.split (':') [1]).split (',');
var lat = line [0].replace ('deg', '').replace ('\'', '').replace ('"', '').split (/\s+/);
var lon = line [1].replace ('deg', '').replace ('\'', '').replace ('"', '').split (/\s+/);
lat = (lat [4] === 'S' ? -1 : 1) * (parseFloat (lat [1]) + parseFloat (lat [2]) / 60 + parseFloat (lat [3]) / 3600);
lon = (lon [4] === 'W' ? -1 : 1) * (parseFloat (lon [1]) + parseFloat (lon [2]) / 60 + parseFloat (lon [3]) / 3600);
if (isNaN (lat) || lat < -90 || lat > 90) lat = undefined;
if (isNaN (lon) || lon < -180 || lon > 180) lon = undefined;
// We set location only if both latitude and longitude are valid
if (lat && lon) output.loc = [lat, lon];
return true;
});
if (onlyLocation) s.next ();
else s.next (s.last.stdout.split ('\n'));
},
function (s) {
if (onlyLocation) return s.next ();
output.dates = {};
// We first detect the mimetype to ascertain whether this is a vid or a pic
dale.stopNot (s.last, undefined, function (line) {
if (! line.match (/^MIME Type\s+:/)) return;
output.mimetype = line.split (':') [1].trim ();
if (line.match (/^MIME Type\s+:\s+video\//)) output.isVid = true;
return true;
});
var error = dale.stopNot (s.last, undefined, function (line) {
if (line.match (/^Warning\s+:/)) {
var exceptions = new RegExp (['minor', 'Invalid EXIF text encoding', 'Bad IFD1 directory', 'Bad IFD2 directory', 'Bad length ICC_Profile', 'Invalid CanonCameraSettings data', 'Truncated', 'Invalid atom size', 'Non-standard header for APP1 XMP segment'].join ('|'));
if (line.match (exceptions)) return;
return line;
}
else if (line.match (/^Error\s+:/)) return line;
else if (line.match (/date/i)) {
var key = line.split (':') [0].trim ();
if (! key.match (/\bdate\b/i)) return;
if (key.match (/gps|profile|manufacture|extension|firmware/i)) return;
// Ignore metadata fields related to the newly created file itself, because they have the same date as the upload itself and they are irrelevant for dating the piv
if (inc (['File Modification Date/Time', 'File Access Date/Time', 'File Inode Change Date/Time'], key)) return;
var value = line.split (':').slice (1).join (':').trim ();
// If value doesn't start with a number or only contains zeroes, we ignore it.
if (! value.match (/^\d/) || ! value.match (/[1-9]/)) return;
output.dates [key] = value;
}
else if (line.match (/^File Type\s+:/)) {
output.format = line.split (':') [1].trim ().toLowerCase ();
if (output.format === 'extended webp') output.format = 'webp';
}
else if (! output.isVid && line.match (/^Image Width\s+:/)) output.dimw = parseInt (line.split (':') [1].trim ());
else if (! output.isVid && line.match (/^Image Height\s+:/)) output.dimh = parseInt (line.split (':') [1].trim ());
else if ((! output.isVid && line.match (/^Orientation\s+:/)) || (output.isVid && line.match (/Rotation\s+:/))) {
if (line.match ('270')) output.deg = -90;
if (line.match ('90')) output.deg = 90;
if (line.match ('180')) output.deg = 180;
}
});
if (error) return s.next (null, {error: error});
if (! output.isVid) return s.next ();
a.seq (s, [
[k, 'ffprobe', '-i', path, '-show_streams'],
function (s) {
var ffprobeMetadata = (s.last.stdout + '\n' + s.last.stderr).split ('\n');
var formats = [];
// ffprobe metadata is only used to detect width, height and the names of the codecs of the video & audio streams
dale.go (ffprobeMetadata, function (line) {
if (line.match (/^width=\d+$/)) output.dimw = parseInt (line.split ('=') [1]);
if (line.match (/^height=\d+$/)) output.dimh = parseInt (line.split ('=') [1]);
if (line.match (/^codec_name=/)) {
var format = line.split ('=') [1];
if (format !== 'unknown') formats.push (format);
}
});
if (formats.length) output.format += ':' + formats.sort ().join ('/');
s.next ();
}
]);
},
function (s) {
if (onlyLocation) return s.next (output);
if (! output.format) return s.next (null, {error: 'Missing format'});
if (! output.mimetype) return s.next (null, {error: 'Missing mimetype'});
// Despite our trust in exiftool and ffprobe, we make sure that the required output fields are present, but only for files that belong to supported formats
if (inc (CONFIG.allowedFormats, output.mimetype)) {
if (type (output.dimw) !== 'integer' || output.dimw < 1) return s.next (null, {error: 'Invalid width: ' + output.dimw});
if (type (output.dimh) !== 'integer' || output.dimh < 1) return s.next (null, {error: 'Invalid height: ' + output.dimh});
}
// All dates are considered to be UTC, unless they explicitly specify a timezone.
// The underlying server must be in UTC to not add a timezone offset to dates that specify no timezone.
// The client also ignores timezones, except for applying a timezone offset for the `last modified` metadata of the piv in the filesystem when it is uploaded.
output.dates ['upload:lastModified'] = lastModified;
if (H.dateFromName (name) !== -1) output.dates ['upload:fromName'] = name;
var validDates = dale.obj (output.dates, function (date, key) {
var parsed = key.match ('fromName') ? H.dateFromName (date) : H.parseDate (date);
// We ignore invalid dates (-1) or dates before the Unix epoch (< 0).
if (parsed > -1) return [key, parsed];
});
// We first try to find a valid Date/Time Original, if it's the case, then we will use that date.
if (validDates ['Date/Time Original']) {
output.date = validDates ['Date/Time Original'];
output.dateSource = 'Date/Time Original';
}
// Otherwise, of all the valid dates, we will set the oldest one.
else {
dale.go (validDates, function (date, key) {
if (output.date && output.date <= date) return;
output.date = date;
output.dateSource = key;
});
}
// If the date source is upload:fromName and there's another valid date entry on the same date (but a later time), we use the latest one of them. This avoids files with a name that contains a date without time to override the date + time combination of another metadata tag.
if (output.dateSource === 'upload:fromName') {
var adjustedDate;
dale.go (validDates, function (date, key) {
if (date - output.date < 1000 * 60 * 60 * 24) {
if (! adjustedDate) adjustedDate = [key, date];
else {
if (date < adjustedDate [1]) adjustedDate = [key, date];
}
}
});
if (adjustedDate) {
output.dateSource = adjustedDate [0];
output.date = adjustedDate [1];
}
}
s.next (output);
}
]);
}
H.getUploads = function (s, username, filters, maxResults, listAlreadyUploaded) {
filters = filters || {};
a.seq (s, [
// This function is very expensive because of the call below.
[Redis, 'lrange', 'ulog:' + username, 0, -1],
function (s) {
var uploads = {}, completed = 0;
if (filters.id) maxResults = 1;
dale.stop (s.last, true, function (log) {
log = JSON.parse (log);
if (log.ev !== 'upload') return;
// We can filter out uploads by id or provider.
if (filters.id && log.id !== filters.id) return;
if (filters.provider && log.provider !== filters.provider) return;
if (filters.provider === null && log.provider !== undefined) return;
if (! uploads [log.id]) {
// If there are already enough results, don't add further results.
if (maxResults && dale.keys (uploads).length === maxResults) return;
uploads [log.id] = {id: log.id};
}
var upload = uploads [log.id];
if (listAlreadyUploaded && ! upload.listAlreadyUploaded) upload.listAlreadyUploaded = [];
if (log.provider && ! upload.provider) upload.provider = log.provider;
if (log.type === 'complete' || log.type === 'cancel' || log.type === 'noCapacity' || log.type === 'error') {
if (! upload.end) upload.end = log.t;
// For complete and error, type of log equals upload.status
// We check if status is already set in case an error comes after either a cancel or a completed
if (! upload.status) upload.status = {cancel: 'cancelled', noCapacity: 'error'} [log.type] || log.type;
if (log.type === 'noCapacity') upload.error = 'You have run out of space!';
// If there's already another error for this upload, we keep it instead of overwriting to show the latest one
if (log.type === 'error' && ! upload.error) upload.error = log.error;
}
else if (log.type === 'providerError') {
if (! upload.providerErrors) upload.providerErrors = [];
upload.providerErrors.push (log.error);
}
else if (log.type === 'wait') {
if (! upload.lastActivity) upload.lastActivity = log.t;
}
else if (log.type === 'start') {
if (! upload.status) {
// If current upload has had no activity in over ten minutes, we consider it stalled. For tests, we only wait three seconds.
var maxInactivity = ENV ? 1000 * 60 * 10 : 1000 * 3;
// We use log.t instead of log.id in case this is an import, because the id of the import might be quite older than the start of its upload process.
if (Date.now () > maxInactivity + (upload.lastActivity || log.t)) {
upload.status = 'stalled';
upload.end = (upload.lastActivity || log.t) + maxInactivity;
}
else upload.status = 'uploading';
}
// We only put the tags added on the `start` event, instead of using those on the `ok` or `repeated` events.
['total', 'tooLarge', 'unsupported', 'alreadyImported', 'tags'].map (function (key) {
// If there are unsupported files that were attempted to be uploaded (and not detected by the client), we concatenate instead of overwriting what's already there.
if (key === 'unsupported' && upload.unsupported && log.unsupported) upload.unsupported = upload.unsupported.concat (log.unsupported);
else if (log [key] !== undefined) upload [key] = log [key];
});
completed++;
// If we completed enough uploads as required, stop the process.
if (maxResults && completed === maxResults) return true;
}
else if (log.type === 'ok') {
if (! upload.lastPiv) upload.lastPiv = {id: log.pivId, deg: log.deg};
if (! upload.lastActivity) upload.lastActivity = log.t;
if (! upload.ok) upload.ok = 0;
upload.ok++;
// Uploaded files go into the alreadyUploaded list to properly track repeated vs alreadyUploaded within the upload
if (listAlreadyUploaded) upload.listAlreadyUploaded.push (log.pivId);
}
else if (log.type === 'alreadyUploaded') {
if (! upload.lastActivity) upload.lastActivity = log.t;
if (! upload.alreadyUploaded) upload.alreadyUploaded = 0;
upload.alreadyUploaded++;
// alreadyUploaded files go into the alreadyUploaded list to properly track repeated vs alreadyUploaded within the upload
if (listAlreadyUploaded) upload.listAlreadyUploaded.push (log.pivId);
}
else if (log.type === 'repeated' || log.type === 'invalid' || log.type === 'tooLarge' || log.type === 'unsupported') {
if (! upload.lastActivity) upload.lastActivity = log.t;
if (! upload [log.type]) upload [log.type] = [];
upload [log.type].push (log.name);
if (log.type === 'repeated') {
if (! upload.repeatedSize) upload.repeatedSize = 0;
upload.repeatedSize += log.size;
}
}
});
s.next (dale.go (uploads, function (v) {delete v.lastActivity; return v}).sort (function (a, b) {
// We sort uploads by their end date. If they don't have an end date, we sort them by id.
if (b.end && a.end) return b.end - a.end;
if (! b.end && ! a.end) return b.id - a.id;
return a.end ? 1 : -1;
}));
},
function (s) {
s.uploads = s.last;
var multi = redis.multi ();
s.checkExists = dale.fil (s.uploads, undefined, function (upload) {
if (! upload.lastPiv) return;
multi.exists ('piv:' + upload.lastPiv.id);
return upload.lastPiv.id;
});
mexec (s, multi);
},
function (s) {
if (s.checkExists.length) {
var exists = dale.obj (s.checkExists, function (v, k) {
return [v, !! s.last [k]];
});
dale.go (s.uploads, function (upload) {
if (upload.lastPiv && ! exists [upload.lastPiv.id]) delete upload.lastPiv;
});
}
s.next (s.uploads);
}
]);
}
H.getImports = function (s, rq, rs, provider, maxResults) {
a.seq (s, [
[a.stop, [H.getGoogleToken, rq.user.username], function (s, error) {
if (! inc ([1, 2], error.errorCode)) return reply (rs, 500, {error: error});
a.seq (s, [
[H.log, rq.user.username, {ev: 'import', type: error.errorCode === 1 ? 'request' : 'requestAgain', provider: 'google'}],
function (s) {
s.redirect = {
redirect: [
'https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=' + encodeURIComponent (CONFIG.domain + 'import/oauth/google'),
'prompt=consent',
'response_type=code',
'client_id=' + SECRET.google.oauth.gdrive.webClientId,
// https://developers.google.com/identity/protocols/oauth2/scopes
'&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.photos.readonly+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.readonly+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.metadata.readonly',
'access_type=offline',
'state=' + rq.user.csrf
].join ('&'),
provider: 'google'
};
s.next ();
}
]);
}],
[a.set, 'current', [Redis, 'hgetall', 'imp:' + {google: 'g', dropbox: 'd'} [provider] + ':' + rq.user.username]],
[a.set, 'uploads', [H.getUploads, rq.user.username, {provider: provider}, maxResults]],
function (s) {
// The only previous imports that are registered in the history are those that had an upload, otherwise they are not considered.
if (s.current) {
var id = parseInt (s.current.id);
var currentUpload = s.uploads [0] && s.uploads [0].id === id ? s.uploads [0] : undefined;
// If current import has no upload entry, create an entry for it.
if (! currentUpload) {
s.uploads.unshift ({
id: id,
provider: provider,
status: s.current.status,
fileCount: parseInt (s.current.fileCount) || 0,
folderCount: parseInt (s.current.folderCount) || 0,
// We attempt to process error as JSON; if it fails, it's either a non-JSON string or undefined.
error: teishi.parse (s.current.error) || s.current.error,
selection: s.current.selection ? JSON.parse (s.current.selection) : undefined,
data: s.current.data ? JSON.parse (s.current.data) : undefined,
// The current import might be finished with an error, so we need to send the `end` field to say when that happened
end: s.current.end ? teishi.parse (s.current.end) : undefined
});
// Delete file data from import since it's not necessary in the client.
if (s.uploads [0].data) delete s.uploads [0].data.files;
}
}
if (s.redirect) s.uploads.unshift (s.redirect);