-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (70 loc) · 2.29 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
/**
* hive.js
* Copyright (C) 2013-2016 Marcel Klehr <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Mozilla Public License version 2
* as published by the Mozilla Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the Mozilla Public License
* along with this program. If not, see <https://www.mozilla.org/en-US/MPL/2.0/>.
*/
var co = require('co')
, through = require('through2')
, JSONParse = require('json-stream')
, path = require('path')
module.exports = setup
module.exports.consumes = ['ui', 'broadcast', 'orm']
function setup(plugin, imports, register) {
var ui = imports.ui
, broadcast = imports.broadcast
, orm = imports.orm
ui.registerModule(path.join(__dirname, 'client.js'))
var cursors = {}
broadcast.registerChannel(new Buffer('codemirror-cursors'), function(user, document, client, brdcst) {
co(function*() {
if((yield orm.collections.document.findOne(document)).type !== 'text/plain') return
if(!cursors[document]) cursors[document] = {}
var writeAll
client
.pipe(JSONParse())
.pipe(through.obj(function(myCursor, enc, callback) {
cursors[document][user.id] = myCursor
var obj = {}
obj[user.id] = myCursor
this.push(obj)
callback()
}))
.pipe(writeAll = JSONStringify())
.pipe(brdcst)
.pipe(JSONParse())
.pipe(through.obj(function(broadcastCursors, enc, callback) {
for(var userId in broadcastCursors) {
cursors[document][userId] = broadcastCursors[userId]
if(!broadcastCursors[userId]) delete cursors[document][userId]
}
this.push(broadcastCursors)
callback()
}))
.pipe(JSONStringify())
.pipe(client)
client.on('close', function() {
writeAll.write({[user.id]: null})
delete cursors[document][user.id]
})
client.write(JSON.stringify(cursors[document])+'\n')
})
})
register()
}
function JSONStringify() {
return through.obj(function(buf, enc, cb) {
this.push(JSON.stringify(buf)+'\n')
cb()
})
}