-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
197 lines (184 loc) · 6.05 KB
/
app.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
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
import { LiveChat } from "youtube-chat";
import { WebSocketServer } from 'ws';
import YoutubeChat from './youtubeChatBotModule.js';
import FS from 'fs';
import tmi from 'tmi.js';
import { v4 as uuidv4 } from 'uuid';
function parseMessage(msgArr) {
let message = "";
for(let i = 0; i < msgArr.length; i++) {
for(let key in msgArr[i]) {
if(key.includes('text')) {
message += msgArr[i][key]
}
if(key.includes('emojiText')) {
message += msgArr[i][key]
}
}
}
return message;
}
const wss = new WebSocketServer({
port: 8081,
perMessageDeflate: {
// Other options settable:
clientNoContextTakeover: true, // Defaults to negotiated value.
serverNoContextTakeover: true, // Defaults to negotiated value.
serverMaxWindowBits: 10, // Defaults to negotiated value.
// Below options specified as default values.
//concurrencyLimit: 10, // Limits zlib concurrency for perf.
threshold: 1024, // Size (in bytes) below which messages
// should not be compressed if context takeover is disabled.
clientTracking: true
}
});
const ytc = new YoutubeChat("./oauth2.keys.json", "tokens");
var tmiIdentity;
var knownIds = new Object;
try{
let rawData = FS.readFileSync('./tmi.credentials.json');
tmiIdentity = JSON.parse(rawData);
if(FS.existsSync('./channels.json')){
let channelsRaw = FS.readFileSync('./channels.json')
knownIds = JSON.parse(channelsRaw);
}
}
catch(err){
console.error(err);
}
const tmiClient = new tmi.Client({
options: { debug: true },
identity: tmiIdentity,
});
tmiClient.connect();
function heartbeat() {
this.isAlive = true;
}
wss.on('connection', function connection(ws, req) {
ws.ip = req.socket.remoteAddress;
let ipCheck = ws.ip;
let connectionCount = 0;
wss.clients.forEach(function each(ws) {
if(ipCheck == ws.ip) {
if(connectionCount > 1) {
ws.send("503");
ws.close();
}
connectionCount++;
}
})
ws.liveChat;
ws.uuid = uuidv4();
ws.waiting = true;
ws.isAlive = true;
ws.livechatStart = false;
ws.tmiMessage = new Object;
ws.send("Connected");
ws.on('pong', heartbeat);
console.log(`connection received from: ${ws.ip}`)
ws.on('close', async function close() {
console.log(`Connection closed: ${ws.ip}`)
clearInterval(interval);
if(ws.livechatStart) {
ws.liveChat.stop();
tmiClient.part(ws.twitchChannel)
tmiClient.off("message", ws.tmiMessage[ws.uuid]);
}
});
ws.on('message', async function message(data) {
try{
const params = JSON.parse(data);
ws.twitchChannel = params.forward;
if(params.channelName) {
if(typeof knownIds[params.channelName] == 'undefined'){
knownIds[params.channelName] = await ytc.getChannelId(params.channelName);
FS.writeFileSync('./channels.json', JSON.stringify(knownIds, null, 2));
}
params.id = knownIds[params.channelName]
}
if(params.id.length == 24 && params.id.startsWith("UC")){
ws.liveChat = new LiveChat({channelId: params.id})
}
else{
ws.liveChat = new LiveChat({liveId: params.id})
}
ws.liveChat.on("start", async (liveId) => {
ws.liveId = liveId;
ws.livechatStart = true;
ws.youtubeChatId = await ytc.getChatId(ws.liveId);
})
try{
await ws.liveChat.start()
}
catch(e){
console.error(e)
ws.send("400");
ws.close();
return;
}
if(ws.twitchChannel){
ws.tmiMessage[ws.uuid] = (channel, userstate, message, self) => {
if(self) return;
console.log("sending twitch message to youtube")
console.log(channel, message)
if(channel == `#${ws.twitchChannel.toLowerCase()}` && !message.startsWith("[YouTube]")) {
if(userstate['message-type' == 'action']) {
message = `*${message}*`
}
message = `[Twitch] ${userstate['display-name']}: ${message}`
ytc.sendMessage(message, ws.youtubeChatId)
}
}
tmiClient.join(ws.twitchChannel)
tmiClient.on("message", ws.tmiMessage[ws.uuid])
}
setTimeout(() => {
ws.waiting = false;//wait 5 seconds before we actually send messages so that the old stuff isn't sent.
}, 5000);
ws.liveChat.on("chat", (chatItem) => {
if(ws.waiting) return;
ws.send(JSON.stringify(chatItem))
if(ws.twitchChannel){
let msg = parseMessage(chatItem.message);
if(msg.startsWith('[Twitch]')) return;
let messageBuilder = `[YouTube] ${chatItem.author.name}: ${msg}`;
tmiClient.say(ws.twitchChannel, messageBuilder);
}
})
ws.liveChat.on("error", (err) => {
ws.send(JSON.stringify(err));
})
ws.liveChat.on("end", (reason) => {
console.log(reason);
ws.send("410");
ws.liveChat.stop();
tmiClient.part(ws.twitchChannel)
tmiClient.off("message", ws.tmiMessage[ws.uuid]);
ws.livechatStart = false;
ws.close();
})
}
catch(e){
console.error(e)
ws.send(`401`)
console.error("Invalid data received from client", e)
}
});
});
const interval = setInterval(function ping() {
wss.clients.forEach(async function each(ws) {
if (ws.isAlive === false) {
ws.liveChat.stop();
tmiClient.part(ws.twitchChannel)
tmiClient.off("message", ws.tmiMessage[ws.uuid]);
ws.liveChat = null;
return ws.terminate();
}
ws.isAlive = false;
ws.ping();
});
}, 30000);
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason.stack);
// application specific logging, throwing an error, or other logic here
});