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

Commit 0f430ef

Browse files
maxlathdaviddias
authored andcommitted
Make url-add follow HTTP redirections (#514)
* Make url-add follow HTTP redirections fix #513 * Check status code before following a redirection * http redirection: added a test * test: make lint pass by handling the error
1 parent 158aa7c commit 0f430ef

File tree

2 files changed

+31
-10
lines changed

2 files changed

+31
-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 (res.statusCode >= 300 && res.statusCode < 400 && 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
}

test/util.spec.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,14 @@ describe('.util', () => {
107107
done()
108108
})
109109
})
110+
111+
it('.urlAdd http with redirection', (done) => {
112+
ipfs.util.addFromURL('http://covers.openlibrary.org/book/id/969165.jpg', (err, result) => {
113+
expect(err).to.not.exist()
114+
expect(result[0].hash).to.equal('QmaL9zy7YUfvWmtD5ZXp42buP7P4xmZJWFkm78p8FJqgjg')
115+
done()
116+
})
117+
})
110118
})
111119

112120
describe('Promise API', () => {})

0 commit comments

Comments
 (0)