Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
399 lines (329 loc) · 13 KB
/
Copy pathindex.js
File metadata and controls
399 lines (329 loc) · 13 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
require('./helpers/ensureDependencies')();
require('dotenv').config({ quiet: true });
const fs = require('fs');
const path = require('path');
const tmi = require('tmi.js');
const state = require('./core/state');
const startEventSub = require("./eventsub");
const startWidgetServer = require("./widget/server");
const { createUpNext } = require('./services/upNext');
const obs = require("./services/obs");
const { sayMessage } = require('./services/messages');
const aliases = require('./services/aliases');
const history = require('./services/history');
const perks = require('./services/perks');
const commandCooldowns = require('./services/commandCooldowns');
const userSettings = require('./config/userSettings');
const { getVerifiedAccessToken } = require('./services/twitchAuth');
const openBrowser = require('./helpers/openBrowser');
const commands = new Map();
const commandFiles = fs
.readdirSync(path.join(__dirname, 'commands'))
.filter(f => f.endsWith('.js'));
const loadedCommands = commandFiles
.map(file => require(`./commands/${file}`))
.filter(command => {
if (!command.name || !command.execute) {
console.warn(`Invalid command file: ${command.name || '(unknown)'}`);
return false;
}
return true;
});
function buildCommandMap() {
commands.clear();
for (const command of loadedCommands) {
const commandNames = [command.name, ...aliases.getAliases(command.name)];
for (const name of commandNames) {
commands.set(name.toLowerCase(), command);
}
}
}
aliases.setDefaultAliases(
Object.fromEntries(loadedCommands.map(command => [command.name, command.aliases || []]))
);
aliases.onReload(buildCommandMap);
buildCommandMap();
const cooldowns = new Map();
// Set once chat is connected. See services/fxReminder.js.
let fxReminder = null;
// Built after ensureSetup(), since setup may be what writes these env values.
function createClient() {
return new tmi.Client({
options: { debug: true },
identity: {
username: process.env.TWITCH_BOT_USERNAME,
password: async () => `oauth:${await getVerifiedAccessToken()}`
},
channels: [process.env.TWITCH_BROADCASTER_USERNAME]
});
}
function dashboardUrl() {
return require('./config/liveEnv').getDashboardUrl();
}
/**
* Blocks until Twitch, Spotify and the reward are configured, hosting the
* setup dashboard while we wait. Returns the dashboard if it started one here,
* so the caller can keep it up rather than closing it. No-op once setup is
* done.
*/
async function ensureSetup() {
const { setupIsComplete, waitForSetup, setHealthIssues } = require('./setup/server');
const { repairSetupState } = require('./services/setupHealth');
// Verify the saved credentials still work with the configured Twitch app
// before trusting them. Anything unusable is cleared, which routes the user
// into the matching setup step instead of failing later.
const issues = await repairSetupState();
setHealthIssues(issues);
for (const issue of issues) {
console.warn(`Setup needs attention: ${issue.message}`);
}
if (setupIsComplete()) return null;
const { url, close } = await openDashboard(null);
if (close) {
openBrowser(url);
} else {
// Setup is already open in another terminal - just wait for it to finish.
console.log('Setup is already running elsewhere.');
}
console.log('');
console.log(` Queueify needs setup. Open: ${url}`);
console.log('');
if (close) {
await waitForSetup();
} else {
// Not our server, so poll instead of waiting on our own signal.
while (!setupIsComplete()) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
console.log('Setup complete. Starting Queueify...');
// Deliberately left running: the same page is the settings page from here on.
return close ? { url, close } : null;
}
/** Is a dashboard - another Queueify, or `npm run setup` - already serving? */
async function dashboardIsServed(url) {
const controller = new AbortController();
// Cleared in `finally`: a live timer here would outlast the probe and keep
// the process from exiting promptly on Ctrl+C.
const timer = setTimeout(() => controller.abort(), 700);
try {
const res = await fetch(`${url}/api/status`, { signal: controller.signal });
return res.ok;
} catch {
return false;
} finally {
clearTimeout(timer);
}
}
/**
* Keeps the dashboard reachable for the whole session, so fixing a scene name
* or a stale cookie never means stopping the bot. Someone else's dashboard on
* the port is fine - the URL still works, we just do not own it.
*
* The port is asked before it is taken: Windows lets a second process bind a
* port that is already listening, so EADDRINUSE alone would let two instances
* fight over which one the browser reaches.
*/
async function openDashboard(existing) {
if (existing) return existing;
const { startSetupServer } = require('./setup/server');
const url = dashboardUrl();
if (await dashboardIsServed(url)) return { url, close: null };
try {
return await startSetupServer();
} catch (err) {
if (err.code !== 'EADDRINUSE') throw err;
return { url, close: null };
}
}
/** The size the browser source needs, which follows the sharpness setting. */
async function widgetSourceSize() {
try {
const res = await fetch('http://localhost:3001/api/widget/config');
const config = await res.json();
return { width: config.width || 680, height: config.height || 192 };
} catch {
return { width: 680, height: 192 };
}
}
function printBanner(dashboard, widget) {
const line = ' ' + '-'.repeat(62);
console.log('');
console.log(line);
console.log(' Queueify is running.');
console.log('');
console.log(` Widget (OBS browser source) http://localhost:3001 ${widget.width} x ${widget.height}`);
console.log(` Settings dashboard ${dashboard.url}`);
console.log('');
console.log(' Open the dashboard any time to reconnect an account, fix your');
console.log(' OBS scene or source, or paste a new Spotify cookie. Changes');
console.log(' apply straight away - no need to stop the bot.');
console.log(line);
console.log('');
}
/**
* A port already in use almost always means Queueify is running in another
* window. That deserves a sentence, not a stack trace - and stopping here is
* right, because a second copy would fight the first over OBS and the queue.
*/
function reportBusyPort(err, what) {
if (err?.code !== 'EADDRINUSE') return false;
console.error('');
console.error(` Queueify cannot start: ${what} needs port ${err.port}, and something else has it.`);
console.error('');
console.error(' If Queueify is already running in another terminal, close that one first.');
console.error(' Otherwise, quit whatever is using the port and try again.');
console.error('');
return true;
}
async function main() {
const startedDashboard = await ensureSetup();
const { syncWithQueue } = require('./services/syncQueue');
try {
await startWidgetServer({
queue: createUpNext({ state, syncWithQueue })
});
} catch (err) {
if (reportBusyPort(err, 'the widget')) process.exit(1);
throw err;
}
const { default: startCanvasApi } = await import("./Spotify-Canvas-API/index.js");
try {
await startCanvasApi();
} catch (err) {
if (reportBusyPort(err, 'the Canvas API')) process.exit(1);
throw err;
}
const { checkVersion } = require('./version-check');
await checkVersion();
// Best effort only: OBS settings are re-read from .env on every widget
// command, so filling them in (or fixing them) later takes effect on the
// next !tr / !bc without restarting the bot.
const { getObsConfig } = require('./config/liveEnv');
const widgetLayout = require('./services/widgetLayout');
// Registered before connecting, and kept whether or not that succeeds: these
// are listeners on the OBS client itself, so opening OBS an hour from now
// still resizes and reloads the widget - keepConnected() below is what
// actually notices it opening.
widgetLayout.watchObsResizes();
widgetLayout.refreshOnConnect();
// A theme can belong to an OBS scene; this is what notices the switch.
require('./services/sceneThemes').watch();
if (getObsConfig().connectable) {
try {
await obs.connect();
// Give the widget the pixels it needs for the space it has in OBS, so
// nobody has to redo their layout after switching themes.
const layout = await widgetLayout.reconcile();
if (layout.applied && layout.changed) {
console.log(`Widget now renders at ${layout.width} x ${layout.height}, matching its size in OBS.`);
}
} catch (err) {
console.warn("Could not connect to OBS yet:", err.message);
console.warn("Queueify connects on its own as soon as OBS is open.");
}
} else {
console.log('OBS is not set up yet. The dashboard link below adds it - no restart needed afterwards.');
}
// Started after the first attempt, so a boot with OBS already open does not
// race it. Knocks only while OBS is closed.
obs.keepConnected();
// Who queued the song playing is worked out as songs change, not when
// somebody asks - see services/playbackWatcher.js.
const playbackWatcher = require('./services/playbackWatcher').start({
state,
getCurrentTrack: require('./spotify').getCurrentTrack,
syncWithQueue
});
const client = createClient();
client.on('message', (channel, tags, message, self) => handleMessage(client, channel, tags, message, self));
await client.connect();
fxReminder = require('./services/fxReminder').start(client);
const eventSub = startEventSub(client);
const dashboard = await openDashboard(startedDashboard);
printBanner(dashboard, await widgetSourceSize());
const shutdown = async () => {
console.log('Shutting down...');
eventSub.stop();
playbackWatcher.stop();
if (dashboard.close) await dashboard.close().catch(() => {});
await client.disconnect().catch(() => {});
// Request-log appends are handed over without being waited for, so the
// last song of a stream would otherwise be lost to a Ctrl+C.
await history.flush().catch(() => {});
// Give debounced state writes (core/state.js, ~100ms) a moment to flush.
// Registering a signal handler suppresses Node's default terminate-on-signal
// behavior, and the widget/canvas HTTP servers keep the event loop alive
// indefinitely, so an explicit exit is required here.
await new Promise(resolve => setTimeout(resolve, 250));
process.exit(0);
};
process.once('SIGINT', shutdown);
process.once('SIGTERM', shutdown);
}
main().catch(err => {
console.error("Failed to start bot:", err);
process.exit(1);
});
async function handleMessage(client, channel, tags, message, self) {
if (self) return;
message = sanitizeChatMessage(message);
// Every message, not only commands: a channel point redeem does not say
// whether somebody subscribes, so this is how their perk knows.
perks.noteChatter(tags);
// The !fx reminder waits for chat to be talking before it says anything.
fxReminder?.noteChat();
const broadcaster = process.env.TWITCH_BROADCASTER_USERNAME?.toLowerCase();
const username = tags.username.toLowerCase();
const isMod = tags.mod || username === broadcaster;
if (!message.startsWith('!')) return;
const args = message.slice(1).split(' ').filter(Boolean);
const command = args.shift()?.toLowerCase();
if (!command) return;
const handler = commands.get(command);
if (!handler) return;
// Before the mod check and without a reply. The blocklist is for bots that
// repeat chat - a translation bot echoing somebody's "!skip" runs it with
// the bot's own mod rights - and answering one is only more to repeat.
if (userSettings.isDeniedUser(username)) {
console.log(`Ignored !${command} from ${username} - they are on the command blocklist.`);
return;
}
if (handler.modOnly && !isMod) {
sayMessage(client, channel, 'general.permissionDenied', { username });
return;
}
// Mods are usually checking on something that looks stuck, which is when
// being made to wait is least useful. Everyone else gets whatever wait the
// command has been given, and is turned down without a word - see
// services/commandCooldowns.js for why it stays quiet.
if (!isMod && !commandCooldowns.allow(state, handler.name, username)) return;
const context = {
client,
channel,
tags,
message,
username,
isMod,
args,
state,
cooldowns
};
try {
await handler.execute(context);
} catch (err) {
const networkCode = err?.code || err?.cause?.code;
if (networkCode) {
console.error(`Command ${command} failed: could not reach Twitch (${networkCode}). Try again in a moment.`);
} else {
console.error(`Command ${command} failed:`, err);
}
sayMessage(client, channel, 'general.commandFailed', { username });
}
}
function sanitizeChatMessage(msg) {
return msg
.replace(/[\u034F\u061C\u115F\u1160\u17B4\u17B5\u180E\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/g, '')
.replace(/\s+/g, ' ')
.trim();
}