-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommandUtils.ts
More file actions
97 lines (91 loc) · 2.82 KB
/
commandUtils.ts
File metadata and controls
97 lines (91 loc) · 2.82 KB
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
import type { DownloadTool } from "./types";
export interface CommandGenerationParams {
originalUrl: string
filename: string | undefined
requestHeaders: Record<string, string> | undefined
cookies: string | undefined
userAgent: string | undefined
referer: string | undefined
tool: DownloadTool
}
export const generateCliCommand = ({
originalUrl,
filename,
requestHeaders,
cookies,
userAgent,
referer,
tool
}: CommandGenerationParams): string => {
let command = ""
const escapedUrl = `'${originalUrl.replace(/'/g, "'\\''")}'`
const effectiveUserAgent =
userAgent ||
(typeof navigator !== "undefined"
? navigator.userAgent
: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36")
const headersToUse = { ...requestHeaders }
const addHeader = (
key: string,
value: string,
toolType: "wget" | "curl" | "aria2"
) => {
const lowerKey = key.toLowerCase()
if (
lowerKey === "user-agent" ||
lowerKey === "cookie" ||
lowerKey === "referer"
) {
return ""
}
const escapedValue = value.replace(/'/g, "'\\''")
if (toolType === "wget" || toolType === "aria2") {
return ` --header='${key}: ${escapedValue}'`
} else {
return ` -H '${key}: ${escapedValue}'`
}
}
switch (tool) {
case "wget":
command = `wget -c --header='User-Agent: ${effectiveUserAgent}'`
if (cookies) command += ` --header='Cookie: ${cookies}'`
if (referer) command += ` --referer='${referer}'`
if (headersToUse) {
for (const key in headersToUse) {
if (headersToUse.hasOwnProperty(key)) {
command += addHeader(key, headersToUse[key], "wget")
}
}
}
command += ` -O '${filename || "downloaded_file"}' ${escapedUrl}`
break
case "aria2":
command = `aria2c -c -x5 -s5 -k1M --user-agent='${effectiveUserAgent}'`
if (cookies) command += ` --header='Cookie: ${cookies}'`
if (referer) command += ` --referer='${referer}'`
if (headersToUse) {
for (const key in headersToUse) {
if (headersToUse.hasOwnProperty(key)) {
command += addHeader(key, headersToUse[key], "aria2")
}
}
}
command += ` -o '${filename || "downloaded_file"}' ${escapedUrl}`
break
case "curl":
default:
command = `curl -L -O -C - ${escapedUrl}`
command += ` -H 'User-Agent: ${effectiveUserAgent}'`
if (cookies) command += ` -H 'Cookie: ${cookies}'`
if (referer) command += ` -H 'Referer: ${referer}'`
if (headersToUse) {
for (const key in headersToUse) {
if (headersToUse.hasOwnProperty(key)) {
command += addHeader(key, headersToUse[key], "curl")
}
}
}
break
}
return command
}