forked from NathanaelA/nativescript-websockets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsockets.android.js
More file actions
670 lines (591 loc) · 20.9 KB
/
websockets.android.js
File metadata and controls
670 lines (591 loc) · 20.9 KB
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
/*****************************************************************************************
* (c) 2015-2017, Master Technology
* Licensed under the MIT license or contact me for a support, changes, enhancements,
* and/or if you require a commercial licensing
*
* Any questions please feel free to email me or put a issue up on github
*
* Version 0.1.2 Nathan@master-technology.com
****************************************************************************************/
"use strict";
/* jshint node: true, browser: true, unused: false, undef: false, camelcase: false, bitwise: false */
/* global android, java, org, require, module */
// --------------------------------------------
var commonWebSockets = require("./websockets-common");
/**
* Checks for running on a emulator
* @returns {boolean}
*/
var checkForEmulator = function() {
//noinspection JSUnresolvedVariable
var res = android.os.Build.FINGERPRINT;
return res.indexOf("generic") !== -1;
};
// IPV6 doesn't work properly on emulators; so we have to disable it
if (checkForEmulator()) {
//noinspection JSUnresolvedVariable
java.lang.System.setProperty("java.net.preferIPv6Addresses", "false");
//noinspection JSUnresolvedVariable
java.lang.System.setProperty("java.net.preferIPv4Stack", "true");
}
var toHashMap = function(obj) {
var map = new java.util.HashMap();
for (var property in obj) {
if (!obj.hasOwnProperty) continue;
if (obj[property] === null) continue;
var val = obj[property];
switch (typeof val) {
case 'object':
map.put(property, toHashMap(val, map));
break;
case 'boolean':
map.put(property, java.lang.Boolean.valueOf(String(val)));
break;
case 'number':
if (Number(val) === val && val % 1 === 0) {
map.put(property, java.lang.Long.valueOf(String(val)));
} else {
map.put(property, java.lang.Double.valueOf(String(val)));
}
break;
case 'string':
map.put(property, String(val));
break;
}
}
return map;
};
//noinspection JSUnresolvedVariable
/**
* This is our extended class that gets the messages back from the Native ANDROID class
* We use a thin shell to just facilitate communication from ANDROID to our JS code
* We also use this class to try and standardize the messages
*/
var _WebSocket = org.java_websocket.client.WebSocketClient.extend({
fragmentInfo: {type: 0, data: [], sizes: 0},
wrapper: null,
onOpen: function () {
if (this.wrapper) {
this.wrapper._notify("open", [this.wrapper]);
}
},
onClose: function (code, reason) {
if (this.wrapper) {
this.wrapper._notify("close", [this.wrapper, code, reason]);
}
},
onMessage: function (message) {
if (this.wrapper) {
this.wrapper._notify("message", [this.wrapper, message]);
}
},
onMessageBinary: function(binaryMessage) {
if (this.wrapper) {
// Make sure binaryMessage is at beginning of buffer
//noinspection JSUnresolvedFunction
binaryMessage.rewind();
// Convert Binary Message into ArrayBuffer/Uint8Array
//noinspection JSUnresolvedFunction
var count = binaryMessage.limit();
var view = new Uint8Array(count);
for (var i=0;i<count;i++) {
view[i] = binaryMessage.get(i);
}
binaryMessage = null;
this.wrapper._notify("message", [this.wrapper, view.buffer]); }
},
onPong: function(){
},
onError: function (err) {
if (this.wrapper) {
this.wrapper._notify("error", [this.wrapper, err]);
}
},
onFragment: function (fragment) {
var optCode = fragment.optcode.toString();
if (optCode !== "CONTINUOUS") {
if (this.fragmentInfo.type !== 0) {
console.log("Missing Fragment info, skipped fragment");
}
// Reset our buffer size when we have a new fragment chain
this.fragmentInfo.sizes = 0;
if (optCode === "TEXT") {
this.fragmentInfo.type = 1;
} else if (optCode === "BINARY") {
this.fragmentInfo.type = 2;
} else {
console.log("Unknown Fragment code: ", optCode);
this.fragmentInfo.type = 0;
}
}
var data = fragment.getPayloadData();
this.fragmentInfo.sizes += data.limit();
this.fragmentInfo.data.push(data);
if (fragment.fin === true) {
var view = new Uint8Array(this.fragmentInfo.sizes);
for (var i = 0, dst = 0; i < this.fragmentInfo.data.length; i++) {
data = this.fragmentInfo.data[i];
var count = data.limit();
for (var src = 0; src < count; src++, dst++) {
view[dst] = data.get(src);
}
}
data = null;
this.fragmentInfo.data = [];
if (this.wrapper) {
// Do our final message callback
if (this.fragmentInfo.type === 2) {
this.wrapper._notify("message", [this.wrapper, view.buffer]);
} else {
this.wrapper._notify("message", [this.wrapper, UTF8ArrayToStr(view)]);
}
view = null;
}
// Reset back to unknown type
this.fragmentInfo.type = 0;
}
if (this.wrapper) {
this.wrapper._notify("fragment", [this.wrapper, fragment]);
}
},
onWebsocketHandshakeReceivedAsClient: function (handshake) {
if (this.wrapper) {
this.wrapper._notify("handshake", [this.wrapper, handshake]);
}
}
});
/**
* This is the Constructor for creating a WebSocket
* @param url {String} - url to open, "ws://" or "wss://"
* @param options {Object} - options
* @constructor
*/
var NativeWebSockets = function(url, options) {
options = options || {};
this._callbacks = {open: [], close: [], message: [], error: [], fragment: [], handshake: [], ping: [], pong: []}; // Ping/Pong not supported yet
this._hasOpened = false;
this._queue = [];
this._queueRunner = null;
// TODO: Replace Hack when we support protocols in Android; we want to "emulate" that the first protocol sent was accepted
this._protocol = options.protocols && options.protocols[0] || "";
this._browser = !!options.browser;
this._timeout = options.timeout;
this._url = url.replace(/\s/g,'+');
//noinspection JSUnresolvedVariable
this._proxy = options.proxy;
this._timeout = options.timeout || 10000;
this._headers = options.headers || [];
this._reCreate();
};
/**
* This function is used to open and re-open sockets so that you don't have to re-create a whole new websocket class
* @private
*/
NativeWebSockets.prototype._reCreate = function() {
var isWSS = (this._url.indexOf("wss:") === 0);
//noinspection JSUnresolvedVariable,JSUnresolvedFunction
var uri = new java.net.URI(this._url);
//noinspection JSUnresolvedVariable,JSUnresolvedFunction
this._socket = new _WebSocket(uri, new org.java_websocket.drafts.Draft_17(), toHashMap(this._headers), this._timeout);
//noinspection JSValidateTypes
this._socket.wrapper = this;
// check for Proxy
var proxy = null;
if (this._proxy) {
if (String.isString(this._proxy)) {
//noinspection JSUnresolvedVariable,JSUnresolvedFunction
proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, new java.net.InetSocketAddress( this._proxy, 80 ) );
} else {
//noinspection JSUnresolvedVariable,JSUnresolvedFunction
proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, new java.net.InetSocketAddress( this._proxy.address, this._proxy.port || 80 ) );
}
}
if (proxy) {
//noinspection JSUnresolvedFunction
this._socket.setProxy(proxy);
}
// Check for SSL/TLS
if (isWSS) {
this._socket.setupSSL();
// This below code is currently broken in NativeScript; so we had to embed the SSL code in the Websocket library.
// TODO: Re-enable this once it is fixed in NativeScript so that the end user can actually setup the specific
// SSL connection he wants...
/* //noinspection JSUnresolvedFunction,JSUnresolvedVariable
var sslContext = javax.net.ssl.SSLContext.getInstance( "TLS" );
sslContext.init( null, null, null );
//noinspection JSUnresolvedFunction
var socketFactory = sslContext.getSocketFactory();
//noinspection JSUnresolvedFunction
this._socket.setSocket( socketFactory.createSocket() ); */
}
};
/**
* This function is used to send the notifications back to the user code in the Advanced webSocket mode
* @param event {String} - event name ("message", "open", "close", "error")
* @param data {String|Array|ArrayBuffer}
* @private
*/
NativeWebSockets.prototype._notify = function(event, data) {
var eventCallbacks = this._callbacks[event];
for (var i=0;i<eventCallbacks.length;i++) {
if (eventCallbacks[i].t) {
eventCallbacks[i].c.apply(eventCallbacks[i].t, data);
} else {
eventCallbacks[i].c.apply(this, data);
}
}
};
/**
* This function is used to send the notifications back to the user code in the Browser webSocket mode
* @param event {String} - Event name ("message", "open", "close", "error")
* @param data {String|Array|ArrayBuffer} - The event Data
* @private
*/
NativeWebSockets.prototype._notifyBrowser = function(event, data) {
var eventResult;
switch (event) {
case 'open':
eventResult = new commonWebSockets.Event({currentTarget: this, srcElement: this, target: this, type: event});
if (typeof this.onopen === "function") {
this.onopen.call(this, eventResult);
}
break;
case 'close':
eventResult = new commonWebSockets.Event({currentTarget: this, srcElement: this, target: this, type: event, code: data[1], reason: data[2], wasClean: data[3]});
if (typeof this.onclose === "function") {
this.onclose.call(this, eventResult);
}
break;
case 'message':
eventResult = new commonWebSockets.Event({currentTarget: this, srcElement: this, target: this, type: event, data: data[1], ports: null, source: null, lastEventId: ""});
if (typeof this.onmessage === "function") {
this.onmessage.call(this,eventResult);
}
break;
case 'error':
eventResult = new commonWebSockets.Event({currentTarget: this, srcElement: this, target: this, type: event, error: data[1], filename: "", lineno: 0});
if (typeof this.onerror === "function") {
this.onerror.call(this,eventResult);
}
break;
default: return;
}
var eventCallbacks = this._callbacks[event];
for (var i=0;i<eventCallbacks.length;i++) {
eventCallbacks[i].c.call(this, eventResult);
}
};
/**
* Attach an event to this webSocket
* @param event {String} - Event Type ("message", "open", "close", "error")
* @param callback {Function} - the function to run on the event
* @param thisArg {Object} - the "this" to use for calling your function, defaults to this current webSocket "this"
*/
NativeWebSockets.prototype.on = function(event, callback, thisArg) {
this.addEventListener(event, callback, thisArg);
};
/**
* Detaches an event from this websocket
* If no callback is provided all events are cleared of that type.
* @param event {String} - Event to detach from
* @param callback {Function} - the function you registered
*/
NativeWebSockets.prototype.off = function(event, callback) {
this.removeEventListener(event, callback);
};
/**
* Attach an event to this webSocket
* @param event {String} - Event Type ("message", "open", "close", "error")
* @param callback {Function} - the function to run on the event
* @param thisArg {Object} - the "this" to use for calling your function, defaults to this current webSocket "this"
*/
NativeWebSockets.prototype.addEventListener = function(event, callback, thisArg) {
if (!Array.isArray(this._callbacks[event])) {
throw new Error("addEventListener passed an invalid event type " + event);
}
this._callbacks[event].push({c: callback, t: thisArg});
};
/**
* Detaches an event from this webSocket
* If no callback is provided all events are cleared of that type.
* @param event {String} - Event to detach from
* @param callback {Function} - the function you registered
*/
NativeWebSockets.prototype.removeEventListener = function(event, callback) {
if (!Array.isArray(this._callbacks[event])) {
throw new Error("Invalid event type in removeEventListener " + event);
}
if (callback) {
var eventCallbacks = this._callbacks[event];
for (var i=eventCallbacks.length-1;i>=0;i--) {
if (eventCallbacks[i].c === callback) {
eventCallbacks.slice(i, 1);
}
}
} else {
this._callbacks[event] = [];
}
};
/**
This opens or re-opens a webSocket.
*/
NativeWebSockets.prototype.open = function() {
if (this._hasOpened) {
// Browser WebSockets aren't allowed to re-open
if (this._browser) {
return;
}
if (this.state() >= 3) {
this._socket.wrapper = null;
this._socket = null;
this._reCreate();
} else {
return;
}
}
this._hasOpened = true;
//noinspection JSUnresolvedFunction
this._socket.connect();
};
/**
* This closes your webSocket
* @param code {Number} - The value to send as the close reason
* @param message {String} - The message as to why you are closing
*/
NativeWebSockets.prototype.close = function(code, message) {
if (arguments.length) {
this._socket.close(code, message || "");
} else {
this._socket.close();
}
};
/**
* This sends a Text or Binary Message (Allows Buffering of messages if this is an advanced WebSocket)
* @param message {string|Array|ArrayBuffer} - Message to send
* @returns {boolean} - returns false if it is unable to send the message at this time, it will queue them up and try later...
*/
NativeWebSockets.prototype.send = function(message) {
var state = this.state();
// If we have a queue, we need to start processing it...
if (this._queue.length && state === this.OPEN) {
for (var i = 0; i < this._queue.length; i++) {
this._send(this._queue[i]);
}
this._queue = [];
if (this._queueRunner) {
clearTimeout(this._queueRunner);
this._queueRunner = null;
}
}
// You shouldn't be sending null/undefined messages; but if you do -- we won't error out.
if (message === null || message === undefined) {
this._startQueueRunner();
return false;
}
// If the socket isn't open, or we have a queue length; we are
if (state !== this.OPEN || this._queue.length) {
if (this._browser) {
return false;
}
this._queue.push(message);
this._startQueueRunner();
return false;
}
this._send(message);
return true;
};
/**
* Internal function to start the Queue Runner timer
* @private
*/
NativeWebSockets.prototype._startQueueRunner = function() {
if (!this._queueRunner && this.state() !== this.OPEN && this._queue.length) {
var self = this;
this._queueRunner = setTimeout(function() {
self._queueRunner = null;
self.send(null);
}, 250);
}
};
/**
* Internal function that actually sends the message
* @param message {String|ArrayBuffer} - Message to send
* @private
*/
NativeWebSockets.prototype._send = function(message) {
if (message instanceof ArrayBuffer || message instanceof Uint8Array || Array.isArray(message)) {
var view;
if (message instanceof ArrayBuffer) {
view = new Uint8Array(message);
} else {
view = message;
}
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.class.getField("TYPE").get(null), view.length);
for (var i=0;i<view.length;i++) {
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
java.lang.reflect.Array.setByte(buffer, i, byte(view[i]));
}
this._socket.send(buffer);
} else {
this._socket.send(message);
}
};
/**
* Returns the state of the Connection
* @returns {Number} - returns this.NOT_YET_CONNECTED, .CONNECTING, .OPEN, .CLOSING or .CLOSED
*/
NativeWebSockets.prototype.state = function() {
//noinspection JSUnresolvedFunction
return this._socket.getState()-1;
};
/**
* Is the connection open
* @returns {boolean} - true if the connection is open
*/
NativeWebSockets.prototype.isOpen = function() {
return this._socket.isOpen();
};
/**
* Is the connection closed
* @returns {boolean} - true if the connection is closed
*/
NativeWebSockets.prototype.isClosed = function() {
return this._socket.isClosed();
};
/**
* Is the connection is in the process of closing
* @returns {boolean} - true if closing
*/
NativeWebSockets.prototype.isClosing = function() {
return this._socket.isClosing();
};
/**
* Is the connection currently connecting
* @returns {boolean} - true if connecting
*/
NativeWebSockets.prototype.isConnecting = function() {
return this._socket.isConnecting();
};
/**
* Returns the Remote address
* @returns {String} - the address
*/
NativeWebSockets.prototype.getRemoteSocketAddress = function() {
return this._socket.getRemoteSocketAddress();
};
/**
* This returns the current protocol
*/
Object.defineProperty(NativeWebSockets.prototype, "protocol", {
get: function () {
return this._protocol;
},
enumerable: true,
configurable: true
});
/**
* This returns the current readyState
*/
Object.defineProperty(NativeWebSockets.prototype, "readyState", {
get: function () {
var s = this.state();
// No such -1 in the web spec
if (s === -1) { return 0; }
return s;
},
enumerable: true
});
/**
* This returns the URL you connected too
*/
Object.defineProperty(NativeWebSockets.prototype, "url", {
get: function () {
return this._url;
},
enumerable: true
});
/**
* This returns the amount of data buffered
*/
Object.defineProperty(NativeWebSockets.prototype, "bufferedAmount", {
get: function () {
// Technically I should return the actual amount of data; but as an optimization we are just returning the number of entries
// as this will allow the developer to know there is still data in the queue.
return this._queue.length;
},
enumerable: true
});
/**
* This returns any extensions running.
*/
Object.defineProperty(NativeWebSockets.prototype, "extensions", {
get: function () {
return "";
},
enumerable: true
});
/**
* This returns true because it is on the ANDROID platform
*/
Object.defineProperty(NativeWebSockets.prototype, "android", {
get: function () {
return true;
},
enumerable: true
});
/**
* This is a list standardized Close Codes
* @type {Number}
*/
NativeWebSockets.CLOSE_CODE = {NORMAL: 1000, GOING_AWAY: 1001, PROTOCOL_ERROR: 1002, REFUSE: 1003, NOCODE: 1005, ABNORMAL_CLOSE:1006, NO_UTF8: 1007, POLICY_VALIDATION: 1008, TOOBIG: 1009, EXTENSION: 1010, UNEXPECTED_CONDITION: 1011, TLS_ERROR: 1015, NEVER_CONNECTED: -1, BUGGYCLOSE: -2, FLASHPOLICY: -3};
/**
* This is the NOT_YET_CONNECTED value
* @type {number}
*/
NativeWebSockets.prototype.NOT_YET_CONNECTED = -1;
/**
* This is the CONNECTING value
* @type {number}
*/
NativeWebSockets.prototype.CONNECTING = 0;
/**
* This is the OPEN value
* @type {number}
*/
NativeWebSockets.prototype.OPEN = 1;
/**
* This is the CLOSING value
* @type {number}
*/
NativeWebSockets.prototype.CLOSING = 2;
/**
* This is the CLOSED value
* @type {number}
*/
NativeWebSockets.prototype.CLOSED = 3;
module.exports = NativeWebSockets;
function UTF8ArrayToStr(data) {
var result='', count=data.length;
var i=0, c1, c2, c3;
while(i < count) {
c1 = data[i++];
switch(c1 >> 4)
{
case 12: // 10xx xxxx
case 13: // 110x xxxx
c2 = (data[i++] & 0x3F);
result += String.fromCharCode(((c1 & 0x1F) << 6) | c2);
break;
case 14: // 1110 xxxx
c2 = (data[i++] & 0x3F) << 6;
c3 = (data[i++] & 0x3F);
result += String.fromCharCode(((c1 & 0x0F) << 12) | c2 | c3);
break;
default: // 0xxxxxxx
result += String.fromCharCode(c1);
break;
}
}
return result;
}