MCPcopy Create free account
hub / github.com/Eltaurus-Lt/CourseDump2022 / downloadFile

Function downloadFile

background.js:20–77  ·  view source on GitHub ↗
(options)

Source from the content-addressed store, hash-verified

18}
19
20function downloadFile(options) {
21 return new Promise(async (resolve, reject) => {
22 let iid, deltas = {};
23 const onDownloadComplete = delta => {
24 if (iid === undefined) {
25 deltas[delta.id] = delta;
26 } else if (delta.id == iid) {
27 checkDelta(delta);
28 }
29 }
30 chrome.downloads.onChanged.addListener(onDownloadComplete);
31 function checkDelta(delta) {
32 if (delta.state && delta.state.current === "complete") {
33 chrome.downloads.onChanged.removeListener(onDownloadComplete);
34 resolve(delta.id);
35 } else if (delta.error) {
36 chrome.downloads.onChanged.removeListener(onDownloadComplete);
37 reject(new Error(delta.error.current));
38 } else if (delta.state && delta.state.current === "interrupted") {
39 chrome.downloads.onChanged.removeListener(onDownloadComplete);
40 reject(new Error(delta.state.current));
41 }
42 }
43 const timeId = setTimeout(async () => {
44 if (iid !== undefined) return;
45 if (options.url) {
46 const query = { url: options.url };
47 const items = await chrome.downloads.search(query);
48 if (items.length) {
49 let item = items[0];
50 let iid = item.id;
51 if (iid in deltas) {
52 console.log(`saved with timeout ${options.filename} | item id = ${iid}`);
53 checkDelta(deltas[iid]);
54 } else if ((item.state && item.state === "complete") || (item.bytesReceived && item.totalBytes && item.bytesReceived === item.totalBytes)) {
55 console.log(`saved from log with timeout ${options.filename} | item id = ${iid}`);
56 chrome.downloads.onChanged.removeListener(onDownloadComplete);
57 resolve(iid);
58 } else {
59 console.log(`download timed out on ${options.filename} | item id = ${iid}`);
60 }
61 return;
62 }
63 }
64 chrome.downloads.onChanged.removeListener(onDownloadComplete);
65 reject(new Error("API timeout"));
66 }, apiTimeout);
67 try {
68 iid = await chrome.downloads.download(options);
69 } catch (err) {
70 chrome.downloads.onChanged.removeListener(onDownloadComplete);
71 return reject(err);
72 } finally {
73 clearTimeout(timeId);
74 }
75 if (iid in deltas) checkDelta(deltas[iid]);
76 });
77}

Callers 1

background.jsFile · 0.85

Calls 1

checkDeltaFunction · 0.85

Tested by

no test coverage detected