This repository has been archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
files.js
487 lines (399 loc) · 12.1 KB
/
files.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
'use strict'
const unixfsEngine = require('ipfs-unixfs-engine')
const importer = unixfsEngine.importer
const exporter = unixfsEngine.exporter
const promisify = require('promisify-es6')
const pull = require('pull-stream')
const sort = require('pull-sort')
const pushable = require('pull-pushable')
const toStream = require('pull-stream-to-stream')
const toPull = require('stream-to-pull-stream')
const deferred = require('pull-defer')
const waterfall = require('async/waterfall')
const isStream = require('is-stream')
const isSource = require('is-pull-stream').isSource
const Duplex = require('readable-stream').Duplex
const OtherBuffer = require('buffer').Buffer
const CID = require('cids')
const toB58String = require('multihashes').toB58String
const errCode = require('err-code')
const parseChunkerString = require('../utils').parseChunkerString
const WRAPPER = 'wrapper/'
function noop () {}
function prepareFile (self, opts, file, callback) {
opts = opts || {}
let cid = new CID(file.multihash)
if (opts.cidVersion === 1) {
cid = cid.toV1()
}
waterfall([
(cb) => opts.onlyHash
? cb(null, file)
: self.object.get(file.multihash, opts, cb),
(node, cb) => {
const b58Hash = cid.toBaseEncodedString()
let size = node.size
if (Buffer.isBuffer(node)) {
size = node.length
}
cb(null, {
path: opts.wrapWithDirectory ? file.path.substring(WRAPPER.length) : (file.path || b58Hash),
hash: b58Hash,
size
})
}
], callback)
}
function normalizeContent (opts, content) {
if (!Array.isArray(content)) {
content = [content]
}
return content.map((data) => {
// Buffer input
if (Buffer.isBuffer(data)) {
data = { path: '', content: pull.values([data]) }
}
// Readable stream input
if (isStream.readable(data)) {
data = { path: '', content: toPull.source(data) }
}
if (isSource(data)) {
data = { path: '', content: data }
}
if (data && data.content && typeof data.content !== 'function') {
if (Buffer.isBuffer(data.content)) {
data.content = pull.values([data.content])
}
if (isStream.readable(data.content)) {
data.content = toPull.source(data.content)
}
}
if (opts.wrapWithDirectory && !data.path) {
throw new Error('Must provide a path when wrapping with a directory')
}
if (opts.wrapWithDirectory) {
data.path = WRAPPER + data.path
}
return data
})
}
function preloadFile (self, opts, file) {
const isRootFile = opts.wrapWithDirectory
? file.path === ''
: !file.path.includes('/')
const shouldPreload = isRootFile && !opts.onlyHash && opts.preload !== false
if (shouldPreload) {
self._preload(file.hash)
}
return file
}
function pinFile (self, opts, file, cb) {
// Pin a file if it is the root dir of a recursive add or the single file
// of a direct add.
const pin = 'pin' in opts ? opts.pin : true
const isRootDir = !file.path.includes('/')
const shouldPin = pin && isRootDir && !opts.onlyHash && !opts.hashAlg
if (shouldPin) {
return self.pin.add(file.hash, err => cb(err, file))
} else {
cb(null, file)
}
}
class AddHelper extends Duplex {
constructor (pullStream, push, options) {
super(Object.assign({ objectMode: true }, options))
this._pullStream = pullStream
this._pushable = push
this._waitingPullFlush = []
}
_read () {
this._pullStream(null, (end, data) => {
while (this._waitingPullFlush.length) {
const cb = this._waitingPullFlush.shift()
cb()
}
if (end) {
if (end instanceof Error) {
this.emit('error', end)
}
} else {
this.push(data)
}
})
}
_write (chunk, encoding, callback) {
this._waitingPullFlush.push(callback)
this._pushable.push(chunk)
}
}
module.exports = function files (self) {
function _addPullStream (options = {}) {
let chunkerOptions
try {
chunkerOptions = parseChunkerString(options.chunker)
} catch (err) {
return pull.map(() => { throw err })
}
const opts = Object.assign({}, {
shardSplitThreshold: self._options.EXPERIMENTAL.sharding
? 1000
: Infinity
}, options, chunkerOptions)
if (opts.hashAlg && opts.cidVersion !== 1) {
opts.cidVersion = 1
}
let total = 0
const prog = opts.progress || noop
const progress = (bytes) => {
total += bytes
prog(total)
}
opts.progress = progress
return pull(
pull.map(normalizeContent.bind(null, opts)),
pull.flatten(),
importer(self._ipld, opts),
pull.asyncMap(prepareFile.bind(null, self, opts)),
pull.map(preloadFile.bind(null, self, opts)),
pull.asyncMap(pinFile.bind(null, self, opts))
)
}
function _catPullStream (ipfsPath, options) {
if (typeof ipfsPath === 'function') {
throw new Error('You must supply an ipfsPath')
}
options = options || {}
ipfsPath = normalizePath(ipfsPath)
const pathComponents = ipfsPath.split('/')
const restPath = normalizePath(pathComponents.slice(1).join('/'))
const filterFile = (file) => (restPath && file.path === restPath) || (file.path === ipfsPath)
if (options.preload !== false) {
self._preload(pathComponents[0])
}
const d = deferred.source()
pull(
exporter(ipfsPath, self._ipld, options),
pull.collect((err, files) => {
if (err) { return d.abort(err) }
if (files && files.length > 1) {
files = files.filter(filterFile)
}
if (!files || !files.length) {
return d.abort(new Error('No such file'))
}
const file = files[0]
const content = file.content
if (!content && file.type === 'dir') {
return d.abort(new Error('this dag node is a directory'))
}
d.resolve(content)
})
)
return d
}
function _lsPullStreamImmutable (ipfsPath, options) {
options = options || {}
const path = normalizePath(ipfsPath)
const recursive = options.recursive
const pathComponents = path.split('/')
const pathDepth = pathComponents.length
const maxDepth = recursive ? global.Infinity : pathDepth
options.maxDepth = options.maxDepth || maxDepth
if (options.preload !== false) {
self._preload(pathComponents[0])
}
return pull(
exporter(ipfsPath, self._ipld, options),
pull.filter(node =>
recursive ? node.depth >= pathDepth : node.depth === pathDepth
),
pull.map(node => {
const cid = new CID(node.hash)
node = Object.assign({}, node, { hash: cid.toBaseEncodedString() })
delete node.content
return node
})
)
}
return {
add: (() => {
const add = promisify((data, options, callback) => {
if (typeof options === 'function') {
callback = options
options = {}
}
options = options || {}
const ok = Buffer.isBuffer(data) ||
isStream.readable(data) ||
Array.isArray(data) ||
OtherBuffer.isBuffer(data) ||
typeof data === 'object' ||
isSource(data)
if (!ok) {
return callback(new Error('first arg must be a buffer, readable stream, pull stream, an object or array of objects'))
}
// CID v0 is for multihashes encoded with sha2-256
if (options.hashAlg && options.cidVersion !== 1) {
options.cidVersion = 1
}
pull(
pull.values([data]),
_addPullStream(options),
sort((a, b) => {
if (a.path < b.path) return 1
if (a.path > b.path) return -1
return 0
}),
pull.collect(callback)
)
})
return function () {
const args = Array.from(arguments)
// If we files.add(<pull stream>), then promisify thinks the pull stream
// is a callback! Add an empty options object in this case so that a
// promise is returned.
if (args.length === 1 && isSource(args[0])) {
args.push({})
}
return add.apply(null, args)
}
})(),
addReadableStream: (options) => {
options = options || {}
const p = pushable()
const s = pull(
p,
_addPullStream(options)
)
const retStream = new AddHelper(s, p)
retStream.once('finish', () => p.end())
return retStream
},
addPullStream: _addPullStream,
cat: promisify((ipfsPath, options, callback) => {
if (typeof options === 'function') {
callback = options
options = {}
}
if (typeof callback !== 'function') {
throw new Error('Please supply a callback to ipfs.files.cat')
}
pull(
_catPullStream(ipfsPath, options),
pull.collect((err, buffers) => {
if (err) { return callback(err) }
callback(null, Buffer.concat(buffers))
})
)
}),
catReadableStream: (ipfsPath, options) => toStream.source(_catPullStream(ipfsPath, options)),
catPullStream: (ipfsPath, options) => _catPullStream(ipfsPath, options),
get: promisify((ipfsPath, options, callback) => {
if (typeof options === 'function') {
callback = options
options = {}
}
options = options || {}
if (options.preload !== false) {
let pathComponents
try {
pathComponents = normalizePath(ipfsPath).split('/')
} catch (err) {
return setImmediate(() => callback(errCode(err, 'ERR_INVALID_PATH')))
}
self._preload(pathComponents[0])
}
pull(
exporter(ipfsPath, self._ipld, options),
pull.asyncMap((file, cb) => {
if (file.content) {
pull(
file.content,
pull.collect((err, buffers) => {
if (err) { return cb(err) }
file.content = Buffer.concat(buffers)
cb(null, file)
})
)
} else {
cb(null, file)
}
}),
pull.collect(callback)
)
}),
getReadableStream: (ipfsPath, options) => {
options = options || {}
if (options.preload !== false) {
let pathComponents
try {
pathComponents = normalizePath(ipfsPath).split('/')
} catch (err) {
return toStream.source(pull.error(errCode(err, 'ERR_INVALID_PATH')))
}
self._preload(pathComponents[0])
}
return toStream.source(
pull(
exporter(ipfsPath, self._ipld, options),
pull.map((file) => {
if (file.content) {
file.content = toStream.source(file.content)
file.content.pause()
}
return file
})
)
)
},
getPullStream: (ipfsPath, options) => {
options = options || {}
if (options.preload !== false) {
let pathComponents
try {
pathComponents = normalizePath(ipfsPath).split('/')
} catch (err) {
return pull.error(errCode(err, 'ERR_INVALID_PATH'))
}
self._preload(pathComponents[0])
}
return exporter(ipfsPath, self._ipld, options)
},
lsImmutable: promisify((ipfsPath, options, callback) => {
if (typeof options === 'function') {
callback = options
options = {}
}
options = options || {}
pull(
_lsPullStreamImmutable(ipfsPath, options),
pull.collect((err, values) => {
if (err) {
callback(err)
return
}
callback(null, values)
})
)
}),
lsReadableStreamImmutable: (ipfsPath, options) => {
return toStream.source(_lsPullStreamImmutable(ipfsPath, options))
},
lsPullStreamImmutable: _lsPullStreamImmutable
}
}
function normalizePath (path) {
if (Buffer.isBuffer(path)) {
path = toB58String(path)
}
if (CID.isCID(path)) {
path = path.toBaseEncodedString()
}
if (path.indexOf('/ipfs/') === 0) {
path = path.substring('/ipfs/'.length)
}
if (path.charAt(path.length - 1) === '/') {
path = path.substring(0, path.length - 1)
}
return path
}