Skip to content
This repository was archived by the owner on Mar 10, 2020. It is now read-only.

Commit 7a01fdd

Browse files
committed
Make url-add follow HTTP redirections
fix #513
1 parent 158aa7c commit 7a01fdd

File tree

1 file changed

+23
-10
lines changed

1 file changed

+23
-10
lines changed

src/util/url-add.js

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,28 +25,41 @@ module.exports = (arg) => {
2525
opts = {}
2626
}
2727

28-
if (typeof url !== 'string' ||
29-
!url.startsWith('http')) {
28+
if (!validUrl(url)) {
3029
return callback(new Error('"url" param must be an http(s) url'))
3130
}
3231

3332
callback = once(callback)
3433

35-
request(parseUrl(url).protocol)(url, (res) => {
36-
res.once('error', callback)
37-
if (res.statusCode >= 400) {
38-
return callback(new Error(`Failed to download with ${res.statusCode}`))
39-
}
34+
requestWithRedirect(url, opts, send, callback)
35+
})
36+
}
37+
38+
const validUrl = (url) => typeof url === 'string' && url.startsWith('http')
39+
40+
const requestWithRedirect = (url, opts, send, callback) => {
41+
request(parseUrl(url).protocol)(url, (res) => {
42+
res.once('error', callback)
43+
if (res.statusCode >= 400) {
44+
return callback(new Error(`Failed to download with ${res.statusCode}`))
45+
}
4046

47+
const redirection = res.headers.location
48+
49+
if (redirection) {
50+
if (!validUrl(redirection)) {
51+
return callback(new Error('redirection url must be an http(s) url'))
52+
}
53+
requestWithRedirect(redirection, opts, send, callback)
54+
} else {
4155
const params = {
4256
path: 'add',
4357
qs: opts,
4458
files: res
4559
}
46-
4760
// Transform the response stream to DAGNode values
4861
const transform = (res, callback) => DAGNodeStream.streamToValue(send, res, callback)
4962
send.andTransform(params, transform, callback)
50-
}).end()
51-
})
63+
}
64+
}).end()
5265
}

0 commit comments

Comments
 (0)