-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpeer.js
More file actions
68 lines (63 loc) · 1.42 KB
/
Copy pathpeer.js
File metadata and controls
68 lines (63 loc) · 1.42 KB
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
(async function () {
//
// Load the existing tape list.
//
var duxtape = {discovered: {}}, written = true
try {
let str = await drive.readFile('/duxtape.json')
duxtape = JSON.parse(str.toString())
} catch {}
console.log(duxtape)
//
// Periodically save an unsaved list.
//
setInterval(async () => {
if (!written) {
try {
await drive.writeFile('/duxtape.json', JSON.stringify(duxtape))
} catch (e) {
console.log(e)
}
written = true
}
}, 5000)
//
// Join the duxtape channel.
//
let topic = `webapp/${drive.discoveryKey.toString('hex')}/duxtape`
console.log(`Join ${topic}`)
let channel = client.peersockets.join(topic, {
onmessage(peer, buf) {
try {
//
// Add any newly announced tapes to the 'discovered' list.
//
var obj = JSON.parse(buf.toString())
console.log([peer, obj])
for (let tape of obj.tapes) {
if (!(tape in duxtape.discovered)) {
duxtape.discovered[tape] = new Date()
written = false
}
}
} catch {}
}
})
//
// Announce the tape list to joining peers.
//
let destroy = client.peers.watchPeers(drive.discoveryKey,
{onjoin: peer => {
try {
console.log(['join', peer])
let tapes = Object.keys(duxtape.discovered)
channel.send(peer, Buffer.from(JSON.stringify({tapes})))
} catch (e) {
console.log(e)
}
}})
return async function () {
channel.close()
await destroy()
}
})();