/
api.js
121 lines (99 loc) · 2.75 KB
/
api.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
//@theory
var Synchronizer = exports.Synchronizer = function Synchronizer() {
//this.sockets = []
//this.doc = undefined
}
//update all clients to current value
Synchronizer.prototype.sync = function(callback/*(err)*/) {
//this.sockets.forEach(socket) {socket.write(this.doc)}
//callback(false)
}
//someone posts an update
Synchronizer.prototype.save = function(doc_or_stream,callback/*(err)*/) {
//this.doc = doc
//callback(false)
}
//someone requests doc
Synchronizer.prototype.get = function(callback/*(err,doc)*/) {
//callback(false,this.doc)
}
//client connects
Synchronizer.prototype.open = function(websocket,callback/*(err)*/) {
//callback(EventEmitter)
// -edit
// -open
// -quit
}
//client closes
Synchronizer.prototype.close = function(websocket,callback/*(err)*/) {
//callback()
}
//@use
var SynchronizedText = exports.SynchronizedText = function SynchronizedText(name) {
this.name = name
this.id = 0
this.clients = []
this.doc = ""
}
SynchronizedText.prototype = new Synchronizer
SynchronizedText.prototype.sync = function(callback) {
var $this = this
this.clients.forEach(function(client){
var data = $this.name+"@"+$this.doc
client.websocket.write(data)
})
if(callback) callback(false)
}
//TODO: Resolve merge errors...
SynchronizedText.prototype.save = function(doc,callback) {
if(typeof doc === "string") {
this.doc = doc
this.sync()
if(callback) callback(false)
if(this.onupdate) this.onupdate(doc)
}
else {
var _tmp = String()
, $this = this
doc.addListener("data",function(chunk){_tmp += String(chunk)})
doc.addListener("close",function(){
$this.doc = _tmp
$this.sync()
if(callback) callback(false)
if($this.onupdate) $this.onupdate(_tmp)
})
}
}
SynchronizedText.prototype.get = function(callback) {
if(callback) callback(false,this.doc)
}
SynchronizedText.prototype.open = function(websocket,callback) {
var $this = this
, listener = function(chunk) {
chunk = String(chunk)
var index = chunk.indexOf("@")
if(index !== -1) {
var target = chunk.slice(0,index)
if(target === $this.name) {
var doc = $this.doc = chunk.slice(index+1)
$this.sync()
if($this.onupdate) $this.onupdate(doc)
}
}
}
this.clients.push({websocket:websocket,listener:listener})
websocket.addListener("message",listener)
var data = this.name+"@"+this.doc
websocket.write(data)
if(callback) callback(false)
}
SynchronizedText.prototype.close = function(websocket,callback) {
var notFound = true
this.clients.forEach(function(client){
if(client.websocket === websocket) {
notFound = false
websocket.removeListener("message",client.listener)
}
})
if(callback) callback(notFound)
}