Files: 6b0e3d2a1e43d3efa7bfab274588c5b8acd70f16 / index.js
1628 bytesRaw
1 | const flumeView = require('flumeview-reduce') |
2 | const mkdirp = require('mkdirp') |
3 | const { join } = require('path') |
4 | const level = require('level') |
5 | const charwise = require('charwise') |
6 | const { isMsg } = require('ssb-ref') |
7 | |
8 | module.exports = { |
9 | name: 'unread', |
10 | version: require('./package.json').version, |
11 | manifest: { |
12 | isRead: 'async', |
13 | markRead: 'async', |
14 | // isUnreadThrough: 'source' // stream via this module to check unread state of msgs as you go? |
15 | }, |
16 | init: function (server, config) { |
17 | |
18 | mkdirp.sync(join(config.path, 'unread')) |
19 | const db = level(join(config.path, 'unread'), { |
20 | valueEncoding: charwise |
21 | }) |
22 | |
23 | markDbBirth(db) |
24 | |
25 | const VERSION = 1 |
26 | server._flumeUse('unread-dummy-index', flumeView( |
27 | VERSION, |
28 | (_, msg) => { |
29 | db.put(msg.key, null, noop) |
30 | |
31 | return _ |
32 | // HACK: leveraging flume to access stream of newest messages |
33 | } |
34 | )) |
35 | |
36 | function isRead (key, cb) { |
37 | if (!isMsg(key)) return cb(null, new Error('ssb-unread requires a valid message key') |
38 | |
39 | db.get(key, (err, ts) => { |
40 | if (err) cb(err) |
41 | else cb(null, Boolean(ts)) |
42 | }) |
43 | } |
44 | |
45 | function markRead (key, cb = noop) { |
46 | if (!isMsg(key)) return cb(null, new Error('ssb-unread requires a valid message key') |
47 | |
48 | db.put(key, Date.now(), cb) |
49 | } |
50 | |
51 | return { |
52 | isRead, |
53 | markRead, |
54 | } |
55 | } |
56 | } |
57 | |
58 | function markDbBirth (db) { |
59 | const STARTED_AT = 'startedAt' |
60 | var startedAt |
61 | db.get(STARTED_AT, (err, ts) => { |
62 | if (ts) { |
63 | startedAt = ts |
64 | return |
65 | } |
66 | |
67 | startedAt = Date.now |
68 | db.put(STARTED_AT, startedAt) |
69 | }) |
70 | } |
71 | |
72 | function noop () {} |
73 |
Built with git-ssb-web