-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloudapp-dl.js
executable file
·190 lines (168 loc) · 5.35 KB
/
cloudapp-dl.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
#!/usr/bin/env node
import axios from 'axios';
import fs from 'fs';
import https from 'https';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import path from 'path';
import cheerio from 'cheerio';
const argv = yargs(hideBin(process.argv))
.option('url', {
alias: 'u',
type: 'string',
description: 'Url of the video in the format https://share.zight.com/[ID]'
})
.option('list', {
alias: 'l',
type: 'string',
description: 'Filename of the text file containing the list of URLs'
})
.option('prefix', {
alias: 'p',
type: 'string',
description: 'Prefix for the output filenames when downloading from a list'
})
.option('out', {
alias: 'o',
type: 'string',
description: 'Path to output the file to or directory to output files when using --list'
})
.option('defaultTitle', {
alias: 'd',
type: 'boolean',
default: false,
description: 'Use the page title as the default video title if available'
})
.option('timeout', {
alias: 't',
type: 'number',
description: 'Timeout in milliseconds to wait between downloads when using --list'
})
.check((argv) => {
if (!argv.url && !argv.list) {
throw new Error('Please provide either a single video URL with --url or a list of URLs with --list to proceed');
}
if (argv.url && argv.list) {
throw new Error('Please provide either --url or --list, not both');
}
if (argv.timeout && argv.timeout < 0) {
throw new Error('Please provide a non-negative number for --timeout');
}
return true;
})
.help()
.alias('help', 'h')
.argv;
const ensureDirectoryExists = (directoryPath) => {
if (!fs.existsSync(directoryPath)) {
fs.mkdirSync(directoryPath, { recursive: true });
}
};
const fetchDownloadUrl = async (pageUrl, useDefaultTitle) => {
try {
const response = await axios.get(pageUrl);
const pageData = response.data;
const $ = cheerio.load(pageData);
const twitterImageValue = $('meta[name="twitter:image"]').attr('value');
const videoTitle = $('meta[property="og:title"]').attr('content');
const firstSplit = twitterImageValue.split('.gif/');
if (firstSplit.length < 2) {
throw new Error('Video not found');
}
const secondSplit = firstSplit[1].split('?source');
if (secondSplit.length === 0) {
throw new Error('Video not found');
}
const mp4Url = `https://${secondSplit[0]}`;
if (useDefaultTitle && videoTitle) {
return { title: videoTitle, mp4Url };
} else {
return { mp4Url };
}
} catch (error) {
throw error;
}
};
const downloadVideo = (url, filename) => {
return new Promise((resolve, reject) => {
const directory = path.dirname(filename);
ensureDirectoryExists(directory);
const file = fs.createWriteStream(filename);
https.get(url, function (response) {
response.pipe(file);
file.on('finish', () => {
resolve(true);
});
file.on('error', (err) => {
fs.unlinkSync(filename);
reject(err);
});
});
});
};
const extractId = (url) => {
url = url.split('?')[0];
return url.split('/').pop();
};
const delay = (duration) => {
return new Promise(resolve => setTimeout(resolve, duration));
};
const downloadFromList = async () => {
const filePath = path.resolve(argv.list);
const fileContent = fs.readFileSync(filePath, 'utf8');
const urls = fileContent.split(/\r?\n/);
const outputDirectory = argv.out || '.';
const useDefaultTitle = argv.defaultTitle;
let completedDownloads = 0;
let totalDownloads = urls.length;
for (let i = 0; i < urls.length; i++) {
if (urls[i].trim()) {
const id = extractId(urls[i]);
const urlInfo = await fetchDownloadUrl(urls[i], useDefaultTitle).catch(e => {
console.error(`Failed to fetch URL for video ${id}: ${e.message}`);
return null;
});
if (!urlInfo) {
continue;
}
let filename;
if (argv.prefix) {
filename = path.join(outputDirectory, `${argv.prefix}-${i + 1}.mp4`);
} else {
filename = path.join(outputDirectory, useDefaultTitle && urlInfo.title ? `${urlInfo.title}.mp4` : `${id}.mp4`);
}
try {
await downloadVideo(urlInfo.mp4Url, filename);
console.log(`Successfully downloaded ${filename}`);
} catch (error) {
console.error(`Error downloading ${filename}: ${error}`);
}
completedDownloads++;
let progress = (completedDownloads / totalDownloads * 100).toFixed(2);
console.clear();
console.log(`Progress: ${progress}% - Downloaded ${completedDownloads} of ${totalDownloads} files`);
if (argv.timeout) {
await delay(argv.timeout);
}
}
}
};
const downloadSingleFile = async () => {
const id = extractId(argv.url);
const urlInfo = await fetchDownloadUrl(argv.url, argv.defaultTitle);
const filename = argv.out || (argv.defaultTitle && urlInfo.title ? `${urlInfo.title}.mp4` : `${id}.mp4`);
console.log(`Downloading video ${argv.defaultTitle && urlInfo.title ? urlInfo.title : id} and saving to ${filename}`);
downloadVideo(urlInfo.mp4Url, filename);
};
const main = async () => {
if (argv.list) {
await downloadFromList().catch(error => {
console.error(error.message);
});
} else if (argv.url) {
await downloadSingleFile().catch(error => {
console.error(error.message);
});
}
};
main();