-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjsdownloader.js
executable file
·184 lines (155 loc) · 5.78 KB
/
jsdownloader.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
import https from 'https';
import fs from 'fs';
import path from 'path';
import os from 'os';
const WebTorrent = (await import('webtorrent')).default;
const waitTime = 3000;
const drawProgressBar = (progress) => {
const barWidth = 30;
const filledWidth = Math.floor(progress / 100 * barWidth);
const emptyWidth = barWidth - filledWidth;
let progressBar = '█'.repeat(filledWidth) + '▒'.repeat(emptyWidth);
let color;
if (progress >= 1 && progress <= 49) {
color = '\x1b[31m';
} else if (progress >= 50 && progress <= 99) {
color = '\x1b[33m';
} else {
color = '\x1b[32m';
}
return `${color}[${progressBar}] ${progress}%\x1b[0m`;
};
const getDownloadDirectory = () => {
let downloadsDir;
switch (os.platform()) {
case 'win32':
downloadsDir = path.join(os.homedir(), 'Desktop', 'downloads');
break;
case 'darwin':
downloadsDir = path.join(os.homedir(), 'Desktop', 'downloads');
break;
case 'linux':
downloadsDir = path.join(os.homedir(), 'Desktop', 'downloads');
break;
default:
throw new Error('Unsupported platform');
}
if (!fs.existsSync(downloadsDir)) {
fs.mkdirSync(downloadsDir, { recursive: true });
}
return downloadsDir;
};
const downloadFile = (url, destination) => {
return new Promise((resolve, reject) => {
const downloadDir = getDownloadDirectory();
https.get(url, (res) => {
const totalSize = parseInt(res.headers['content-length'], 10);
let downloaded = 0;
const writeStream = fs.createWriteStream(destination);
res.on('data', (chunk) => {
downloaded += chunk.length;
const progress = Math.floor((downloaded / totalSize) * 100);
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(`Progress: ${drawProgressBar(progress)}`);
});
res.pipe(writeStream);
writeStream.on('finish', () => {
console.log(`\nDownload finished: ${destination}`);
resolve();
});
writeStream.on('error', (err) => {
console.error(`Error downloading ${url}: ${err.message}`);
reject(err);
});
}).on('error', (err) => {
console.error(`Error downloading ${url}: ${err.message}`);
reject(err);
});
});
};
const downloadTorrent = (torrentLink) => {
return new Promise((resolve, reject) => {
const client = new WebTorrent();
client.on('error', (err) => {
console.error('Error with torrent client: ', err);
reject(err);
});
const downloadDir = getDownloadDirectory();
client.add(torrentLink, { path: downloadDir }, (torrent) => {
torrent.on('download', (bytes) => {
const progress = Math.floor((torrent.downloaded / torrent.length) * 100);
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(`Progress: ${drawProgressBar(progress)}`);
});
torrent.on('done', () => {
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(`Progress: ${drawProgressBar(100)}\n`);
console.log(`Download finished: ${torrent.infoHash}`);
client.destroy();
resolve();
});
});
});
};
const downloadFromTxtFile = (filePath) => {
fs.readFile(filePath, 'utf-8', (err, data) => {
if (err) {
console.error(`Error reading ${filePath}: ${err.message}`);
return;
}
const urls = data.split('\n').map(url => url.trim().replace(/^["']|["']$/g, '')).filter(url => url !== '');
const downloadSequentially = async () => {
for (const url of urls) {
try {
if (url.startsWith('magnet:')) {
await downloadTorrent(url);
} else {
const fileName = path.basename(url);
await downloadFile(url, path.join(getDownloadDirectory(), fileName));
}
} catch (err) {
console.error(`Error during download: ${err.message}`);
break;
}
}
console.log('All downloads finished.');
process.exit(0);
};
downloadSequentially().catch((err) => {
console.error('Error in sequential download process:', err);
process.exit(1);
});
});
};
const downloadFromLink = (urlOrPath) => {
const downloadDir = getDownloadDirectory();
if (urlOrPath.endsWith('.txt')) {
downloadFromTxtFile(urlOrPath);
} else if (urlOrPath.startsWith('magnet:')) {
downloadTorrent(urlOrPath)
.then(() => {
process.exit(0);
})
.catch((err) => {
console.error('Magnet link download error:', err);
process.exit(1);
});
} else {
const fileName = path.basename(urlOrPath);
downloadFile(urlOrPath, path.join(downloadDir, fileName));
}
};
let downloadLink = process.argv[2];
if (downloadLink && downloadLink.startsWith("'") && downloadLink.endsWith("'")) {
downloadLink = downloadLink.slice(1, -1);
} else if (downloadLink && downloadLink.startsWith('"') && downloadLink.endsWith('"')) {
downloadLink = downloadLink.slice(1, -1);
}
if (downloadLink) {
downloadFromLink(downloadLink);
} else {
console.error('Please provide a URL or a path to a .txt file with URLs.');
}