-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathtransport-websocket.js
92 lines (77 loc) · 2.27 KB
/
transport-websocket.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
"use strict";
// force polyfill websockets in Node to support Node 22+
if (typeof(window) == "undefined" || typeof(WebSocket) == "undefined") global.WebSocket = require('ws');
function Transport(ip, port, logger) {
this.host = ip;
this.port = port;
this.interval = null;
this.is_alive = null;
this.ws = new WebSocket("ws://" + ip + ":" + port + "/api");
if (typeof(window) != "undefined") this.ws.binaryType = 'arraybuffer';
this.logger = logger;
this.ws.on('pong', () => this.is_alive = true);
this.ws.onopen = () => {
this.is_alive = true;
this.interval = setInterval(() => {
if (!this.ws) {
this.close();
return;
}
if (this.is_alive === false) {
logger.log(`Roon API Connection to ${this.host}:${this.port} closed due to missed heartbeat`);
return this.ws.terminate();
}
this.is_alive = false;
this.ws.ping();
}, 10000)
this._isonopencalled = true;
this.onopen();
};
this.ws.onclose = () => {
this.is_alive = false;
clearInterval(this.interval);
this.interval = null;
this.close();
};
this.ws.onerror = (err) => {
this.onerror();
}
this.ws.onmessage = (event) => {
if (!this.moo) {
return;
}
const msg = this.moo.parse(event.data);
if (!msg) {
this.close();
return;
}
this.onmessage(msg);
};
}
Transport.prototype.send = function(buf) {
if (!this.ws) {
this.close();
return;
}
this.ws.send(buf, { binary: true, mask: true});
};
Transport.prototype.close = function() {
if (this.ws) {
clearInterval(this.interval);
this.ws.close();
this.ws = undefined;
}
if (!this._onclosecalled && this._isonopencalled) {
this._onclosecalled = true;
this.onclose();
}
if (this.moo) {
this.moo.clean_up();
this.moo = undefined;
}
};
Transport.prototype.onopen = function() { };
Transport.prototype.onclose = function() { };
Transport.prototype.onerror = function() { };
Transport.prototype.onmessage = function() { };
exports = module.exports = Transport;