| 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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361 |
1
1
1
12
12
12
12
12
12
1
1
26
25
4
4
4
4
21
1
26
26
5
1
26
1
25
25
25
23
4
23
22
2
20
20
20
23
6
17
29
29
29
21
21
21
21
21
20
20
1
1
1
8
20
20
20
19
31
1
30
20
38
38
20
18
16
16
16
22
13
11
9
60
60
60
60
60
34
34
60
60
60
32
32
32
32
32
32
32
24
24
12
12
24
5
5
5
4
4
4
4
24
4
24
8
8
50
50
43
43
43
43
50
40
40
7
40
10
55
55
7
7
55
55
55
55
55
60
60
60
4
4
60
44
44
25
25
25
25
25
25
25
1
8
8
1
1
1
1
1
1
| /*
* Copyright 2014-2016, Sébastien Piquemal <sebpiq@gmail.com>
*
* rhizome is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* rhizome 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 GNU General Public License
* along with rhizome. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
var EventEmitter = require('events').EventEmitter
, querystring = require('querystring')
, Buffer = require('buffer').Buffer
, _ = require('underscore')
, WebSocket = require('ws')
, expect = require('chai').expect
, oscMin = require('osc-min')
, cookies = require('cookies-js')
, coreMessages = require('../core/messages')
, coreValidation = require('../core/validation')
, isBrowser = typeof window !== 'undefined'
Iif (isBrowser) WebSocket = global.WebSocket
var Client = module.exports = function(config) {
config = config || {}
EventEmitter.apply(this)
this._socket = null
this.id = null // Unique id of the client
this._config = config // Set config defaults
this._reconnectTimeout = null // Handle to cancel the reconnection timeout
}
Client._isBrowser = isBrowser // little hack to allow testing some features on node
// This function returns `true` if the web client is supported by the current browser, `false` otherwise.
Client.isSupported = function() {
// For tests
if (Client._isNotSupported) return false
// Test 'websocketsbinary' copied from Modernizr source code :
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/websockets/binary.js
if (Client._isBrowser) {
var protocol = 'https:' == location.protocol ? 'wss' : 'ws',
protoBin
Eif ('WebSocket' in window) {
Eif (protoBin = 'binaryType' in WebSocket.prototype) {
return protoBin
}
try {
return !!(new WebSocket(protocol + '://.').binaryType)
} catch (e) {}
}
return false
} else return true
}
_.extend(Client.prototype, EventEmitter.prototype, coreValidation.ValidateConfigMixin, {
// ========================= PUBLIC API ========================= //
// Starts the client, calling `done(err)` when the client is connected, or when it failed to start.
start: function(done) {
this.log('starting')
var self = this
, _returnErr = function(err) {
if (done) return done(err)
else throw err
}
if (!Client.isSupported())
return _returnErr(new NotSupported('the current browser is not supported'))
Iif (this._socket) {
this._socket.close()
this._clean()
}
this.validateConfig(function(err) {
if (err) return _returnErr(err)
if (Client._isBrowser)
self.id = cookies.get(self._config.cookieName) || null
var _connectCallback = function(err) {
if (err)
return _returnErr(err)
else {
// !!! We want to emit 'connected' only after the `done`
if (done) done()
self.log('connected')
self.emit('connected')
}
}
if (self._config.reconnect)
self._connectWithRetry(0, _connectCallback)
else
self._connect(_connectCallback)
})
},
// Stops the client, calling `done(err)` when the connection was closed successfully.
stop: function(done) {
this.log('stopping')
var self = this
if (this._socket) {
var _onceClosed = function() {
self._clean()
self.log('stopped')
Eif (done) done(null)
}
if (this._socket.readyState === this._socket.OPEN) {
this._socket.onclose = _onceClosed
this._socket.close()
} else Eif (this._socket.readyState === this._socket.CONNECTING) {
this._socket.close()
_onceClosed()
} else _onceClosed()
} else Eif (done) done(null)
},
// Sends a message to OSC `address`, with arguments `args`,
send: function(address, args) {
var self = this
, buffer
// Handle ArrayBuffers
args = args || []
if (_.isArray(args)) {
args = _.map(args, function(arg) {
if (arg instanceof ArrayBuffer)
return new Buffer(new Uint8Array(arg))
else return arg
})
}
// Check that address is not a reserved address, and args are valid.
var _assertValid = function(func, value) {
var err = func(value)
if (err !== null) throw new Error(err)
}
_assertValid(coreMessages.validateAddressForSend, address)
_assertValid(coreMessages.validateArgs, args)
// Browser version of `Buffer` is basically just a `Uint8Array` when typed arrays
// are supported : https://github.com/feross/buffer/blob/master/index.js#L225
// When they are not, `Buffer` is an object and sending it will cause
// `Buffer.toString` to be called.
buffer = oscMin.toBuffer({ address: address, args: args })
buffer.toString = function() { return Buffer.prototype.toString.call(this, 'binary') }
this._socket.send(buffer)
},
// Returns the current status of the client. Values can be `stopped` or `started`.
status: function() {
if (this._socket) {
if (this.id === null) return 'stopped'
else return _.contains([ this._socket.OPEN, this._socket.CONNECTING ],
this._socket.readyState) ? 'started' : 'stopped'
} else return 'stopped'
},
// This function is used by the client to log events. By default it is a no-op.
log: function() {},
// ========================= PRIVATE API ========================= //
// Tries a single time to establish connection, and calls `done(err)`
_connect: function(done) {
var self = this
, url = this._getUrl()
this.log('connecting to ' + url)
this._socket = new WebSocket(url)
this._socket.binaryType = 'arraybuffer'
var _onCloseOrError = function() {
self._clean()
done(new Error('connect error'))
}
this._socket.onerror = _onCloseOrError
this._socket.onclose = _onCloseOrError
this._socket.onopen = function(event) {
self._socket.onerror = function(err) {
// If there's no listener, we don't want an error to be thrown
if (self.listeners('error').length)
self.emit('error', err)
self.log('socket error ' + (err ? err.toString() : ''))
}
// Once socket has opened, we wait for connection status message,
// to get an id and confirm that server has accepted socket connection.
self._socket.onmessage = function(event) {
var decoded = self._decodeMessage(event.data)
Eif (decoded.address === coreMessages.connectionStatusAddress) {
self._socket.onmessage = null
var statusCode = decoded.args[0]
// If `statusCode` is 0, connection succeeded
if (statusCode === 0) {
self.id = decoded.args[1]
self._socket.onmessage = function(event) {
var decoded = self._decodeMessage(event.data)
self.emit('message', decoded.address, decoded.args)
}
self._socket.onclose = function(event) {
self.id = null
self.emit('connection lost')
if (self._config.reconnect) {
self._connectWithRetry(0, function(err) {
Iif (err) throw err
self.log('connected')
self.emit('connected')
})
}
}
if (Client._isBrowser)
cookies.set(self._config.cookieName, self.id)
Eif (done) return done()
// If `statusCode` is 1, the server is full
} else Eif (statusCode === 1)
return done(new ConnectionRefused(statusCode, decoded.args[1]))
}
}
}
},
_connectWithRetry: function(time, done) {
var self = this
this._reconnectTimeout = setTimeout(function() {
// It could happen that this callback is in the event queue
// right after a call to the `Client.stop` method.
// The following test makes sure that if `Client.stop` has been called,
// we don't execute the reconnection.
Iif (!self._reconnectTimeout) return
self._reconnectTimeout = null
self.log('socket reconnecting')
self._connect(function(err) {
if (err) {
self.log('socket failed reconnecting ' + err.toString())
if (err instanceof ConnectionRefused) {
Eif (err.code === 1) self.emit('server full')
}
self._connectWithRetry(self._config.reconnect, done)
} else done()
})
}, time)
},
_clean: function() {
this.id = null
if (this._reconnectTimeout) {
clearTimeout(this._reconnectTimeout)
this._reconnectTimeout = null
}
// !!! Somehow the WebSocket - at least on node - might throw an (unhandled) error
// if we assign `null` to handlers even after closed.
this._socket.onclose = function() {}
this._socket.onerror = function() {}
this._socket.onopen = function() {}
this._socket.onmessage = function() {}
this._socket = null
},
_getUrl: function() {
var query = {}
if (this.id) query.id = this.id
if (Client._isBrowser) {
query.os = global.navigator.oscpu || global.navigator.platform
query.browser = global.navigator.userAgent
}
return this._config.protocol + '://'
+ this._config.hostname + ':' + this._config.port
+ '/?' + querystring.stringify(query)
},
_decodeMessage: function(data) {
var msg = oscMin.fromBuffer(data)
, address = msg.address
, args = _.pluck(msg.args, 'value')
return { address: address, args: args }
},
configValidator: new coreValidation.ChaiValidator({
protocol: function(val) {
expect(val).to.be.a('string')
.and.to.satisfy(function(val) { return _.contains(['ws', 'wss'], val) })
},
port: function(val) {
expect(val).to.be.a('number')
.and.to.be.within(0, 65535)
},
hostname: function(val) {
expect(val).to.be.a('string')
},
reconnect: function(val) {
expect(val).to.be.a('number')
},
cookieName: function(val) {
expect(val).to.be.a('string')
},
useCookies: function(val) {
expect(val).to.be.a('boolean')
}
}),
configDefaults: {
port: (isBrowser ?
(window.location.port.length ?
parseInt(window.location.port, 10): ({'http:': 80, 'https:': 443})[window.location.protocol]
)
: undefined),
protocol: isBrowser ? ({'http:': 'ws', 'https:': 'wss'})[window.location.protocol] : 'ws',
hostname: isBrowser ? window.location.hostname : undefined,
reconnect: 2000,
cookieName: 'rhizome',
useCookies: true
}
})
// --------------- Error classes --------------- //
// Error for when the config of an object is not valid
var ConnectionRefused = function ConnectionRefused(code, message) {
this.code = code
this.message = message
}
ConnectionRefused.prototype = Object.create(Error.prototype)
ConnectionRefused.prototype.name = 'ConnectionRefused'
// Error for when the client is not supported
var NotSupported = function NotSupported(message) {
this.message = message
}
NotSupported.prototype = Object.create(Error.prototype)
NotSupported.prototype.name = 'NotSupported'
|