-
Notifications
You must be signed in to change notification settings - Fork 196
Expand file tree
/
Copy pathconnectionWrapper.js
More file actions
138 lines (109 loc) · 4.03 KB
/
connectionWrapper.js
File metadata and controls
138 lines (109 loc) · 4.03 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
const { WebcastPushConnection } = require('tiktok-live-connector');
const { EventEmitter } = require('events');
let globalConnectionCount = 0;
/**
* TikTok LIVE connection wrapper with advanced reconnect functionality and error handling
*/
class TikTokConnectionWrapper extends EventEmitter {
constructor(uniqueId, options, enableLog) {
super();
this.uniqueId = uniqueId;
this.enableLog = enableLog;
// Connection State
this.clientDisconnected = false;
this.reconnectEnabled = true;
this.reconnectCount = 0;
this.reconnectWaitMs = 1000;
this.maxReconnectAttempts = 5;
this.connection = new WebcastPushConnection(uniqueId, options);
this.connection.on('streamEnd', () => {
this.log(`streamEnd event received, giving up connection`);
this.reconnectEnabled = false;
})
this.connection.on('disconnected', ({ code, reason }) => {
globalConnectionCount -= 1;
this.log(`TikTok connection disconnected (code: ${code}, reason: ${reason})`);
this.scheduleReconnect();
});
this.connection.on('error', (err) => {
this.log(`Error event triggered: ${err.info}, ${err.exception}`);
console.error(err);
})
}
connect(isReconnect) {
this.connection.connect().then((state) => {
this.log(`${isReconnect ? 'Reconnected' : 'Connected'} to roomId ${state.roomId}`);
globalConnectionCount += 1;
// Reset reconnect vars
this.reconnectCount = 0;
this.reconnectWaitMs = 1000;
// Client disconnected while establishing connection => drop connection
if (this.clientDisconnected) {
this.connection.disconnect();
return;
}
// Notify client
if (!isReconnect) {
this.emit('connected', state);
}
}).catch((err) => {
this.log(`${isReconnect ? 'Reconnect' : 'Connection'} failed, ${err}`);
let errorMessage = err.message || err.toString();
// Extract detailed sub-errors if available (e.g. FetchIsLiveError)
if (Array.isArray(err.errors) && err.errors.length > 0) {
const details = err.errors
.map(e => e.message || e.toString())
.filter(Boolean)
.join(' | ');
if (details) {
errorMessage += ': ' + details;
}
}
if (isReconnect) {
// Schedule the next reconnect attempt
this.scheduleReconnect(errorMessage);
} else {
// Notify client
this.emit('disconnected', errorMessage);
}
})
}
scheduleReconnect(reason) {
if (!this.reconnectEnabled) {
return;
}
if (this.reconnectCount >= this.maxReconnectAttempts) {
this.log(`Give up connection, max reconnect attempts exceeded`);
this.emit('disconnected', `Connection lost. ${reason}`);
return;
}
this.log(`Try reconnect in ${this.reconnectWaitMs}ms`);
setTimeout(() => {
if (!this.reconnectEnabled || this.reconnectCount >= this.maxReconnectAttempts) {
return;
}
this.reconnectCount += 1;
this.reconnectWaitMs *= 2;
this.connect(true);
}, this.reconnectWaitMs)
}
disconnect() {
this.log(`Client connection disconnected`);
this.clientDisconnected = true;
this.reconnectEnabled = false;
if (this.connection.isConnected) {
this.connection.disconnect();
}
}
log(logString) {
if (this.enableLog) {
console.log(`WRAPPER @${this.uniqueId}: ${logString}`);
}
}
}
module.exports = {
TikTokConnectionWrapper,
getGlobalConnectionCount: () => {
return globalConnectionCount;
}
};