lanRouter.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const pull = require('./node_modules/pull-stream');
  2. const Ref = require('./node_modules/ssb-ref');
  3. const fs = require('fs');
  4. const path = require('path');
  5. const staged = new Set();
  6. function readOasisConfig() {
  7. try {
  8. const p = path.join(__dirname, '..', 'configs', 'oasis-config.json');
  9. return JSON.parse(fs.readFileSync(p, 'utf8')) || {};
  10. } catch (_) { return {}; }
  11. }
  12. function stagePeer(ssb, address, key, eagerReplicate) {
  13. if (!address || !key || key === ssb.id) return;
  14. if (staged.has(address)) return;
  15. staged.add(address);
  16. let routed = false;
  17. try {
  18. if (ssb.conn && typeof ssb.conn.stage === 'function') {
  19. ssb.conn.stage(address, { type: 'lan', key });
  20. routed = true;
  21. }
  22. } catch (_) {}
  23. if (!routed) {
  24. try {
  25. if (ssb.gossip && typeof ssb.gossip.add === 'function') {
  26. ssb.gossip.add(address, 'local');
  27. }
  28. } catch (_) {}
  29. }
  30. if (eagerReplicate) {
  31. try {
  32. if (ssb.ebt && typeof ssb.ebt.request === 'function') {
  33. ssb.ebt.request(key, true);
  34. }
  35. } catch (_) {}
  36. try {
  37. if (ssb.replicate && typeof ssb.replicate.request === 'function') {
  38. ssb.replicate.request(key, true);
  39. }
  40. } catch (_) {}
  41. }
  42. }
  43. function handleDiscovery(ssb, d, opts) {
  44. if (!d || !d.address) return;
  45. if (!d.verified && !opts.acceptUnverified) return;
  46. let key = null;
  47. try { key = Ref.getKeyFromAddress(d.address); } catch (_) {}
  48. if (key) stagePeer(ssb, d.address, key, opts.eagerReplicate);
  49. }
  50. function startRouter(ssb, opts) {
  51. if (!ssb.lan || typeof ssb.lan.discoveredPeers !== 'function') return;
  52. const oasisCfg = readOasisConfig();
  53. if (oasisCfg.lanBroadcasting === false) return;
  54. try { ssb.lan.start(); } catch (_) {}
  55. pull(
  56. ssb.lan.discoveredPeers(),
  57. pull.drain(d => handleDiscovery(ssb, d, opts), () => {})
  58. );
  59. }
  60. module.exports = {
  61. name: 'lanRouter',
  62. version: '1.1.0',
  63. manifest: {},
  64. init(ssb, config) {
  65. const lanCfg = (config && config.lan) || {};
  66. const opts = {
  67. acceptUnverified: lanCfg.acceptUnverified === true,
  68. eagerReplicate: lanCfg.eagerReplicate === true
  69. };
  70. setImmediate(() => startRouter(ssb, opts));
  71. return {};
  72. }
  73. };