This repository was archived by the owner on Mar 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy pathurl-add.js
69 lines (54 loc) · 1.83 KB
/
url-add.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
'use strict'
const promisify = require('promisify-es6')
const parseUrl = require('url').parse
const request = require('../utils/request')
const SendOneFile = require('../utils/send-one-file-multiple-results')
const FileResultStreamConverter = require('../utils/file-result-stream-converter')
module.exports = (send) => {
const sendOneFile = SendOneFile(send, 'add')
return promisify((url, opts, callback) => {
if (typeof (opts) === 'function' &&
callback === undefined) {
callback = opts
opts = {}
}
// opts is the real callback --
// 'callback' is being injected by promisify
if (typeof opts === 'function' &&
typeof callback === 'function') {
callback = opts
opts = {}
}
if (!validUrl(url)) {
return callback(new Error('"url" param must be an http(s) url'))
}
requestWithRedirect(url, opts, sendOneFile, callback)
})
}
const validUrl = (url) => typeof url === 'string' && url.startsWith('http')
const requestWithRedirect = (url, opts, sendOneFile, callback) => {
const parsedUrl = parseUrl(url)
const req = request(parsedUrl.protocol)(url, (res) => {
if (res.statusCode >= 400) {
return callback(new Error(`Failed to download with ${res.statusCode}`))
}
const redirection = res.headers.location
if (res.statusCode >= 300 && res.statusCode < 400 && redirection) {
if (!validUrl(redirection)) {
return callback(new Error('redirection url must be an http(s) url'))
}
requestWithRedirect(redirection, opts, sendOneFile, callback)
} else {
const requestOpts = {
qs: opts,
converter: FileResultStreamConverter
}
sendOneFile({
content: res,
path: parsedUrl.pathname.split('/').pop()
}, requestOpts, callback)
}
})
req.once('error', callback)
req.end()
}