optional multicast advertised port, ipfs adapter raw sketch

This commit is contained in:
Martti Malmi 2019-01-08 11:51:47 +02:00
parent 399cde49a7
commit 7b918aeba0
2 changed files with 50 additions and 9 deletions

45
lib/ipfs.js Normal file
View File

@ -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();
});
}

View File

@ -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);