From 580651094f42183c44d45b919cd5260c5c1d591f Mon Sep 17 00:00:00 2001 From: DenAntonov Date: Sat, 14 Jun 2025 13:36:06 +0300 Subject: [PATCH] remove websocket add polling --- server/index.ts | 18 +- .../routers/kfu-m-24-1/sber_mobile/index.js | 14 +- .../kfu-m-24-1/sber_mobile/polling-chat.js | 822 ++++++++++++++++++ .../kfu-m-24-1/sber_mobile/socket-chat.js | 457 ---------- .../kfu-m-24-1/sber_mobile/supabaseClient.js | 65 +- 5 files changed, 894 insertions(+), 482 deletions(-) create mode 100644 server/routers/kfu-m-24-1/sber_mobile/polling-chat.js delete mode 100644 server/routers/kfu-m-24-1/sber_mobile/socket-chat.js diff --git a/server/index.ts b/server/index.ts index d39f65f..7f1d913 100644 --- a/server/index.ts +++ b/server/index.ts @@ -21,6 +21,7 @@ import escRouter from './routers/esc' import connectmeRouter from './routers/connectme' import questioneerRouter from './routers/questioneer' import { setIo } from './io' +const { createChatPollingRouter } = require('./routers/kfu-m-24-1/sber_mobile/polling-chat') export const app = express() @@ -64,8 +65,6 @@ const initServer = async () => { console.log('warming up πŸ”₯') - const server = setIo(app) - const sess = { secret: "super-secret-key", resave: true, @@ -90,10 +89,18 @@ const initServer = async () => { ) app.use(root) + // Π˜Π½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΡ Polling для Ρ‡Π°Ρ‚Π° (послС настройки middleware) + const { router: chatPollingRouter, chatHandler } = createChatPollingRouter(express) + + /** * ДобавляйтС сюда свои routers. */ app.use("/kfu-m-24-1", kfuM241Router) + + // ДобавляСм Polling Ρ€ΠΎΡƒΡ‚Π΅Ρ€ для Ρ‡Π°Ρ‚Π° + app.use("/kfu-m-24-1/sber_mobile", chatPollingRouter) + app.use("/epja-2024-1", epja20241Router) app.use("/v1/todo", todoRouter) app.use("/dogsitters-finder", dogsittersFinderRouter) @@ -109,9 +116,10 @@ const initServer = async () => { app.use(errorHandler) - server.listen(process.env.PORT ?? 8044, () => + // Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ ΠΎΠ±Ρ‹Ρ‡Π½Ρ‹ΠΉ HTTP сСрвСр + const server = app.listen(process.env.PORT ?? 8044, () => { console.log(`πŸš€ Π‘Π΅Ρ€Π²Π΅Ρ€ Π·Π°ΠΏΡƒΡ‰Π΅Π½ Π½Π° http://localhost:${process.env.PORT ?? 8044}`) - ) + }) // ΠžΠ±Ρ€Π°Π±ΠΎΡ‚ΠΊΠ° сигналов Π·Π°Π²Π΅Ρ€ΡˆΠ΅Π½ΠΈΡ процСсса process.on('SIGTERM', () => { @@ -145,6 +153,8 @@ const initServer = async () => { process.exit(1) }) }) + + return server } initServer().catch(console.error) diff --git a/server/routers/kfu-m-24-1/sber_mobile/index.js b/server/routers/kfu-m-24-1/sber_mobile/index.js index 854576e..2fdc6bd 100644 --- a/server/routers/kfu-m-24-1/sber_mobile/index.js +++ b/server/routers/kfu-m-24-1/sber_mobile/index.js @@ -15,9 +15,6 @@ const buildingsRouter = require('./buildings'); const userApartmentsRouter = require('./user_apartments'); const avatarRouter = require('./media'); const supportRouter = require('./supportApi'); -const {setIo, getIo } = require('../../../io'); -// Π˜ΠΌΠΏΠΎΡ€Ρ‚ ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊΠ° Ρ‡Π°Ρ‚Π° -const { initializeChatSocket } = require('./socket-chat') module.exports = router; @@ -39,12 +36,5 @@ router.use('', userApartmentsRouter); router.use('', avatarRouter); router.use('', supportRouter); - - // Π˜Π½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΡ Socket.IO для Ρ‡Π°Ρ‚Π° - const io = getIo() - if (io) { - const chatHandler = initializeChatSocket(io) - // БохраняСм ссылку Π½Π° chat handler для доступа ΠΈΠ· эндпоинтов - io.chatHandler = chatHandler - console.log('βœ… Socket.IO для Ρ‡Π°Ρ‚Π° ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΠΎΠ²Π°Π½') - } \ No newline at end of file + + diff --git a/server/routers/kfu-m-24-1/sber_mobile/polling-chat.js b/server/routers/kfu-m-24-1/sber_mobile/polling-chat.js new file mode 100644 index 0000000..db528ca --- /dev/null +++ b/server/routers/kfu-m-24-1/sber_mobile/polling-chat.js @@ -0,0 +1,822 @@ +const { getSupabaseClient, initializationPromise } = require('./supabaseClient'); + +class ChatPollingHandler { + constructor() { + this.connectedClients = new Map(); // user_id -> { user_info, chats: Set(), lastActivity: Date } + this.chatParticipants = new Map(); // chat_id -> Set(user_id) + this.userEventQueues = new Map(); // user_id -> [{id, event, data, timestamp}] + this.eventIdCounter = 0; + this.realtimeSubscription = null; + + // Π˜Π½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΡƒΠ΅ΠΌ Supabase подписку с Π·Π°Π΄Π΅Ρ€ΠΆΠΊΠΎΠΉ ΠΈ ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ°ΠΌΠΈ + this.initializeWithRetry(); + + // ΠžΡ‡ΠΈΡΡ‚ΠΊΠ° старых событий ΠΊΠ°ΠΆΠ΄Ρ‹Π΅ 5 ΠΌΠΈΠ½ΡƒΡ‚ + setInterval(() => { + this.cleanupOldEvents(); + }, 5 * 60 * 1000); + } + + // Π˜Π½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΡ с ΠΏΠΎΠ²Ρ‚ΠΎΡ€Π½Ρ‹ΠΌΠΈ ΠΏΠΎΠΏΡ‹Ρ‚ΠΊΠ°ΠΌΠΈ + async initializeWithRetry() { + try { + // Π‘Π½Π°Ρ‡Π°Π»Π° ΠΆΠ΄Π΅ΠΌ Π·Π°Π²Π΅Ρ€ΡˆΠ΅Π½ΠΈΡ основной ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΠΈ + await initializationPromise; + + this.setupRealtimeSubscription(); + this.testRealtimeConnection(); + return; + + } catch (error) { + console.log('❌ [Supabase] Основная инициализация Π½Π΅ΡƒΠ΄Π°Ρ‡Π½Π°, ΠΏΡ€ΠΎΠ±ΡƒΠ΅ΠΌ Π°Π»ΡŒΡ‚Π΅Ρ€Π½Π°Ρ‚ΠΈΠ²Π½Ρ‹ΠΉ ΠΏΠΎΠ΄Ρ…ΠΎΠ΄'); + } + + // Если основная инициализация Π½Π΅ ΡƒΠ΄Π°Π»Π°ΡΡŒ, ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅ΠΌ ΠΏΠΎΠ²Ρ‚ΠΎΡ€Π½Ρ‹Π΅ ΠΏΠΎΠΏΡ‹Ρ‚ΠΊΠΈ + let attempts = 0; + const maxAttempts = 10; + const baseDelay = 2000; // 2 сСкунды + + while (attempts < maxAttempts) { + try { + attempts++; + + // Π–Π΄Π΅ΠΌ ΠΏΠ΅Ρ€Π΅Π΄ ΠΏΠΎΠΏΡ‹Ρ‚ΠΊΠΎΠΉ + await new Promise(resolve => setTimeout(resolve, baseDelay * attempts)); + + // ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡΠ΅ΠΌ Π³ΠΎΡ‚ΠΎΠ²Π½ΠΎΡΡ‚ΡŒ Supabase ΠΊΠ»ΠΈΠ΅Π½Ρ‚Π° + const supabase = getSupabaseClient(); + if (supabase) { + this.setupRealtimeSubscription(); + this.testRealtimeConnection(); + return; // УспСх, Π²Ρ‹Ρ…ΠΎΠ΄ΠΈΠΌ + } + } catch (error) { + console.log(`❌ [Supabase] ΠŸΠΎΠΏΡ‹Ρ‚ΠΊΠ° #${attempts} Π½Π΅ΡƒΠ΄Π°Ρ‡Π½Π°:`, error.message); + + if (attempts === maxAttempts) { + console.error('❌ [Supabase] ВсС ΠΏΠΎΠΏΡ‹Ρ‚ΠΊΠΈ ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΠΈ исчСрпаны'); + console.error('❌ [Supabase] Realtime подписка Π±ΡƒΠ΄Π΅Ρ‚ нСдоступна'); + return; + } + } + } + } + + // АутСнтификация ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ + async handleAuthentication(req, res) { + const { user_id, token } = req.body; + + if (!user_id) { + res.status(400).json({ error: 'user_id is required' }); + return; + } + + try { + // ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡΠ΅ΠΌ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ Π² Π±Π°Π·Π΅ Π΄Π°Π½Π½Ρ‹Ρ… + const supabase = getSupabaseClient(); + const { data: userProfile, error } = await supabase + .from('user_profiles') + .select('*') + .eq('id', user_id) + .single(); + + if (error) { + console.log('❌ [Polling Server] ΠŸΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒ Π½Π΅ Π½Π°ΠΉΠ΄Π΅Π½:', error); + res.status(401).json({ error: 'User not found' }); + return; + } + + // РСгистрируСм ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ + this.connectedClients.set(user_id, { + user_info: { + user_id, + profile: userProfile, + last_seen: new Date() + }, + chats: new Set(), + lastActivity: new Date() + }); + + // Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ ΠΎΡ‡Π΅Ρ€Π΅Π΄ΡŒ событий для ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ + if (!this.userEventQueues.has(user_id)) { + this.userEventQueues.set(user_id, []); + } + + // ДобавляСм событиС Π°ΡƒΡ‚Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ†ΠΈΠΈ Π² ΠΎΡ‡Π΅Ρ€Π΅Π΄ΡŒ + this.addEventToQueue(user_id, 'authenticated', { + message: 'Successfully authenticated', + user: userProfile + }); + + res.json({ + success: true, + message: 'Successfully authenticated', + user: userProfile + }); + + } catch (error) { + console.error('❌ [Polling Server] Ошибка Π°ΡƒΡ‚Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ†ΠΈΠΈ:', error); + res.status(500).json({ error: 'Authentication failed' }); + } + } + + // Π­Π½Π΄ΠΏΠΎΠΈΠ½Ρ‚ для получСния событий (polling) + async handleGetEvents(req, res) { + try { + const { user_id, last_event_id } = req.query; + + if (!user_id) { + res.status(400).json({ error: 'user_id is required' }); + return; + } + + const client = this.connectedClients.get(user_id); + if (!client) { + res.status(401).json({ error: 'Not authenticated' }); + return; + } + + // ОбновляСм врСмя послСднСй активности + client.lastActivity = new Date(); + + // ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ ΠΎΡ‡Π΅Ρ€Π΅Π΄ΡŒ событий ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ + const eventQueue = this.userEventQueues.get(user_id) || []; + + // Π€ΠΈΠ»ΡŒΡ‚Ρ€ΡƒΠ΅ΠΌ события послС last_event_id + const lastEventId = parseInt(last_event_id) || 0; + const newEvents = eventQueue.filter(event => event.id > lastEventId); + + res.json({ + success: true, + events: newEvents, + last_event_id: eventQueue.length > 0 ? Math.max(...eventQueue.map(e => e.id)) : lastEventId + }); + + } catch (error) { + console.error('❌ [Polling Server] Ошибка получСния событий:', error); + res.status(500).json({ error: 'Failed to get events' }); + } + } + + // HTTP эндпоинт для присоСдинСния ΠΊ Ρ‡Π°Ρ‚Ρƒ + async handleJoinChat(req, res) { + try { + const { user_id, chat_id } = req.body; + + if (!user_id || !chat_id) { + res.status(400).json({ error: 'user_id and chat_id are required' }); + return; + } + + const client = this.connectedClients.get(user_id); + if (!client) { + res.status(401).json({ error: 'Not authenticated' }); + return; + } + + // ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡΠ΅ΠΌ, Ρ‡Ρ‚ΠΎ Ρ‡Π°Ρ‚ сущСствуСт ΠΈ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒ ΠΈΠΌΠ΅Π΅Ρ‚ доступ ΠΊ Π½Π΅ΠΌΡƒ + const supabase = getSupabaseClient(); + const { data: chat, error } = await supabase + .from('chats') + .select(` + *, + buildings ( + management_company_id, + apartments ( + apartment_residents ( + user_id + ) + ) + ) + `) + .eq('id', chat_id) + .single(); + + if (error || !chat) { + res.status(404).json({ error: 'Chat not found' }); + return; + } + + // ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡΠ΅ΠΌ доступ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ ΠΊ Ρ‡Π°Ρ‚Ρƒ Ρ‡Π΅Ρ€Π΅Π· ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Ρ‹ Π² Π΄ΠΎΠΌΠ΅ + const hasAccess = chat.buildings.apartments.some(apartment => + apartment.apartment_residents.some(resident => + resident.user_id === user_id + ) + ); + + if (!hasAccess) { + res.status(403).json({ error: 'Access denied to this chat' }); + return; + } + + // ДобавляСм ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ Π² Ρ‡Π°Ρ‚ + client.chats.add(chat_id); + + if (!this.chatParticipants.has(chat_id)) { + this.chatParticipants.set(chat_id, new Set()); + } + this.chatParticipants.get(chat_id).add(user_id); + + // ДобавляСм событиС присоСдинСния Π² ΠΎΡ‡Π΅Ρ€Π΅Π΄ΡŒ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ + this.addEventToQueue(user_id, 'joined_chat', { + chat_id, + chat: chat, + message: 'Successfully joined chat' + }); + + // УвСдомляСм Π΄Ρ€ΡƒΠ³ΠΈΡ… участников ΠΎ ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠΈ + this.broadcastToChatExcludeUser(chat_id, user_id, 'user_joined', { + chat_id, + user: client.user_info.profile, + timestamp: new Date() + }); + + res.json({ success: true, message: 'Joined chat successfully' }); + + } catch (error) { + res.status(500).json({ error: 'Failed to join chat' }); + } + } + + // HTTP эндпоинт для покидания Ρ‡Π°Ρ‚Π° + async handleLeaveChat(req, res) { + try { + const { user_id, chat_id } = req.body; + + if (!user_id || !chat_id) { + res.status(400).json({ error: 'user_id and chat_id are required' }); + return; + } + + const client = this.connectedClients.get(user_id); + if (!client) { + res.status(401).json({ error: 'Not authenticated' }); + return; + } + + // УдаляСм ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ ΠΈΠ· Ρ‡Π°Ρ‚Π° + client.chats.delete(chat_id); + + if (this.chatParticipants.has(chat_id)) { + this.chatParticipants.get(chat_id).delete(user_id); + + // Если Ρ‡Π°Ρ‚ пуст, удаляСм Π΅Π³ΠΎ + if (this.chatParticipants.get(chat_id).size === 0) { + this.chatParticipants.delete(chat_id); + } + } + + // УвСдомляСм Π΄Ρ€ΡƒΠ³ΠΈΡ… участников ΠΎΠ± ΠΎΡ‚ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠΈ + this.broadcastToChatExcludeUser(chat_id, user_id, 'user_left', { + chat_id, + user: client.user_info.profile, + timestamp: new Date() + }); + + res.json({ success: true, message: 'Left chat successfully' }); + + } catch (error) { + res.status(500).json({ error: 'Failed to leave chat' }); + } + } + + // HTTP эндпоинт для ΠΎΡ‚ΠΏΡ€Π°Π²ΠΊΠΈ сообщСния + async handleSendMessage(req, res) { + try { + const { user_id, chat_id, text } = req.body; + + if (!user_id || !chat_id || !text) { + res.status(400).json({ error: 'user_id, chat_id and text are required' }); + return; + } + + const client = this.connectedClients.get(user_id); + if (!client) { + res.status(401).json({ error: 'Not authenticated' }); + return; + } + + if (!client.chats.has(chat_id)) { + res.status(403).json({ error: 'Not joined to this chat' }); + return; + } + + // БохраняСм сообщСниС Π² Π±Π°Π·Ρƒ Π΄Π°Π½Π½Ρ‹Ρ… + const supabase = getSupabaseClient(); + const { data: message, error } = await supabase + .from('messages') + .insert({ + chat_id, + user_id, + text + }) + .select(` + *, + user_profiles ( + id, + full_name, + avatar_url + ) + `) + .single(); + + if (error) { + res.status(500).json({ error: 'Failed to save message' }); + return; + } + + // ΠžΡ‚ΠΏΡ€Π°Π²Π»ΡΠ΅ΠΌ сообщСниС всСм участникам Ρ‡Π°Ρ‚Π° + this.broadcastToChat(chat_id, 'new_message', { + message, + timestamp: new Date() + }); + + res.json({ success: true, message: 'Message sent successfully' }); + + } catch (error) { + res.status(500).json({ error: 'Failed to send message' }); + } + } + + // HTTP эндпоинт для ΠΈΠ½Π΄ΠΈΠΊΠ°Ρ†ΠΈΠΈ пСчатания + async handleTypingStart(req, res) { + try { + const { user_id, chat_id } = req.body; + + if (!user_id || !chat_id) { + res.status(400).json({ error: 'user_id and chat_id are required' }); + return; + } + + const client = this.connectedClients.get(user_id); + if (!client) { + res.status(401).json({ error: 'Not authenticated' }); + return; + } + + if (!client.chats.has(chat_id)) { + res.status(403).json({ error: 'Not joined to this chat' }); + return; + } + + this.broadcastToChatExcludeUser(chat_id, user_id, 'user_typing_start', { + chat_id, + user: client.user_info.profile, + timestamp: new Date() + }); + + res.json({ success: true }); + + } catch (error) { + res.status(500).json({ error: 'Failed to send typing indicator' }); + } + } + + // HTTP эндпоинт для остановки ΠΈΠ½Π΄ΠΈΠΊΠ°Ρ†ΠΈΠΈ пСчатания + async handleTypingStop(req, res) { + try { + const { user_id, chat_id } = req.body; + + if (!user_id || !chat_id) { + res.status(400).json({ error: 'user_id and chat_id are required' }); + return; + } + + const client = this.connectedClients.get(user_id); + if (!client) { + res.status(401).json({ error: 'Not authenticated' }); + return; + } + + if (!client.chats.has(chat_id)) { + res.status(403).json({ error: 'Not joined to this chat' }); + return; + } + + this.broadcastToChatExcludeUser(chat_id, user_id, 'user_typing_stop', { + chat_id, + user: client.user_info.profile, + timestamp: new Date() + }); + + res.json({ success: true }); + + } catch (error) { + res.status(500).json({ error: 'Failed to send typing indicator' }); + } + } + + // ΠžΠ±Ρ€Π°Π±ΠΎΡ‚ΠΊΠ° ΠΎΡ‚ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ ΠΊΠ»ΠΈΠ΅Π½Ρ‚Π° + handleClientDisconnect(user_id) { + const client = this.connectedClients.get(user_id); + if (!client) return; + + // УдаляСм ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ ΠΈΠ· всСх Ρ‡Π°Ρ‚ΠΎΠ² + client.chats.forEach(chat_id => { + if (this.chatParticipants.has(chat_id)) { + this.chatParticipants.get(chat_id).delete(user_id); + + // УвСдомляСм Π΄Ρ€ΡƒΠ³ΠΈΡ… участников ΠΎΠ± ΠΎΡ‚ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠΈ + this.broadcastToChatExcludeUser(chat_id, user_id, 'user_left', { + chat_id, + user: client.user_info.profile, + timestamp: new Date() + }); + + // Если Ρ‡Π°Ρ‚ пуст, удаляСм Π΅Π³ΠΎ + if (this.chatParticipants.get(chat_id).size === 0) { + this.chatParticipants.delete(chat_id); + } + } + }); + + // УдаляСм ΠΊΠ»ΠΈΠ΅Π½Ρ‚Π° + this.connectedClients.delete(user_id); + } + + // Π”ΠΎΠ±Π°Π²Π»Π΅Π½ΠΈΠ΅ события Π² ΠΎΡ‡Π΅Ρ€Π΅Π΄ΡŒ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ + addEventToQueue(user_id, event, data) { + if (!this.userEventQueues.has(user_id)) { + this.userEventQueues.set(user_id, []); + } + + const eventQueue = this.userEventQueues.get(user_id); + const eventId = ++this.eventIdCounter; + + eventQueue.push({ + id: eventId, + event, + data, + timestamp: new Date() + }); + + // ΠžΠ³Ρ€Π°Π½ΠΈΡ‡ΠΈΠ²Π°Π΅ΠΌ Ρ€Π°Π·ΠΌΠ΅Ρ€ ΠΎΡ‡Π΅Ρ€Π΅Π΄ΠΈ (послСдниС 100 событий) + if (eventQueue.length > 100) { + eventQueue.splice(0, eventQueue.length - 100); + } + } + + // Рассылка события всСм участникам Ρ‡Π°Ρ‚Π° + broadcastToChat(chat_id, event, data) { + const participants = this.chatParticipants.get(chat_id); + if (!participants) return; + + participants.forEach(user_id => { + this.addEventToQueue(user_id, event, data); + }); + } + + // Рассылка события всСм участникам Ρ‡Π°Ρ‚Π° ΠΊΡ€ΠΎΠΌΠ΅ отправитСля + broadcastToChatExcludeUser(chat_id, exclude_user_id, event, data) { + const participants = this.chatParticipants.get(chat_id); + if (!participants) return; + + participants.forEach(user_id => { + if (user_id !== exclude_user_id) { + this.addEventToQueue(user_id, event, data); + } + }); + } + + // ΠŸΠΎΠ»ΡƒΡ‡Π΅Π½ΠΈΠ΅ списка ΠΎΠ½Π»Π°ΠΉΠ½ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ Π² Ρ‡Π°Ρ‚Π΅ + getOnlineUsersInChat(chat_id) { + const participants = this.chatParticipants.get(chat_id) || new Set(); + const onlineUsers = []; + const now = new Date(); + const ONLINE_THRESHOLD = 2 * 60 * 1000; // 2 ΠΌΠΈΠ½ΡƒΡ‚Ρ‹ + + participants.forEach(user_id => { + const client = this.connectedClients.get(user_id); + if (client && (now - client.lastActivity) < ONLINE_THRESHOLD) { + onlineUsers.push(client.user_info.profile); + } + }); + + return onlineUsers; + } + + // ΠžΡ‚ΠΏΡ€Π°Π²ΠΊΠ° систСмного сообщСния Π² Ρ‡Π°Ρ‚ + async sendSystemMessage(chat_id, text) { + this.broadcastToChat(chat_id, 'system_message', { + chat_id, + text, + timestamp: new Date() + }); + } + + // ΠžΡ‡ΠΈΡΡ‚ΠΊΠ° старых событий + cleanupOldEvents() { + const now = new Date(); + const MAX_EVENT_AGE = 24 * 60 * 60 * 1000; // 24 часа + const INACTIVE_USER_THRESHOLD = 60 * 60 * 1000; // 1 час + + // ΠžΡ‡ΠΈΡ‰Π°Π΅ΠΌ старыС события + this.userEventQueues.forEach((eventQueue, user_id) => { + const filteredEvents = eventQueue.filter(event => + (now - event.timestamp) < MAX_EVENT_AGE + ); + + if (filteredEvents.length !== eventQueue.length) { + this.userEventQueues.set(user_id, filteredEvents); + } + }); + + // УдаляСм Π½Π΅Π°ΠΊΡ‚ΠΈΠ²Π½Ρ‹Ρ… ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ + this.connectedClients.forEach((client, user_id) => { + if ((now - client.lastActivity) > INACTIVE_USER_THRESHOLD) { + this.handleClientDisconnect(user_id); + this.userEventQueues.delete(user_id); + } + }); + } + + // ВСстированиС Real-time подписки + async testRealtimeConnection() { + try { + const supabase = getSupabaseClient(); + if (!supabase) { + return false; + } + + // Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ тСстовый ΠΊΠ°Π½Π°Π» для ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ + const testChannel = supabase + .channel('test_connection') + .subscribe((status, error) => { + if (error) { + console.error('❌ [Supabase] ВСстовый ΠΊΠ°Π½Π°Π» - ошибка:', error); + } + + if (status === 'SUBSCRIBED') { + // ΠžΡ‚ΠΏΠΈΡΡ‹Π²Π°Π΅ΠΌΡΡ ΠΎΡ‚ тСстового ΠΊΠ°Π½Π°Π»Π° + setTimeout(() => { + testChannel.unsubscribe(); + }, 2000); + } + }); + + return true; + } catch (error) { + console.error('❌ [Supabase] Ошибка тСстирования Realtime:', error); + return false; + } + } + + // ΠŸΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° статуса подписки + checkSubscriptionStatus() { + if (this.realtimeSubscription) { + return true; + } else { + return false; + } + } + + setupRealtimeSubscription() { + // Π£Π±ΠΈΡ€Π°Π΅ΠΌ setTimeout, Π²Ρ‹Π·Ρ‹Π²Π°Π΅ΠΌ сразу + this._doSetupRealtimeSubscription(); + } + + _doSetupRealtimeSubscription() { + try { + const supabase = getSupabaseClient(); + + if (!supabase) { + console.log('❌ [Supabase] Supabase ΠΊΠ»ΠΈΠ΅Π½Ρ‚ Π½Π΅ Π½Π°ΠΉΠ΄Π΅Π½'); + throw new Error('Supabase client not available'); + } + + // ΠŸΠΎΠ΄ΠΏΠΈΡΡ‹Π²Π°Π΅ΠΌΡΡ Π½Π° измСнСния Π² Ρ‚Π°Π±Π»ΠΈΡ†Π΅ messages + const subscription = supabase + .channel('messages_changes') + .on( + 'postgres_changes', + { + event: 'INSERT', + schema: 'public', + table: 'messages' + }, + async (payload) => { + try { + const newMessage = payload.new; + if (!newMessage) { + return; + } + + if (!newMessage.chat_id) { + return; + } + + // ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ ΠΏΡ€ΠΎΡ„ΠΈΠ»ΡŒ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ + const { data: userProfile, error: profileError } = await supabase + .from('user_profiles') + .select('id, full_name, avatar_url') + .eq('id', newMessage.user_id) + .single(); + + if (profileError) { + console.error('❌ [Supabase] Ошибка получСния профиля ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ:', profileError); + } + + // ОбъСдиняСм сообщСниС с ΠΏΡ€ΠΎΡ„ΠΈΠ»Π΅ΠΌ + const messageWithProfile = { + ...newMessage, + user_profiles: userProfile || null + }; + + // ΠžΡ‚ΠΏΡ€Π°Π²Π»ΡΠ΅ΠΌ сообщСниС всСм участникам Ρ‡Π°Ρ‚Π° + this.broadcastToChat(newMessage.chat_id, 'new_message', { + message: messageWithProfile, + timestamp: new Date() + }); + + } catch (callbackError) { + console.error('❌ [Supabase] Ошибка Π² ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊΠ΅ сообщСния:', callbackError); + } + } + ) + .subscribe((status, error) => { + if (error) { + console.error('❌ [Supabase] Ошибка подписки:', error); + } + + if (status === 'CHANNEL_ERROR') { + console.error('❌ [Supabase] Ошибка ΠΊΠ°Π½Π°Π»Π°'); + } else if (status === 'TIMED_OUT') { + console.error('❌ [Supabase] Π’Π°ΠΉΠΌΠ°ΡƒΡ‚ подписки'); + } + }); + + // БохраняСм ссылку Π½Π° подписку для возмоТности отписки + this.realtimeSubscription = subscription; + + } catch (error) { + console.error('❌ [Supabase] ΠšΡ€ΠΈΡ‚ΠΈΡ‡Π΅ΡΠΊΠ°Ρ ошибка ΠΏΡ€ΠΈ настройкС подписки:', error); + throw error; // ΠŸΡ€ΠΎΠ±Ρ€Π°ΡΡ‹Π²Π°Π΅ΠΌ ΠΎΡˆΠΈΠ±ΠΊΡƒ для ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚ΠΊΠΈ Π² initializeWithRetry + } + } + + // ΠŸΠΎΠ»ΡƒΡ‡Π΅Π½ΠΈΠ΅ статистики ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠΉ + getConnectionStats() { + return { + connectedClients: this.connectedClients.size, + activeChats: this.chatParticipants.size, + totalChatParticipants: Array.from(this.chatParticipants.values()) + .reduce((total, participants) => total + participants.size, 0), + totalEventQueues: this.userEventQueues.size, + totalEvents: Array.from(this.userEventQueues.values()) + .reduce((total, queue) => total + queue.length, 0) + }; + } +} + +// Ѐункция для создания Ρ€ΠΎΡƒΡ‚Π΅Ρ€Π° с polling эндпоинтами +function createChatPollingRouter(express) { + const router = express.Router(); + const chatHandler = new ChatPollingHandler(); + + // CORS middleware для всСх запросов + router.use((req, res, next) => { + res.header('Access-Control-Allow-Origin', '*'); + res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); + res.header('Access-Control-Allow-Headers', 'Content-Type, Cache-Control, Authorization'); + res.header('Access-Control-Allow-Credentials', 'true'); + + // ΠžΠ±Ρ€Π°Π±Π°Ρ‚Ρ‹Π²Π°Π΅ΠΌ OPTIONS запросы + if (req.method === 'OPTIONS') { + res.status(200).end(); + return; + } + + next(); + }); + + // Π­Π½Π΄ΠΏΠΎΠΈΠ½Ρ‚ для Π°ΡƒΡ‚Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ†ΠΈΠΈ + router.post('/auth', (req, res) => { + chatHandler.handleAuthentication(req, res); + }); + + // Π­Π½Π΄ΠΏΠΎΠΈΠ½Ρ‚ для получСния событий (polling) + router.get('/events', (req, res) => { + chatHandler.handleGetEvents(req, res); + }); + + // HTTP эндпоинты для дСйствий + router.post('/join-chat', (req, res) => { + chatHandler.handleJoinChat(req, res); + }); + + router.post('/leave-chat', (req, res) => { + chatHandler.handleLeaveChat(req, res); + }); + + router.post('/send-message', (req, res) => { + chatHandler.handleSendMessage(req, res); + }); + + router.post('/typing-start', (req, res) => { + chatHandler.handleTypingStart(req, res); + }); + + router.post('/typing-stop', (req, res) => { + chatHandler.handleTypingStop(req, res); + }); + + // Π­Π½Π΄ΠΏΠΎΠΈΠ½Ρ‚ для получСния ΠΎΠ½Π»Π°ΠΉΠ½ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ Π² Ρ‡Π°Ρ‚Π΅ + router.get('/online-users/:chat_id', (req, res) => { + const { chat_id } = req.params; + const onlineUsers = chatHandler.getOnlineUsersInChat(chat_id); + res.json({ onlineUsers }); + }); + + // Π­Π½Π΄ΠΏΠΎΠΈΠ½Ρ‚ для получСния статистики + router.get('/stats', (req, res) => { + const stats = chatHandler.getConnectionStats(); + res.json(stats); + }); + + // Π­Π½Π΄ΠΏΠΎΠΈΠ½Ρ‚ для ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ статуса Supabase подписки + router.get('/supabase-status', (req, res) => { + const isConnected = chatHandler.checkSubscriptionStatus(); + res.json({ + supabaseSubscriptionActive: isConnected, + subscriptionExists: !!chatHandler.realtimeSubscription, + subscriptionInfo: chatHandler.realtimeSubscription ? { + channel: chatHandler.realtimeSubscription.topic, + state: chatHandler.realtimeSubscription.state + } : null + }); + }); + + // Π­Π½Π΄ΠΏΠΎΠΈΠ½Ρ‚ для ΠΏΡ€ΠΈΠ½ΡƒΠ΄ΠΈΡ‚Π΅Π»ΡŒΠ½ΠΎΠ³ΠΎ ΠΏΠ΅Ρ€Π΅ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ ΠΊ Supabase + router.post('/reconnect-supabase', (req, res) => { + try { + // ΠžΡ‚ΠΏΠΈΡΡ‹Π²Π°Π΅ΠΌΡΡ ΠΎΡ‚ Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΉ подписки + if (chatHandler.realtimeSubscription) { + chatHandler.realtimeSubscription.unsubscribe(); + chatHandler.realtimeSubscription = null; + } + + // Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ Π½ΠΎΠ²ΡƒΡŽ подписку + chatHandler.setupRealtimeSubscription(); + + res.json({ + success: true, + message: 'Reconnection initiated' + }); + } catch (error) { + console.error('❌ [Polling Server] Ошибка ΠΏΠ΅Ρ€Π΅ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ:', error); + res.status(500).json({ + success: false, + error: 'Reconnection failed', + details: error.message + }); + } + }); + + // ВСстовый эндпоинт для создания сообщСния Π² ΠΎΠ±Ρ…ΠΎΠ΄ API + router.post('/test-message', async (req, res) => { + const { chat_id, user_id, text } = req.body; + + if (!chat_id || !user_id || !text) { + res.status(400).json({ error: 'chat_id, user_id ΠΈ text ΠΎΠ±ΡΠ·Π°Ρ‚Π΅Π»ΡŒΠ½Ρ‹' }); + return; + } + + try { + // Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ тСстовоС событиС Π½Π°ΠΏΡ€ΡΠΌΡƒΡŽ + chatHandler.broadcastToChat(chat_id, 'new_message', { + message: { + id: `test_${Date.now()}`, + chat_id, + user_id, + text, + created_at: new Date().toISOString(), + user_profiles: { + id: user_id, + full_name: 'Test User', + avatar_url: null + } + }, + timestamp: new Date() + }); + + res.json({ + success: true, + message: 'Test message sent to polling clients' + }); + } catch (error) { + console.error('❌ [Polling Server] Ошибка ΠΎΡ‚ΠΏΡ€Π°Π²ΠΊΠΈ тСстового сообщСния:', error); + res.status(500).json({ + success: false, + error: 'Failed to send test message', + details: error.message + }); + } + }); + + return { router, chatHandler }; +} + +module.exports = { + ChatPollingHandler, + createChatPollingRouter +}; \ No newline at end of file diff --git a/server/routers/kfu-m-24-1/sber_mobile/socket-chat.js b/server/routers/kfu-m-24-1/sber_mobile/socket-chat.js deleted file mode 100644 index 62102c5..0000000 --- a/server/routers/kfu-m-24-1/sber_mobile/socket-chat.js +++ /dev/null @@ -1,457 +0,0 @@ -const { getSupabaseClient } = require('./supabaseClient'); - -class ChatSocketHandler { - constructor(io) { - this.io = io; - this.onlineUsers = new Map(); // Π₯Ρ€Π°Π½Π΅Π½ΠΈΠ΅ ΠΎΠ½Π»Π°ΠΉΠ½ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ: socket.id -> user info - this.chatRooms = new Map(); // Π₯Ρ€Π°Π½Π΅Π½ΠΈΠ΅ участников ΠΊΠΎΠΌΠ½Π°Ρ‚: chat_id -> Set(socket.id) - this.realtimeSubscription = null; // Бсылка Π½Π° подписку для управлСния - - this.setupSocketHandlers(); - - try { - this.setupRealtimeSubscription(); // ДобавляСм Real-time подписки - } catch (error) { - // Ignore error - } - - // ЗапускаСм тСстированиС Ρ‡Π΅Ρ€Π΅Π· 2 сСкунды послС ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΠΈ - setTimeout(() => { - this.testRealtimeConnection(); - }, 2000); - - // ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡΠ΅ΠΌ статус подписки Ρ‡Π΅Ρ€Π΅Π· 5 сСкунд - setTimeout(() => { - this.checkSubscriptionStatus(); - }, 5000); - } - - setupSocketHandlers() { - this.io.on('connection', (socket) => { - // АутСнтификация ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ - socket.on('authenticate', async (data) => { - await this.handleAuthentication(socket, data); - }); - - // ΠŸΡ€ΠΈΡΠΎΠ΅Π΄ΠΈΠ½Π΅Π½ΠΈΠ΅ ΠΊ Ρ‡Π°Ρ‚Ρƒ - socket.on('join_chat', async (data) => { - await this.handleJoinChat(socket, data); - }); - - // ПокиданиС Ρ‡Π°Ρ‚Π° - socket.on('leave_chat', (data) => { - this.handleLeaveChat(socket, data); - }); - - // ΠžΡ‚ΠΏΡ€Π°Π²ΠΊΠ° сообщСния - socket.on('send_message', async (data) => { - await this.handleSendMessage(socket, data); - }); - - // ΠŸΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒ Π½Π°Ρ‡Π°Π» ΠΏΠ΅Ρ‡Π°Ρ‚Π°Ρ‚ΡŒ - socket.on('typing_start', (data) => { - this.handleTypingStart(socket, data); - }); - - // ΠŸΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒ Π·Π°ΠΊΠΎΠ½Ρ‡ΠΈΠ» ΠΏΠ΅Ρ‡Π°Ρ‚Π°Ρ‚ΡŒ - socket.on('typing_stop', (data) => { - this.handleTypingStop(socket, data); - }); - - // ΠžΡ‚ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠ΅ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ - socket.on('disconnect', () => { - this.handleDisconnect(socket); - }); - }); - } - - async handleAuthentication(socket, data) { - try { - const { user_id, token } = data; - - if (!user_id) { - socket.emit('auth_error', { message: 'user_id is required' }); - return; - } - - // ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ ΠΈΠ½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΡŽ ΠΎ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ ΠΈΠ· Π±Π°Π·Ρ‹ Π΄Π°Π½Π½Ρ‹Ρ… - const supabase = getSupabaseClient(); - const { data: userProfile, error } = await supabase - .from('user_profiles') - .select('*') - .eq('id', user_id) - .single(); - - if (error) { - socket.emit('auth_error', { message: 'User not found' }); - return; - } - - // БохраняСм ΠΈΠ½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΡŽ ΠΎ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ - this.onlineUsers.set(socket.id, { - user_id, - socket_id: socket.id, - profile: userProfile, - last_seen: new Date() - }); - - socket.user_id = user_id; - socket.emit('authenticated', { - message: 'Successfully authenticated', - user: userProfile - }); - } catch (error) { - socket.emit('auth_error', { message: 'Authentication failed' }); - } - } - - async handleJoinChat(socket, data) { - try { - const { chat_id } = data; - - if (!socket.user_id) { - socket.emit('error', { message: 'Not authenticated' }); - return; - } - - if (!chat_id) { - socket.emit('error', { message: 'chat_id is required' }); - return; - } - // ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡΠ΅ΠΌ, Ρ‡Ρ‚ΠΎ Ρ‡Π°Ρ‚ сущСствуСт ΠΈ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡŒ ΠΈΠΌΠ΅Π΅Ρ‚ доступ ΠΊ Π½Π΅ΠΌΡƒ - const supabase = getSupabaseClient(); - const { data: chat, error } = await supabase - .from('chats') - .select(` - *, - buildings ( - management_company_id, - apartments ( - apartment_residents ( - user_id - ) - ) - ) - `) - .eq('id', chat_id) - .single(); - - if (error || !chat) { - socket.emit('error', { message: 'Chat not found' }); - return; - } - - // ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡΠ΅ΠΌ доступ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ ΠΊ Ρ‡Π°Ρ‚Ρƒ Ρ‡Π΅Ρ€Π΅Π· ΠΊΠ²Π°Ρ€Ρ‚ΠΈΡ€Ρ‹ Π² Π΄ΠΎΠΌΠ΅ - const hasAccess = chat.buildings.apartments.some(apartment => - apartment.apartment_residents.some(resident => - resident.user_id === socket.user_id - ) - ); - - if (!hasAccess) { - socket.emit('error', { message: 'Access denied to this chat' }); - return; - } - // ДобавляСм сокСт Π² ΠΊΠΎΠΌΠ½Π°Ρ‚Ρƒ - socket.join(chat_id); - - // ОбновляСм список участников ΠΊΠΎΠΌΠ½Π°Ρ‚Ρ‹ - if (!this.chatRooms.has(chat_id)) { - this.chatRooms.set(chat_id, new Set()); - } - - const participantsBefore = this.chatRooms.get(chat_id).size; - this.chatRooms.get(chat_id).add(socket.id); - const participantsAfter = this.chatRooms.get(chat_id).size; - - socket.emit('joined_chat', { - chat_id, - chat: chat, - message: 'Successfully joined chat' - }); - - // УвСдомляСм Π΄Ρ€ΡƒΠ³ΠΈΡ… участников ΠΎ ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠΈ - const userInfo = this.onlineUsers.get(socket.id); - - socket.to(chat_id).emit('user_joined', { - chat_id, - user: userInfo?.profile, - timestamp: new Date() - }); - } catch (error) { - socket.emit('error', { message: 'Failed to join chat' }); - } - } - - handleLeaveChat(socket, data) { - const { chat_id } = data; - - if (!chat_id) return; - - socket.leave(chat_id); - - // УдаляСм ΠΈΠ· списка участников - if (this.chatRooms.has(chat_id)) { - this.chatRooms.get(chat_id).delete(socket.id); - - // Если ΠΊΠΎΠΌΠ½Π°Ρ‚Π° пуста, удаляСм Π΅Ρ‘ - if (this.chatRooms.get(chat_id).size === 0) { - this.chatRooms.delete(chat_id); - } - } - - // УвСдомляСм Π΄Ρ€ΡƒΠ³ΠΈΡ… участников ΠΎΠ± ΠΎΡ‚ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠΈ - const userInfo = this.onlineUsers.get(socket.id); - socket.to(chat_id).emit('user_left', { - chat_id, - user: userInfo?.profile, - timestamp: new Date() - }); - - - } - - async handleSendMessage(socket, data) { - try { - const { chat_id, text } = data; - - if (!socket.user_id) { - socket.emit('error', { message: 'Not authenticated' }); - return; - } - - if (!chat_id || !text) { - socket.emit('error', { message: 'chat_id and text are required' }); - return; - } - - // БохраняСм сообщСниС Π² Π±Π°Π·Ρƒ Π΄Π°Π½Π½Ρ‹Ρ… - const supabase = getSupabaseClient(); - const { data: message, error } = await supabase - .from('messages') - .insert({ - chat_id, - user_id: socket.user_id, - text - }) - .select(` - *, - user_profiles ( - id, - full_name, - avatar_url - ) - `) - .single(); - - if (error) { - socket.emit('error', { message: 'Failed to save message' }); - return; - } - - // ΠžΡ‚ΠΏΡ€Π°Π²Π»ΡΠ΅ΠΌ сообщСниС всСм участникам Ρ‡Π°Ρ‚Π° - this.io.to(chat_id).emit('new_message', { - message, - timestamp: new Date() - }); - - } catch (error) { - socket.emit('error', { message: 'Failed to send message' }); - } - } - - handleTypingStart(socket, data) { - const { chat_id } = data; - - if (!socket.user_id || !chat_id) return; - - const userInfo = this.onlineUsers.get(socket.id); - socket.to(chat_id).emit('user_typing_start', { - chat_id, - user: userInfo?.profile, - timestamp: new Date() - }); - } - - handleTypingStop(socket, data) { - const { chat_id } = data; - - if (!socket.user_id || !chat_id) return; - - const userInfo = this.onlineUsers.get(socket.id); - socket.to(chat_id).emit('user_typing_stop', { - chat_id, - user: userInfo?.profile, - timestamp: new Date() - }); - } - - handleDisconnect(socket) { - - // УдаляСм ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ ΠΈΠ· всСх ΠΊΠΎΠΌΠ½Π°Ρ‚ - this.chatRooms.forEach((participants, chat_id) => { - if (participants.has(socket.id)) { - participants.delete(socket.id); - - // УвСдомляСм Π΄Ρ€ΡƒΠ³ΠΈΡ… участников ΠΎΠ± ΠΎΡ‚ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠΈ - const userInfo = this.onlineUsers.get(socket.id); - socket.to(chat_id).emit('user_left', { - chat_id, - user: userInfo?.profile, - timestamp: new Date() - }); - - // Если ΠΊΠΎΠΌΠ½Π°Ρ‚Π° пуста, удаляСм Π΅Ρ‘ - if (participants.size === 0) { - this.chatRooms.delete(chat_id); - } - } - }); - - // УдаляСм ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ ΠΈΠ· списка ΠΎΠ½Π»Π°ΠΉΠ½ - this.onlineUsers.delete(socket.id); - } - - // ΠŸΠΎΠ»ΡƒΡ‡Π΅Π½ΠΈΠ΅ списка ΠΎΠ½Π»Π°ΠΉΠ½ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ Π² Ρ‡Π°Ρ‚Π΅ - getOnlineUsersInChat(chat_id) { - const participants = this.chatRooms.get(chat_id) || new Set(); - const onlineUsers = []; - - participants.forEach(socketId => { - const userInfo = this.onlineUsers.get(socketId); - if (userInfo) { - onlineUsers.push(userInfo.profile); - } - }); - - return onlineUsers; - } - - // ΠžΡ‚ΠΏΡ€Π°Π²ΠΊΠ° систСмного сообщСния Π² Ρ‡Π°Ρ‚ - async sendSystemMessage(chat_id, text) { - this.io.to(chat_id).emit('system_message', { - chat_id, - text, - timestamp: new Date() - }); - } - - // ВСстированиС Real-time подписки - async testRealtimeConnection() { - try { - const supabase = getSupabaseClient(); - if (!supabase) { - return false; - } - - // Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ тСстовый ΠΊΠ°Π½Π°Π» для ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ - const testChannel = supabase - .channel('test_connection') - .subscribe((status, error) => { - if (status === 'SUBSCRIBED') { - // ΠžΡ‚ΠΏΠΈΡΡ‹Π²Π°Π΅ΠΌΡΡ ΠΎΡ‚ тСстового ΠΊΠ°Π½Π°Π»Π° - setTimeout(() => { - testChannel.unsubscribe(); - }, 2000); - } - }); - - return true; - } catch (error) { - return false; - } - } - - // ΠŸΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° статуса подписки - checkSubscriptionStatus() { - if (this.realtimeSubscription) { - return true; - } else { - return false; - } - } - - setupRealtimeSubscription() { - // ДобавляСм Π½Π΅Π±ΠΎΠ»ΡŒΡˆΡƒΡŽ Π·Π°Π΄Π΅Ρ€ΠΆΠΊΡƒ, Ρ‡Ρ‚ΠΎΠ±Ρ‹ ΡƒΠ±Π΅Π΄ΠΈΡ‚ΡŒΡΡ, Ρ‡Ρ‚ΠΎ Supabase ΠΊΠ»ΠΈΠ΅Π½Ρ‚ ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΠΎΠ²Π°Π½ - setTimeout(() => { - this._doSetupRealtimeSubscription(); - }, 1000); - } - - _doSetupRealtimeSubscription() { - try { - const supabase = getSupabaseClient(); - - if (!supabase) { - return; - } - - // ΠŸΠΎΠ΄ΠΏΠΈΡΡ‹Π²Π°Π΅ΠΌΡΡ Π½Π° измСнСния Π² Ρ‚Π°Π±Π»ΠΈΡ†Π΅ messages - const subscription = supabase - .channel('messages_changes') - .on( - 'postgres_changes', - { - event: 'INSERT', - schema: 'public', - table: 'messages' - }, - async (payload) => { - try { - const newMessage = payload.new; - if (!newMessage) { - return; - } - - if (!newMessage.chat_id) { - return; - } - - // ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ ΠΏΡ€ΠΎΡ„ΠΈΠ»ΡŒ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ - const { data: userProfile, error: profileError } = await supabase - .from('user_profiles') - .select('id, full_name, avatar_url') - .eq('id', newMessage.user_id) - .single(); - - // ОбъСдиняСм сообщСниС с ΠΏΡ€ΠΎΡ„ΠΈΠ»Π΅ΠΌ - const messageWithProfile = { - ...newMessage, - user_profiles: userProfile || null - }; - - // ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡΠ΅ΠΌ, Π΅ΡΡ‚ΡŒ Π»ΠΈ участники Π² Ρ‡Π°Ρ‚Π΅ - const chatRoomParticipants = this.chatRooms.get(newMessage.chat_id); - - // ΠžΡ‚ΠΏΡ€Π°Π²Π»ΡΠ΅ΠΌ сообщСниС Ρ‡Π΅Ρ€Π΅Π· Socket.IO всСм участникам Ρ‡Π°Ρ‚Π° - this.io.to(newMessage.chat_id).emit('new_message', { - message: messageWithProfile, - timestamp: new Date() - }); - } catch (callbackError) { - // Ignore error - } - } - ) - .subscribe(); - - // БохраняСм ссылку Π½Π° подписку для возмоТности отписки - this.realtimeSubscription = subscription; - - } catch (error) { - // Ignore error - } - } -} - -// Ѐункция ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΠΈ Socket.IO для Ρ‡Π°Ρ‚ΠΎΠ² -function initializeChatSocket(io) { - const chatHandler = new ChatSocketHandler(io); - - return chatHandler; -} - -module.exports = { - ChatSocketHandler, - initializeChatSocket -}; \ No newline at end of file diff --git a/server/routers/kfu-m-24-1/sber_mobile/supabaseClient.js b/server/routers/kfu-m-24-1/sber_mobile/supabaseClient.js index 938cc18..0568afa 100644 --- a/server/routers/kfu-m-24-1/sber_mobile/supabaseClient.js +++ b/server/routers/kfu-m-24-1/sber_mobile/supabaseClient.js @@ -3,12 +3,30 @@ const { createClient } = require('@supabase/supabase-js'); const { getSupabaseUrl, getSupabaseKey, getSupabaseServiceKey } = require('./get-constants'); let supabase = null; +let initializationPromise = null; async function initSupabaseClient() { - const supabaseUrl = await getSupabaseUrl(); - const supabaseAnonKey = await getSupabaseKey(); - const supabaseServiceRoleKey = await getSupabaseServiceKey(); - supabase = createClient(supabaseUrl, supabaseServiceRoleKey); + console.log('πŸ”„ [Supabase Client] НачинаСм ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΡŽ...'); + + try { + console.log('πŸ”„ [Supabase Client] ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ ΠΊΠΎΠ½Ρ„ΠΈΠ³ΡƒΡ€Π°Ρ†ΠΈΡŽ...'); + const supabaseUrl = await getSupabaseUrl(); + const supabaseAnonKey = await getSupabaseKey(); + const supabaseServiceRoleKey = await getSupabaseServiceKey(); + + + if (!supabaseUrl || !supabaseServiceRoleKey) { + throw new Error('Missing required Supabase configuration'); + } + + supabase = createClient(supabaseUrl, supabaseServiceRoleKey); + + return supabase; + + } catch (error) { + console.error('❌ [Supabase Client] Ошибка ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΠΈ:', error); + throw error; + } } function getSupabaseClient() { @@ -20,20 +38,49 @@ function getSupabaseClient() { // POST /refresh-supabase-client router.post('/refresh-supabase-client', async (req, res) => { -try { + try { await initSupabaseClient(); res.json({ success: true, message: 'Supabase client refreshed' }); -} catch (error) { + } catch (error) { + console.error('❌ [Supabase Client] Ошибка обновлСния:', error); res.status(500).json({ error: error.message }); -} + } +}); + +// GET /supabase-client-status +router.get('/supabase-client-status', (req, res) => { + console.log('πŸ” [Supabase Client] ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡΠ΅ΠΌ статус ΠΊΠ»ΠΈΠ΅Π½Ρ‚Π°...'); + + const isInitialized = !!supabase; + + res.json({ + initialized: isInitialized, + clientExists: !!supabase, + timestamp: new Date().toISOString() + }); }); // Π˜Π½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΡ ΠΊΠ»ΠΈΠ΅Π½Ρ‚Π° ΠΏΡ€ΠΈ стартС -(async () => { +initializationPromise = (async () => { + try { await initSupabaseClient(); + } catch (error) { + console.error('❌ [Supabase Client] Ошибка ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΠΈ ΠΏΡ€ΠΈ стартС:', error); + // ΠŸΠ»Π°Π½ΠΈΡ€ΡƒΠ΅ΠΌ ΠΏΠΎΠ²Ρ‚ΠΎΡ€Π½ΡƒΡŽ ΠΏΠΎΠΏΡ‹Ρ‚ΠΊΡƒ Ρ‡Π΅Ρ€Π΅Π· 5 сСкунд + setTimeout(async () => { + try { + await initSupabaseClient(); + } catch (retryError) { + console.error('❌ [Supabase Client] ΠŸΠΎΠ²Ρ‚ΠΎΡ€Π½Π°Ρ инициализация Π½Π΅ΡƒΠ΄Π°Ρ‡Π½Π°:', retryError); + } + }, 5000); + } })(); module.exports = { getSupabaseClient, - supabaseRouter: router + initSupabaseClient, + supabaseRouter: router, + // ЭкспортируСм промис ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΠΈ для возмоТности оТидания + initializationPromise }; \ No newline at end of file