-
Notifications
You must be signed in to change notification settings - Fork 1
/
ipfsloader.js
109 lines (91 loc) · 2.71 KB
/
ipfsloader.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
'use strict'
const {performance} = require('perf_hooks');
class HlsjsIPFSLoader {
constructor(config) {
this.ipfs = config.ipfs
this.hash = config.ipfsHash
}
destroy() {
}
abort() {
}
load(context, config, callbacks) {
this.context = context
this.config = config
this.callbacks = callbacks
this.stats = { trequest: performance.now(), retry: 0 }
this.retryDelay = config.retryDelay
this.loadInternal()
}
loadInternal() {
var stats = this.stats,
context = this.context,
config = this.config,
callbacks = this.callbacks
stats.tfirst = Math.max(performance.now(), stats.trequest)
stats.loaded = 0
var urlParts = context.url.split("/")
var filename = urlParts[urlParts.length - 1]
getFile(this.ipfs, this.hash, filename, function(err, res) {
if (err) {
console.log(err);
return
}
var data,len
if (context.responseType === 'arraybuffer') {
data = res
len = res.length
} else {
data = buf2str(res)
len = data.length
}
stats.loaded = stats.total = len
stats.tload = Math.max(stats.tfirst, performance.now())
var response = { url: context.url, data: data }
callbacks.onSuccess(response, stats, context)
})
}
}
function getFile(ipfs, rootHash, filename, callback) {
if (!callback) callback = function (err, res) {}
console.log("Fetching hash for '" + rootHash + "/" + filename + "'")
ipfs.object.get(rootHash, function(err, res) {
if (err) return callback(err)
var hash = null
var fileSize, fileName
res.links.forEach(function(link) {
if (link.name === filename) {
hash = link.cid.toString()
fileSize = link.size
fileName = link.name
return false
}
});
if (!hash) {
var msg = "File not found: " + rootHash + "/" + filename
return callback(new Error(msg), null)
}
console.log("Requesting '" + rootHash + "/" + filename + "'")
var resBuf = new ArrayBuffer(fileSize)
var bufView = new Uint8Array(resBuf)
var offs = 0
const stream = ipfs.catReadableStream(hash)
console.log("Received stream for file '" + rootHash + "/" + fileName + "'")
stream.on('data', function (chunk) {
console.log("Received " + chunk.length + " bytes for file '" +
rootHash + "/" + fileName + "'")
bufView.set(chunk, offs)
offs += chunk.length
});
stream.on('error', function (err) {
callback(err, null)
});
stream.on('end', function () {
callback(null, resBuf)
});
});
}
function buf2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf))
}
exports = module.exports = HlsjsIPFSLoader