-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
184 lines (161 loc) · 5.84 KB
/
index.js
File metadata and controls
184 lines (161 loc) · 5.84 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
process.on('unhandledRejection', (reason, promise) => {
console.error('🔥 UNHANDLED PROMISE REJECTION:', reason);
});
import express from 'express';
import http from 'http';
import path from 'path';
import { execSync } from 'child_process';
import { Server } from 'socket.io';
import basicAuth from 'express-basic-auth';
import dotenv from 'dotenv';
import { io as ioClient } from 'socket.io-client';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import routes from './routes.js';
import { initializeSocketHandlers, handleSubathonAddTime } from './socketHandlers.js';
import {
initializeTormentMeter,
recordContribution as recordTormentContribution,
shutdownTormentMeter
} from './tormentMeterService.js';
import { initializeEventSub } from './eventSub.js';
import { initializeBotCommands } from './botCommands.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
dotenv.config();
const app = express();
global.app = app; // Make app available globally for EventSub
const port = 3000;
const server = http.createServer(app);
const io = new Server(server);
let eventSubClient;
let streamlabsSocket;
initializeTormentMeter(io).catch(error => {
console.error('Failed to initialize Torment Meter:', error);
});
// Initialize Streamlabs Socket
if (process.env.streamlabs_socket_token) {
streamlabsSocket = ioClient(`https://sockets.streamlabs.com?token=${process.env.streamlabs_socket_token}`, {
transports: ['websocket']
});
streamlabsSocket.on('connect', () => {
console.log('Connected to Streamlabs websocket');
});
streamlabsSocket.on('event', async (eventData) => {
if (eventData.type === 'donation') {
const amount = parseFloat(eventData.message[0].amount);
if (!isNaN(amount)) {
// Add 1 minute per dollar
const minutes = Math.floor(amount);
if (minutes > 0) {
const socketHandlers = app.get('socketHandlers');
if (socketHandlers && socketHandlers.handleSubathonAddTime) {
await socketHandlers.handleSubathonAddTime(minutes * 60, `donation_$${amount}`, io);
} else {
console.error('Socket handlers not found for Streamlabs donation');
}
}
const messageText = String(eventData.message?.[0]?.message || '').toLowerCase();
if (!messageText.includes('merch')) {
try {
await recordTormentContribution({
amountCents: Math.round(amount * 100),
source: 'streamlabs_donation',
metadata: {
name: eventData.message?.[0]?.name || null,
message: eventData.message?.[0]?.message || null
}
});
} catch (error) {
console.error('Failed to record torment meter contribution from Streamlabs donation:', error);
}
}
}
}
});
streamlabsSocket.on('disconnect', () => {
console.log('Disconnected from Streamlabs websocket');
});
}
// Make io available to routes
app.set('io', io);
function resolveBuildVersion() {
const envSha =
process.env.RAILWAY_GIT_COMMIT_SHA ||
process.env.RAILWAY_DEPLOYMENT_ID ||
process.env.BUILD_VERSION;
if (envSha) return String(envSha).slice(0, 12);
try {
return execSync('git rev-parse --short HEAD', { cwd: __dirname }).toString().trim();
} catch {
return Date.now().toString(36);
}
}
app.locals.BUILD_VERSION = resolveBuildVersion();
console.log(`Build version: ${app.locals.BUILD_VERSION}`);
app.use(express.static(path.join(__dirname, "public"), { maxAge: "1d" }));
app.set("view engine", "ejs");
// Initialize Routes
app.use("/", routes);
// Basic Auth Middleware
app.use(
basicAuth({
users: { [process.env.web_user]: process.env.web_pass },
challenge: true,
})
);
// Initialize Socket Handlers
// Store socket handlers for use by other parts of the app
app.set('socketHandlers', { handleSubathonAddTime });
initializeSocketHandlers(io);
// Initialize EventSub and Bot
async function initialize() {
// Verify required EventSub environment variables
const requiredEnvVars = {
development: ['EVENTSUB_CLIENT_ID', 'EVENTSUB_CLIENT_SECRET', 'TEST_CHANNEL_ID'],
production: ['EVENTSUB_CLIENT_ID', 'EVENTSUB_CLIENT_SECRET', 'TWITCH_CHANNEL_ID']
};
const currentEnv = process.env.NODE_ENV || 'production';
const missingVars = requiredEnvVars[currentEnv].filter(varName => !process.env[varName]);
if (missingVars.length > 0) {
console.error(`Missing required environment variables for ${currentEnv} mode:`, missingVars);
console.error('EventSub initialization skipped');
} else {
try {
eventSubClient = await initializeEventSub(io);
if (eventSubClient?.needsAuth) {
console.log('Twitch authentication required. Please visit https://leantube.org/auth/ to authenticate.');
} else if (eventSubClient?.warning === 'eventsub_disabled') {
console.warn('⚠️ EventSub was disabled due to connection issues. Bot is running in degraded mode.');
} else if (eventSubClient) {
console.log('EventSub initialized successfully');
app.set('eventSubClient', eventSubClient);
} else {
console.warn('⚠️ EventSub not initialized. Some features may not work.');
}
} catch (error) {
console.error('Failed to initialize EventSub:', error);
}
}
// Ensure bot is connected
initializeBotCommands(io);
}
// Start server and initialize services
server.listen(port, () => {
console.log(`Listening on *:${port}`);
initialize().catch(error => {
console.error('Failed to initialize services:', error);
});
});
// Handle process termination
process.on('SIGINT', async () => {
console.log('Shutting down...');
if (eventSubClient) {
await eventSubClient.stop();
}
if (streamlabsSocket) {
streamlabsSocket.disconnect();
}
await shutdownTormentMeter();
process.exit(0);
});