-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
92 lines (83 loc) · 2.63 KB
/
server.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
var diffsync = require('./diffsync.js')
console.log('diffsync version ' + diffsync.version)
var bus = require('statebus')()
bus.sqlite_store()
var channels = {}
for (var key in bus.cache) {
if (!bus.cache.hasOwnProperty(key)) { continue }
var o = bus.cache[key]
if (key.startsWith('commit/')) {
if (!channels[o.channel])
channels[o.channel] = { commits : {}, members : {} }
// backwards compatability with 1022
if (o.parents) {
channels[o.channel].commits[o.id] = {
to_parents : o.parents,
from_parents : o.from_parents
}
if (o.text)
channels[o.channel].commits[o.id].text = o.text
} else {
channels[o.channel].commits[o.id] = o.commit
}
}
if (key.startsWith('member/')) {
if (!channels[o.channel])
channels[o.channel] = { commits : {}, members : {} }
channels[o.channel].members[o.id] = o.member
}
}
var fs = require('fs')
var web_server = null
var server_type = null
if (fs.existsSync('privkey.pem') && fs.existsSync('fullchain.pem')) {
web_server = require('https').createServer({
key : fs.readFileSync('privkey.pem'),
cert : fs.readFileSync('fullchain.pem')
})
server_type = 'https'
} else {
web_server = require('http').createServer()
server_type = 'http'
}
var port = diffsync.port
web_server.listen(port)
console.log('openning ' + server_type + ' server on port ' + port)
var WebSocket = require('ws')
var wss = new WebSocket.Server({ server : web_server })
var diff_server = diffsync.create_server({
wss : wss,
initial_data : channels,
on_change : function (changes) {
for (var id in changes.commits) {
if (!changes.commits.hasOwnProperty(id)) { continue }
var c = changes.commits[id]
var key = 'commit/' + id
if (c) {
bus.save({
key : key,
id : id,
channel : changes.channel,
commit : c
})
} else {
bus.del(key)
}
}
for (var id in changes.members) {
if (!changes.members.hasOwnProperty(id)) { continue }
var m = changes.members[id]
var key = 'member/' + id + '/of/' + changes.channel
if (m) {
bus.save({
key : key,
id : id,
channel : changes.channel,
member : m
})
} else {
bus.del(key)
}
}
}
})