-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
1441 lines (1122 loc) · 37.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const readline = require('readline');
const https = require('https');
const path = require('path');
const fs = require('fs');
const async = require('async');
const bodyParser = require('body-parser');
const config = require('./config.js');
const express = require('express');
const http = require('http');
const persist = require('node-persist');
const request = require('request-promise');
const session = require('express-session');
const sessionFileStore = require('session-file-store');
const uuid = require('uuid');
const req = require('request');
const querystring = require('querystring');
const lodash = require('lodash');
const mime = require('mime-types');
const kt = require('./bintree/keytree');
const keytree = kt.keytree;
const KeyResult = kt.KeyResult;
const sizeof = require('object-sizeof');
const items = require('./storemgr/itemstore');
const sql = require('sqlite3').verbose();
const mountinfo = require('./mountinfoparser');
var nodownload = false;
config.startService = refreshtimerrestart;
var storetree = {};
var processedstats = {
userid: '',
missinglocal: 0,
missingonline: 0,
notfinished: 0,
// finnotequaltostat: 0,
finished: 0,
total: 0,
sizeretry: 0,
size: 0,
itemretry: 0,
item: 0,
mediaerror404: 0,
skipped: 0
};
//backupFile('itemstore.json');
//backupFile('accountstores.json');
// on occasion the sessions directory will interfere with oauth 2, and for some reason
// this will cause the wrong authentication token to be passed into the express stack.
// which of course causes all network transactions with the photos api to fail.
console.log('deleting sessions subdirectory');
fs.rmSync('./sessions', { recursive: true, force: true });
const app = express();
const fileStore = sessionFileStore(session);
const server = http.Server(app);
// Use the EJS template engine
app.set('view engine', 'ejs');
// Set up a cache for media items that expires after 55 minutes.
const mediaItemCache = persist.create({
dir: 'persist-mediaitemcache/',
ttl: 3300000 // 55 minutes
});
mediaItemCache.init();
// Temporarily cache a list of the albums owned by the user.
const albumCache = persist.create({
dir: 'persist-albumcache/',
ttl: 600000 // 10 minutes
});
albumCache.init();
// For each user, the app stores the last search parameters or album
const storage = persist.create({ dir: 'persist-storage/' });
storage.init();
// this is absolutely necessary
// Set up OAuth 2.0 authentication through the passport.js library.
const passport = require('passport');
const auth = require('./auth');
const { match } = require('assert');
const { waitForDebugger } = require('inspector');
const { json } = require('express');
const { WSAENOTSOCK } = require('constants');
const { exception } = require('console');
const { CONNREFUSED } = require('dns');
const { debounce, size, isNull } = require('lodash');
const itemstore = require('./storemgr/itemstore');
const { UpdateSize } = require('./storemgr/itemstore');
const GoogleAccount = require('./storemgr/googleaccount.js');
const makehash = require('./makehash.js');
const getrows = require('./storemgr/getRows.js');
const { hasUncaughtExceptionCaptureCallback } = require('process');
const { HashItem } = require('./makehash.js');
var universaldb = OpenDatabase();
itemstore.InitDB(universaldb);
//loadandsortStored();
loadUserStore().then(
(val) => {
console.log('Accounts Loaded.');
},
(reason) => {
console.log('Accounts Load Failed: ' + reason);
}
);
auth(passport);
// Set up a session middleware to handle user sessions.
const sessionMiddleware = session({
resave: true,
saveUninitialized: true,
store: new fileStore({}),
secret: 'photo frame sample'
});
// Set up static routes for hosted libraries.
app.use(express.static('static'));
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist/'));
// Parse application/json request data.
app.use(bodyParser.json({ extended: true, limit: '50mb' }));
// Parse application/xwww-form-urlencoded request data.
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
// Enable user session handling.
app.use(sessionMiddleware);
// Set up passport and session handling.
app.use(passport.initialize());
app.use(passport.session());
// Middleware that adds the user of this session as a local variable
app.use((req, res, next) => {
res.locals.name = '-';
if (req.user && req.user.profile && req.user.profile.name) {
res.locals.name = req.user.profile.name.givenName || req.user.profile.displayName;
}
res.locals.avatarUrl = '';
if (req.user && req.user.profile && req.user.profile.photos) {
res.locals.avatarUrl = req.user.profile.photos[0].value;
}
next();
});
app.get('/info', (req, res) => {
res.send(config.username + '<' + config.emailid + '>');
});
-
app.get('/', (req, res) => {
if (!checkauth()) {
console.log('sending user to authenticate page.');
res.redirect('/auth/google');
} else {
console.log('sending user to sucess page');
res.sendFile(__dirname + '/success.html');
}
});
//TODO: UPDATE THIS TO USE SQLITE.
app.post('/redownloadstart', async (req, res) => {
nodownload = false;
processedstats.userid = config.userid;
var res1 = await CheckDownloads();
//TODO: FIX THIS ! RESULTS FROM UPDATE TO IMAGEDIRECTORIES
var totals = await MoveOriginalsUpdateStore();
// resolve the problem where original size is less than that on server but the original is missing
var res2 = await itemstore.resolveMissingLocalSizeandDownload(config.curraccount.userid);
endtimer = false;
// kick off the queue timer.
// in redesign queue timer will begin querying the database for items to run.
timecall();
});
app.get('/updatesizes', async (req, res) => {
var count = await itemstore.getMissingSizeCount(config.curraccount.userid);
console.log('There are ' + count + ' items for current user without sizes set.');
nodownload = true;
console.log("Starting Timer.")
sizetimecall();
});
app.get('/getlist', async (req, res) => {
if (checkauth()) {
// less than optimal is where it doesnt check length.
// unfortunately how can it without downloading every item if fucking google doesnt expose that field ?
var total = await FillInitialQueueFromServer();
var dls = await CheckDownloads();
var locals = await MoveOriginalsUpdateStore();
// resolve the problem where original size is less than that on server but the original is missing
var res2 = await itemstore.resolveMissingLocalSizeandDownload(config.curraccount.userid);
res.status(200).send({ message: 'completed', totals: total, local: locals });
console.log('sent item info to client');
} else {
// user isn't authenticated. send to login.
res.redirect('/auth/google');
}
});
app.get('/logout', (req, res) => {
req.logout();
req.session.destroy();
res.redirect('/');
});
app.get('/clearsizefail', async (req, res) => {
await itemstore.ClearSizeFailureCount(config.userid);
console.log('Cleared Size Flags.');
var count = await itemstore.getMissingSizeCount(config.curraccount.userid);
console.log('There are ' + count + ' items for current user without sizes set.');
res.sendStatus(200);
});
function acallback(arg1, arg2, arg3, arg4) {
console.log('reached auth callback');
}
app.get('/getaccounts', async(req,res) =>
{
res.send( JSON.stringify(accounts)).status(200);
});
async function grabNextHashQueue()
{
console.log("Retrieving all storeitems with unprocessed hashes.");
var sql = 'select * from storeitem where DownloadedSha256 is null and userid=? and DownloadMissingLocal <> 1 limit ?'
var r = await getrows(universaldb,sql,[config.userid,100]);
var missing = 0;
r.rows.forEach(element => {
var filename = path.join(config.curraccount.localdir().Directory,element.FileNameOnServer);
if (fs.existsSync(filename))
{
hashqueue.push(element)
itemstore.MarkMissingLocal(element.Id, 0)
}
else
{
missing++;
itemstore.MarkMissingLocal(element.Id, 1)
}
});
}
app.get('/processhashes', async(req,res) =>
{
if (hashrunning)
{
console.log("A hash job is already running. please wait till finished.");
}
else
{
processHashes();
}
});
app.get('/upload', async (req, res) => {
testUpload('./images.jpeg');
});
// Start the OAuth login process for Google.
app.get(
'/auth/google',
passport.authenticate(
'google',
{
scope: config.scopes,
failureFlash: true, // Display errors to the user.
session: true
},
acallback
)
);
app.get('/jquery.js', (req, res) => {
res.send(fs.readFileSync('./node_modules/jquery/dist/jquery.js'));
});
app.get(
'/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/', failureFlash: true, session: true }),
async (req, res) => {
// User has logged in.
console.log('User has logged in.');
// moved this to be called by authenbticate callback.
// refreshtimerrestart();
// grab information about current user post authentication
config.userid = req.user.profile.id;
config.emailid = req.user.profile.emails[0].value;
config.username = config.emailid.substring(0, config.emailid.indexOf('@'));
var userexists = await GoogleAccount.CheckExistsDb(universaldb, config.userid);
if (!userexists) {
await createUser();
} else {
findUser();
}
//loadUserStore();
//loadandsortStored();
res.redirect('/');
}
);
app.get('/forcerefresh', async (req, res) => {
var result = await refreshAccessToken();
res.status(200).send(result);
});
server.listen(config.port, () => {
console.log(`App listening on port ${config.port}`);
console.log('Press Ctrl+C to quit.');
});
//FINISHED
function pushtoQueue(destfilename, storeitem) {
console.log('sent to queue.');
waiting.push({ filename: destfilename, item: storeitem });
}
async function CheckDownloads() {
// fuck them i did this before.
var files = recursepath(config.curraccount.localdir().Directory).map(function(v) {
return path.basename(v);
});
await itemstore.UpdateMissingDownloadsByNames(files, config.curraccount.userid);
}
//FINISHED
async function MoveOriginalsUpdateStore() {
// get the originals stored in the originals and server organizer directories.
var paths = config.curraccount.originalsdirectory().map(v=> v.Directory);
var files = [];
console.log('recursing originals store');
// retrieve a list of local files.
for (var i in paths) {
files = files.concat(recursepath(paths[i]));
}
var onservercount = 0;
var localonlycount = 0;
// just in case we're processing a lot of files this offsets the performance hit to follow !
var serverfiletree = {};
// supporting multiple users now, reduce extra uploading etc.
var itemnames = files.map(function(v) {
return path.basename(v);
});
console.log('Comparing.');
// get a list by filename from the itemstore
var items = await itemstore.CheckExistsFileByNames(itemnames, config.curraccount.userid);
// update the originalmissing field.
var res4 = await itemstore.UpdateMissingLocalByNames(itemnames, config.curraccount.userid);
for (var i in items) {
keytree.addToTree(serverfiletree, items[i].FileNameOnServer, items[i]);
}
// empty results list
items = null;
// var updatelist = [];
// these don't do shit yet.
// var onservermntpoint = await mountPoint(config.curraccount.onserverdirectory().Directory);
// var destmntpoint = await mountPoint(config.curraccount.localdir().Directory);
for (var i in files) {
var filemntpnt = await mountPoint(files[i]);
// decide what to do with local files in the processing directories
var found = keytree.findInTree(serverfiletree, path.basename(files[i]));
if (found.Found) {
// get the basename of the file.
var bname = path.basename(files[i]);
// move item to the onserver directory
//await moveItems(files[i], config.curraccount.onserverdirectory());
onservercount++;
// update the file entry for the changed location
files[i] = path.join(config.curraccount.onserverdirectory().Directory, bname);
// get the original's size
// TODO: THIS IS CAUSING PROBLEMS BECAUSE THE ITEM MOVE IS BROKEN
// PRESENTLY AND THEREFORE NOT OCCURRING
// SO THIS WILL NEED FIXED.
//var stat = fs.statSync(files[i]);
// updatelist.push([ files[i], stat.size ]);
// the downloads filename.
var localdl = path.join(config.curraccount.localdir().Directory, bname);
//TODO: FIX THIS, COMMENTED OUT BECAUSE STAT IS BROKEN BECAUSE
// IT EXPECTS A FILE LOCATION THAT HAS NOT BEEN UPDATED
// BECAUSE OF PRESENT DIFFICULTIES WITH MOVEITEMS
// ALSO, IN THE CASE OF THIS NEED TO ADD LOGIC TO MARK LOCATION OF
// ORIGINAL, AS IT MAY NOT BE IN SAID DIRECTORY. THOUGH IT SHOULD BE
// PERHAPS ALLOW PER DEVICE ONSERVER ORGANIZER SO CROSS DEVICE MOVES
// DON'T HAVE TO OCCUR. ORIGINALS CAN TAKE A LOT OF SPACE.
// update the original size field if necessary
// if (found.Obj.OriginalSize == null) {
// itemstore.UpdateOriginalSizeIf(found.Obj.Id, stat.size);
// }
var szupdated = false;
//TODO: AWAITING FIX OF OTHER ORIGINALS ORIENTED CODE.
// if (!found.Obj.OriginalSha256)
// {
// // TODO: MAKE SEPERATE THREAD FOR THIS LATER IF DETERMINED NECESSARY
// var hash = await HashItem(universaldb, found.Obj, path.dirname(files[i]),true );
// if (hash.success)
// {
// console.log("Generated hash:"+ hash.hash);
// }
// }
if (found.Obj.SizeOnServer == -1) {
szupdated = true;
var res = await updateSize(found.Obj, 5);
if (!res.Success) {
console.log('Could not update size. Deletion could be accidental, skipping.');
continue;
}
}
if (fs.existsSync(localdl)) {
var statdl = fs.statSync(localdl);
if (statdl.size != found.Obj.SizeOnServer && !szupdated) {
var res = await updateSize(found.Obj, 5);
if (!res.Success) {
console.log('Could not update size. Deletion could be accidental, skipping.');
continue;
}
}
// google occasionally reports values less than it should
// size wise and then these can be viewed and are of quality just the same.
if (statdl.size < found.Obj.SizeOnServer) {
fs.rmSync(localdl);
processedstats.notfinished++;
itemstore.MarkFinished(found.Obj.Id, false, 0, true);
} else {
itemstore.MarkFinished(found.Obj.Id, true, statdl.size, false);
}
} else {
processedstats.missinglocal++;
itemstore.MarkFinished(found.Obj.Id, false, 0, true);
}
} else {
//await moveItems(files[i], config.curraccount.localdir().Directory);
localonlycount++;
}
}
console.log('LocalOnly: ' + localonlycount + ' OnServer: ' + onservercount);
return { local: localonlycount, server: onservercount };
}
//FINISHED
async function updateSize(storeitem, maxretries = 5) {
if (maxretries <= 0) {
throw 'Maxtries in updateSize CANNOT BE <=0 ! This will cause a fatal error.';
}
processedstats.size++;
// we do this because this is a temporary url.
var url = await refreshStoredUrl(storeitem);
if (!url) {
console.log("Size Update Canceled, couldn't retrieve url.");
await itemstore.UpdateSize(storeitem.Id, -1);
return { Success: false, item: storeitem };
}
console.log('Found URL: ' + url);
var retry = true;
var retries = 0;
while (retry && retries < maxretries) {
retry = false;
if (retries > 0) {
console.log('Retry Get Header #' + retries + ' of 5');
}
try {
var h = await request.head(url + '=d' + (storeitem.VideoOption ? 'v' : ''), {}, (req, res) => {
if (!res) {
// returns blank response it seems.
retry = true;
retries++;
itemstore.IncrementSizeFailure(storeitem.Id);
storeitem.SizeUpdateFailureCount++;
console.log('Get header failed for ' + storeitem.FileNameOnServer);
} else {
// size update happens here.
storeitem.SizeOnServer = res.headers['content-length'];
}
});
} catch (err) {
if (err.statusCode == 500) {
itemstore.IncrementSizeFailure(storeitem.Id);
storeitem.SizeUpdateFailureCount++;
console.log('Head request failed with error 500, excluding from this session.');
await itemstore.MarkWaitTillNext(storeitem.Id, false);
return { Success: false, item: storeitem };
} else {
itemstore.IncrementSizeFailure(storeitem.Id);
storeitem.SizeUpdateFailureCount++;
console.log('Head request failed.');
retry = true;
retries++;
processedstats.sizeretry++;
}
}
if (!retry) {
await itemstore.UpdateSize(storeitem.Id, storeitem.SizeOnServer);
}
}
if (retries >= maxretries) {
console.log('Failed to Update Size.');
return { Success: false, item: storeitem };
} else {
console.log('Updated size.');
return { Success: true, item: storeitem };
}
}
//TODO: TEST THIS
async function refreshStoredUrl(storeitem) {
//console.log("started refresh of url")
var result = await getPhotoItem(storeitem.Id, 5);
if (!result) {
console.log('Could not retrieve item url');
return null;
} else {
storeitem.VideoOption = result.mediaMetadata.video ? true : false;
await itemstore.SetVideoOption(storeitem.Id, storeitem.VideoOption);
console.log('Updated URL');
return result.baseUrl;
}
}
//TODO: MOVE THIS TO BEGINNING
function OpenDatabase() {
console.log("Item Store database doesn't exist, creating.");
if (!fs.existsSync('ItemStore.sqlite')) {
fs.copyFileSync('EmptyStoreDB.sqlite', 'ItemStore.sqlite');
}
var db = new sql.Database('ItemStore.sqlite');
return db;
}
//TODO: TEST THIS
async function startJob(destfilename, storeitem) {
// var db = OpenDatabase();
if (fs.existsSync(destfilename)) {
var stat = fs.statSync(destfilename);
{
if (storeitem.SizeOnServer <= stat.size) {
console.log('Check file: ' + storeitem.FileNameOnServer);
console.log(
'Had no size defined ahead of download call, but file exists and is larger to or equal to size on server.'
);
return null;
}
}
}
var url = await refreshStoredUrl(storeitem);
if (!url) {
console.log(storeitem.FileNameOnServer);
console.log('JOB Canceled. Item is missing from online.');
await itemstore.MarkFinished(storeitem.Id, true);
storeitem.Finished = true;
storeitem.missingonline = true;
writeStored();
// db.close();
return null;
}
var ostream = fs.createWriteStream(destfilename);
ostream.on('finish', async function() {
console.log(' PIPE FINISHED !: ' + this.filename);
if (!this.storeitem.error) {
var size = fs.statSync(this.destination);
processedstats.finished++;
this.storeitem.Finished = true;
this.storeitem.Finishedsize = size.size;
console.log('finished size: ' + this.storeitem.Finishedsize);
await itemstore.MarkFinished(this.storeitem.Id, true);
await itemstore.SetFinishedSize(this.storeitem.Id, size.size);
// clear from queue.
await itemstore.MarkWaitTillNext(this.storeitem.Id, false);
if (!hashrunning) { processHashes();}
} else {
console.log('Request promise sent error.');
}
console.log('===>Id:' + this.storeitem.Id);
pipes.splice(pipes.indexOf(this), 1);
});
ostream.on('error', function(err) {
console.log(' PIPE ERROR LOADING ! : ' + this.filename);
console.log(err);
});
var req = request.get(url + '=d' + (storeitem.VideoOption ? 'v' : ''));
req.on('error', async function(err) {
console.log('error with ' + this.filename);
console.log('placing job back in queue.');
var id = this.storeitem.Id;
// this.path.replace('/', '');
var pipeindex = -1;
for (var i in pipes) {
if (pipes[i].storeitem.Id == id) {
pipeindex = i;
break;
}
}
if (pipeindex > -1) {
//var db = OpenDatabase();
var p = pipes[pipeindex];
p.close();
if (fs.existsSync(p.destination)) {
console.log('deleting partial file.');
fs.rmSync(p.destination);
}
pipes.splice(pipeindex, 1);
p.storeitem.Finished = false;
p.storeitem.error = true;
await itemstore.MarkFinished(p.storeitem.Id, false);
/// db.close();
}
pushtoQueue(this.destination, this.storeitem);
});
req.catch(function(err) {
var issue = err;
console.log('Default error handler for request reached.');
});
// this is still the request promise.
req.storeitem = storeitem;
req.filename = storeitem.FileNameOnServer;
req.destination = destfilename;
req.expectedSize = storeitem.SizeOnServer;
// this is the ouput stream, maybe rename some shit ? LOL
req.pipe(ostream);
ostream.storeitem = storeitem;
ostream.filename = storeitem.FileNameOnServer;
ostream.expectedSize = storeitem.SizeOnServer;
ostream.destination = destfilename;
// tag the stream with the request object just in case we need to reference this.
ostream.req = req;
pipes.push(ostream);
console.log('Active pipes: ' + pipes.length);
console.log('Started Job For ' + storeitem.FileNameOnServer);
return ostream;
}
var sizequeue = [];
var sizerunning = false;
async function sizecall(overide = false) {
if (sizerunning && !overide) {
// like a fork. sort of. if true this method should already be running or waiting for a timer call.
// override should only be set from inside this call.
return;
}
sizerunning = true;
var queueswap = [];
while (sizequeue.length > 0) {
var item = sizequeue.shift();
// we should never encounter this if either the updatesize is not running or we already have a size.
// so add back into queue and/or start the updatesize job.
if (item.SizeOnServer == -1) {
queueswap.push(item);
if (!item.running) {
item.running = true;
updateSize(item)
.then((v) => {
if (v.Success) {
if (!nodownload) {
console.log('Adding item to waiting download queue. Size Updated.');
waiting.push(v.item);
} else {
console.log('Size Updated.');
}
console.log(v.item.SizeOnServer);
} else {
processedstats.skipped++;
// itemstore.IncrementSizeFailure(v.item.Id)
if (v.item.SizeUpdateFailureCount > 20) {
itemstore.MarkWaitTillNext(v.item.Id, true);
lodash.remove(waiting, function(i) {
return i.Id == v.item.Id;
});
lodash.remove(queueswap, function(i) {
return i.Id == v.item.Id;
});
//console.log("Size Failed For Item more than 20 times, removed from queue.");
}
console.log('Update size failed. Leaving out of queue. ');
}
})
.catch((err) => {
processedstats.skipped++;
console.log('updateSize failed: ' + err);
});
}
}
}
sizequeue = queueswap;
if (sizequeue.length > 0) {
// continue processing.
setTimeout(() => {
sizecall(true);
}, 5000);
} else {
sizerunning = false;
}
}
async function sizetimecall()
{
var items = await itemstore.getNext100WaitingSize(config.userid)
if (items.length == 0) {
console.log('==============> No more items in size update queue, ending timer <==========')
sizerunning = false;
return;
}
else {sizerunning = true;}
while (items.length > 0)
{
var item = items.shift()
updateSize(item)
.then((v) =>
{
if (v.Success)
{
console.log('Size Updated.');
console.log(v.item.SizeOnServer);
} else {
processedstats.skipped++;
// itemstore.IncrementSizeFailure(v.item.Id)
if (v.item.SizeUpdateFailureCount > 20) {
itemstore.updateProcessSize(v.item.Id, false);
}
console.log('Update size failed. Leaving out of queue. ');
}
})
.catch((err) => {
processedstats.skipped++;
console.log('updateSize failed: ' + err);
});
}
if (sizerunning) {
// continue processing.
setTimeout(() => {
sizetimecall();
}, 5000);
} else {
console.log("================> QUEUE PROCESSED ENDING SIZE UPDATE JOB <============")
sizerunning = false;
}
}
// TODO: TEST THIS
// this function starts the queue timer and starts jobs as queue slots become available.
async function timecall() {
endtimer = true;
var googlegayasslimit = 4;
var started = 0;
var queueswap = [];
// try to grab another 100 items waiting.
if (pipes.length + waiting.length + sizequeue.length == 0) {
waiting = await itemstore.getNext100Waiting(config.curraccount.userid);
for (var i in waiting) {
if (waiting[i].SizeOnServer == -1) {
sizequeue.push(waiting[i]);
sizecall();
} else {
// if size is defined, download is ready to go.
queueswap.push(waiting[i]);
}
}
// put the altered queue in place of the original waiting queue.
waiting = queueswap;
}
while (waiting.length > 0 && pipes.length < maxpipes) {
endtimer = false;
if (started == googlegayasslimit) break;
var i = waiting.shift();
var job = await startJob(path.join(config.curraccount.localdir().Directory, i.FileNameOnServer), i);
if (!job) {
console.log('Job Canceled.');
processedstats.skipped++;
}
}
var message = '';
var waitingcount = (await itemstore.getCountWaiting(config.curraccount.userid)) - pipes.length;
var inmemqueue = waiting.length;
var inmemsize = sizequeue.length;
message += 'Active Pipes: ' + pipes.length + ' In DB Waiting: ' + waitingcount + '\n';
message += 'Waiting in Mem: ' + inmemqueue + ' Size Queue Size: ' + inmemsize + '\n';
message += "Hash Queue: "+hashqueue.length +" \n";
for (var i in pipes) {
var rate = 0;
if (pipes[i].lastbytes) {
rate = (pipes[i].bytesWritten - pipes[i].lastbytes) / (Date.now() - pipes[i].lastdate) / 1024 * 1000;
}
var perc = pipes[i].bytesWritten / pipes[i].storeitem.SizeOnServer * 100;
message +=
i +
') ' +
pipes[i].filename +
' ' +
pipes[i].bytesWritten +
'/' +
pipes[i].storeitem.SizeOnServer +
' (' +
perc.toLocaleString(undefined, {
minimumFractionDigits: 1,
maximumFractionDigits: 1
}) +
'%) ' +
rate.toLocaleString(undefined, {
minimumFractionDigits: 3,
maximumFractionDigits: 3
}) +
' kb/s\n';
pipes[i].lastbytes = pipes[i].bytesWritten;
pipes[i].lastdate = Date.now();
}
console.log(message);
if (waiting.length == 0 && pipes.length == 0 && sizequeue.length == 0) {
console.log('stopping timer');
} else {
setTimeout(() => {
timecall();
}, 5000);
}
console.log(processedstats);
}
var hashqueue = []
var hashjobs = 0
const hashjoblimit = 15;
var hashrunning = false;
var hashcall = null;
async function startHashJob(item)
{
hashjobs++;