-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
110 lines (92 loc) · 2.38 KB
/
main.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
const path = require("path");
const os = require("os");
const { app } = require("electron").remote;
const { download } = require("./lib/downloader");
const $url = document.querySelector('input[name="url"]');
const $btn = document.querySelector("button");
const $output = document.querySelector('input[name="output"]');
const $info = document.querySelector("#info");
const $progress = document.querySelector("#progress");
const $err = document.querySelector("#err");
const $done = document.querySelector("#done");
let downloading = false;
$btn.addEventListener("click", () => {
clear();
clearInfo();
if (downloading) {
alert("正在处理中,不要重复点击");
return;
}
const dir = getPath($output) || app.getPath("downloads");
if (!dir) {
alert("无法获取下载目录");
return;
}
const url = $url.value.replace(/\s/g, "");
if (!/^https?:\/\//.test(url)) {
alert("网址格式不正确");
return;
}
let failed = false;
downloading = true;
disableBtn();
const onData = (progress) => {
if (failed) return;
if (/title/.test(progress)) {
const text = progress
.split("\n")
.filter((t) => /(site|title)/.test(t))
.join("\n");
$info.innerText = text;
return;
}
$progress.innerText = progress;
};
const onErr = (err) => {
failed = true;
downloading = false;
enableBtn();
clear();
if (/file already exists/.test(err)) {
$err.innerText = "文件已存在, 清除缓存后重新下载";
} else {
$err.innerText = err;
}
};
const onEnd = (code) => {
if (failed) return;
clear();
$done.innerText = code === 0 ? "下载完成" : "未知错误";
};
try {
download(url, dir, onData, onErr, onEnd);
} catch (e) {
onErr(e.message || "未知异常");
downloading = false;
enableBtn();
failed = false;
}
});
$output.addEventListener("change", (event) => {});
function clear() {
$err.innerText = "";
$progress.innerText = "";
$done.innerText = "";
}
function clearInfo() {
$info.innerText = "";
}
function disableBtn() {
$btn.classList.add("disable");
$btn.innerText = "下载中";
}
function enableBtn() {
$btn.classList.remove("disable");
$btn.innerText = "开始";
}
function getPath(input) {
if (!input.files.length) return "";
const file = input.files[0].path;
const dir = path.dirname(file);
return dir;
}