This repository has been archived by the owner on Dec 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
104 lines (88 loc) · 2.45 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const path = require('path')
const crypto = require('crypto')
const hyperdrive = require('hyperdrive')
const datStorage = require('./dat-storage')
const pda = require('pauls-dat-api')
const dft = require('diff-file-tree')
const swarmDefaults = require('datland-swarm-defaults')
const discoverySwarm = require('discovery-swarm')
const hypercoreProtocol = require('hypercore-protocol')
const DAT_SWARM_PORT = 3282
// globals
// =
var BASE_PATH = undefined
var networkId = crypto.randomBytes(32)
var archiveSwarm
var archive
// exported api
// =
exports.setup = async function ({beakerDataDir}) {
BASE_PATH = beakerDataDir
await datStorage.setup()
archiveSwarm = discoverySwarm(swarmDefaults({
id: networkId,
hash: false,
utp: true,
tcp: true,
dht: false,
stream: createReplicationStream
}))
archiveSwarm.once('error', () => archiveSwarm.listen(0))
archiveSwarm.listen(DAT_SWARM_PORT)
}
exports.exportFiles = async function (key, targetPath) {
await loadArchive(key)
var diff = await dft.diff({fs: archive, name: '/'}, targetPath)
await dft.applyRight({fs: archive, name: '/'}, targetPath, diff)
return pda.readdir(archive, '/', {recursive: true})
}
// internal
// =
function getArchiveMetaPath (key) {
return path.join(BASE_PATH, 'Dat', 'Archives', 'Meta', key.slice(0, 2), key.slice(2))
}
async function loadArchive (key) {
var metaPath = getArchiveMetaPath(key)
archive = hyperdrive(datStorage.create(metaPath), Buffer.from(key, 'hex'), {sparse: true})
archive.on('error', err => {
throw err
})
await new Promise((resolve, reject) => {
archive.ready(err => {
if (err) reject(err)
else resolve()
})
})
archiveSwarm.join(archive.discoveryKey)
if (!archive.writable && !archive.metadata.length) {
// wait to receive a first update
await new Promise((resolve, reject) => {
archive.metadata.update(err => {
if (err) reject(err)
else resolve()
})
})
}
if (!archive.writable) {
await pda.download(archive, '/')
}
}
function createReplicationStream (info) {
// create the protocol stream
var stream = hypercoreProtocol({
id: networkId,
live: true,
encrypt: true
})
stream.peerInfo = info
// add the archive if the discovery network gave us any info
if (info.channel) {
add(info.channel)
}
// add any requested archives
stream.on('feed', add)
function add (dkey) {
archive.replicate({stream, live: true})
}
return stream
}