Files: be227038215cfd41dc8aee4c1ece14657a72abce / backup / async / exportIdentity.js
2749 bytesRaw
1 | const nest = require('depnest') |
2 | const { onceTrue } = require('mutant') |
3 | const path = require('path') |
4 | const fs = require('fs') |
5 | const parallel = require('run-parallel') |
6 | const mapLimit = require('map-limit') |
7 | |
8 | const config = require('../../config').create().config.sync.load() |
9 | const gossipFile = path.join(config.path, 'gossip.json') |
10 | const secretFile = path.join(config.path, 'secret') |
11 | |
12 | exports.gives = nest('backup.async.exportIdentity') |
13 | |
14 | exports.needs = nest({ |
15 | 'sbot.obs.connection': 'first' |
16 | }) |
17 | |
18 | exports.create = function (api) { |
19 | return nest('backup.async.exportIdentity', (filename, cb) => { |
20 | if (typeof filename === 'undefined') return cb(new Error('backup requires a filename')) |
21 | |
22 | console.log(`should export identity to file ${filename}`) |
23 | |
24 | var backup = { |
25 | exportDate: new Date().toISOString(), |
26 | secret: fs.readFileSync(secretFile, 'utf8'), |
27 | gossip: require(gossipFile) |
28 | } |
29 | |
30 | onceTrue(api.sbot.obs.connection, sbot => { |
31 | parallel([ |
32 | getLatestSequence, |
33 | getGossipFollowers, |
34 | getPeersSequence |
35 | ], save) |
36 | |
37 | function getLatestSequence (done) { |
38 | sbot.latestSequence(sbot.id, (err, seq) => { |
39 | if (err) return done(err) |
40 | |
41 | backup.latestSequence = seq |
42 | done(null) |
43 | }) |
44 | } |
45 | |
46 | function getGossipFollowers (done) { |
47 | // the peers in gossip list who follow me |
48 | sbot.friends.get({ dest: sbot.id }, (err, followers) => { |
49 | if (err) return done(err) |
50 | |
51 | backup.gossip.forEach(record => { |
52 | if (followers[record.key]) record.followsMe = true |
53 | }) |
54 | |
55 | done(null) |
56 | }) |
57 | } |
58 | |
59 | function getPeersSequence (done) { |
60 | sbot.friends.get({ source: sbot.id }, (err, d) => { |
61 | if (err) return done(err) |
62 | |
63 | var follows = Object.keys(d).filter(id => d[id] === true) |
64 | |
65 | mapLimit(follows, 5, |
66 | (id, cb) => sbot.latestSequence(id, (err, seq) => { |
67 | if (err && err.message && err.message.indexOf('not found') > 0) { |
68 | console.error(err) |
69 | return cb(null, null) // don't include this user |
70 | } |
71 | |
72 | cb(null, [ id, seq ]) |
73 | }), |
74 | (err, peers) => { |
75 | if (err) return done(err) |
76 | |
77 | backup.peersSequence = peers |
78 | .filter(Boolean) |
79 | .reduce((soFar, [ id, seq ]) => { |
80 | if (seq) soFar[id] = seq |
81 | return soFar |
82 | }, {}) |
83 | done(null) |
84 | } |
85 | ) |
86 | }) |
87 | } |
88 | }) |
89 | |
90 | function save (err, success) { |
91 | if (err) return cb(err) |
92 | |
93 | fs.writeFileSync(filename, JSON.stringify(backup, null, 2), 'utf8') |
94 | cb(null, true) |
95 | } |
96 | |
97 | return true |
98 | }) |
99 | } |
100 |
Built with git-ssb-web