diff --git a/lib/ipfs.js b/lib/ipfs.js new file mode 100644 index 00000000..789fdbb0 --- /dev/null +++ b/lib/ipfs.js @@ -0,0 +1,45 @@ +var opt = gun._.opt, u; +if (u === opt.ipfs.directory) { + opt.ipfs.directory = '/gun'; +} +opt.store = {}; +opt.store.put = function(file, data, cb){ + var uri = opt.ipfs.directory + '/' + file; + opt.ipfs.instance.files.write(uri, Buffer.from(JSON.stringify(data)), {create:true}) + .then(res => { + console.log('File written to IPFS directory', uri, res); + return opt.ipfs.instance.files.stat(opt.ipfs.directory, {hash:true}); + }).then(res => { + console.log('Directory hash:', res.hash); + return opt.ipfs.instance.name.publish(res.hash); + // currently throws "This command must be run in online mode. Try running 'ipfs daemon' first." for some reason, maybe js-ipfs IPNS not ready yet + }).then(res => { + console.log('IPFS put request successful:', res); + cb(undefined, 1); + }).catch(error => { + console.error('IPFS put request failed', error); + }); +} +opt.store.get = function(file, cb){ + var uri = opt.ipfs.directory + '/' + file; + opt.ipfs.instance.files.read(uri, {}) + .then(res => { + var data = JSON.parse(res.toString()); + console.log(uri + ' was loaded from ipfs:', data); + cb(data); + }); +} +opt.store.list = function(cb){ + var stream = opt.ipfs.files.lsReadableStream(opt.ipfs.directory); + + stream.on('data', (file) => { + console.log('ls', file.name); + if (cb(file.name)) { + stream.destroy(); + } + }); + + stream.on('finish', () => { + cb(); + }); +} diff --git a/lib/multicast.js b/lib/multicast.js index 862e6e51..83b781a1 100644 --- a/lib/multicast.js +++ b/lib/multicast.js @@ -7,6 +7,7 @@ Gun.on('create', function(root){ return; // do nothing for now - Chrome extensions could use multicast though } if(false === opt.multicast){ return } + opt.multicast = opt.multicast || {}; var MULTICAST_ADDR = "233.255.255.255"; var PORT = 20000; @@ -22,22 +23,17 @@ Gun.on('create', function(root){ var address; socket.on("listening", function() { socket.addMembership(MULTICAST_ADDR); - setInterval(sendMessage, 1000); + if (opt.multicast && opt.multicast.port) { // if port is specified, advertise our node + setInterval(sendMessage, 1000); + } address = socket.address(); - /* - console.log( - `UDP socket listening on ${address.address}:${address.port} pid: ${ - process.pid - }` - ); - */ }); function sendMessage() { var msgObj = { gun: { version: Gun.version, - port: 8765 // TODO: get actual port instead of default 8765 + port: opt.multicast.port || 8765 } }; var message = Buffer.from(JSON.stringify(msgObj), ENC);