This repository has been archived by the owner on Jan 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
67 lines (58 loc) · 1.81 KB
/
index.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
var assert = require('assert')
var stringKey = require('dat-encoding').toStr
var get = require('simple-get')
var datDns = require('dat-dns')()
var debug = require('debug')('dat-link-resolve')
module.exports = resolve
function resolve (link, cb) {
assert.ok(link, 'dat-link-resolve: link required')
assert.strictEqual(typeof cb, 'function', 'dat-link-resolve: callback required')
var key = null
try {
// validates + removes dat://
// also works for http urls with keys in them
key = stringKey(link)
} catch (e) {
lookup()
return
}
cb(null, key)
function lookup () {
// if it starts with http or dat: use as is, otherwise prepend http://
var urlLink = (link.indexOf('http') && link.indexOf('dat:')) ? ('http://' + link) : link
function resolveName () {
datDns.resolveName(urlLink, function (err, key) {
debug('resolveName', urlLink, err, key)
if (key) return cb(null, key)
if (err) debug('datDns.resolveName() error')
cb(err)
})
}
debug('resolveKey', link, urlLink)
get({
url: urlLink.replace('dat://', 'http://'),
json: true,
timeout: 1500
}, function (err, resp, body) {
// no ressource at given URL
if (err || resp.statusCode !== 200) {
return resolveName()
}
// first check if key is in header response
key = resp.headers['hyperdrive-key'] || resp.headers['dat-key']
if (key) {
debug('Received key from http header:', key)
return cb(null, key)
}
// else fall back to parsing the body
try {
key = stringKey(body.url)
debug('Received key via json:', key, typeof body, body && typeof body.url)
if (key) return cb(null, key)
} catch (e) {
// fall back to datDns
resolveName()
}
})
}
}