Skip to content
This repository has been archived by the owner on Nov 2, 2023. It is now read-only.

Commit

Permalink
fix download timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
takayama-lily committed Feb 28, 2021
1 parent 543ed04 commit 85367e6
Showing 1 changed file with 14 additions and 20 deletions.
34 changes: 14 additions & 20 deletions lib/service.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,7 @@ async function highwayUpload(ip, port, o, cmd) {
*/
async function downloadFromWeb(url, headers, timeout, proxy, mime_type, maxsize = MAX_UPLOAD_SIZE, redirect = false) {
if (timeout > 0 === false)
timeout = 120;
timeout = parseInt(timeout * 1000);
timeout = 60;
const protocol = url.startsWith("https") ? https : http;
if (typeof headers === "string") {
try {
Expand All @@ -117,7 +116,7 @@ async function downloadFromWeb(url, headers, timeout, proxy, mime_type, maxsize
headers = null;
}
}
const options = { timeout, headers };
const options = { headers };
if (proxy && process.env.http_proxy) {
try {
const agent = new HttpsProxyAgent(process.env.http_proxy);
Expand All @@ -128,27 +127,21 @@ async function downloadFromWeb(url, headers, timeout, proxy, mime_type, maxsize
}
return new Promise((resolve, reject) => {
try {
const req = protocol.get(url, options, async (res) => {
// 重定向一次(没有好的库暂时手动实现)
const req = protocol.get(url, options, (res) => {
// 重定向一次(暂时手动实现)
if (String(res.statusCode).startsWith("3") && !redirect && res.headers["location"]) {
try {
resolve(await downloadFromWeb(res.headers["location"], headers, timeout, proxy, mime_type, maxsize, true));
} catch (e) {
reject(e);
}
return;
return downloadFromWeb(res.headers["location"], headers, timeout, proxy, mime_type, maxsize, true)
.then(resolve)
.catch(reject);
}
if (res.statusCode !== 200) {
reject("http status code: " + res.statusCode);
return;
return reject("http status code: " + res.statusCode);
}
if (mime_type && (!res.headers["content-type"] || !res.headers["content-type"].includes(mime_type))) {
reject("不是合法的" + mime_type + "文件。");
return;
return reject("不是合法的" + mime_type + "文件。");
}
if (res.headers["content-length"] && res.headers["content-length"] > maxsize) {
reject(`文件体积太大(maxsize=${maxsize})。`);
return;
return reject(`文件体积太大(maxsize=${maxsize})。`);
}
let data = Buffer.alloc(0);
res.on("data", (chunk) => {
Expand All @@ -164,10 +157,11 @@ async function downloadFromWeb(url, headers, timeout, proxy, mime_type, maxsize
});
req.on("error", (e) => {
reject(e.message);
}).on("timeout", () => {
req.destroy();
reject("connect ETIMEDOUT");
});
setTimeout(() => {
req.destroy();
reject(`下载超时 (${timeout}s)`);
}, timeout * 1000);
} catch (e) {
reject(e.message);
}
Expand Down

0 comments on commit 85367e6

Please sign in to comment.