1 | 'use strict'
|
2 |
|
3 | const pull = require('pull-stream')
|
4 | const Buffer = require('safe-buffer').Buffer
|
5 | const EventEmitter = require('events')
|
6 |
|
7 | const emitter = new EventEmitter()
|
8 |
|
9 | function handler (protocol, conn) {
|
10 | conn.getPeerInfo((err, peerInfo) => {
|
11 | if (err) {
|
12 | console.log(err)
|
13 | return
|
14 | }
|
15 |
|
16 | const peerId = peerInfo.id.toB58String()
|
17 |
|
18 | pull(
|
19 | conn,
|
20 | pull.map((message) => {
|
21 | let msg
|
22 | try {
|
23 | msg = JSON.parse(message.toString())
|
24 | } catch (err) {
|
25 | emitter.emit('warning', err.message)
|
26 | return
|
27 | }
|
28 |
|
29 | if (peerId !== msg.from) {
|
30 | emitter.emit('warning', 'no peerid match ' + msg.from)
|
31 | return
|
32 | }
|
33 |
|
34 | const topicIDs = msg.topicIDs
|
35 | if (!Array.isArray(topicIDs)) {
|
36 | emitter.emit('warning', 'no topic IDs')
|
37 | return
|
38 | }
|
39 |
|
40 | msg.data = Buffer.from(msg.data, 'hex')
|
41 | msg.seqno = Buffer.from(msg.seqno, 'hex')
|
42 |
|
43 | topicIDs.forEach((topic) => {
|
44 | emitter.emit(topic, msg)
|
45 | })
|
46 |
|
47 | return msg
|
48 | }),
|
49 | pull.onEnd(() => {
|
50 |
|
51 | })
|
52 | )
|
53 | })
|
54 | }
|
55 |
|
56 | exports = module.exports = {
|
57 | handler: handler,
|
58 | emitter: emitter
|
59 | }
|