File size: 8,213 Bytes
d9a03db
 
e0e1da7
d9a03db
 
 
 
 
 
 
e0e1da7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a03db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0e1da7
d9a03db
e0e1da7
d9a03db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0e1da7
d9a03db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import WebSocket from 'ws';
import axios from 'axios';
import { getSetting, setSetting, logModAction } from './db.js';

let ws = null;
let broadcasterUserId = null;
let keepAliveTimer = null;
let lastKeepAlive = null;
let reconnecting = false;

/**
 * Validate current access token and refresh it if expired/invalid
 */
export async function getOrRefreshAccessToken() {
  let token = await getSetting('twitch_streamer_access_token');
  const refreshToken = await getSetting('twitch_streamer_refresh_token');

  if (!token) {
    return null;
  }

  // Validate the current token via Twitch API
  try {
    await axios.get('https://id.twitch.tv/oauth2/validate', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    // Token is valid!
    return token;
  } catch (err) {
    const status = err.response?.status;
    console.log(`[EventSub] Access token validation failed (Status: ${status}). Attempting to refresh...`);

    if (!refreshToken) {
      console.error('[EventSub] Refresh token is missing in database. Cannot refresh access token.');
      return null;
    }

    try {
      const response = await axios.post('https://id.twitch.tv/oauth2/token', null, {
        params: {
          client_id: process.env.TWITCH_CLIENT_ID,
          client_secret: process.env.TWITCH_CLIENT_SECRET,
          grant_type: 'refresh_token',
          refresh_token: refreshToken
        }
      });

      const { access_token, refresh_token: newRefreshToken } = response.data;
      await setSetting('twitch_streamer_access_token', access_token);
      if (newRefreshToken) {
        await setSetting('twitch_streamer_refresh_token', newRefreshToken);
      }
      console.log('[EventSub] Access token refreshed successfully.');
      return access_token;
    } catch (refreshErr) {
      console.error('[EventSub] Token refresh request failed:', refreshErr.response?.data || refreshErr.message);
      return null;
    }
  }
}

/**
 * Initialize Twitch EventSub WebSocket connection
 */
export async function initializeEventSub(streamerId = null) {
  // Try to load broadcaster ID from database if not passed
  if (!streamerId) {
    broadcasterUserId = await getSetting('twitch_broadcaster_id');
  } else {
    broadcasterUserId = streamerId;
  }

  if (!broadcasterUserId) {
    console.log('[EventSub] Broadcaster ID is not configured yet. Waiting for Streamer login.');
    return;
  }

  const token = await getOrRefreshAccessToken();
  if (!token) {
    console.log('[EventSub] Streamer access token is missing or invalid. Waiting for Streamer login.');
    return;
  }

  if (ws) {
    console.log('[EventSub] Connection already exists, closing it first...');
    try {
      ws.close();
    } catch (e) {}
  }

  connect('wss://eventsub.wss.twitch.tv/ws');
}

/**
 * Connect to EventSub WebSocket
 */
function connect(url) {
  console.log(`[EventSub] Connecting to ${url}...`);
  ws = new WebSocket(url);
  reconnecting = false;

  ws.on('open', () => {
    console.log('[EventSub] WebSocket connection opened.');
    lastKeepAlive = Date.now();
    startKeepAliveCheck();
  });

  ws.on('message', async (data) => {
    try {
      const message = JSON.parse(data.toString());
      await handleMessage(message);
    } catch (err) {
      console.error('[EventSub] Error parsing message:', err);
    }
  });

  ws.on('close', (code, reason) => {
    console.log(`[EventSub] WebSocket connection closed: Code ${code}, Reason: ${reason}`);
    cleanup();
    if (!reconnecting) {
      // Reconnect after 5 seconds if not a controlled migration
      console.log('[EventSub] Reconnecting in 5 seconds...');
      setTimeout(() => initializeEventSub(), 5000);
    }
  });

  ws.on('error', (err) => {
    console.error('[EventSub] WebSocket error:', err);
  });
}

/**
 * Handle incoming EventSub WebSocket messages
 */
async function handleMessage(message) {
  const { metadata, payload } = message;
  const messageType = metadata.message_type;

  lastKeepAlive = Date.now();

  switch (messageType) {
    case 'session_welcome': {
      const sessionId = payload.session.id;
      console.log(`[EventSub] Welcome received. Session ID: ${sessionId}`);
      await subscribeToEvents(sessionId);
      break;
    }
    case 'session_keepalive':
      // Just updating lastKeepAlive is enough
      break;
    case 'session_reconnect': {
      const reconnectUrl = payload.session.reconnect_url;
      console.log(`[EventSub] Reconnect requested. Migrating connection to: ${reconnectUrl}`);
      reconnecting = true;
      connect(reconnectUrl);
      break;
    }
    case 'notification': {
      await handleNotification(payload);
      break;
    }
    case 'revocation':
      console.warn('[EventSub] Subscription revoked:', payload.subscription.type);
      break;
    default:
      console.log('[EventSub] Unknown message type:', messageType);
  }
}

/**
 * Handle incoming event notifications
 */
async function handleNotification(payload) {
  const { subscription, event } = payload;
  const type = subscription.type;

  console.log(`[EventSub] Event received: ${type}`);

  switch (type) {
    case 'channel.ban': {
      // Event triggers on ban or timeout
      const isTimeout = event.ends_at !== null;
      await logModAction({
        actionType: isTimeout ? 'timeout' : 'ban',
        moderator: event.moderator_user_name,
        targetUser: event.user_name,
        duration: isTimeout ? Math.round((new Date(event.ends_at) - new Date(event.banned_at)) / 1000) : null,
        reason: event.reason,
        timestamp: event.banned_at
      });
      break;
    }
    case 'channel.unban': {
      await logModAction({
        actionType: 'unban',
        moderator: event.moderator_user_name,
        targetUser: event.user_name,
        timestamp: new Date().toISOString()
      });
      break;
    }
    case 'channel.chat.message_delete': {
      await logModAction({
        actionType: 'delete',
        moderator: event.moderator_user_name,
        targetUser: event.target_user_name,
        messageText: event.message_body,
        timestamp: new Date().toISOString()
      });
      break;
    }
    default:
      console.log('[EventSub] Unhandled event type:', type);
  }
}

/**
 * Register EventSub subscriptions via Twitch Helix API
 */
async function subscribeToEvents(sessionId) {
  const clientId = process.env.TWITCH_CLIENT_ID;
  const token = await getOrRefreshAccessToken();

  if (!clientId || !token) {
    console.error('[EventSub] Cannot subscribe: Client ID or token is missing!');
    return;
  }

  const subscriptions = [
    { type: 'channel.ban', version: '1' },
    { type: 'channel.unban', version: '1' },
    { type: 'channel.chat.message_delete', version: '1' }
  ];

  const headers = {
    'Client-ID': clientId,
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  };

  for (const sub of subscriptions) {
    try {
      const body = {
        type: sub.type,
        version: sub.version,
        condition: {
          broadcaster_user_id: broadcasterUserId
        },
        transport: {
          method: 'websocket',
          session_id: sessionId
        }
      };

      const response = await axios.post('https://api.twitch.tv/helix/eventsub/subscriptions', body, { headers });
      console.log(`[EventSub] Subscribed to ${sub.type}. Status: ${response.status}`);
    } catch (err) {
      console.error(`[EventSub] Subscription failed for ${sub.type}:`, err.response?.data || err.message);
    }
  }
}

/**
 * Keep WebSocket connection healthy
 */
function startKeepAliveCheck() {
  cleanupKeepAlive();
  keepAliveTimer = setInterval(() => {
    // Twitch sends keepalives every 10 seconds. If no message for 20 seconds, reconnect.
    if (Date.now() - lastKeepAlive > 20000) {
      console.warn('[EventSub] Keepalive timeout. Reconnecting WebSocket...');
      cleanupKeepAlive();
      if (ws) {
        try { ws.terminate(); } catch (e) {}
      }
      initializeEventSub();
    }
  }, 10000);
}

function cleanupKeepAlive() {
  if (keepAliveTimer) {
    clearInterval(keepAliveTimer);
    keepAliveTimer = null;
  }
}

function cleanup() {
  cleanupKeepAlive();
  ws = null;
}