-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathservice.js
164 lines (149 loc) · 3.83 KB
/
service.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
/**
* The method `chrome.downloads.download` does not work with the option:
* "Ask where to save each file before downloading" enabled.
* If the option is disabled (chrome://settings/downloads), this feature will work fine.
*
* This is an issue with the actual chrome API (only MV3, not MV2) — see:
* [https://bugs.chromium.org/p/chromium/issues/detail?id=1173497]
* [https://bugs.chromium.org/p/chromium/issues/detail?id=1246717]
*
* Anyways...
* This method is prioritized because it's very useful if it works, but fallbacks are needed.
*/
/** Default options for the addon to use */
const options = {
'download-fallback-tab-focus': {
type: 'toggle',
default: true,
current: null
},
'download-subfolder-path': {
type: 'text',
default: false,
current: null
},
'download-naming-template': {
type: 'text',
default: false,
current: null
}
};
/** Set default storage values */
Object.keys(options).forEach((key) => {
chrome.storage.local.get(key, (result) => {
if(result && !result.hasOwnProperty(key)) {
let value = new Object();
value[key] = options[key].default;
chrome.storage.local.set(value);
}
});
});
/**
* Options getter
*/
const optionsGet = (args) => {
return args.sendResponse(options);
};
/**
* Attempts to download a file using `chrome.downloads.download`
*
* @param {object} args
*/
const fileDownload = (args) => {
let [filename, url, subFolder] = [
args.data.filename,
args.data.url,
args.data.subFolder
];
if(subFolder && subFolder.length > 1 && !subFolder.endsWith('/')) {
subFolder = (subFolder + '/');
}
try {
console.log('[TTDB]', 'Attempting download', {
filename: `${subFolder ? subFolder : ''}${filename}`,
url: url
});
chrome.downloads.download({
conflictAction: 'uniquify',
filename: `${subFolder ? subFolder : ''}${filename}`,
url: url,
method: 'GET',
saveAs: false
}, (itemId) =>
{
chrome.downloads.onChanged.addListener((delta) => {
if(itemId === delta.id) {
console.log('[TTDB]', delta);
if(delta.endTime || (delta.state && delta.state.current === 'complete')) {
// Successful download
args.sendResponse({ itemId: itemId, success: true });
} else if(delta.error) {
// Error encountered
args.sendResponse({ success: false });
}
}
});
});
} catch(error) {
// Error encountered
args.sendResponse({ success: false });
}
};
/**
* Opens the default download folder
*/
const showDefaultFolder = () => {
chrome.downloads.showDefaultFolder();
};
/**
* Opens a new tab in Chrome
*
* @param {object} args
*/
const windowOpen = (args) => {
chrome.tabs.create({
url: args.data.url,
active: args.data.active ? args.data.active : false
}, () => { // May wanna handle errors here, not a priority for now however
args.sendResponse({
success: true
});
});
};
/**
* Fetching function
*/
const serviceFetch = async (args) => {
const url = args.data.url;
const options = args.data.options || {};
return fetch(url, options).then((response) => {
return response.json();
}).then((data) => {
args.sendResponse({ data: data, error: false });
}).catch((error) => {
console.info('Caught a fetching error:', error);
args.sendResponse({ data: null, error: error });
})
};
/**
* `onMessage` listener
*/
chrome.runtime.onMessage.addListener((data, sender, sendResponse) => {
// Task IDs and their corresponding methods
const tasks = {
'fileDownload': fileDownload,
'windowOpen': windowOpen,
'fileShow': showDefaultFolder,
'optionsGet': optionsGet,
'fetch': serviceFetch
};
if(tasks[data.task])
{
tasks[data.task]({ // Perform task
data,
sender,
sendResponse
});
}
return true;
});