From a2487e5c2fca07cb8b919af33e0e2309644ad1d1 Mon Sep 17 00:00:00 2001 From: "borja (aider)" Date: Sun, 30 Mar 2025 14:11:25 +0200 Subject: [PATCH] feat: add initial group sync check at startup --- src/server.ts | 4 ++++ src/services/group-sync.ts | 40 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/server.ts b/src/server.ts index d55b76e..e0b5139 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,5 +1,6 @@ /// import { CommandService } from './services/command'; +import { GroupSyncService } from './services/group-sync'; import { ResponseQueue } from './services/response-queue'; import { WebhookManager } from './services/webhook-manager'; @@ -216,6 +217,9 @@ export class WebhookServer { process.exit(1); } } + + // Initialize groups - critical for operation + await GroupSyncService.checkInitialGroups(); } catch (error) { console.error('❌ Failed to setup webhook:', error instanceof Error ? error.message : error); process.exit(1); diff --git a/src/services/group-sync.ts b/src/services/group-sync.ts index 418c3e2..4f2af8e 100644 --- a/src/services/group-sync.ts +++ b/src/services/group-sync.ts @@ -2,6 +2,9 @@ import { db } from '../db'; // Environment variables will be mocked in tests const env = process.env; +// In-memory cache for active groups +const activeGroupsCache = new Map(); // groupId -> groupName + type EvolutionGroup = { id: string; subject: string; @@ -92,6 +95,43 @@ export class GroupSyncService { return data.response; } + private static cacheActiveGroups(): void { + const groups = db.prepare('SELECT id, name FROM groups WHERE active = TRUE').all(); + activeGroupsCache.clear(); + for (const group of groups) { + activeGroupsCache.set(group.id, group.name); + } + console.log(`Cached ${activeGroupsCache.size} active groups`); + } + + private static getActiveGroupsCount(): number { + const result = db.prepare('SELECT COUNT(*) as count FROM groups WHERE active = TRUE').get(); + return result?.count || 0; + } + + static async checkInitialGroups(): Promise { + const count = this.getActiveGroupsCount(); + if (count > 0) { + this.cacheActiveGroups(); + console.log(`✅ Using ${count} existing groups from database`); + return; + } + + console.log('⚠️ No groups found in database - performing initial sync'); + try { + const { added } = await this.syncGroups(); + if (added === 0) { + throw new Error('Initial group sync completed but no groups were added'); + } + this.cacheActiveGroups(); + console.log(`✅ Initial group sync completed - added ${added} groups`); + } catch (error) { + console.error('❌ Critical: Initial group sync failed - no groups available'); + console.error(error instanceof Error ? error.message : 'Unknown error'); + process.exit(1); + } + } + private static async upsertGroups(groups: EvolutionGroup[]): Promise<{ added: number; updated: number }> { let added = 0; let updated = 0;