forked from xifangczy/cat-catch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
download.js
290 lines (276 loc) · 10.1 KB
/
download.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
// url 参数解析
const params = new URL(location.href).searchParams;
const _url = params.get("url");
// const _referer = params.get("referer");
const _initiator = params.get("initiator");
const _requestHeaders = params.get("requestHeaders");
const _fileName = params.get("filename");
// const autosend = params.get("autosend");
// const autoClose = params.get("autoClose");
const downStream = params.get("downStream");
const title = params.get("title");
// const fileFlag = params.get("fileFlag");
const _ffmpeg = params.get("ffmpeg");
const _quantity = params.get("quantity");
const _taskId = params.get("taskId");
// 修改当前标签下的所有xhr的Referer
let requestHeaders = JSONparse(_requestHeaders);
if (!requestHeaders.referer && _initiator) {
requestHeaders.referer = _initiator;
}
setRequestHeaders(requestHeaders, () => { awaitG(start); });
function start() {
$("#autoClose").prop("checked", G.downAutoClose);
// $("#downActive").prop("checked", G.downActive);
$("#downStream").prop("checked", G.downStream);
$(`<style>${G.css}</style>`).appendTo("head");
// 流式下载服务端
streamSaver.mitm = G.streamSaverConfig.url;
chrome.tabs.getCurrent(function (tab) {
startDownload(tab.id);
});
}
function startDownload(tabId) {
// 没有url 打开输入框
if (!_url) {
$("#getURL").show();
$("#getURL_btn").click(function () {
const url = $("#getURL #url").val().trim();
const referer = $("#getURL #referer").val().trim();
let href = `?url=${encodeURIComponent(url)}&requestHeaders=${encodeURIComponent(JSON.stringify({ referer: referer }))}`;
if ($("#downStream").prop("checked")) {
href += "&downStream=true";
}
window.location.href = href;
});
return;
}
$("#downfile").show();
const $downFilepProgress = $("#downFilepProgress");
const $progress = $(".progress");
let blobUrl = ""; // 储存blob
let downId = 0; // 下载的文件ID
// 标题 显示 进度
let timer = null;
let lastUpdate = 0;
const setProgressText = (progress, html) => {
const now = Date.now();
html && $downFilepProgress.html(progress);
if (now - lastUpdate >= 500) {
document.title = progress;
lastUpdate = now;
}
timer && clearInterval(timer);
timer = setInterval(() => {
document.title = progress;
lastUpdate = Date.now();
}, 500);
}
// 是否边下边存
let fileStream = null;
const filename = _fileName ? stringModify(_fileName) : getUrlFileName(_url);
if ((downStream || G.downStream) && !_ffmpeg) {
fileStream = streamSaver.createWriteStream(filename).getWriter();
}
// 开始下载
let receivedLength = 0; // 已下载大小
$("#stopDownload").show();
const controller = new AbortController();
fetch(_url, {
signal: controller.signal,
headers: new Headers({
'Cache-Control': 'no-cache'
})
}).then(response => {
if (!response.ok) {
// 某些网站需要传输 range
if (!requestHeaders.range) {
requestHeaders.range = "bytes=0-";
params.set("requestHeaders", JSON.stringify(requestHeaders));
const href = window.location.origin + window.location.pathname + "?" + params.toString();
window.location.href = href;
return;
}
$downFilepProgress.html(response.status);
console.error(response);
throw new Error(response.statusText + " " + response.status);
}
const reader = response.body.getReader();
const contentLength = parseInt(response.headers.get('content-length')) || 0;
const contentLengthFormat = byteToSize(contentLength);
const contentType = response.headers.get('content-type') ?? 'video/mp4';
const chunks = [];
const pump = async () => {
while (true) {
const { value, done } = await reader.read();
if (done) { break; }
fileStream ? fileStream.write(new Uint8Array(value)) : chunks.push(value);
receivedLength += value.length;
const receivedLengthFormat = byteToSize(receivedLength);
if (contentLength) {
const progress = (receivedLength / contentLength * 100).toFixed(2) + "%";
setProgressText(progress);
$downFilepProgress.html(receivedLengthFormat + " / " + contentLengthFormat + " " + progress);
$progress.css("width", progress);
} else {
setProgressText(receivedLengthFormat, true);
}
}
setProgressText(i18n.downloadComplete, true);
if (!fileStream) {
let position = 0;
const allChunks = new Uint8Array(receivedLength);
for (const chunk of chunks) {
allChunks.set(chunk, position);
position += chunk.length;
}
return new Blob([allChunks], { type: contentType });
}
fileStream.close();
}
return pump();
}).then(blob => {
$("#stopDownload").hide();
if (fileStream) {
setProgressText(i18n.downloadComplete, true);
fileStream = null;
setTimeout(() => {
$("#autoClose").prop("checked") && window.close();
}, Math.ceil(Math.random() * 999));
return;
}
try {
blobUrl = URL.createObjectURL(blob);
$("#ffmpeg").show();
// 自动发送到ffmpeg
if (_ffmpeg) {
setProgressText(i18n.sendFfmpeg, true);
sendFile("merge");
return;
}
setProgressText(i18n.saving, true);
chrome.downloads.download({
url: blobUrl,
filename: filename,
saveAs: G.saveAs
}, function (downloadId) {
setProgressText(i18n.downloadComplete, true);
downId = downloadId;
});
} catch (e) {
$downFilepProgress.html(i18n.saveFailed + e);
setProgressText(i18n.saveFailed);
}
}).catch(error => {
highlight();
if (fileStream) {
receivedLength ? fileStream.close() : fileStream.abort();
fileStream = null;
}
$("#stopDownload").hide();
if (error.name === 'AbortError') {
setProgressText(i18n.stopDownload);
$downFilepProgress.html(i18n.stopDownload);
} else {
setProgressText(i18n.downloadFailed);
$downFilepProgress.html(i18n.downloadFailed + " " + error);
console.error(error);
}
});
// 监听下载事件 修改提示
chrome.downloads.onChanged.addListener(function (downloadDelta) {
if (!downloadDelta.state) { return; }
if (downloadDelta.state.current == "complete" && downId != 0) {
document.title = i18n.downloadComplete;
$downFilepProgress.html(i18n.savePrompt);
if ($("#autoClose").prop("checked")) {
setTimeout(() => {
window.close();
}, Math.ceil(Math.random() * 999));
}
}
});
// 返回上一页
$("#historyBack").click(function () {
if (window.history.length > 1) {
window.history.back();
return;
}
window.location.href = "/download.html";
});
// 打开目录
$(".openDir").click(function () {
if (downId) {
chrome.downloads.show(downId);
return;
}
chrome.downloads.showDefaultFolder();
});
// 发送到在线ffmpeg
$("#ffmpeg").click(function () {
sendFile();
});
// 停止下载
$("#stopDownload").click(function () {
if (fileStream) {
fileStream.close();
fileStream = null;
}
controller.abort();
$("#stopDownload").hide();
});
function highlight() {
chrome.tabs.getCurrent(function name(params) {
chrome.tabs.highlight({ tabs: params.index });
});
}
function sendFile(action = "addFile") {
chrome.tabs.query({ url: G.ffmpegConfig.url }, function (tabs) {
if (tabs.length && tabs[0].status != "complete") {
setTimeout(() => {
sendFile(action);
}, 500);
return;
}
const data = {
Message: "catCatchFFmpeg",
action: action,
files: [{ data: blobUrl, name: getUrlFileName(_url) }],
title: title,
tabId: tabId,
taskId: _taskId ?? tabId
};
if (_quantity) {
data.quantity = parseInt(_quantity);
}
if (_taskId) {
data.taskId = _taskId;
}
chrome.runtime.sendMessage(data);
});
}
chrome.runtime.onMessage.addListener(function (Message, sender, sendResponse) {
if (!Message.Message || Message.Message != "catCatchFFmpegResult" || Message.state != "ok" || tabId == 0 || Message.tabId != tabId) { return; }
$downFilepProgress.html(i18n.sendFfmpeg);
setTimeout(() => {
$("#autoClose").prop("checked") && window.close();
}, Math.ceil(Math.random() * 999));
});
function getUrlFileName() {
try {
const pathname = new URL(_url).pathname;
const fileName = pathname.substring(pathname.lastIndexOf('/') + 1);
return fileName ? fileName : 'NULL';
} catch (error) {
return "NULL";
}
}
// 刷新/关闭页面 检查边下边存
window.addEventListener('beforeunload', function (e) {
if (fileStream) {
e.preventDefault();
e.returnValue = i18n.streamOnbeforeunload;
fileStream.close();
}
});
}