Files: 4f85a663f11b42d3b209019fcf598a738e7e43ee / backup / async / exportIdentity.js
2421 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 | // gossip: JSON.parse(fs.readFileSync(gossipFile)), |
29 | } |
30 | |
31 | onceTrue(api.sbot.obs.connection, sbot => { |
32 | parallel([ |
33 | getLatestSequence, |
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 getPeersSequence (done) { |
47 | sbot.friends.get({ source: sbot.id }, (err, d) => { |
48 | if (err) return done(err) |
49 | |
50 | var follows = Object.keys(d).filter(id => d[id] === true) |
51 | |
52 | mapLimit(follows, 5, |
53 | (id, cb) => sbot.latestSequence(id, (err, seq) => { |
54 | if (err && err.message && err.message.indexOf('not found') > 0) { |
55 | console.error(err) |
56 | return cb(null, null) // don't include this user |
57 | } |
58 | |
59 | cb(null, [ id, seq ]) |
60 | }), |
61 | (err, peers) => { |
62 | if (err) return done(err) |
63 | |
64 | backup.peersSequence = peers |
65 | .filter(Boolean) |
66 | .reduce((soFar, [ id, seq ]) => { |
67 | if (seq) soFar[id] = seq |
68 | return soFar |
69 | }, {}) |
70 | done(null) |
71 | } |
72 | ) |
73 | }) |
74 | } |
75 | }) |
76 | |
77 | function save (err, success) { |
78 | if (err) return cb(err) |
79 | |
80 | fs.writeFileSync(filename, JSON.stringify(backup, null, 2), 'utf8') |
81 | cb(null, true) |
82 | } |
83 | |
84 | return true |
85 | }) |
86 | } |
87 |
Built with git-ssb-web