-
Notifications
You must be signed in to change notification settings - Fork 10
/
background.js
135 lines (102 loc) · 2.61 KB
/
background.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
(function() {
"use strict";
var imagesWaiting,
windowId,
openTabs,
openTabsCount,
autoDownload;
function cleanBeforeLoad() {
imagesWaiting = [];
openTabs = {};
openTabsCount = 0;
}
function openNextImage() {
if( imagesWaiting.length > 0 ) {
// Not too many waiting or not auto downloading?
if( openTabsCount < 5 || !autoDownload ) {
chrome.tabs.create({
windowId: windowId,
url: imagesWaiting.shift(),
active: false
}, tabOpened);
}
} else {
stopListeningForTabClose();
}
}
function tabOpened(tab) {
if( tab ) {
openTabs[ tab.id ] = true;
openTabsCount++;
openNextImage();
}
}
function listenForTabClose() {
stopListeningForTabClose();
chrome.tabs.onRemoved.addListener(tabClosed);
}
function stopListeningForTabClose() {
chrome.tabs.onRemoved.removeListener(tabClosed);
}
function tabClosed(tabId, removeInfo) {
if( openTabs[tabId] === true ) {
delete openTabs[tabId];
openTabsCount--;
openNextImage();
}
}
//////////////////////
function newDownloadNext() {
if( imagesWaiting.length > 0 && openTabsCount < 5 ) {
openTabsCount++;
callDownload(imagesWaiting.shift(), true);
newDownloadNext();
}
}
function callDownload(image, canRetry) {
chrome.downloads.download(image, function(downloadId) {
if( downloadId ) {
openTabs[downloadId] = true;
} else if(canRetry) {
// Couldn't download? Try removing title from name and fallback to original.
delete image.filename;
callDownload(image, false);
}
});
}
chrome.downloads.onChanged.addListener(function(delta) {
if( delta.state && delta.state.current === "complete" && openTabs[delta.id] === true ) {
delete openTabs[delta.id];
openTabsCount--;
newDownloadNext();
}
});
//////////////////////
// Listen for request to open all photos
chrome.extension.onRequest.addListener( function(request, sender, sendResponse)
{
if (request.msg === "openAllPhotos")
{
cleanBeforeLoad();
imagesWaiting = request.imgs;
if( imagesWaiting.length === 1 ) {
imagesWaiting[0].saveAs = true;
}
newDownloadNext();
// if( confirm("Are you sure you want to open " + request.imgs.length + " tab(s)? It may take a while to load everything.") )
// {
// // Open a new window with a blank page
// chrome.windows.create({url: "about:blank"}, function(win) {
// cleanBeforeLoad();
// windowId = win.id;
// autoDownload = request.autoDownload;
// imagesWaiting = request.imgs;
// if( autoDownload ) {
// listenForTabClose();
// }
// openNextImage();
// });
// }
}
});
})();