-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathemo.js
342 lines (251 loc) · 9.39 KB
/
emo.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
var bus = require('statebus-server')(),
express = require('express'),
app = express(),
fs = require('fs'),
path = require('path'),
jsondiffpatch = require('jsondiffpatch'),
urlParse = require('url')
// ##############
// Setup the HTTP server
if (fs.existsSync('certs')) {
// Load with TLS/SSL
console. log('Encryption ON')
var https = require('https')
var ssl_options = {
key: fs.readFileSync('certs/private-key'),
cert: fs.readFileSync('certs/certificate'),
ciphers: 'ECDHE-RSA-AES256-SHA:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM',
honorCipherOrder: true}
var server = https.createServer(ssl_options, app)
}
else {
// Load unencrypted server
console.log('Encryption off')
var http = require('http')
var server = http.createServer(app)
}
server = server.listen(4000, function () {
var host = server.address().address
var port = server.address().port
console.log('Listening at https://%s:%s', host, port)
})
var https = require('https')
// var options = { host: 'npmcdn.com', path: '/[email protected]'}
// var callback = function(response) {
// var str = '';
// //another chunk of data has been recieved, so append it to `str`
// response.on('data', function (chunk) {
// str += chunk;
// });
// //the whole response has been recieved, so we just print it out here
// response.on('end', function () {
// console.log(str);
// });
// }
// var request = https.request(options, callback).end();
function requestCode(url, callback){
var parsedurl = urlParse.parse(url)
var options = {'host' : parsedurl.hostname, port: parsedurl.port, path: parsedurl.path}
var protocol = http;
if(parsedurl.protocol === 'https:')
protocol = https;
var cb = function(response){
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
callback(str);
});
}
protocol.request(options, cb).end();
}
bus.file_store('/*', 'db', 'backups') // Save our cache across server restarts
bus.sockjs_server(server, userbusfunk) // Accept statebus network connections
bus('*').on_save = function (obj) { bus.pub(obj) } // Everything is shared w/ no security
// ##############
// HTTP routes go here
function send_file (name) {
return function (req, res) {
res.sendFile(path.join(__dirname, '.', name)) }
}
if (!String.prototype.endsWith) {
Object.defineProperty(String.prototype, 'endsWith', {
enumerable: false,
configurable: false,
writable: false,
value: function (searchString, position) {
position = position || this.length;
position = position - searchString.length;
var lastIndex = this.lastIndexOf(searchString);
return lastIndex !== -1 && lastIndex === position;
}
});
}
app.get('/', send_file('emo.html'))
app.get('/emo/:codeUrl', send_file('emo.html') )
app.get('/demos', send_file('sbdemos.html'))
app.get('/jsondiffpatch.js', send_file('jsondiffpatch.js'))
app.get('/google_diff_match_patch.js', send_file('google_diff_match_patch.js'))
app.get('/textwidget/:codeUrl', send_file('textwidget.html'))
app.get('/scripts/:subdir?/:filename',
function(req, res){
var filename = req.params.filename;
var subdir = ''
if (!filename.endsWith('.js'))
filename += '.js';
if(req.params.subdir)
subdir = req.params.subdir + '/'
return send_file('scripts/' + subdir + filename)(req, res)
}
);
app.get('/lib/:filename',
function(req, res){
var filename = req.params.filename;
if (!filename.endsWith('.js'))
filename += '.js';
return send_file('scripts/lib/' + filename)(req, res)
}
);
bus.diffPatcher = new jsondiffpatch.create({textDiff : {minLength : 1}});
bus('/url/*').on_fetch = function(key){
key = key.substring('/url/'.length);
if(key.startsWith('http')){
var callback = function(str){ bus.pub({key : '/url/' + key, content: str}) }
requestCode(key, callback);
}
}
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position){
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
function clone(obj){
return JSON.parse(JSON.stringify(obj))
}
var clientbuses = {}
function rememberClientForDiffSync(clientid, clientbus, diffsynckey){
if(clientbuses[diffsynckey] === undefined)
clientbuses[diffsynckey] = {}
clientbuses[diffsynckey][clientid] = clientbus;
}
function forgetClientForDiffSync(clientid, diffsynckey){
delete clientbuses[diffsynckey][clientid];
}
function fetch_once(key, callback) {
fetch(key, wrapper)
function wrapper (obj) {
callback(obj)
bus.forget(key, wrapper)
}
}
// we want to create a bus for each client
// this will let us do collaborative edits
// cuz we can keep a shadow for each client
function userbusfunk (clientbus, conn){
// clientbus.serves_auth(conn, bus)
clientbus('/serverdiff/*').on_fetch = function (key){
if(key.startsWith('/serverdiff/')){
var strippedKey = key.substring('/serverdiff/'.length)
rememberClientForDiffSync(conn.id, clientbus, strippedKey);
//Fetching the whole doc and then pubbing it to the client.
function pubWholeDoc(shared){
if(shared.doc == undefined){
shared.doc = {key : strippedKey};
}
clientbus.pub({key : key, doc: shared.doc});
}
fetch_once('/' + strippedKey, pubWholeDoc);
}else{
return bus.fetch(key)
}
}
clientbus('*').on_forget = function(key){
if(key.startsWith('/serverdiff/')){
var strippedKey = key.substring('/serverdiff/'.length)
forgetClientForDiffSync(conn.id, strippedKey)
var shared = fetch('/' + strippedKey);
console.log(shared)
if(shared.doc.cursors){
delete shared.doc.cursors
save(shared);
}
// }
}else if(key.startsWith('/cursors/')){
var cursors = fetch(key);
if(cursors.cursors){
delete cursors.cursors
save(cursors);
}
}
else
bus.forget(key);
}
clientbus('*').on_save = function(obj){
if(!obj.key.startsWith('/clientdiff/')){
bus.save(obj)
}else{
var strippedKey = obj.key.substring('/clientdiff/'.length);
if(!clientbuses[strippedKey] || !clientbuses[strippedKey][conn.id])
return;
saveIncomingEdits(obj);
}
}
function saveIncomingEdits(message){
var strippedKey = message.key.substring('/clientdiff/'.length);
// The main doc that is what is edited.
var shared = bus.fetch('/' + strippedKey);
//The shadow copy for the current client
var shadow = bus.fetch('shadow/' + conn.id + '/' + strippedKey);
if(shared.doc === undefined){
shared.doc = {key : strippedKey};
bus.save(shared)
}
//Initialize any of these if they don't exist
if(shadow.doc === undefined){
shadow.doc = clone(shared.doc)
}
//If the client sent an older version, we can ignore it.
if(message.diff){
shadow.doc = bus.diffPatcher.patch(shadow.doc, message.diff)
shared.doc = bus.diffPatcher.patch(shared.doc, message.diff)
bus.save(shared)
}
bus.save(shadow);
saveOutgoingEdits(conn.id, strippedKey);
}
var editcounter = {};
//Let's compare a shadow for a client with our current version
//Returns an object that contains the server text version
//along with a stack of edits that the client should apply.
//This also increments the server text version #, saves
//the stack of edits to state, and updates the shadow to
//reflect the current server text and it's version #.
function saveOutgoingEdits(clientid, strippedKey){
//Get the server text
var shared = bus.fetch('/' + strippedKey);
//get the shadow corresponding to this client
var shadow = bus.fetch('shadow/' + clientid + '/' + strippedKey);
//Apply the diffs
var diff = bus.diffPatcher.diff(shadow.doc, shared.doc);
//Return the edits
var clientbus = clientbuses[strippedKey][clientid];
var message = {key: '/serverdiff/' + strippedKey}
if(editcounter[shadow.key] === undefined)
editcounter[shadow.key] = 0
message.counter = editcounter[shadow.key];
editcounter[shadow.key]++;
if(diff){
//Add these diffs to the stack we will send
message.diff = diff;
//Copy the server text to the shadow
shadow.doc = clone(shared.doc);
//Save everything
bus.save(shadow);
}
clientbus.pub(message);
}
}