Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(status): add StatusStoreService with TTL purge and the IncomingStatus mapper
Yudhi Armyndharisd79f5629e5cd
diff --git a/src/app.module.ts b/src/app.module.tsindex 7045abbf0..e98a73207 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -32,6 +32,7 @@ import { StorageModule } from './common/storage/storage.module';import { StatsModule } from './modules/stats/stats.module';import { MetricsModule } from './modules/metrics/metrics.module';import { StatusModule } from './modules/status/status.module';+import { StatusStoreModule } from './modules/status-store/status-store.module';import { CatalogModule } from './modules/catalog/catalog.module';import { HooksModule } from './core/hooks';import { PluginsModule } from './core/plugins';@@ -285,6 +286,7 @@ if (dashboardServingEnabled && dashboardBuildPresent) {StatsModule, // Phase 3: Statistics DashboardMetricsModule, // Prometheus /api/metricsStatusModule, // Phase 3: Status/Stories API+ StatusStoreModule, // Phase 3: inbound status/story TTL store (24h purge + media persistence)CatalogModule, // Phase 3: Catalog API (WhatsApp Business)PluginsApiModule, // Phase 5: Plugins APIAgentToolsModule, // Agent-invocable tool registry (protocol-neutral)diff --git a/src/common/storage/storage.service.s3.spec.ts b/src/common/storage/storage.service.s3.spec.tsindex 3680461fc..ad6087354 100644--- a/src/common/storage/storage.service.s3.spec.ts+++ b/src/common/storage/storage.service.s3.spec.ts@@ -20,6 +20,7 @@ jest.mock('@aws-sdk/client-s3', () => {ListObjectsV2Command: jest.fn(),GetObjectCommand: jest.fn(),PutObjectCommand: jest.fn(),+ DeleteObjectCommand: jest.fn(),};});diff --git a/src/common/storage/storage.service.spec.ts b/src/common/storage/storage.service.spec.tsindex 72bdc7b90..bd940de3c 100644--- a/src/common/storage/storage.service.spec.ts+++ b/src/common/storage/storage.service.spec.ts@@ -75,6 +75,22 @@ describe('StorageService (local) path traversal protection', () => {await expect(service.getFile('../secret.txt')).rejects.toThrow();});+ it('deletes a file within the storage root', async () => {+ await service.putFile('sub/gone.txt', Buffer.from('bye'));+ await service.deleteFile('sub/gone.txt');+ expect(fs.existsSync(path.join(localPath, 'sub/gone.txt'))).toBe(false);+ });++ it('deleting an already-missing file resolves without throwing', async () => {+ await expect(service.deleteFile('never-existed.txt')).resolves.toBeUndefined();+ });++ it('rejects deleting a file outside the storage root', async () => {+ fs.writeFileSync(path.join(baseDir, 'secret.txt'), 'topsecret');+ await expect(service.deleteFile('../secret.txt')).rejects.toThrow();+ expect(fs.existsSync(path.join(baseDir, 'secret.txt'))).toBe(true);+ });+it('imports safe entries but refuses tar entries that escape the storage root', async () => {const gz = await makeTarGz([{ name: 'safe.txt', data: 'good' },diff --git a/src/common/storage/storage.service.ts b/src/common/storage/storage.service.tsindex 0147fefdf..039fce736 100644--- a/src/common/storage/storage.service.ts+++ b/src/common/storage/storage.service.ts@@ -11,6 +11,7 @@ import {ListObjectsV2Command,GetObjectCommand,PutObjectCommand,+ DeleteObjectCommand,HeadBucketCommand,CreateBucketCommand,} from '@aws-sdk/client-s3';@@ -188,6 +189,22 @@ export class StorageService {return this.putLocalFile(filePath, data);}+ /**+ * Delete a file previously written via `putFile`. Same unsafe-key guard as `getFile`/`putFile` (both+ * backends key off it, S3's has no host filesystem to check `isPathWithin` against). Missing-file is+ * treated as success on both backends (local: ENOENT is swallowed; S3 DeleteObject is idempotent by+ * design) so a caller doesn't have to special-case "already gone".+ */+ async deleteFile(filePath: string): Promise<void> {+ if (!isSafeStorageKey(filePath)) {+ throw new Error(`Refusing to delete an unsafe storage key: ${filePath}`);+ }+ if (this.storageType === 's3' && this.s3Client && this.s3Available) {+ return this.deleteS3File(filePath);+ }+ return this.deleteLocalFile(filePath);+ }+async getFileCount(): Promise<{ count: number; sizeBytes: number }> {if (this.storageType === 's3' && this.s3Client && this.s3Available) {// ListObjectsV2 already returns each object's Size, so report the real total instead of a@@ -425,6 +442,18 @@ export class StorageService {await fs.promises.writeFile(fullPath, data);}+ private async deleteLocalFile(filePath: string): Promise<void> {+ if (!isPathWithin(this.localPath, filePath)) {+ throw new Error(`Refusing to delete outside storage root: ${filePath}`);+ }+ const fullPath = path.join(this.localPath, filePath);+ try {+ await fs.promises.unlink(fullPath);+ } catch (error: unknown) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ }+// ============================================================================// S3 Storage Operations// ============================================================================@@ -493,4 +522,15 @@ export class StorageService {}),);}++ private async deleteS3File(filePath: string): Promise<void> {+ if (!this.s3Client) throw new Error('S3 client not initialized');++ await this.s3Client.send(+ new DeleteObjectCommand({+ Bucket: this.s3Bucket,+ Key: `media/${filePath}`,+ }),+ );+ }}diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 2b8d83b8d..60622b6d5 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -184,6 +184,16 @@ export default () => ({})(),},+ // Status/Stories store configuration+ status: {+ // Per-file cap on status media persisted to disk/S3 (default 10 MiB). A status whose media exceeds+ // this is stored omitted (mediaOmitted=true, omitReason='over_cap') rather than rejected outright.+ mediaMaxBytes: (() => {+ const n = parseInt(process.env.STATUS_MEDIA_MAX_BYTES ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : 10 * 1024 * 1024;+ })(),+ },+// Storage configurationstorage: {type: process.env.STORAGE_TYPE || 'local',diff --git a/src/modules/status-store/incoming-status.spec.ts b/src/modules/status-store/incoming-status.spec.tsnew file mode 100644index 000000000..e574fc506--- /dev/null+++ b/src/modules/status-store/incoming-status.spec.ts@@ -0,0 +1,55 @@+import { buildIncomingStatus } from './incoming-status';+import type { IncomingMessage } from '../../engine/interfaces/whatsapp-engine.interface';++const base: IncomingMessage = {+ id: 'false_status@broadcast_ABC',+ from: 'status@broadcast',+ to: '[email protected]',+ chatId: 'status@broadcast',+ author: '[email protected]',+ body: 'hello story',+ type: 'text',+ timestamp: 1700000000,+ fromMe: false,+ isGroup: false,+ isStatusBroadcast: true,+ kind: 'status',+};++it('maps a text status to IncomingStatus with the poster as contactJid', () => {+ const s = buildIncomingStatus(base)!;+ expect(s.contactJid).toBe('[email protected]');+ expect(s.waStatusId).toBe('false_status@broadcast_ABC');+ expect(s.type).toBe('text');+ expect(s.caption).toBe('hello story');+ expect(s.postedAt).toBe(1700000000 * 1000);+});++it('carries media and collapses the type to the status union', () => {+ const s = buildIncomingStatus({+ ...base,+ type: 'image',+ body: 'cap',+ media: { mimetype: 'image/jpeg', data: 'AAAA' },+ })!;+ expect(s.type).toBe('image');+ expect(s.caption).toBe('cap');+ expect(s.media).toEqual({ mimetype: 'image/jpeg', data: 'AAAA' });+});++it('returns null when the message is not a status', () => {+ expect(buildIncomingStatus({ ...base, isStatusBroadcast: false })).toBeNull();+});++it('falls back to `from` as the poster when the engine did not set `author`', () => {+ const s = buildIncomingStatus({ ...base, author: undefined, from: '[email protected]' })!;+ expect(s.contactJid).toBe('[email protected]');+});++it('returns null when there is no resolvable poster (author/from both the broadcast pseudo-JID)', () => {+ expect(buildIncomingStatus({ ...base, author: undefined, from: 'status@broadcast' })).toBeNull();+});++it('returns null when the message has no id', () => {+ expect(buildIncomingStatus({ ...base, id: '' })).toBeNull();+});diff --git a/src/modules/status-store/incoming-status.ts b/src/modules/status-store/incoming-status.tsnew file mode 100644index 000000000..ff1a83dd7--- /dev/null+++ b/src/modules/status-store/incoming-status.ts@@ -0,0 +1,50 @@+import type { IncomingMessage } from '../../engine/interfaces/whatsapp-engine.interface';++/** Engine-neutral inbound status/story, produced by {@link buildIncomingStatus} for `StatusStoreService.ingest`. */+export interface IncomingStatus {+ waStatusId: string;+ contactJid: string;+ contactName?: string;+ contactPushName?: string;+ type: 'text' | 'image' | 'video';+ caption?: string;+ backgroundColor?: string;+ font?: number;+ media?: { mimetype: string; data?: string; omitted?: boolean; sizeBytes?: number };+ postedAt: number;+}++/** Collapse the rich MessageType to the status union (image/video, else text). */+function statusType(t: string): 'text' | 'image' | 'video' {+ return t === 'image' || t === 'video' ? t : 'text';+}++/**+ * Build a neutral IncomingStatus from an inbound status-broadcast message, or null if `msg` is not a+ * usable status: not a status broadcast, missing an id, or the resolved poster is empty/the+ * `status@broadcast` pseudo-JID itself. For a status broadcast the adapter puts the actual poster in+ * `author` (`from` is the shared `status@broadcast` channel), falling back to `from` for engines that+ * don't set `author`.+ */+export function buildIncomingStatus(msg: IncomingMessage): IncomingStatus | null {+ if (!msg.isStatusBroadcast || !msg.id) return null;+ const contactJid = msg.author ?? msg.from;+ if (!contactJid || contactJid === 'status@broadcast') return null;+ return {+ waStatusId: msg.id,+ contactJid,+ contactName: msg.contact?.name,+ contactPushName: msg.contact?.pushName,+ type: statusType(msg.type),+ caption: msg.body || undefined,+ media: msg.media+ ? {+ mimetype: msg.media.mimetype,+ data: msg.media.data,+ omitted: msg.media.omitted,+ sizeBytes: msg.media.sizeBytes,+ }+ : undefined,+ postedAt: msg.timestamp * 1000,+ };+}diff --git a/src/modules/status-store/status-store.module.ts b/src/modules/status-store/status-store.module.tsnew file mode 100644index 000000000..b6fb4a501--- /dev/null+++ b/src/modules/status-store/status-store.module.ts@@ -0,0 +1,13 @@+import { Module } from '@nestjs/common';+import { TypeOrmModule } from '@nestjs/typeorm';+import { ConfigModule } from '@nestjs/config';+import { StatusUpdate } from './entities/status-update.entity';+import { StatusStoreService } from './status-store.service';+import { StorageModule } from '../../common/storage/storage.module';++@Module({+ imports: [TypeOrmModule.forFeature([StatusUpdate], 'data'), ConfigModule, StorageModule],+ providers: [StatusStoreService],+ exports: [StatusStoreService],+})+export class StatusStoreModule {}diff --git a/src/modules/status-store/status-store.service.spec.ts b/src/modules/status-store/status-store.service.spec.tsnew file mode 100644index 000000000..31ec68208--- /dev/null+++ b/src/modules/status-store/status-store.service.spec.ts@@ -0,0 +1,281 @@+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import { DataSource, Repository } from 'typeorm';+import { ConfigService } from '@nestjs/config';++jest.mock('archiver', () => ({ default: jest.fn() }));++import { StorageService } from '../../common/storage/storage.service';+import { StatusUpdate } from './entities/status-update.entity';+import { StatusStoreService } from './status-store.service';++/** A ConfigService stub that returns each call's default unless overridden by `overrides`. */+function fakeConfigService(overrides: Record<string, unknown> = {}): ConfigService {+ return {+ get: (key: string, defaultValue?: unknown) => (key in overrides ? overrides[key] : defaultValue),+ } as unknown as ConfigService;+}++function makeStorageService(localPath: string): StorageService {+ return new StorageService(fakeConfigService({ 'storage.type': 'local', 'storage.localPath': localPath }));+}++describe('StatusStoreService (ingest / list / getMedia)', () => {+ let baseDir: string;+ let ds: DataSource;+ let repository: Repository<StatusUpdate>;+ let storageService: StorageService;+ let service: StatusStoreService;++ beforeAll(async () => {+ baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-status-store-'));+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [StatusUpdate], synchronize: true });+ await ds.initialize();+ repository = ds.getRepository(StatusUpdate);+ storageService = makeStorageService(path.join(baseDir, 'media'));+ service = new StatusStoreService(repository, storageService, fakeConfigService());+ });++ afterAll(async () => {+ if (ds.isInitialized) await ds.destroy();+ fs.rmSync(baseDir, { recursive: true, force: true });+ });++ it('ingest writes a text row with expiresAt = postedAt + 24h', async () => {+ const row = await service.ingest('sess', {+ waStatusId: 'w1',+ contactJid: '[email protected]',+ type: 'text',+ caption: 'hi',+ postedAt: 1000,+ });+ expect(row.expiresAt).toBe(1000 + 24 * 60 * 60 * 1000);+ expect(row.mediaOmitted).toBe(false);+ expect(row.mediaPath).toBeFalsy();+ });++ it('ingest persists media to a file under the cap and records mediaPath', async () => {+ const row = await service.ingest('sess', {+ waStatusId: 'w2',+ contactJid: '[email protected]',+ type: 'image',+ media: { mimetype: 'image/jpeg', data: Buffer.from('x').toString('base64') },+ postedAt: 2000,+ });+ expect(row.mediaPath).toBeTruthy();+ expect(row.mediaMimetype).toBe('image/jpeg');+ expect(row.mediaOmitted).toBe(false);+ expect(row.mediaPath!.endsWith('.jpg')).toBe(true);+ // The file was actually written under the storage root.+ expect(fs.readFileSync(path.join(baseDir, 'media', row.mediaPath!), 'utf8')).toBe('x');+ });++ it('ingest marks media omitted when the engine already omitted it', async () => {+ const row = await service.ingest('sess', {+ waStatusId: 'w3',+ contactJid: '[email protected]',+ type: 'image',+ media: { mimetype: 'image/jpeg', omitted: true, sizeBytes: 99 },+ postedAt: 3000,+ });+ expect(row.mediaOmitted).toBe(true);+ expect(row.omitReason).toBe('engine_omitted');+ expect(row.mediaPath).toBeFalsy();+ });++ it('ingest marks media omitted when sizeBytes exceeds STATUS_MEDIA_MAX_BYTES', async () => {+ const row = await service.ingest('sess', {+ waStatusId: 'w4',+ contactJid: '[email protected]',+ type: 'image',+ media: { mimetype: 'image/jpeg', data: '...', sizeBytes: 999_999_999 },+ postedAt: 4000,+ });+ expect(row.mediaOmitted).toBe(true);+ expect(row.omitReason).toBe('over_cap');+ expect(row.mediaPath).toBeFalsy();+ });++ it('ingest is idempotent on (sessionId, waStatusId)', async () => {+ await service.ingest('sess', { waStatusId: 'dup', contactJid: '[email protected]', type: 'text', postedAt: 1 });+ const second = await service.ingest('sess', {+ waStatusId: 'dup',+ contactJid: '[email protected]',+ type: 'text',+ postedAt: 1,+ });+ const rows = await repository.find({ where: { sessionId: 'sess', waStatusId: 'dup' } });+ expect(rows).toHaveLength(1);+ expect(second.id).toBe(rows[0].id);+ });++ it('list maps rows to the Status shape newest-first, media path -> mediaUrl endpoint', async () => {+ const out = await service.list('sess');+ expect(out[0].contact.id).toBe('[email protected]');+ expect(out[0].timestamp).toBeInstanceOf(Date);+ expect(out[0].expiresAt).toBeInstanceOf(Date);+ // Sorted newest (highest postedAt) first: w4 (4000) precedes w1 (1000).+ const postedOrder = out.map(s => s.timestamp.getTime());+ expect(postedOrder).toEqual([...postedOrder].sort((a, b) => b - a));++ const withMedia = out.find(s => s.id === 'w2')!;+ expect(withMedia.mediaUrl).toBe('/api/sessions/sess/status/w2/media');+ const omitted = out.find(s => s.id === 'w3')!;+ expect(omitted.mediaUrl).toBeUndefined();+ const textOnly = out.find(s => s.id === 'w1')!;+ expect(textOnly.mediaUrl).toBeUndefined();+ });++ it('listByContact filters to only that contact', async () => {+ await service.ingest('sess', { waStatusId: 'w5', contactJid: '[email protected]', type: 'text', postedAt: 6000 });+ const out = await service.listByContact('sess', '[email protected]');+ expect(out).toHaveLength(1);+ expect(out[0].contact.id).toBe('[email protected]');+ });++ it('getMedia returns the path/mimetype for a status with kept media', async () => {+ const media = await service.getMedia('sess', 'w2');+ expect(media?.mimetype).toBe('image/jpeg');+ expect(media?.path).toContain('statuses/sess/');+ });++ it('getMedia returns null for an omitted-media status', async () => {+ expect(await service.getMedia('sess', 'w3')).toBeNull();+ });++ it('getMedia returns null for a text-only status', async () => {+ expect(await service.getMedia('sess', 'w1')).toBeNull();+ });++ it('getMedia returns null for an unknown status id', async () => {+ expect(await service.getMedia('sess', 'nope')).toBeNull();+ });++ it('ingest marks media write_failed when the storage backend throws', async () => {+ const failingStorage = {+ putFile: jest.fn().mockRejectedValue(new Error('disk full')),+ } as unknown as StorageService;+ const failingService = new StatusStoreService(repository, failingStorage, fakeConfigService());+ const row = await failingService.ingest('sess', {+ waStatusId: 'w6',+ contactJid: '[email protected]',+ type: 'image',+ media: { mimetype: 'image/jpeg', data: Buffer.from('y').toString('base64') },+ postedAt: 7000,+ });+ expect(row.mediaOmitted).toBe(true);+ expect(row.omitReason).toBe('write_failed');+ expect(row.mediaPath).toBeFalsy();+ });++ it('respects a configured status.mediaMaxBytes cap', async () => {+ const strictService = new StatusStoreService(+ repository,+ storageService,+ fakeConfigService({ 'status.mediaMaxBytes': 0 }),+ );+ const row = await strictService.ingest('sess', {+ waStatusId: 'w7',+ contactJid: '[email protected]',+ type: 'image',+ media: { mimetype: 'image/png', data: Buffer.from('z').toString('base64') },+ postedAt: 8000,+ });+ expect(row.mediaOmitted).toBe(true);+ expect(row.omitReason).toBe('over_cap');+ });+});++describe('StatusStoreService.purgeExpired', () => {+ let baseDir: string;+ let ds: DataSource;+ let repository: Repository<StatusUpdate>;+ let storageService: StorageService;+ let service: StatusStoreService;++ beforeEach(async () => {+ baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-status-purge-'));+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [StatusUpdate], synchronize: true });+ await ds.initialize();+ repository = ds.getRepository(StatusUpdate);+ storageService = makeStorageService(path.join(baseDir, 'media'));+ service = new StatusStoreService(repository, storageService, fakeConfigService());+ });++ afterEach(async () => {+ if (ds.isInitialized) await ds.destroy();+ fs.rmSync(baseDir, { recursive: true, force: true });+ });++ const ingestWithMedia = (waStatusId: string, postedAt: number): Promise<StatusUpdate> =>+ service.ingest('sess', {+ waStatusId,+ contactJid: '[email protected]',+ type: 'image',+ media: { mimetype: 'image/jpeg', data: Buffer.from(waStatusId).toString('base64') },+ postedAt,+ });++ it('deletes expired rows and their media files, keeps live ones', async () => {+ const expiredWithMedia = await ingestWithMedia('expired-media', 1000);+ await service.ingest('sess', {+ waStatusId: 'expired-text',+ contactJid: '[email protected]',+ type: 'text',+ postedAt: 2000,+ });+ const live = await ingestWithMedia('live-media', Date.now());++ const mediaFile = path.join(baseDir, 'media', expiredWithMedia.mediaPath!);+ expect(fs.existsSync(mediaFile)).toBe(true);++ const now = 2000 + 24 * 60 * 60 * 1000 + 1; // after both 1000/2000-posted rows expire, before `live`+ const removed = await service.purgeExpired(now);++ expect(removed).toBe(2);+ expect(fs.existsSync(mediaFile)).toBe(false);+ const remaining = await repository.find();+ expect(remaining.map(r => r.waStatusId)).toEqual(['live-media']);+ expect(fs.existsSync(path.join(baseDir, 'media', live.mediaPath!))).toBe(true);+ });++ it('returns 0 and touches nothing when no rows are expired', async () => {+ await ingestWithMedia('live', Date.now());+ const removed = await service.purgeExpired(0);+ expect(removed).toBe(0);+ expect(await repository.count()).toBe(1);+ });+});++describe('StatusStoreService onModuleInit/onModuleDestroy (purge scheduling)', () => {+ const mockDeps = (): { repo: Repository<StatusUpdate>; storage: StorageService; find: jest.Mock } => {+ const find = jest.fn().mockResolvedValue([]);+ const repo = { find } as unknown as Repository<StatusUpdate>;+ const storage = {} as StorageService;+ return { repo, storage, find };+ };++ it('purges once at startup and schedules a recurring sweep, cleared on destroy', () => {+ const { repo, storage } = mockDeps();+ const service = new StatusStoreService(repo, storage, fakeConfigService());++ jest.useFakeTimers();+ try {+ const purgeSpy = jest.spyOn(service, 'purgeExpired').mockResolvedValue(0);+ service.onModuleInit();+ expect(purgeSpy).toHaveBeenCalledTimes(1);++ purgeSpy.mockClear();+ jest.advanceTimersByTime(15 * 60 * 1000);+ expect(purgeSpy).toHaveBeenCalledTimes(1);++ service.onModuleDestroy();+ purgeSpy.mockClear();+ jest.advanceTimersByTime(15 * 60 * 1000);+ expect(purgeSpy).not.toHaveBeenCalled();+ } finally {+ jest.useRealTimers();+ }+ });+});diff --git a/src/modules/status-store/status-store.service.ts b/src/modules/status-store/status-store.service.tsnew file mode 100644index 000000000..34ca04018--- /dev/null+++ b/src/modules/status-store/status-store.service.ts@@ -0,0 +1,179 @@+import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { ConfigService } from '@nestjs/config';+import { LessThan, Repository } from 'typeorm';+import { randomUUID } from 'crypto';+import { StatusUpdate } from './entities/status-update.entity';+import type { IncomingStatus } from './incoming-status';+import type { Status } from '../../engine/interfaces/whatsapp-engine.interface';+import { StorageService } from '../../common/storage/storage.service';+import { createLogger } from '../../common/services/logger.service';++/** A status/story lives for 24h from posting, matching WhatsApp's own expiry. */+const STATUS_TTL_MS = 24 * 60 * 60 * 1000;+/** How often the TTL purge sweeps expired rows. */+const PURGE_INTERVAL_MS = 15 * 60 * 1000;+const DEFAULT_MEDIA_MAX_BYTES = 10 * 1024 * 1024;++/** Subtypes whose registered mimetype name differs from the conventional file extension. */+const MIME_SUBTYPE_EXT_OVERRIDES: Record<string, string> = { jpeg: 'jpg', quicktime: 'mov' };++/** File extension to store a status media blob under, derived from its mimetype; 'bin' when unrecognized. */+function extFromMimetype(mimetype: string): string {+ const subtype = mimetype.split('/')[1]?.split(';')[0]?.trim().toLowerCase();+ if (!subtype || !/^[a-z0-9]+$/.test(subtype)) return 'bin';+ return MIME_SUBTYPE_EXT_OVERRIDES[subtype] ?? subtype;+}++/**+ * Persists inbound status/story broadcasts (`StatusUpdate` rows) with a 24h TTL, storing any attached+ * media through `StorageService`. Runs its own purge sweep (once at startup, then every 15 minutes) so+ * the store never accumulates stories past their WhatsApp-side expiry.+ */+@Injectable()+export class StatusStoreService implements OnModuleInit, OnModuleDestroy {+ private readonly logger = createLogger('StatusStoreService');+ private purgeTimer?: ReturnType<typeof setInterval>;++ constructor(+ @InjectRepository(StatusUpdate, 'data')+ private readonly repository: Repository<StatusUpdate>,+ private readonly storageService: StorageService,+ private readonly configService: ConfigService,+ ) {}++ onModuleInit(): void {+ const runPurge = (): void => {+ this.purgeExpired(Date.now()).catch(err =>+ this.logger.error('Status purge failed', err instanceof Error ? err.stack : String(err)),+ );+ };+ runPurge(); // sweep once at startup+ this.purgeTimer = setInterval(runPurge, PURGE_INTERVAL_MS);+ this.purgeTimer.unref?.();+ }++ onModuleDestroy(): void {+ if (this.purgeTimer) clearInterval(this.purgeTimer);+ }++ /** Insert a status row (idempotent on `(sessionId, waStatusId)`), persisting any attached media. */+ async ingest(sessionId: string, s: IncomingStatus): Promise<StatusUpdate> {+ const existing = await this.repository.findOne({ where: { sessionId, waStatusId: s.waStatusId } });+ if (existing) return existing;++ const row = new StatusUpdate();+ row.sessionId = sessionId;+ row.contactJid = s.contactJid;+ row.contactName = s.contactName;+ row.contactPushName = s.contactPushName;+ row.waStatusId = s.waStatusId;+ row.type = s.type;+ row.caption = s.caption;+ row.backgroundColor = s.backgroundColor;+ row.font = s.font;+ row.postedAt = s.postedAt;+ row.expiresAt = s.postedAt + STATUS_TTL_MS;+ await this.attachMedia(row, sessionId, s);++ try {+ return await this.repository.save(row);+ } catch (error) {+ // The unique (sessionId, waStatusId) index is the idempotency backstop for a concurrent ingest+ // of the same status racing past the findOne check above; the loser re-reads and returns the+ // row the winner just inserted instead of surfacing a constraint violation to the caller.+ const winner = await this.repository.findOne({ where: { sessionId, waStatusId: s.waStatusId } });+ if (winner) return winner;+ throw error;+ }+ }++ /** Sets the row's media* / mediaOmitted / omitReason fields, writing the file via StorageService when kept. */+ private async attachMedia(row: StatusUpdate, sessionId: string, s: IncomingStatus): Promise<void> {+ const media = s.media;+ if (!media) {+ row.mediaOmitted = false;+ return;+ }++ const maxBytes = this.configService.get<number>('status.mediaMaxBytes', DEFAULT_MEDIA_MAX_BYTES);+ const sizeBytes = media.sizeBytes ?? (media.data ? Buffer.byteLength(media.data, 'base64') : undefined);+ const withinCap = sizeBytes !== undefined && sizeBytes <= maxBytes;++ if (!media.omitted && media.data && withinCap) {+ const key = `statuses/${sessionId}/${randomUUID()}.${extFromMimetype(media.mimetype)}`;+ try {+ await this.storageService.putFile(key, Buffer.from(media.data, 'base64'));+ row.mediaPath = key;+ row.mediaMimetype = media.mimetype;+ row.mediaOmitted = false;+ return;+ } catch (error) {+ this.logger.error(+ `Failed to persist status media for session ${sessionId}, status ${s.waStatusId}`,+ error instanceof Error ? error.stack : String(error),+ );+ row.mediaOmitted = true;+ row.omitReason = 'write_failed';+ return;+ }+ }++ row.mediaOmitted = true;+ row.omitReason = media.omitted ? 'engine_omitted' : 'over_cap';+ }++ async list(sessionId: string): Promise<Status[]> {+ const rows = await this.repository.find({ where: { sessionId }, order: { postedAt: 'DESC' } });+ return rows.map(row => this.toStatus(row));+ }++ async listByContact(sessionId: string, contactJid: string): Promise<Status[]> {+ const rows = await this.repository.find({ where: { sessionId, contactJid }, order: { postedAt: 'DESC' } });+ return rows.map(row => this.toStatus(row));+ }++ private toStatus(row: StatusUpdate): Status {+ return {+ id: row.waStatusId,+ contact: { id: row.contactJid, name: row.contactName, pushName: row.contactPushName },+ type: row.type,+ caption: row.caption,+ mediaUrl:+ row.mediaPath && !row.mediaOmitted+ ? `/api/sessions/${row.sessionId}/status/${row.waStatusId}/media`+ : undefined,+ backgroundColor: row.backgroundColor,+ font: row.font,+ timestamp: new Date(row.postedAt),+ expiresAt: new Date(row.expiresAt),+ };+ }++ async getMedia(sessionId: string, statusId: string): Promise<{ path: string; mimetype: string } | null> {+ const row = await this.repository.findOne({ where: { sessionId, waStatusId: statusId } });+ if (!row || row.mediaOmitted || !row.mediaPath || !row.mediaMimetype) return null;+ return { path: row.mediaPath, mimetype: row.mediaMimetype };+ }++ /** Deletes rows (and their media files) whose `expiresAt` is before `now`. Returns the count removed. */+ async purgeExpired(now: number): Promise<number> {+ const expired = await this.repository.find({ where: { expiresAt: LessThan(now) } });+ if (expired.length === 0) return 0;++ await Promise.all(+ expired+ .filter((row): row is StatusUpdate & { mediaPath: string } => !!row.mediaPath)+ .map(row =>+ this.storageService+ .deleteFile(row.mediaPath)+ .catch(err =>+ this.logger.warn(`Failed to delete expired status media ${row.mediaPath}`, { error: String(err) }),+ ),+ ),+ );++ const result = await this.repository.delete(expired.map(row => row.id));+ return result.affected ?? expired.length;+ }+}