import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import { describe, expect, it } from 'vitest' import { MessageDb } from '../src/main/db' import { fetchRange, SyncEngine, toNewMessage, ymd } from '../src/main/sync' import type { RawSms, VoipMs } from '../src/main/voipms' const DAY = 86_400_000 function fakeApi(all: RawSms[]) { const calls: Array<{ from: string; to: string }> = [] return { calls, async getSms({ from, to, limit = 10000 }: { from: string; to: string; limit?: number }) { calls.push({ from, to }) return all.filter((m) => m.date.slice(0, 10) >= from && m.date.slice(0, 10) <= to).slice(0, limit) } } } const raw = (id: number, date: string, type = '1'): RawSms => ({ id: String(id), date: `${date} 12:00:00`, type, did: '15550001111', contact: '5415550142', message: `m${id}` }) describe('toNewMessage', () => { it('maps voip.ms rows', () => { expect(toNewMessage(raw(7, '2024-02-03', '0'))).toEqual({ id: 7, did: '5550001111', contact: '5415550142', direction: 'out', body: 'm7', ts: Date.UTC(2024, 1, 3, 12) }) }) }) describe('fetchRange', () => { it('splits a window that hits the page limit so nothing is truncated', async () => { const all = Array.from({ length: 10 }, (_, i) => raw(i, ymd(Date.UTC(2024, 0, 1) + i * DAY))) const api = fakeApi(all) const got = await fetchRange(api, Date.UTC(2024, 0, 1), Date.UTC(2024, 0, 10), 4) expect(got.map((m) => Number(m.id)).sort((a, b) => a - b)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) }) }) describe('SyncEngine backfill', () => { it('walks back through history and stops at the floor', async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'voipms-sync-')) const db = new MessageDb(path.join(dir, 'm.db')) const now = Date.now() const all = [raw(1, ymd(now - DAY)), raw(2, ymd(now - 200 * DAY)), raw(3, ymd(now - 700 * DAY))] const api = fakeApi(all) const engine = new SyncEngine(db, api as unknown as VoipMs, { pollSeconds: 3600, dids: [], backfillFloor: ymd(now - 800 * DAY) }) const done = new Promise((resolve) => engine.on('status', (s) => s.backfillDone && resolve())) engine.start() await done engine.stop() expect(db.count()).toBe(3) expect(db.get('backfill_done')).toBe('1') // Everything imported during the first sync counts as already read. expect(db.listConversations()[0].unread).toBe(0) db.close() fs.rmSync(dir, { recursive: true, force: true }) }, 20_000) })