-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
129 lines (105 loc) · 2.77 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
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
const EventEmitter = require('events')
const hyperdb = require('hyperdb')
const hyperid = require('hyperid')
const pump = require('pump')
const forEachChunk = require('../../lib/for-each-chunk')
const uuid = hyperid()
module.exports = class Saga extends EventEmitter {
constructor (storage, key, username) {
super()
this.messages = new Map()
this.users = new Map()
this.username = username
this.timestamp = Date.now()
this.db = hyperdb(storage, key, { valueEncoding: 'json' })
}
async initialize () {
await this._ready()
this._updateHistory(this._watchForMessages.bind(this))
}
replicate () {
// NEW method !!!
return this.db.replicate({
live: true,
userData: JSON.stringify({
key: this.db.local.key,
username: this.username,
timestamp: this.timestamp
})
})
}
async connect (peer) {
if (!peer.remoteUserData) {
throw new Error('peer does not have userData')
}
// const data = JSON.parse(/* ... */)
// const username = data.username
// secure copy the buffer
// const key = Buffer.from(data.key)
// (4) authorize peer
// ...
// This block will be helpful later
if (!this.users.has(username)) {
this.users.set(username, new Date())
this.emit('join', data)
peer.on('close', () => {
if (!this.users.has(username)) return
this.users.delete(username)
this.emit('leave', data)
})
}
}
writeMessage (message) {
const key = `messages/${uuid()}`
const data = {
key,
message,
username: this.username,
timestamp: Date.now()
}
return new Promise((resolve, reject) => {
this.db.put(key, data, (err) => {
if (err) return reject(err)
resolve(key)
})
})
}
_updateHistory (onFinish) {
const h = this.db.createHistoryStream({ reverse: true })
const ws = forEachChunk({ objectMode: true }, (data, enc, next) => {
const { key, value } = data
if (/messages/.test(key)) {
if (this.messages.has(key)) {
h.destroy()
return
}
this.messages.set(key, value)
this.emit('message', value, key)
}
next()
})
pump(h, ws, onFinish)
}
_watchForMessages () {
this.db.watch('messages', () => {
this._updateHistory()
})
}
_authorize (key) {
return new Promise((resolve, reject) => {
this.db.authorized(key, (err, auth) => {
if (err) return reject(err)
if (auth) {
return resolve('AUTHORIZED')
}
this.db.authorize(key, (err) => {
if (err) return reject(err)
resolve('AUTHORIZED')
})
})
})
}
_ready () {
return new Promise(resolve => this.db.ready(resolve))
}
}