-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathdownload.js
313 lines (310 loc) · 10.5 KB
/
download.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
const request = require('request')
const mime = require('mime-types')
const fs = require('fs')
const path = require('path')
const downloadDir = require('./downloadDir')
const filelist = require('./fileList')
const metaDir = require('./metaDir')
const ffmpeg = require('easy-ffmpeg')
const files = filelist.get()
const isWin = process.platform === 'win32'
files.forEach((el, ij) => {
if (!el.error && (!el.finished || !el.filePath || !fs.existsSync(el.filePath)))
files[ij].error = true
})
filelist.set(files)
function saveFiles() {
saveFilesTimer = null
const waitFor = filelist.set(files)
saveFilesTimer = setTimeout(saveFiles, 60 * 60 * 1000)
}
// no need to save on app start
let saveFilesTimer = setTimeout(saveFiles, 60 * 60 * 1000)
function clone(obj) { return JSON.parse(JSON.stringify(obj)) }
function checkFilePath(origPath, filePath, nr) {
filePath = filePath || origPath
nr = nr || 0
if (fs.existsSync(filePath)) {
const parts = origPath.split('.')
nr++
parts[parts.length -2] = parts[parts.length -2] + ' (' + nr + ')'
newFilePath = parts.join('.')
return checkFilePath(origPath, newFilePath, nr)
}
return filePath
}
function removeIllegalCharacters(name) {
if (!name)
return false
if (isWin) {
// illegal characters on windows are: < > : " / \ | ? *
return name.replace(/\<|\>|\:|\"|\/|\\|\||\?|\*/g,' ').replace(/ +/g, ' ')
} else {
// illegal characters on Linux / OSX are: /
return name.split('/').join(' ').replace(/ +/g, ' ')
}
}
function decideFilename(name, url, contentType) {
let isHls = false
if (contentType && hlsTypes.includes(contentType.toLowerCase()))
isHls = true
const ext = isHls ? 'mp4' : mime.extension(contentType)
if (name && ext)
return name + '.' + ext
let filename = url.split('/').pop()
if ((filename || '').includes('?'))
filename = filename.split('?')[0]
if (!filename || filename.length < 4 || !filename.includes('.') || isHls) {
if (contentType) {
if (name)
return name + '.' + ext
else
return 'Unknown.' + ext
} else
return false
} else
return filename
}
const hlsTypes = [
'video/m3u',
'video/m3u8',
'video/hls',
'application/x-mpegurl',
'vnd.apple.mpegURL',
'video/mp2t',
'application/vnd.apple.mpegurl'
]
function getMeta(url, metaUrl, metaId, metaType) {
request.get(metaUrl, (err, resp, body) => {
if (!err && body)
metaDir.setMeta(metaId, metaType, body)
})
}
const download = {
list: () => {
return clone(files).map(file => {
file.progress = Math.floor((file.current/file.total) * 100)
delete file.current
return file
}).reverse()
},
get: (name, url, streamId, filenameCb, metaUrl, metaId, metaType) => {
request.head(url, function(err, res, body){
if (!(res || {}).headers) {
filenameCb(false)
return
}
const total = res.headers['content-length']
const type = res.headers['content-type']
files.some((el, ij) => {
if (el.url == url) {
const waitFor = download.remove(null, url)
return true
}
})
const filename = removeIllegalCharacters(decideFilename(name, url, type))
if (!filename) {
filenameCb(false)
return
}
filenameCb(filename)
const downDir = downloadDir.get()
let filePath = path.join(downDir, filename)
filePath = checkFilePath(filePath)
if (type && hlsTypes.includes(type.toLowerCase())) {
// ffmpeg -i "http://example.com/video_url.m3u8" -c copy -bsf:a aac_adtstoasc "output.mp4"
const args = [
'-c copy',
'-bsf:a aac_adtstoasc'
]
const command = ffmpeg({ source: url, timeout: false })
command.on('start', (commandLine) => {
console.log('Spawned Ffmpeg with command: ', commandLine);
}).on('error', (err) => {
const idx = download.findIdx(url)
if (idx > -1 && !files[idx].stopped)
files[idx].error = true
}).on('close', (err, msg) => {
const idx = download.findIdx(url)
if (idx > -1 && err && !files[idx].stopped)
files[idx].error = true
}).on('exit', (err, msg) => {
const idx = download.findIdx(url)
if (idx > -1 && err && !files[idx].stopped)
files[idx].error = true
})
.on('end', (err, stdout, stderr) => {
const idx = download.findIdx(url)
if (idx > -1) {
files[idx].finished = true
const stats = fs.statSync(files[idx].filePath)
files[idx].total = (stats || {}).size || 0
}
})
command.outputOptions(args)
command.save(filePath)
files.push({
filename,
url,
type,
streamId,
total: 0,
current: 0,
isHls: true,
time: Date.now(),
filePath,
error: false,
finished: false,
stopped: false,
meta: { url: metaUrl, type: metaType, id: metaId },
getCommand: () => { return command }
})
} else {
const req = request(url)
const writeStream = fs.createWriteStream(filePath)
files.push({
filename,
url,
type,
streamId,
total,
current: 0,
time: Date.now(),
filePath,
error: false,
finished: false,
stopped: false,
meta: { url: metaUrl, type: metaType, id: metaId },
getReq: () => { return req },
closeStream: () => {
try {
writeStream.end()
} catch(e) {}
return true
}
})
req.pipe(writeStream).on('close', () => {
const idx = download.findIdx(url)
if (idx > -1) {
if (files[idx].current < files[idx].total && !files[idx].stopped) {
files[idx].error = true
if (files[idx].closeStream)
files[idx].closeStream()
} else if (!files[idx].stopped)
files[idx].finished = true
}
})
req.on('data', chunk => {
const idx = download.findIdx(url)
if (idx > -1)
files[idx].current += chunk.length
})
req.on('error', err => {
const idx = download.findIdx(url)
if (idx > -1 && !files[idx].stopped) {
files[idx].error = true
if (files[idx].closeStream)
files[idx].closeStream()
}
})
}
if (metaUrl)
getMeta(url, metaUrl, metaId, metaType)
})
},
remove: (filename, url) => {
let file
let meta = {}
files.some((el, ij) => {
if (el.url == url) {
file = el
meta = JSON.parse(JSON.stringify(file.meta))
if (file.getReq) {
const req = file.getReq()
if (req) req.abort()
}
if (file.getCommand) {
const command = file.getCommand()
if ((command || {}).kill)
command.kill('SIGINT')
}
let waitFor
if (files[ij].closeStream)
waitFor = files[ij].closeStream()
files.splice(ij, 1)
return true
}
})
if (file) {
try {
fs.unlinkSync(file.filePath)
} catch(e) {}
}
if (meta.id && meta.type) {
const keepMeta = files.some(el => {
if (el.meta.id == meta.id && el.meta.type == meta.type)
return true
})
if (!keepMeta)
metaDir.removeMeta(meta.id, meta.type)
}
return true
},
stop: (filename, url) => {
let file
files.some((el, ij) => {
if (el.url == url) {
file = el
if (file.getReq) {
const req = file.getReq()
if (req) req.abort()
}
if (file.getCommand) {
const command = file.getCommand()
if ((command || {}).kill)
command.kill('SIGINT')
}
let waitFor
if (files[ij].closeStream)
waitFor = files[ij].closeStream()
files[ij].stopped = true
return true
}
})
},
find: (url) => {
let file
files.some((el, ij) => {
if (el.url == url) {
file = el
return true
}
})
return file
},
findIdx: (url) => {
let idx = -1
files.some((el, ij) => {
if (el.url == url) {
idx = ij
return true
}
})
return idx
},
findById: (id, type) => {
const fls = []
files.some((el, ij) => {
if (el.streamId == id && (el.meta || {}).type == type)
fls.push(el)
})
return fls
},
cleanEnd: cb => {
if (saveFilesTimer)
clearTimeout(saveFilesTimer)
filelist.set(files)
cb()
}
}
module.exports = download