forked from c0de0ff/DownloadManager
-
Notifications
You must be signed in to change notification settings - Fork 1
/
popup.js
1079 lines (977 loc) · 34.7 KB
/
popup.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
function pointInElement(p, elem) {
return ((p.x >= elem.offsetLeft) &&
(p.x <= (elem.offsetLeft + elem.offsetWidth)) &&
(p.y >= elem.offsetTop) &&
(p.y <= (elem.offsetTop + elem.offsetHeight)));
};
function setLastOpened() {
localStorage.popupLastOpened = (new Date()).getTime();
chrome.runtime.sendMessage('poll');
};
function loadI18nMessages() {
function setProperty(selector, prop, msg) {
document.querySelector(selector)[prop] = chrome.i18n.getMessage(msg);
}
setProperty('title', 'innerText', 'tabTitle');
setProperty('#q', 'placeholder', 'searchPlaceholder');
setProperty('#all-downloads', 'title', 'AllDownloadsTitle');
setProperty('#options-open', 'title', 'optionsTitle');
setProperty('#clear-all', 'title', 'clearAllTitle');
setProperty('#clear-all-text', 'innerText', 'clearAllText');
setProperty('#clear-completed', 'title', 'clearCompletedTitle');
setProperty('#clear-completed-text', 'innerText', 'clearCompletedText');
setProperty('#clear-failed', 'title', 'clearFailedTitle');
setProperty('#clear-failed-text', 'innerText', 'clearFailedText');
setProperty('#clear-deleted', 'title', 'clearDeletedTitle');
setProperty('#clear-deleted-text', 'innerText', 'clearDeletedText');
setProperty('#open-folder', 'title', 'openDownloadsFolderTitle');
setProperty('#open-folder-text', 'innerText', 'openDownloadsFolderText');
setProperty('#help', 'title', 'settingsTitle');
setProperty('#help-text', 'innerText', 'settingsText');
setProperty('#empty', 'innerText', 'zeroItems');
setProperty('#searching', 'innerText', 'searching');
setProperty('#search-zero', 'innerText', 'zeroSearchResults');
setProperty('#management-permission-info', 'innerText',
'managementPermissionInfo');
setProperty('#grant-management-permission', 'innerText',
'grantManagementPermission');
setProperty('#older', 'innerText', 'showOlderDownloads');
setProperty('#loading-older', 'innerText', 'loadingOlderDownloads');
setProperty('.pause', 'title', 'pauseTitle');
setProperty('.resume', 'title', 'resumeTitle');
setProperty('.cancel', 'title', 'cancelTitle');
setProperty('.show-folder', 'title', 'showInFolderTitle');
setProperty('.erase', 'title', 'eraseTitle');
setProperty('.url', 'title', 'retryTitle');
setProperty('.referrer', 'title', 'referrerTitle');
setProperty('.open-filename', 'title', 'openTitle');
setProperty('#bad-chrome-version', 'innerText', 'badChromeVersion');
setProperty('.remove-file', 'title', 'removeFileTitle');
document.querySelector('.myprogress').style.minWidth =
getTextWidth(formatBytes(1024 * 1024 * 1023.9) + '/' +
formatBytes(1024 * 1024 * 1023.9)) + 'px';
var max_time_left_width = 0;
for (var i = 0; i < 4; ++i) {
max_time_left_width = Math.max(max_time_left_width, getTextWidth(
formatTimeLeft(0 == (i % 2),
(i < 2) ? 0 : ((100 * 24) + 23) * 60 * 60 * 1000)));
}
document.querySelector('body div.item span.time-left').style.minWidth =
max_time_left_width + 'px';
};
function getTextWidth(s) {
var probe = document.getElementById('text-width-probe');
probe.innerText = s;
return probe.offsetWidth;
};
function formatDateTime(date) {
var now = new Date();
var zpad_mins = ':' + (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();
if (date.getYear() != now.getYear()) {
return '' + (1900 + date.getYear());
} else if ((date.getMonth() != now.getMonth()) ||
(date.getDate() != now.getDate())) {
return date.getDate() + ' ' + chrome.i18n.getMessage(
'month' + date.getMonth() + 'abbr');
} else if (date.getHours() == 12) {
return '12' + zpad_mins + 'pm';
} else if (date.getHours() > 12) {
return (date.getHours() - 12) + zpad_mins + 'pm';
}
return date.getHours() + zpad_mins + 'am';
}
function formatBytes(n) {
if (n < 1024) {
return n + 'B';
}
var prefixes = 'KMGTPEZY';
var mul = 1024;
for (var i = 0; i < prefixes.length; ++i) {
if (n < (1024 * mul)) {
return (parseInt(n / mul) + '.' + parseInt(10 * ((n / mul) % 1)) +
prefixes[i] + 'B');
}
mul *= 1024;
}
return '!!!';
}
function formatSpeed(ms, bytes){
if (ms < 1000) {
return '0KB/s';
}
var sec = ms/1000;
var speed = bytes/sec;
if(speed < 1024){
return Math.round(speed*10)/10+'bytes/s';
}
if(speed < 1048576){
return Math.round((speed/(1024))*10)/10+'KB/s';
}
else return Math.round((speed/(1024*1024))*10)/10+'MB/s';
}
function formatTimeLeft(openWhenComplete, ms) {
var prefix = openWhenComplete ? 'openWhenComplete' : 'timeLeft';
if (ms < 1000) {
return chrome.i18n.getMessage(prefix + 'Finishing');
}
var days = parseInt(ms / (24 * 60 * 60 * 1000));
var hours = parseInt(ms / (60 * 60 * 1000)) % 24;
if (days) {
return chrome.i18n.getMessage(prefix + 'Days', [days, hours]);
}
var minutes = parseInt(ms / (60 * 1000)) % 60;
if (hours) {
return chrome.i18n.getMessage(prefix + 'Hours', [hours, minutes]);
}
var seconds = parseInt(ms / 1000) % 60;
if (minutes) {
return chrome.i18n.getMessage(prefix + 'Minutes', [minutes, seconds]);
}
return chrome.i18n.getMessage(prefix + 'Seconds', [seconds]);
}
function binarySearch(array, target, cmp) {
var low = 0, high = array.length - 1, i, comparison;
while (low <= high) {
i = (low + high) >> 1;
comparison = cmp(target, array[i]);
if (comparison < 0) {
low = i + 1;
} else if (comparison > 0) {
high = i - 1;
} else {
return i;
}
}
return i;
};
function arrayFrom(seq) {
return Array.prototype.slice.apply(seq);
};
function DownloadItem(data) {
var item = this;
for (var prop in data) {
item[prop] = data[prop];
}
item.startTime = new Date(item.startTime);
if (item.canResume == undefined) {
DownloadItem.canResumeHack = true;
}
item.div = document.querySelector('body>div.item').cloneNode(true);
item.div.id = 'item' + item.id;
item.div.item = item;
var items_div = document.getElementById('items');
if ((items_div.childNodes.length == 0) ||
(item.startTime.getTime() < items_div.childNodes[
items_div.childNodes.length - 1].item.startTime.getTime())) {
items_div.appendChild(item.div);
} else if (item.startTime.getTime() >
items_div.childNodes[0].item.startTime.getTime()) {
items_div.insertBefore(item.div, items_div.childNodes[0]);
} else {
var adjacent_div = items_div.childNodes[
binarySearch(arrayFrom(items_div.childNodes),
item.startTime.getTime(),
function(target, other) {
return target - other.item.startTime.getTime();
})];
var adjacent_item = adjacent_div.item;
if (adjacent_item.startTime.getTime() < item.startTime.getTime()) {
items_div.insertBefore(item.div, adjacent_div);
} else {
items_div.insertBefore(item.div, adjacent_div.nextSibling);
}
}
item.getElement('referrer').onclick = function(event) {
chrome.tabs.create({url: item.referrer});
event.stopPropagation();
return false;
};
item.getElement('url').onclick = function(event) {
chrome.tabs.create({url: item.url});
event.stopPropagation();
return false;
};
item.getElement('by-ext').onclick = function(event) {
chrome.tabs.create({url: 'chrome://extensions#' + item.byExtensionId});
event.stopPropagation();
return false;
}
item.getElement('open-filename').onclick = function(event) {
item.open();
window.close();
event.stopPropagation();
return false;
};
//$(item.div).contextMenu(menu1,{theme:'vista'});
item.div.oncontextmenu = function(event){
//alert("right clicked");
return false;
};
item.div.onclick = function(event){
item.open();
window.close();
return false;
};
item.div.onmouseover = function(){
var openable = (item.state != 'interrupted') && item.exists && !item.deleted;
if(openable){
item.div.style.borderLeftColor='#5bc0de';
}
else {
item.div.style.borderLeftColor='#d9534f';
}
if(item.state == 'in_progress' || item.state == 'interrupted' || !item.exists || item.deleted) item.getElement('info').style.display = 'none';
else item.getElement('info').style.display = 'inline';
return false;
};
item.div.onmouseout = function(){
item.div.style.borderLeftColor='#eee';
//item.getElement('info').style.display = 'none';
return false;
};
item.div.ondragstart = function() {
item.drag();
return false;
};
item.getElement('pause').onclick = function(event) {
item.pause();
event.stopPropagation();
return false;
};
item.getElement('cancel').onclick = function(event) {
item.cancel();
event.stopPropagation();
return false;
};
item.getElement('resume').onclick = function(event) {
item.resume();
event.stopPropagation();
return false;
};
item.getElement('show-folder').onclick = function(event) {
item.show();
event.stopPropagation();
return false;
};
item.getElement('remove-file').onclick = function(event) {
item.removeFile();
event.stopPropagation();
return false;
};
item.getElement('erase').onclick = function(event) {
item.erase();
event.stopPropagation();
return false;
};
/*item.more_mousemove = function(evt) {
if (item.getElement('more') &&
(pointInElement(evt, item.div) ||
pointInElement(evt, item.getElement('more')))) {
return;
}
if (item.getElement('more')) {
item.getElement('more').hidden = true;
}
window.removeEventListener('mousemove', item.more_mousemove);
};
[item.getElement('icon'), item.getElement('more')].concat(
item.getElement('more').children).forEach(function(elem) {
elem.onmouseover = function() {
arrayFrom(items_div.children).forEach(function(other) {
if (other.item != item) {
other.item.getElement('more').hidden = true;
}
});
item.getElement('more').hidden = false;
item.getElement('more').style.top =
(item.div.offsetTop + item.div.offsetHeight) + 'px';
item.getElement('more').style.left = item.div.offsetLeft + 'px';
if (window.innerHeight < (parseInt(item.getElement('more').style.top) +
item.getElement('more').offsetHeight)) {
item.getElement('more').style.top = (
item.div.offsetTop - item.getElement('more').offsetHeight) + 'px';
}
window.addEventListener('mousemove', item.more_mousemove);
};
});*/
if (item.referrer) {
item.getElement('ref').innerText = item.referrer.substr(0,25)+"...";
} else {
item.getElement('ref').hidden = true;
}
item.getElement('url').href = item.url;
//item.getElement('url').innerHTML = "<img class=\"info_control\" src=\"icons/ic_action_replay.png\"></img>";
item.render();
}
DownloadItem.canResumeHack = false;
DownloadItem.prototype.getElement = function(name) {
return document.querySelector('#item' + this.id + ' .' + name);
};
DownloadItem.prototype.render = function() {
var item = this;
var now = new Date();
var in_progress = (item.state == 'in_progress')
var openable = (item.state != 'interrupted') && item.exists && !item.deleted;
item.startTime = new Date(item.startTime);
if (DownloadItem.canResumeHack) {
item.canResume = in_progress && item.paused;
}
if (item.filename) {
item.basename = item.filename.substring(Math.max(
item.filename.lastIndexOf('\\'),
item.filename.lastIndexOf('/')) + 1);
if(item.basename.length>40){
item.basename = item.basename.substr(0,30)+"..."+item.basename.substr(item.basename.length-7,item.basename.length);
}
}
if (item.estimatedEndTime) {
item.estimatedEndTime = new Date(item.estimatedEndTime);
}
if (item.endTime) {
item.endTime = new Date(item.endTime);
}
if (item.filename && !item.icon_url) {
chrome.downloads.getFileIcon(
item.id,
{'size': 32},
function(icon_url) {
//item.getElement('icon').hidden = !icon_url;
if (icon_url) {
item.icon_url = icon_url;
item.getElement('icon').src = icon_url;
}
});
}
item.div.style.cursor = openable ? 'pointer' : '';
item.getElement('removed').style.display = openable ? 'none' : 'inline';
item.getElement('open-filename').style.display = (
openable ? 'inline' : 'none');
item.getElement('in-progress').hidden = !in_progress;
item.getElement('pause').style.display = (
!in_progress || item.paused) ? 'none' : 'inline-block';
item.getElement('resume').style.display = (
!in_progress || !item.canResume) ? 'none' : 'inline-block';
item.getElement('cancel').style.display = (
!in_progress ? 'none' : 'inline-block');
item.getElement('remove-file').hidden = (
(item.state != 'complete') ||
!item.exists ||
item.deleted ||
!chrome.downloads.removeFile);
item.getElement('erase').hidden = in_progress;
item.getElement('complete-size').hidden = in_progress;
item.getElement('start-time').hidden = in_progress;
item.getElement('ref').hidden = in_progress;
item.getElement('dash').hidden = in_progress;
item.getElement('show-folder').hidden = in_progress || !openable;
item.getElement('url').hidden = in_progress;
var could_progress = in_progress || item.canResume;
item.getElement('myprogress').style.display = (
could_progress ? 'inline-block' : 'none');
item.getElement('meter').hidden = !could_progress || !item.totalBytes;
item.getElement('removed').innerText = item.basename;
item.getElement('open-filename').innerText = item.basename;
function setByExtension(show) {
if (show) {
item.getElement('by-ext').title = item.byExtensionName;
item.getElement('by-ext').href =
'chrome://extensions#' + item.byExtensionId;
item.getElement('by-ext img').src =
'chrome://extension-icon/' + item.byExtensionId + '/48/1';
} else {
item.getElement('by-ext').hidden = true;
}
}
if (item.byExtensionId && item.byExtensionName) {
chrome.permissions.contains({permissions: ['management']},
function(result) {
if (result) {
setByExtension(true);
} else {
setByExtension(false);
if (!localStorage.managementPermissionDenied) {
document.getElementById('request-management-permission').hidden =
false;
document.getElementById('grant-management-permission').onclick =
function() {
chrome.permissions.request({permissions: ['management']},
function(granted) {
setByExtension(granted);
if (!granted) {
localStorage.managementPermissionDenied = true;
}
});
return false;
};
}
}
});
} else {
setByExtension(false);
}
item.getElement('complete-size').innerText = formatBytes(
item.bytesReceived);
if (item.totalBytes && (item.state != 'complete')) {
item.getElement('myprogress').innerText = (
item.getElement('complete-size').innerText + ' of ' +
formatBytes(item.totalBytes));
item.getElement('meter').children[0].style.width = parseInt(
100 * item.bytesReceived / item.totalBytes) + '%';
}
if (in_progress) {
if (item.estimatedEndTime && !item.paused) {
var openWhenComplete = false;
try {
openWhenComplete = JSON.parse(localStorage.openWhenComplete).indexOf(
item.id) >= 0;
} catch (e) {
}
var timeLeftInMS = item.estimatedEndTime.getTime() - now.getTime();
var sizeLeftInBytes = item.totalBytes - item.bytesReceived;
item.getElement('speed').innerText = formatSpeed(timeLeftInMS, sizeLeftInBytes);
item.getElement('time-left').innerText = formatTimeLeft(
openWhenComplete, item.estimatedEndTime.getTime() - now.getTime());
} else {
item.getElement('time-left').innerText = String.fromCharCode(160);
}
}
if (item.startTime) {
item.getElement('start-time').innerText = formatDateTime(
item.startTime);
}
this.maybeAccept();
};
DownloadItem.prototype.onChanged = function(delta) {
for (var key in delta) {
if (key != 'id') {
this[key] = delta[key].current;
}
}
this.render();
if (delta.state) {
setLastOpened();
}
if ((this.state == 'in_progress') && !this.paused) {
DownloadManager.startPollingProgress();
}
if(this.state=="interrupted" && this.filename==""){
this.erase();
}
};
DownloadItem.prototype.onErased = function() {
window.removeEventListener('mousemove', this.more_mousemove);
document.getElementById('items').removeChild(this.div);
};
DownloadItem.prototype.drag = function() {
chrome.downloads.drag(this.id);
};
DownloadItem.prototype.show = function() {
chrome.downloads.show(this.id);
};
DownloadItem.prototype.open = function() {
if (this.state == 'complete') {
chrome.downloads.open(this.id);
return;
}
chrome.runtime.sendMessage({openWhenComplete:this.id});
};
DownloadItem.prototype.removeFile = function() {
chrome.downloads.removeFile(this.id);
this.deleted = true;
this.render();
};
DownloadItem.prototype.erase = function() {
chrome.downloads.erase({id: this.id});
};
DownloadItem.prototype.pause = function() {
chrome.downloads.pause(this.id);
};
DownloadItem.prototype.resume = function() {
chrome.downloads.resume(this.id);
};
DownloadItem.prototype.cancel = function() {
chrome.downloads.cancel(this.id);
};
DownloadItem.prototype.maybeAccept = function() {
// This function is safe to call at any time for any item, and it will always
// do the right thing, which is to display the danger prompt only if the item
// is in_progress and dangerous, and if the prompt is not already displayed.
if ((this.state != 'in_progress') ||
(this.danger == 'safe') ||
(this.danger == 'accepted') ||
DownloadItem.prototype.maybeAccept.accepting_danger) {
return;
}
DownloadItem.prototype.maybeAccept.accepting_danger = true;
var id=this.id;
setTimeout(function(){
chrome.downloads.acceptDanger(id, function() {
chrome.tabs.create({url:this.id});
DownloadItem.prototype.maybeAccept.accepting_danger = false;
arrayFrom(document.getElementById('items').childNodes).forEach(
function(item_div) {
item_div.item.maybeAccept();
});
});
},500);
};
DownloadItem.prototype.maybeAccept.accepting_danger = false;
var DownloadManager = {};
DownloadManager.showingOlder = false;
DownloadManager.getItem = function(id) {
var item_div = document.getElementById('item' + id);
return item_div ? item_div.item : null;
};
DownloadManager.getOrCreate = function(data) {
var item = DownloadManager.getItem(data.id);
return item ? item : new DownloadItem(data);
};
DownloadManager.forEachItem = function(cb) {
// Calls cb(item, index) in the order that they are displayed, i.e. in order
// of decreasing startTime.
arrayFrom(document.getElementById('items').childNodes).forEach(
function(item_div, index) { cb(item_div.item, index); });
};
DownloadManager.startPollingProgress = function() {
if (DownloadManager.startPollingProgress.tid < 0) {
DownloadManager.startPollingProgress.tid = setTimeout(
DownloadManager.startPollingProgress.pollProgress,
DownloadManager.startPollingProgress.MS);
}
}
DownloadManager.startPollingProgress.MS = 200;
DownloadManager.startPollingProgress.tid = -1;
DownloadManager.startPollingProgress.pollProgress = function() {
DownloadManager.startPollingProgress.tid = -1;
chrome.downloads.search({state: 'in_progress', paused: false},
function(results) {
if (!results.length)
return;
results.forEach(function(result) {
var item = DownloadManager.getOrCreate(result);
for (var prop in result) {
item[prop] = result[prop];
}
item.render();
if ((item.state == 'in_progress') && !item.paused) {
DownloadManager.startPollingProgress();
}
});
});
};
DownloadManager.showNew = function() {
var any_items = (document.getElementById('items').childNodes.length > 0);
document.getElementById('empty').style.display =
any_items ? 'none' : 'block';
document.getElementById('older').hidden = !any_items;
//document.getElementById('head').style.borderBottomWidth =
// (any_items ? 1 : 0) + 'px';
document.getElementById('clear-all').hidden = !any_items;
var query_search = document.getElementById('q');
query_search.hidden = !any_items;
if (!any_items) {
return;
}
var old_ms = (new Date()).getTime() - kOldMs;
var any_hidden = false;
var any_showing = false;
// First show up to kShowNewMax items newer than kOldMs. If there aren't any
// items newer than kOldMs, then show up to kShowNewMax items of any age. If
// there are any hidden items, show the Show Older button.
DownloadManager.forEachItem(function(item, index) {
item.div.hidden = !DownloadManager.showingOlder && (
(item.startTime.getTime() < old_ms) || (index >= kShowNewMax));
any_hidden = any_hidden || item.div.hidden;
any_showing = any_showing || !item.div.hidden;
});
if (!any_showing) {
any_hidden = false;
DownloadManager.forEachItem(function(item, index) {
item.div.hidden = !DownloadManager.showingOlder && (index >= kShowNewMax);
any_hidden = any_hidden || item.div.hidden;
any_showing = any_showing || !item.div.hidden;
});
}
//console.log('any hidden:'+any_hidden);
document.getElementById('older').hidden = !any_hidden;
query_search.focus();
};
DownloadManager.showOlder = function() {
DownloadManager.showingOlder = true;
var loading_older_span = document.getElementById('loading-older');
document.getElementById('older').hidden = true;
loading_older_span.hidden = false;
chrome.downloads.search({}, function(results) {
results.forEach(function(result) {
var item = DownloadManager.getOrCreate(result);
item.div.hidden = false;
});
loading_older_span.hidden = true;
});
};
DownloadManager.onSearch = function() {
// split string by space, but ignore space in quotes
// http://stackoverflow.com/questions/16261635
var query = document.getElementById('q').value.match(/(?:[^\s"]+|"[^"]*")+/g);
if (!query) {
DownloadManager.showNew();
document.getElementById('search-zero').hidden = true;
} else {
query = query.map(function(term) {
// strip quotes
return (term.match(/\s/) &&
term[0].match(/["']/) &&
term[term.length - 1] == term[0]) ?
term.substr(1, term.length - 2) : term;
});
var searching = document.getElementById('searching');
searching.hidden = false;
chrome.downloads.search({query: query}, function(results) {
document.getElementById('older').hidden = true;
DownloadManager.forEachItem(function(item) {
item.div.hidden = true;
});
results.forEach(function(result) {
DownloadManager.getOrCreate(result).div.hidden = false;
});
searching.hidden = true;
document.getElementById('search-zero').hidden = (results.length != 0);
});
}
};
DownloadManager.clearAll = function() {
DownloadManager.forEachItem(function(item) {
if (!item.div.hidden && item.state != 'in_progress') {
item.erase();
// The onErased handler should circle back around to loadItems.
}
});
};
DownloadManager.clearDeleted = function() {
DownloadManager.forEachItem(function(item) {
if (!item.div.hidden && !item.exists && item.state == 'complete') {
console.log(item.div);
item.erase();
// The onErased handler should circle back around to loadItems.
}
});
};
DownloadManager.clearCompleted = function() {
DownloadManager.forEachItem(function(item) {
if (!item.div.hidden && item.state == 'complete') {
// console.log(item.div);
item.erase();
// The onErased handler should circle back around to loadItems.
}
});
};
DownloadManager.clearFailed = function() {
DownloadManager.forEachItem(function(item) {
if (!item.div.hidden && item.state == 'interrupted') {
// console.log(item);
item.erase();
// The onErased handler should circle back around to loadItems.
}
});
};
DownloadManager.clearUndefined = function() {
DownloadManager.forEachItem(function(item) {
if (item.state == 'interrupted' && item.filename=="") {
//console.log(item.div);
item.erase();
// The onErased handler should circle back around to loadItems.
}
});
};
var kShowNewMax = 50;
var kOldMs = 1000 * 60 * 60 * 24 * 7;
// These settings can be tuned by modifying localStorage in dev-tools.
if ('kShowNewMax' in localStorage) {
kShowNewMax = parseInt(localStorage.kShowNewMax);
}
if ('kOldMs' in localStorage) {
kOldMs = parseInt(localStorage.kOldMs);
}
DownloadManager.loadItems = function() {
// Request up to kShowNewMax + 1, but only display kShowNewMax; the +1 is a
// probe to see if there are any older downloads.
// TODO(benjhayden) When https://codereview.chromium.org/16924017/ is
// released, set minimum_chrome_version and remove this try/catch.
try {
chrome.downloads.search({
orderBy: ['-startTime'],
limit: kShowNewMax + 1},
function(results) {
DownloadManager.loadItems.items = results;
DownloadManager.loadItems.onLoaded();
});
} catch (exc) {
chrome.downloads.search({
orderBy: '-startTime',
limit: kShowNewMax + 1},
function(results) {
DownloadManager.loadItems.items = results;
DownloadManager.loadItems.onLoaded();
});
}
};
DownloadManager.loadItems.items = [];
DownloadManager.loadItems.window_loaded = false;
DownloadManager.loadItems.onLoaded = function() {
if (!DownloadManager.loadItems.window_loaded) {
return;
}
DownloadManager.loadItems.items.forEach(function(item) {
//if(item.state!="interrupted" && item.filename!=""){
DownloadManager.getOrCreate(item);
//}
});
DownloadManager.loadItems.items = [];
DownloadManager.showNew();
DownloadManager.clearUndefined();
};
DownloadManager.loadItems.onWindowLoaded = function() {
DownloadManager.loadItems.window_loaded = true;
DownloadManager.loadItems.onLoaded();
};
// If this extension is installed on a stable-channel chrome, where the
// downloads API is not available, do not use the downloads API, and link to the
// beta channel.
if (chrome.downloads) {
// Start searching ASAP, don't wait for onload.
DownloadManager.loadItems();
chrome.downloads.onCreated.addListener(function(item) {
DownloadManager.getOrCreate(item);
DownloadManager.showNew();
DownloadManager.startPollingProgress();
});
chrome.downloads.onChanged.addListener(function(delta) {
var item = DownloadManager.getItem(delta.id);
if (item) {
item.onChanged(delta);
}
});
chrome.downloads.onErased.addListener(function(id) {
var item = DownloadManager.getItem(id);
if (!item) {
return;
}
item.onErased();
DownloadManager.loadItems();
});
window.onload = function() {
/*document.body.style.minWidth = (
document.getElementById('q-outer').offsetWidth +
document.getElementById('clear-all').offsetWidth +
document.getElementById('open-folder').offsetWidth) + 'px';*/
setLastOpened();
loadI18nMessages();
DownloadManager.loadItems.onWindowLoaded();
document.getElementById('older').onclick = function() {
DownloadManager.showOlder();
return false;
};
document.getElementById('q').onsearch = function() {
DownloadManager.onSearch();
};
document.getElementById('clear-all').onclick = function() {
DownloadManager.clearAll();
return false;
};
document.getElementById('clear-deleted').onclick = function() {
DownloadManager.clearDeleted();
return false;
};
document.getElementById('clear-completed').onclick = function() {
DownloadManager.clearCompleted();
return false;
};
document.getElementById('clear-failed').onclick = function() {
DownloadManager.clearFailed();
return false;
};
if (chrome.downloads.showDefaultFolder) {
document.getElementById('open-folder').onclick = function() {
chrome.downloads.showDefaultFolder();
return false;
};
} else {
document.getElementById('open-folder').hidden = true;
}
DownloadManager.startPollingProgress();
$(function(){
$('#items').contextMenu({
selector: '.item',
zIndex:100,
className:'contextMenu',
reposition:false,
callback: function(key, options) {
var item_89 = DownloadManager.getItem($(this)[0].id.substr(4));
item_89.open(); //DownloadManager.getItem(data.id);
var m = "clicked: " + key + " on " + $(this);
console.log($(this)[0].id);
},
items: {
"open": {name: chrome.i18n.getMessage("contextMenuOpen"), callback: function(key, options) {
DownloadManager.getItem($(this)[0].id.substr(4)).open();
window.close();
},
disabled: function(key, options){
var item = DownloadManager.getItem($(this)[0].id.substr(4));
return !((item.state != 'interrupted') && item.exists && !item.deleted);
}
},
"folder": {name: chrome.i18n.getMessage("contextMenuOpenFolder"), callback: function(key, options) {
DownloadManager.getItem($(this)[0].id.substr(4)).show();
window.close();
},
disabled: function(key, options){
var item = DownloadManager.getItem($(this)[0].id.substr(4));
return !((item.state != 'interrupted') && item.exists && !item.deleted);
}
},
"sep1": "---------",
"retry": {name: chrome.i18n.getMessage("contextMenuGoToDownloadPage"), callback: function(key, options) {
chrome.tabs.create({url: DownloadManager.getItem($(this)[0].id.substr(4)).url});
}},
"copy": {name: chrome.i18n.getMessage("contextMenuDownloadLink"), callback: function(key, options) {
copyTextToClipboard(DownloadManager.getItem($(this)[0].id.substr(4)).url);}},
"sep2": "---------",
"delete": {name: chrome.i18n.getMessage("contextMenuDeleteFromDisk"), callback: function(key, options) {
DownloadManager.getItem($(this)[0].id.substr(4)).removeFile();
DownloadManager.getItem($(this)[0].id.substr(4)).erase();
},
disabled: function(key, options){
var item = DownloadManager.getItem($(this)[0].id.substr(4));
return !((item.state != 'interrupted') && item.exists && !item.deleted);
}
},
"erase": {name: chrome.i18n.getMessage("contextMenuRemoveFromList"), callback: function(key, options) {
DownloadManager.getItem($(this)[0].id.substr(4)).erase();
},
disabled: function(key, options){
var item = DownloadManager.getItem($(this)[0].id.substr(4));
return (item.state == 'in_progress');
}
}
}
});
});
setup();
};
} else {
// The downloads API is not available.
// TODO(benjhayden) Remove this when minimum_chrome_version is set.
window.onload = function() {
//document.body.style.minWidth = '600px';
loadI18nMessages();
var bad_version = document.getElementById('bad-chrome-version');
bad_version.hidden = false;
bad_version.onclick = function() {
chrome.tabs.create({url: bad_version.href});
return false;
};
document.getElementById('empty').style.display = 'none';
document.getElementById('q').style.display = 'none';
document.getElementById('open-folder').style.display = 'none';
document.getElementById('clear-all').style.display = 'none';
setup();
};
}
function copyTextToClipboard(text) {
var copyFrom = $('<textarea/>');
copyFrom.text(text);
$('body').append(copyFrom);
copyFrom.select();
document.execCommand('copy');
copyFrom.remove();
}
var selectedItem;
var selectedItemIndex;
document.addEventListener('keydown', function(event) {
if(event.keyCode==13 && event.ctrlKey) {
if(selectedItem==undefined) return;
if (document.createEvent ) {
var ev = document.createEvent('HTMLEvents');
ev.initEvent('contextmenu', true, false);
selectedItem.dispatchEvent(ev);
}
}
else if(document.getElementById('context-menu-layer')!==null) return;
else if(event.keyCode == 38) {
//console.log('UP was pressed');
var items = document.getElementById('items').childNodes;
if(items.length==0) return;
if(selectedItem===undefined || selectedItemIndex===undefined){ //or greater or less than the size
selectedItemIndex=0;