-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
topics.js
59 lines (52 loc) · 1.71 KB
/
topics.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
var View = require('kappa-view-level')
var EventEmitter = require('events').EventEmitter
module.exports = function (lvl) {
var events = new EventEmitter()
return View(lvl, {
map: function (msg) {
if (!sanitize(msg)) return []
var mappings = []
if (msg.value.type === 'chat/topic' && msg.value.content && msg.value.content.channel) {
var key = 'channel!topic!' + msg.value.content.channel
var value = msg.value.content.text
mappings.push([key, value])
}
return mappings
},
indexed: function (msgs) {
msgs
.filter(msg => Boolean(sanitize(msg)))
.filter(msg => msg.value.type.startsWith('chat/topic') && msg.value.content && msg.value.content.channel)
.sort(cmpMsg)
.forEach(function (msg) {
events.emit(msg.value.content.channel, msg)
events.emit('update', msg)
})
},
api: {
get: function (core, channel, cb) {
if (!channel) return
this.ready(function () {
lvl.get('channel!topic!' + channel, (err, topic) => {
cb(err, topic)
})
})
},
events: events
}
})
}
function cmpMsg (a, b) {
return a.value.timestamp - b.value.timestamp
}
// Either returns a well-formed channel message, or null.
function sanitize (msg) {
if (typeof msg !== 'object') return null
if (typeof msg.value !== 'object') return null
if (typeof msg.value.content !== 'object') return null
if (typeof msg.value.timestamp !== 'number') return null
if (typeof msg.value.type !== 'string') return null
if (typeof msg.value.content.channel !== 'string') return null
if (typeof msg.value.content.text !== 'string') return null
return msg
}