/
index.js
276 lines (239 loc) · 7.12 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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
var kappa = require('kappa-core')
var events = require('events')
var inherits = require('inherits')
var level = require('level-mem')
var thunky = require('thunky')
var timestamp = require('monotonic-timestamp')
var sublevel = require('subleveldown')
var crypto = require('hypercore-crypto')
var createChannelView = require('./views/channels')
var createMembershipsView = require('./views/channel-membership')
var createMessagesView = require('./views/messages')
var createTopicsView = require('./views/topics')
var createUsersView = require('./views/users')
var createModerationView = require('./views/moderation')
var swarm = require('./swarm')
var DATABASE_VERSION = 1
var CHANNELS = 'c'
var MEMBERSHIPS = 'j' // j for joined memberships..? :3
var MESSAGES = 'm'
var TOPICS = 't'
var USERS = 'u'
var MODERATION = 'x'
module.exports = Cabal
module.exports.databaseVersion = DATABASE_VERSION
/**
* Create a new cabal. This is the object handling all
* local nickname -> mesh interactions for a single user.
* @constructor
* @param {string|function} storage - A hyperdb compatible storage function, or a string representing the local data path.
* @param {string} key - a protocol string, optionally with url parameters
*/
function Cabal (storage, key, opts) {
if (!(this instanceof Cabal)) return new Cabal(storage, key, opts)
if (!opts) opts = {}
events.EventEmitter.call(this)
this.setMaxListeners(Infinity)
var json = {
encode: function (obj) {
return Buffer.from(JSON.stringify(obj))
},
decode: function (buf) {
var str = buf.toString('utf8')
try { var obj = JSON.parse(str) } catch (err) { return {} }
return obj
},
buffer: true
}
this.maxFeeds = opts.maxFeeds
this.modKeys = []
this.adminKeys = []
if (!key) this.key = generateKeyHex()
else {
if (Buffer.isBuffer(key)) key = key.toString('hex')
if (!key.startsWith('cabal://')) key = 'cabal://' + key
const uri = new URL(key)
this.key = sanitizeKey(uri.host)
this.modKeys = uri.searchParams.getAll('mod')
this.adminKeys = uri.searchParams.getAll('admin')
}
if (!isHypercoreKey(this.key)) throw new Error('invalid cabal key')
this.db = opts.db || level()
this.kcore = kappa(storage, {
valueEncoding: json,
encryptionKey: isHypercoreKey(this.key) ? this.key : null
})
// Create (if needed) and open local write feed
var self = this
this.feed = thunky(function (cb) {
self.kcore.ready(function () {
self.kcore.writer('local', function (err, feed) {
cb(feed)
})
})
})
// views
this.kcore.use('memberships', createMembershipsView(
sublevel(this.db, MEMBERSHIPS, { valueEncoding: json })))
this.kcore.use('channels', createChannelView(
sublevel(this.db, CHANNELS, { valueEncoding: json })))
this.kcore.use('messages', createMessagesView(
sublevel(this.db, MESSAGES, { valueEncoding: json })))
this.kcore.use('topics', createTopicsView(
sublevel(this.db, TOPICS, { valueEncoding: json })))
this.kcore.use('users', createUsersView(
sublevel(this.db, USERS, { valueEncoding: json })))
this.kcore.use('moderation', createModerationView(
this, sublevel(this.db, MODERATION, { valueEncoding: json }))
)
this.messages = this.kcore.api.messages
this.channels = this.kcore.api.channels
this.memberships = this.kcore.api.memberships
this.topics = this.kcore.api.topics
this.users = this.kcore.api.users
this.moderation = this.kcore.api.moderation
}
inherits(Cabal, events.EventEmitter)
Cabal.prototype.getDatabaseVersion = function (cb) {
if (!cb) cb = noop
process.nextTick(cb, DATABASE_VERSION)
}
/**
* Get information about a user that they've volunteered about themselves.
* @param {String} key - The hex key of the user.
*/
Cabal.prototype.getUser = function (key, cb) {
if (typeof key === 'function') {
cb = key
key = null
}
var self = this
this.feed(function (feed) {
if (!key) key = feed.key.toString('hex')
self.kcore.api.users.get(key, cb)
})
}
/**
* Publish a message to your feed.
* @param {String} message - The message to publish.
* @param {Object} opts - Options
* @param {function} cb - When message has been successfully added.
*/
Cabal.prototype.publish = function (message, opts, cb) {
if (!cb) cb = noop
if (!message) return cb()
if (typeof opts === 'function') return this.publish(message, null, opts)
if (!opts) opts = {}
this.feed(function (feed) {
message.timestamp = message.timestamp || timestamp()
feed.append(message, function (err) {
cb(err, err ? null : message)
})
})
}
Cabal.prototype.publishNick = function (nick, cb) {
// TODO: sanity checks on reasonable names
if (!cb) cb = noop
if (!nick) return cb()
this.feed(function (feed) {
var msg = {
type: 'about',
content: {
name: nick
},
timestamp: timestamp()
}
feed.append(msg, cb)
})
}
Cabal.prototype.publishChannelTopic = function (channel, topic, cb) {
if (!cb) cb = noop
if (!channel || typeof channel !== 'string') return cb()
if (!topic || typeof topic !== 'string') return cb()
this.feed(function (feed) {
var msg = {
type: 'chat/topic',
content: {
channel: channel,
text: topic
},
timestamp: timestamp()
}
feed.append(msg, cb)
})
}
Cabal.prototype.getLocalKey = function (cb) {
if (!cb) return
this.feed(function (feed) {
cb(null, feed.key.toString('hex'))
})
}
Cabal.prototype.getMessage = function (feedAtSeq, cb) {
if (typeof feedAtSeq === 'string') {
var p = feedAtSeq.split('@')
feedAtSeq = { key: p[0], seq: Number(p[1]) }
}
this.kcore._logs.feed(feedAtSeq.key).get(feedAtSeq.seq, cb)
}
Cabal.prototype.swarm = function (opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
if (!cb) cb = noop
const self = this
swarm(this, opts, function (err, swarm) {
if (err) return cb(err)
self._swarm = swarm
cb(null, swarm)
})
}
Cabal.prototype.replicate = function (isInitiator, opts) {
opts = opts || {}
opts = Object.assign({}, {
live: true,
maxFeeds: 1024
}, opts)
return this.kcore.replicate(isInitiator, opts)
}
Cabal.prototype.ready = function (cb) {
this.kcore.ready(cb)
}
Cabal.prototype._addConnection = function (key) {
this.emit('peer-added', key)
}
Cabal.prototype._removeConnection = function (key) {
this.emit('peer-dropped', key)
}
Cabal.prototype.close = function (cb) {
const self = this
if (this._swarm) {
this._swarm.once('close', close)
this._swarm.destroy()
} else {
close()
}
function close () {
self.kcore.pause()
self.kcore._logs.close(cb)
}
}
function generateKeyHex () {
return crypto.keyPair().publicKey.toString('hex')
}
function isHypercoreKey (key) {
if (typeof key === 'string') return /^[0-9a-f]{64}$/.test(key)
else if (Buffer.isBuffer(key)) return key.length === 32
}
// Ensures 'key' is a hex string
function sanitizeKey (key) {
// force to hex string
if (Buffer.isBuffer(key)) {
key = key.toString('hex')
}
// remove any protocol uri prefix
if (typeof key === 'string') key = key.replace(/^.*:\/\//, '')
else key = undefined
return key
}
function noop () {}