-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfriends.js
More file actions
226 lines (191 loc) · 5.79 KB
/
Copy pathfriends.js
File metadata and controls
226 lines (191 loc) · 5.79 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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
const log = require('debug')('ipfs-friends:lib-friends')
const CID = require('cids')
const EventEmitter = require('events')
const explain = require('explain-error')
class FriendDaemon extends EventEmitter {
constructor (ipfs, options) {
super()
this._ipfs = ipfs
this._index = null
this.onMessage = this.onMessage.bind(this)
this._options = options || {}
this._state = 'stopped'
}
async start () {
if (this._state !== 'stopped') throw new Error(`unable to start from ${this._state}`)
this._state = 'starting'
try {
const ipfs = this._ipfs
const { id } = await ipfs.id()
const index = await readFriends(ipfs, { dir: this._options.dataDir })
this.peerId = id
this._index = index
const peerIds = Object.keys(index)
await Promise.all(peerIds.map(peerId => {
return ipfs.pubsub.subscribe(peerId, this.onMessage)
}))
this._publish({ action: 'online' })
.catch(err => log('failed to publish online message', err))
this._state = 'started'
} catch (err) {
this._state = 'stopped'
throw err
}
return this
}
async onMessage (msg) {
const peerId = msg.topicIDs[0]
if (msg.from !== peerId) {
return log('Bad message!', msg)
}
if (peerId === this.peerId) {
return log('ignoring own message', msg)
}
let res
try {
res = JSON.parse(msg.data)
} catch (err) {
return log('failed to parse message', err)
}
const { action, payload } = res
if (action === 'share') {
try {
await this._ipfs.pin.add(payload.cid)
} catch (err) {
return log(`failed to pin ${payload.cid}`, err)
}
try {
await this._publish({
action: 'shared',
payload: { cid: payload.cid, shareName: payload.shareName }
})
} catch (err) {
return log(`failed publish shared message ${payload.cid}`, err)
}
this.emit('message:share', {
peerId,
peerName: this._index[peerId],
cid: payload.cid,
shareName: payload.shareName
})
} else if (action === 'shared') {
this.emit('message:shared', {
peerId,
peerName: this._index[peerId],
cid: payload.cid,
shareName: payload.shareName
})
} else if (action === 'online') {
this.emit('message:online', { peerId, peerName: this._index[peerId] })
} else if (action === 'offline') {
this.emit('message:offline', { peerId, peerName: this._index[peerId] })
}
}
async add (peerId, name) {
if (this._state !== 'started') throw new Error('not started')
if (!peerId) throw new Error('missing friend peer ID')
if (!name) throw new Error('missing friend name')
validateCid(peerId)
if (Object.keys(this._index).includes(peerId)) {
await this.dump(peerId)
}
this._index[peerId] = name
await writeFriends(this._ipfs, this._index, { dir: this._options.dataDir })
await this._ipfs.pubsub.subscribe(peerId, this.onMessage)
}
async share (cid, name) {
if (this._state !== 'started') throw new Error('not started')
if (!cid) throw new Error('missing share CID')
if (!name) throw new Error('missing share name')
validateCid(cid)
await this._publish({
action: 'share',
payload: { cid, shareName: name }
})
}
ls () {
return JSON.parse(JSON.stringify(this._index))
}
async dump (peerIdOrName) {
if (this._state !== 'started') throw new Error('not started')
if (!peerIdOrName) throw new Error('missing friend peer ID or name')
const index = this._index
let peerId
if (Object.keys(index).includes(peerIdOrName)) {
peerId = peerIdOrName
} else if (Object.values(index).includes(peerIdOrName)) {
for (peerId of Object.keys(index)) {
if (index[peerId] === peerIdOrName) break
}
} else {
throw new Error('no such friend!')
}
delete index[peerId]
await writeFriends(this._ipfs, index, { dir: this._options.dataDir })
await this._ipfs.pubsub.unsubscribe(peerId, this.onMessage)
this._index = index
}
async stop () {
if (this._state !== 'started') throw new Error('not started')
this._state = 'stopping'
const peerIds = Object.keys(this._index)
// Unsubscribe from all our friends
try {
await Promise.all(peerIds.map(peerId => {
return this._ipfs.pubsub.unsubscribe(peerId, this.onMessage)
}))
} catch (err) {
log('failed to unsubscribe from all the peerIds', err)
}
this._index = null
try {
await this._publish({ action: 'offline' })
} catch (err) {
log('failed to publish offline message', err)
}
this.peerId = null
this._state = 'stopped'
return this
}
_publish (msg) {
const { peerId, _ipfs: ipfs } = this
return ipfs.pubsub.publish(peerId, Buffer.from(JSON.stringify(msg)))
}
state () {
return this._state
}
}
module.exports = FriendDaemon
const DEFAULT_FRIENDS_DIR = '/friends'
async function readFriends (ipfs, options) {
options = options || {}
const dir = options.dir || DEFAULT_FRIENDS_DIR
try {
const index = await ipfs.files.read(dir + '/index.json')
return JSON.parse(index)
} catch (err) {
log('failed to read /friends/index.json', err)
return {}
}
}
async function writeFriends (ipfs, index, options) {
options = options || {}
const dir = options.dir || DEFAULT_FRIENDS_DIR
const data = Buffer.from(JSON.stringify(index))
try {
await ipfs.files.write(dir + '/index.json', data, {
create: true,
parents: true,
truncate: true
})
} catch (err) {
throw explain(err, 'failed to write to friends index')
}
}
function validateCid (str) {
try {
new CID(str) // eslint-disable-line
} catch (err) {
throw explain(err, 'invalid CID')
}
}