-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathipfs.server.js
103 lines (72 loc) · 2.65 KB
/
ipfs.server.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
var Writable = Npm.require('stream').Writable;
var streamBuffers = Npm.require("stream-buffers");
var ipfsAPI = Npm.require('ipfs-api')
FS.Store.IPFS = function( name, options ) {
var self = this;
if (!(self instanceof FS.Store.IPFS))
throw new Error('FS.Store.IPFS missing keyword "new"');
// connect to ipfs daemon API server
var ipfs = ipfsAPI( options.host, options.port );
return new FS.StorageAdapter(name, options, {
typeName: 'storage.ipfs',
fileKey: function( fileObj, param ) {
var key = "";
// Lookup the copy
var info = fileObj && fileObj._getInfo(name);
// If the store and key is found return the key
if (info && info.key) {
key = info.key;
}
return key;
},
createReadStream: function(fileKey, options) {
var wrappedIPFSCat = Meteor.wrapAsync(ipfs.cat);
var readableStreamBuffer = new streamBuffers.ReadableStreamBuffer();
var currentChunk = Buffer(0);
var res = wrappedIPFSCat([fileKey]);
res.on('data', function (chunk) {
currentChunk = Buffer.concat([currentChunk, chunk]);
});
res.on('end', function() {
// Get the chunk data
var uploadingChunk = Buffer(currentChunk.length);
currentChunk.copy(uploadingChunk);
readableStreamBuffer.put(uploadingChunk);
});
return readableStreamBuffer;
},
createWriteStream: function(fileKey, options) {
var currentChunk = Buffer(0);
var maxChunkSize = 5242880;
var writeStream = Writable({
highWaterMark: 4194304 // 4 MB
});
writeStream._write = function (chunk, enc, next, last) {
currentChunk = Buffer.concat([currentChunk, chunk]);
next();
};
var _originalEnd = writeStream.end;
writeStream.end = function (chunk, encoding, callback) {
// Get the chunk data
var uploadingChunk = Buffer(currentChunk.length);
currentChunk.copy(uploadingChunk);
ipfs.add( uploadingChunk, function(err, res) {
if(err || !res) return console.error(err)
writeStream.emit('stored', {
fileKey: res[0].Hash,
storedAt: new Date()
});
});
_originalEnd.call( this, chunk, encoding );
};
return writeStream;
},
remove: function(fileKey, callback) {
console.log('removing ipfs files not implemented');
callback();
},
stats: function(fileKey, callback) {
callback();
}
});
}