v0.2.0: bubble for Android 0.2.0 — chat search, swipe for unread, faster chat opening
Desktop: - Search lists chats whose own name matches first, so a named group isn't pushed out of the top 8 by chats that merely include a member. Android (Rabbit R1) app, 0.2.0: - Pull the chat list past its top for a search box (name, person, number, then group members; archived chats too; Back clears it). - Swipe right to left marks a chat unread / read over a magenta band; left to right still archives (SwipeActions replaces SwipeArchive). - Google Voice chats don't offer voice notes in the paperclip bubble. - Chats open with their newest 60 messages, then the full history; marking read (and the Google Voice network call) waits until they're on screen. Cached pictures show at once, and one slow download no longer blocks the other images. Fixed a contacts reload race. - Sandbox data gains filler chats, a named group and a 4,000-message chat. Also: the Android app, Google Voice support, media, export, emoji and the other work since the first commit, and a CLAUDE.md carrying the privacy rule.
This commit is contained in:
+226
@@ -81,6 +81,174 @@ describe('MessageDb', () => {
|
||||
expect(db.search('fail')).toEqual([])
|
||||
})
|
||||
|
||||
it('stores MMS media and previews it in the conversation list', () => {
|
||||
const url = 'https://voip.ms/media/x/media.jpeg'
|
||||
db.upsertMessages([{ ...msg(1, 'a', '', 1000), kind: 'mms', media: [{ url }] }])
|
||||
expect(db.getMessage(1)).toMatchObject({ kind: 'mms', media: [{ url }] })
|
||||
expect(db.getMessage(1)).not.toHaveProperty('media_json')
|
||||
expect(db.listConversations()[0]).toMatchObject({ lastKind: 'mms', lastBody: '', lastMedia: { url } })
|
||||
db.setMediaFile(1, 0, { file: 'abc.jpg', mime: 'image/jpeg' })
|
||||
expect(db.getMessage(1)?.media).toEqual([{ url, file: 'abc.jpg', mime: 'image/jpeg' }])
|
||||
db.upsertMessages([msg(2, 'a', 'plain', 2000)])
|
||||
expect(db.getMessage(2)).not.toHaveProperty('media')
|
||||
expect(db.listConversations()[0]).not.toHaveProperty('lastMedia')
|
||||
})
|
||||
|
||||
it('keeps local attachment files when a sent MMS was already synced', () => {
|
||||
const t = db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body: '', ts: 1, kind: 'mms', media: [{ file: 'local.jpg', mime: 'image/jpeg' }] })
|
||||
db.upsertMessages([{ ...msg(50, 'a', '', 2, 'out'), kind: 'mms', media: [{ url: 'https://x/m.jpeg' }] }])
|
||||
db.confirmPending(t, 50)
|
||||
expect(db.getMessage(t)).toBeUndefined()
|
||||
expect(db.getMessage(50)?.media).toEqual([{ url: 'https://x/m.jpeg', file: 'local.jpg', mime: 'image/jpeg' }])
|
||||
})
|
||||
|
||||
it('migrates v1 databases by restarting the history import', () => {
|
||||
db.set('backfill_done', '1')
|
||||
db.set('backfill_cursor', '2010-01-01')
|
||||
db.set('unread_floor', '123')
|
||||
// Recreate read_state as v1 had it (before the archive columns).
|
||||
db.db.exec(`DROP TABLE read_state;
|
||||
CREATE TABLE read_state (did TEXT NOT NULL, contact TEXT NOT NULL, last_read_ts INTEGER NOT NULL, PRIMARY KEY (did, contact))`)
|
||||
db.db.pragma('user_version = 1')
|
||||
db.close()
|
||||
db = new MessageDb(path.join(dir, 'messages.db'))
|
||||
expect(db.get('backfill_done')).toBeUndefined()
|
||||
expect(db.get('backfill_cursor')).toBeUndefined()
|
||||
expect(db.get('unread_floor')).toBe('123')
|
||||
db.upsertMessages([msg(1, 'a', 'hi', 1000)])
|
||||
db.setArchived('5550001111', 'a', true)
|
||||
expect(db.listConversations()[0].archived).toBe(true)
|
||||
})
|
||||
|
||||
it('archives conversations until a newer message arrives', () => {
|
||||
db.upsertMessages([msg(1, 'a', 'hi', 1000), msg(2, 'b', 'yo', 2000)])
|
||||
db.setArchived('5550001111', 'a', true, 5000)
|
||||
expect(db.listConversations().find((c) => c.contact === 'a')).toMatchObject({ archived: true })
|
||||
expect(db.listConversations().find((c) => c.contact === 'b')).toMatchObject({ archived: false })
|
||||
// Older history (e.g. from the backfill) doesn't unarchive.
|
||||
db.upsertMessages([msg(3, 'a', 'old', 4000)])
|
||||
expect(db.listConversations().find((c) => c.contact === 'a')?.archived).toBe(true)
|
||||
// A new message (incoming, or one we send) does.
|
||||
db.upsertMessages([msg(4, 'a', 'new', 6000)])
|
||||
expect(db.listConversations().find((c) => c.contact === 'a')?.archived).toBe(false)
|
||||
db.setArchived('5550001111', 'a', true, 7000)
|
||||
db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body: 'sent', ts: 8000 })
|
||||
expect(db.listConversations().find((c) => c.contact === 'a')?.archived).toBe(false)
|
||||
db.setArchived('5550001111', 'b', true)
|
||||
db.setArchived('5550001111', 'b', false)
|
||||
expect(db.listConversations().find((c) => c.contact === 'b')?.archived).toBe(false)
|
||||
})
|
||||
|
||||
it('marks conversations unread until opened', () => {
|
||||
db.upsertMessages([msg(1, 'a', 'hi', 1000)])
|
||||
db.markRead('5550001111', 'a')
|
||||
expect(db.listConversations()[0]).toMatchObject({ unread: 0, markedUnread: false })
|
||||
db.markUnread('5550001111', 'a')
|
||||
expect(db.listConversations()[0]).toMatchObject({ unread: 0, markedUnread: true })
|
||||
db.markRead('5550001111', 'a')
|
||||
expect(db.listConversations()[0].markedUnread).toBe(false)
|
||||
})
|
||||
|
||||
it('migrates to v4: shifts voip.ms times out of the DST hour, keeps local send times', () => {
|
||||
const summer = Date.UTC(2026, 8, 18, 7, 35, 47) // as voip.ms reported it
|
||||
const winter = Date.UTC(2026, 0, 20, 2, 44, 49)
|
||||
const local = Date.UTC(2026, 8, 18, 6, 35, 34) + 465 // stamped on send
|
||||
db.upsertMessages([
|
||||
{ ...msg(1, 'a', 'summer', summer), kind: 'mms' },
|
||||
msg(2, 'a', 'winter', winter),
|
||||
msg(3, 'a', 'sent here', local, 'out'),
|
||||
{ ...msg(4, 'a', '', summer), kind: 'mms', media: [{ url: 'u' }] }
|
||||
])
|
||||
db.db.pragma('user_version = 3')
|
||||
db.close()
|
||||
db = new MessageDb(path.join(dir, 'messages.db'))
|
||||
expect(db.getMessage(1)).toMatchObject({ ts: summer - 3_600_000, kind: 'sms' })
|
||||
expect(db.getMessage(2)?.ts).toBe(winter)
|
||||
expect(db.getMessage(3)?.ts).toBe(local)
|
||||
expect(db.getMessage(4)).toMatchObject({ ts: summer - 3_600_000, kind: 'mms' })
|
||||
})
|
||||
|
||||
it('migrates to v5: labels texts too long for one SMS as MMS', () => {
|
||||
db.upsertMessages([msg(1, 'a', 'x'.repeat(161), 1000), msg(2, 'a', 'x'.repeat(160), 2000), msg(3, 'a', '😀'.repeat(160), 3000)])
|
||||
db.db.pragma('user_version = 4')
|
||||
db.close()
|
||||
db = new MessageDb(path.join(dir, 'messages.db'))
|
||||
expect(db.getMessage(1)?.kind).toBe('mms')
|
||||
expect(db.getMessage(2)?.kind).toBe('sms')
|
||||
expect(db.getMessage(3)?.kind).toBe('sms')
|
||||
})
|
||||
|
||||
it('keeps a sent text-only MMS labelled MMS when the poll got there first', () => {
|
||||
const t = db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body: 'short mms', ts: 1, kind: 'mms' })
|
||||
db.upsertMessages([msg(60, 'a', 'short mms', 2, 'out')])
|
||||
db.confirmPending(t, 60)
|
||||
expect(db.getMessage(t)).toBeUndefined()
|
||||
expect(db.getMessage(60)?.kind).toBe('mms')
|
||||
})
|
||||
|
||||
it('records why a send failed', () => {
|
||||
const t = db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body: 'x', ts: 1 })
|
||||
expect(db.getMessage(t)?.error).toBeUndefined()
|
||||
db.markFailed(t, "voip.ms didn't respond in time.")
|
||||
expect(db.getMessage(t)).toMatchObject({ status: 'failed', error: "voip.ms didn't respond in time." })
|
||||
})
|
||||
|
||||
it('migrates to v6: adds the send error column', () => {
|
||||
db.db.exec('ALTER TABLE messages DROP COLUMN error')
|
||||
db.db.pragma('user_version = 5')
|
||||
db.close()
|
||||
db = new MessageDb(path.join(dir, 'messages.db'))
|
||||
const t = db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body: 'x', ts: 1 })
|
||||
db.markFailed(t, 'nope')
|
||||
expect(db.getMessage(t)?.error).toBe('nope')
|
||||
})
|
||||
|
||||
describe('reconcileSent', () => {
|
||||
const MIN = 60_000
|
||||
const pending = (body: string, ts: number): number => db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body, ts })
|
||||
const poll = (...msgs: NewMessage[]): number[] => db.reconcileSent(db.upsertMessages(msgs))
|
||||
|
||||
it('replaces a failed copy that actually went out', () => {
|
||||
const t = pending('breakfast?', 10 * MIN)
|
||||
db.markFailed(t, 'timeout')
|
||||
expect(poll(msg(500, 'a', 'breakfast?', 11 * MIN, 'out'))).toEqual([t])
|
||||
expect(db.getMessage(t)).toBeUndefined()
|
||||
expect(db.getMessage(500)?.status).toBe('delivered')
|
||||
expect(db.getConversationMessages('5550001111', 'a')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('replaces a pending copy, and the late send reply is then a no-op', () => {
|
||||
const t = pending('hi', 10 * MIN)
|
||||
expect(poll(msg(501, 'a', 'hi', 10 * MIN, 'out'))).toEqual([t])
|
||||
db.confirmPending(t, 501)
|
||||
expect(db.getConversationMessages('5550001111', 'a').map((m) => m.id)).toEqual([501])
|
||||
})
|
||||
|
||||
it('ignores other texts, other chats, incoming messages, and far-off times', () => {
|
||||
const t = pending('hi', 100 * MIN)
|
||||
db.markFailed(t)
|
||||
expect(
|
||||
poll(
|
||||
msg(1, 'a', 'hello', 100 * MIN, 'out'),
|
||||
msg(2, 'b', 'hi', 100 * MIN, 'out'),
|
||||
msg(3, 'a', 'hi', 100 * MIN, 'in'),
|
||||
msg(4, 'a', 'hi', 80 * MIN, 'out'),
|
||||
msg(5, 'a', 'hi', 120 * MIN, 'out')
|
||||
)
|
||||
).toEqual([])
|
||||
expect(db.getMessage(t)?.status).toBe('failed')
|
||||
})
|
||||
|
||||
it('matches identical texts one to one, oldest first', () => {
|
||||
const t1 = pending('ok', 10 * MIN)
|
||||
const t2 = pending('ok', 10 * MIN + 1)
|
||||
expect(poll(msg(600, 'a', 'ok', 10 * MIN, 'out'))).toEqual([t1])
|
||||
expect(db.getMessage(t2)?.status).toBe('pending')
|
||||
expect(poll(msg(601, 'a', 'ok', 10 * MIN + 2000, 'out'))).toEqual([t2])
|
||||
expect(db.getConversationMessages('5550001111', 'a').map((m) => m.id)).toEqual([600, 601])
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the FTS index in sync when ids change', () => {
|
||||
const t = db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body: 'unique words', ts: 1 })
|
||||
db.confirmPending(t, 555)
|
||||
@@ -106,3 +274,61 @@ describe('toFtsQuery', () => {
|
||||
expect(toFtsQuery(' ')).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('conversation names', () => {
|
||||
it('names a conversation locally and clears it', () => {
|
||||
db.upsertMessages([msg(1, '5550002222,5550003333', 'hi', 10)])
|
||||
db.setName('5550001111', '5550002222,5550003333', ' Hike crew ')
|
||||
expect(db.listConversations()[0].name).toBe('Hike crew')
|
||||
expect(db.getName('5550001111', '5550002222,5550003333')).toBe('Hike crew')
|
||||
db.setName('5550001111', '5550002222,5550003333', '')
|
||||
expect(db.listConversations()[0].name).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('name merging', () => {
|
||||
it('keeps the newest rename from either side', () => {
|
||||
db.setName('5550001111', 'a,b', 'Desk name', 100)
|
||||
db.setName('5550001111', 'c,d', 'Old', 100)
|
||||
const n = db.namesImport([
|
||||
{ did: '5550001111', contact: 'a,b', name: 'Older rabbit name', ts: 50 },
|
||||
{ did: '5550001111', contact: 'c,d', name: 'Rabbit name', ts: 200 },
|
||||
{ did: '5550001111', contact: 'e,f', name: null, ts: 300 }
|
||||
])
|
||||
expect(n).toBe(2)
|
||||
expect(db.getName('5550001111', 'a,b')).toBe('Desk name')
|
||||
expect(db.getName('5550001111', 'c,d')).toBe('Rabbit name')
|
||||
expect(db.namesExport()).toHaveLength(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('read state merging', () => {
|
||||
it('takes the later read point and the newer unread/archived change', () => {
|
||||
db.upsertMessages([msg(1, 'a', 'hi', 10), msg(2, 'b', 'yo', 20), msg(3, 'c', 'sup', 30)])
|
||||
db.markRead('5550001111', 'a') // read up to 10, here
|
||||
db.setArchived('5550001111', 'b', true, 1000)
|
||||
const n = db.readStateImport([
|
||||
{ did: '5550001111', contact: 'a', lastRead: 5, markedUnread: true, unreadTs: 1, archivedAt: null, archivedTs: null },
|
||||
{ did: '5550001111', contact: 'b', lastRead: 20, markedUnread: false, unreadTs: null, archivedAt: null, archivedTs: Date.now() + 1000 },
|
||||
{ did: '5550001111', contact: 'c', lastRead: 30, markedUnread: false, unreadTs: Date.now(), archivedAt: null, archivedTs: null }
|
||||
])
|
||||
expect(n).toBe(2)
|
||||
const conv = (c: string) => db.listConversations().find((x) => x.contact === c)!
|
||||
expect(conv('a').markedUnread).toBe(false) // our mark-read is newer than their mark-unread
|
||||
expect(conv('b').archived).toBe(false) // their unarchive is newer
|
||||
expect(conv('c').unread).toBe(0) // read on the other device
|
||||
expect(db.readStateExport()).toHaveLength(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('drafts', () => {
|
||||
it('keeps unsent text per contact until cleared, across reopening', () => {
|
||||
db.setDraft('5551230001', 'see you at ')
|
||||
db.setDraft('5551230002', 'ok')
|
||||
db.setDraft('5551230002', ' ')
|
||||
db.set('backfill_cursor', 'x') // other kv state isn't a draft
|
||||
db.close()
|
||||
db = new MessageDb(path.join(dir, 'messages.db'))
|
||||
expect(db.getDrafts()).toEqual({ '5551230001': 'see you at ' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { emojiQuery, exactEmoji, searchEmoji } from '../src/renderer/src/emoji'
|
||||
|
||||
const at = (s: string) => emojiQuery(s, s.length)
|
||||
|
||||
describe('emojiQuery', () => {
|
||||
it('finds a shortname being typed at the start, after a space or bracket', () => {
|
||||
expect(at(':jo')).toEqual({ start: 0, query: 'jo' })
|
||||
expect(at('ha :thumb')).toEqual({ start: 3, query: 'thumb' })
|
||||
expect(at('(:+1')).toEqual({ start: 1, query: '+1' })
|
||||
})
|
||||
it('ignores times, URLs and one-letter queries', () => {
|
||||
expect(at('meet at 10:30')).toBeNull()
|
||||
expect(at('http://example')).toBeNull()
|
||||
expect(at(':a')).toBeNull()
|
||||
expect(at('ok :')).toBeNull()
|
||||
})
|
||||
it('only looks at the text before the caret', () => {
|
||||
expect(emojiQuery(':joy and more', 13)).toBeNull()
|
||||
expect(emojiQuery(':joy and more', 3)).toEqual({ start: 0, query: 'jo' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('searchEmoji', () => {
|
||||
it('ranks an exact name, then prefixes, then word starts, then substrings', () => {
|
||||
expect(searchEmoji('jo')[0]).toEqual({ char: '😂', name: 'joy' })
|
||||
expect(searchEmoji('heart')[0].name).toBe('heart')
|
||||
const names = searchEmoji('cat', 50).map((m) => m.name)
|
||||
const firstWordStart = names.findIndex((n) => !n.startsWith('cat') && n.includes('_cat'))
|
||||
const firstSubstring = names.findIndex((n) => !n.startsWith('cat') && !n.includes('_cat'))
|
||||
expect(firstWordStart).toBeGreaterThan(0)
|
||||
if (firstSubstring >= 0) expect(firstSubstring).toBeGreaterThan(firstWordStart)
|
||||
})
|
||||
it('matches any of an emoji’s names, once per emoji, within the limit', () => {
|
||||
expect(searchEmoji('thumbsup').map((m) => m.char)).toContain('👍')
|
||||
const smiles = searchEmoji('smile', 5)
|
||||
expect(smiles).toHaveLength(5)
|
||||
expect(new Set(smiles.map((m) => m.char)).size).toBe(5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('exactEmoji', () => {
|
||||
it('resolves full shortnames', () => {
|
||||
expect(exactEmoji('joy')).toBe('😂')
|
||||
expect(exactEmoji('+1')).toBe('👍')
|
||||
expect(exactEmoji('not_an_emoji')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { ChatExport, Message } from '@shared/types'
|
||||
import { exportHtml, exportText, inRange, rangeLabel } from '../src/main/export'
|
||||
|
||||
let nextId = 1
|
||||
const at = (day: string, hhmm: string): number => new Date(`${day}T${hhmm}`).getTime()
|
||||
const msg = (ts: number, body: string, opts: Partial<Message> = {}): Message => ({
|
||||
id: nextId++,
|
||||
did: '5550000000',
|
||||
contact: '5550001111',
|
||||
direction: 'in',
|
||||
body,
|
||||
ts,
|
||||
kind: 'sms',
|
||||
status: 'delivered',
|
||||
...opts
|
||||
})
|
||||
const opts = (o: Partial<ChatExport> = {}): ChatExport => ({ format: 'txt', attachments: false, title: 'Aaron', names: {}, ...o })
|
||||
|
||||
describe('inRange', () => {
|
||||
const msgs = [
|
||||
msg(at('2026-10-01', '23:59'), 'a'),
|
||||
msg(at('2026-10-02', '00:00'), 'b'),
|
||||
msg(at('2026-10-03', '12:00'), 'c', { direction: 'out', status: 'failed' }),
|
||||
msg(at('2026-10-04', '23:59'), 'd')
|
||||
]
|
||||
it('keeps everything but failed sends for all time', () => {
|
||||
expect(inRange(msgs, {}).map((m) => m.body)).toEqual(['a', 'b', 'd'])
|
||||
})
|
||||
it('includes both end days, in local time', () => {
|
||||
expect(inRange(msgs, { from: '2026-10-02', to: '2026-10-04' }).map((m) => m.body)).toEqual(['b', 'd'])
|
||||
expect(inRange(msgs, { from: '2026-10-01', to: '2026-10-01' }).map((m) => m.body)).toEqual(['a'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('exportText', () => {
|
||||
it('heads each day and lines up continuation lines', () => {
|
||||
const text = exportText(
|
||||
'5550001111',
|
||||
[
|
||||
msg(at('2026-10-02', '09:05'), 'hi\nthere'),
|
||||
msg(at('2026-10-02', '09:06'), '', { direction: 'out', media: [{ file: 'x.jpg', mime: 'image/jpeg' }] })
|
||||
],
|
||||
opts()
|
||||
)
|
||||
const lines = text.split('\n')
|
||||
expect(lines[0]).toBe('Chat with Aaron ((555) 000-1111)')
|
||||
expect(text).toContain('Friday, October 2, 2026')
|
||||
const first = lines.findIndex((l) => l.endsWith('Aaron: hi'))
|
||||
expect(lines[first + 1]).toBe(' '.repeat(lines[first].indexOf('hi')) + 'there')
|
||||
expect(lines[first + 2]).toMatch(/Me: \[Photo\]$/)
|
||||
})
|
||||
it('names group senders', () => {
|
||||
const text = exportText(
|
||||
'5550001111,5550002222',
|
||||
[msg(at('2026-10-02', '09:05'), 'yo', { contact: '5550001111,5550002222', sender: '5550002222' })],
|
||||
opts({ title: 'Hike crew', names: { '5550002222': 'Bea' } })
|
||||
)
|
||||
expect(text).toContain('Chat with Hike crew\n')
|
||||
expect(text).toContain('Bea: yo')
|
||||
})
|
||||
})
|
||||
|
||||
describe('exportHtml', () => {
|
||||
const m = msg(at('2026-10-02', '09:05'), '<b>&', { media: [{ file: 'x.jpg', mime: 'image/jpeg' }, { file: 'y.m4a', mime: 'audio/mp4' }] })
|
||||
it('escapes text and shows photos it has, labels for the rest', () => {
|
||||
const html = exportHtml('5550001111', [m], opts({ format: 'pdf' }), (_m, i) => (i === 0 ? 'file:///media/x.jpg' : undefined))
|
||||
expect(html).toContain('<b>&')
|
||||
expect(html).toContain('<img src="file:///media/x.jpg">')
|
||||
expect(html).toContain('[Audio]')
|
||||
})
|
||||
})
|
||||
|
||||
describe('rangeLabel', () => {
|
||||
it('describes the dates', () => {
|
||||
expect(rangeLabel({})).toBe('All messages')
|
||||
expect(rangeLabel({ from: '2026-10-02', to: '2026-10-02' })).toBe('Oct 2, 2026')
|
||||
expect(rangeLabel({ from: '2026-10-02', to: '2026-10-09' })).toBe('Oct 2, 2026 – Oct 9, 2026')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,317 @@
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { MessageDb } from '../src/main/db'
|
||||
import { sendWithRetry } from '../src/main/send'
|
||||
import { classifyGvError, decodeBody, GVoice, GVoiceError, gvErrorMessage, readBody, sapisidHash, toE164, type Transport } from '../src/main/gvoice/client'
|
||||
import { decode, encode, fromPblite, toPblite, type Schema } from '../src/main/gvoice/proto'
|
||||
import * as S from '../src/main/gvoice/schema'
|
||||
import { gvMessageId, GvSyncEngine, isGvMessageId, threadContact, toNewMessage } from '../src/main/gvoice/sync'
|
||||
|
||||
const SELF = '5415550100'
|
||||
|
||||
const sms = (id: string, ts: number, type: number, text: string, extra: Partial<S.GvMessage> = {}): S.GvMessage => ({
|
||||
id,
|
||||
timestamp: ts,
|
||||
type,
|
||||
text,
|
||||
transactionId: 0,
|
||||
...extra
|
||||
})
|
||||
|
||||
const thread = (id: string, phoneNumbers: string[], messages: S.GvMessage[], paginationToken = ''): S.GvThread => ({
|
||||
id,
|
||||
read: true,
|
||||
messages,
|
||||
paginationToken,
|
||||
contacts: [],
|
||||
isText: true,
|
||||
phoneNumbers
|
||||
})
|
||||
|
||||
// A protobuf HTTP response, the way Google sends it (base64 in a length-prefixed text chunk).
|
||||
function protoResponse(schema: Schema, msg: Record<string, unknown>): Response {
|
||||
const b64 = Buffer.from(encode(schema, msg)).toString('base64')
|
||||
return new Response(`${b64.length}\n${b64}`, {
|
||||
headers: { 'content-type': 'text/plain; charset=utf-8', 'x-goog-safety-content-type': 'application/x-protobuf' }
|
||||
})
|
||||
}
|
||||
|
||||
describe('protobuf codec', () => {
|
||||
it('round-trips nested and repeated fields through binary', () => {
|
||||
const t = thread('t.+15415550199', ['+15415550199'], [
|
||||
sms('a', 1_700_000_000_123, S.MessageType.SMS_IN, 'hi 👋', {
|
||||
mms: {
|
||||
text: 'pic',
|
||||
subject: '',
|
||||
senderPhoneNumber: '+15415550199',
|
||||
participants: [],
|
||||
attachments: [{ id: 'm1', mimeType: 'image/jpeg', status: 1, metadata: [{ size: 1, width: 640, height: 480 }] }]
|
||||
}
|
||||
})
|
||||
])
|
||||
const back = decode(S.Thread, encode(S.Thread, t as unknown as Record<string, unknown>)) as unknown as S.GvThread
|
||||
expect(back.id).toBe('t.+15415550199')
|
||||
expect(back.phoneNumbers).toEqual(['+15415550199'])
|
||||
expect(back.messages[0].timestamp).toBe(1_700_000_000_123)
|
||||
expect(back.messages[0].text).toBe('hi 👋')
|
||||
expect(back.messages[0].mms!.attachments[0]).toMatchObject({ id: 'm1', metadata: [{ width: 640, height: 480 }] })
|
||||
// Missing fields come back as defaults.
|
||||
expect(back.paginationToken).toBe('')
|
||||
expect(back.contacts).toEqual([])
|
||||
})
|
||||
|
||||
it('skips unknown fields and reads packed repeated numbers', () => {
|
||||
// field 99 (unknown varint), then field 1 = "x"; then a packed field 3 [1,2] against a repeated int schema
|
||||
const buf = new Uint8Array([0x98, 0x06, 0x05, 0x0a, 0x01, 0x78, 0x1a, 0x02, 0x01, 0x02])
|
||||
expect(decode({ s: { n: 1, t: 'string' }, nums: { n: 3, t: 'int', rep: true } }, buf)).toEqual({ s: 'x', nums: [1, 2] })
|
||||
})
|
||||
|
||||
it('writes pblite the way the web client does', () => {
|
||||
const out = toPblite(S.ReqSendSMS, {
|
||||
text: 'yo',
|
||||
threadId: 't.+15415550199',
|
||||
recipients: [],
|
||||
transactionId: { id: 42 },
|
||||
media: { type: 2, data: new Uint8Array([1, 2, 3]) },
|
||||
trackingData: { data: '!' }
|
||||
})
|
||||
expect(out).toEqual([null, null, null, null, 'yo', 't.+15415550199', null, null, [42], [2, 'AQID'], ['!']])
|
||||
})
|
||||
|
||||
it('reads pblite with string int64s and a trailing sparse-field object', () => {
|
||||
const r = fromPblite(S.RespSendSMS, [null, 'thread', null, { '4': '1700000000123', '3': 'item' }])
|
||||
expect(r).toEqual({ threadId: 'thread', threadItemId: 'item', timestampMs: 1_700_000_000_123 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('Google Voice client', () => {
|
||||
it('computes SAPISIDHASH', () => {
|
||||
expect(sapisidHash('abc123', 1_700_000_000_999)).toBe('SAPISIDHASH 1700000000_0af60f2c8319974dffd04c264464cd61b24a1ffd')
|
||||
})
|
||||
|
||||
it('formats numbers as E.164', () => {
|
||||
expect(toE164('5415550199')).toBe('+15415550199')
|
||||
expect(toE164('447700900123')).toBe('+447700900123')
|
||||
})
|
||||
|
||||
it('unwraps base64 protobuf in a text chunk', async () => {
|
||||
const res = protoResponse(S.RespSendSMS, { threadId: 't.x', threadItemId: 'i', timestampMs: 5 })
|
||||
expect(decodeBody(S.RespSendSMS, await readBody(res))).toEqual({ threadId: 't.x', threadItemId: 'i', timestampMs: 5 })
|
||||
})
|
||||
|
||||
function fakeTransport(respond: (url: URL, init: RequestInit) => Response, cookie: string | undefined = 'sapi') {
|
||||
const calls: Array<{ url: URL; init: RequestInit }> = []
|
||||
const t: Transport = {
|
||||
fetch: async (url, init) => {
|
||||
const u = new URL(url)
|
||||
calls.push({ url: u, init })
|
||||
return respond(u, init)
|
||||
},
|
||||
cookie: async (name) => (name === 'SAPISID' ? cookie : undefined)
|
||||
}
|
||||
return { t, calls }
|
||||
}
|
||||
|
||||
it('reads the GV number from the account', async () => {
|
||||
const { t, calls } = fakeTransport(() =>
|
||||
protoResponse(S.RespGetAccount, { account: { primaryDestinationId: '+15415550000', phones: [{ accountPhone: { phoneNumber: { e164: '+15415550100' } } }] } })
|
||||
)
|
||||
expect(await new GVoice(t).getAccount()).toBe('+15415550100')
|
||||
const { url, init } = calls[0]
|
||||
expect(url.pathname).toBe('/voice/v1/voiceclient/account/get')
|
||||
expect(url.searchParams.get('alt')).toBe('proto')
|
||||
expect(url.searchParams.get('key')).toBeTruthy()
|
||||
const h = init.headers as Record<string, string>
|
||||
expect(h['Authorization']).toMatch(/^SAPISIDHASH \d+_[0-9a-f]{40}$/)
|
||||
expect(h['Content-Type']).toBe('application/json+protobuf')
|
||||
expect(JSON.parse(init.body as string)).toEqual([null, 1])
|
||||
})
|
||||
|
||||
it('sends recipients only when starting a new thread', async () => {
|
||||
const { t, calls } = fakeTransport(() => protoResponse(S.RespSendSMS, { threadId: 't.+15415550199', threadItemId: 'i1', timestampMs: 1 }))
|
||||
const gv = new GVoice(t)
|
||||
await gv.sendSms({ threadId: 't.+15415550199', recipients: ['+15415550199'], text: 'a', transactionId: 7 })
|
||||
await gv.sendSms({ threadId: '', recipients: ['+15415550199', '+15415550198'], text: 'b', transactionId: 8 })
|
||||
const [first, second] = calls.map((c) => JSON.parse(c.init.body as string) as unknown[])
|
||||
expect(first[6]).toBeNull()
|
||||
expect(first[5]).toBe('t.+15415550199')
|
||||
expect(second[6]).toEqual(['+15415550199', '+15415550198'])
|
||||
expect(second[10]).toEqual(['!']) // unsigned
|
||||
})
|
||||
|
||||
it("refuses attachments GV can't carry", async () => {
|
||||
const { t } = fakeTransport(() => new Response(''))
|
||||
await expect(new GVoice(t).sendSms({ threadId: 'x', recipients: [], text: '', transactionId: 1, media: { mime: 'video/mp4', data: new Uint8Array() } })).rejects.toThrow(
|
||||
/only photos/
|
||||
)
|
||||
})
|
||||
|
||||
it('reports a dead sign-in as signed out', async () => {
|
||||
const { t } = fakeTransport(() => new Response('nope', { status: 401 }))
|
||||
const err = await new GVoice(t).listThreads().catch((e: GVoiceError) => e)
|
||||
expect(err).toBeInstanceOf(GVoiceError)
|
||||
expect((err as GVoiceError).signedOut).toBe(true)
|
||||
const noCookie = fakeTransport(() => new Response(''), '')
|
||||
expect(((await new GVoice(noCookie.t).listThreads().catch((e) => e)) as GVoiceError).signedOut).toBe(true)
|
||||
})
|
||||
|
||||
it('classifies send failures for retrying', () => {
|
||||
expect(classifyGvError(new GVoiceError('x', undefined, 'ERR_INTERNET_DISCONNECTED'))).toBe('safe')
|
||||
expect(classifyGvError(new GVoiceError('x', undefined, 'ERR_CONNECTION_RESET'))).toBe('unknown')
|
||||
expect(classifyGvError(new GVoiceError('x', 429))).toBe('safe')
|
||||
expect(classifyGvError(new GVoiceError('x', 503))).toBe('unknown')
|
||||
expect(classifyGvError(new GVoiceError('x', 401))).toBe('fatal')
|
||||
expect(gvErrorMessage(new GVoiceError('x', undefined, 'ERR_NAME_NOT_RESOLVED'))).toMatch(/internet connection/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Google Voice messages', () => {
|
||||
it('keeps message ids stable and out of voip.ms range', () => {
|
||||
expect(gvMessageId('abc')).toBe(gvMessageId('abc'))
|
||||
expect(gvMessageId('abc')).not.toBe(gvMessageId('abd'))
|
||||
expect(isGvMessageId(gvMessageId('abc'))).toBe(true)
|
||||
expect(Number.isSafeInteger(gvMessageId('zzz'))).toBe(true)
|
||||
expect(isGvMessageId(987654321)).toBe(false)
|
||||
})
|
||||
|
||||
it('maps threads to conversations', () => {
|
||||
expect(threadContact({ phoneNumbers: ['+15415550199'] }, SELF)).toBe('5415550199')
|
||||
expect(threadContact({ phoneNumbers: ['+15415550199', '+15415550101', '+15415550100'] }, SELF)).toBe('5415550101,5415550199')
|
||||
})
|
||||
|
||||
it('converts texts, photos and group senders; skips calls', () => {
|
||||
const inMsg = toNewMessage(sms('a', 10, S.MessageType.SMS_IN, 'hey'), SELF, '5415550199', false)!
|
||||
expect(inMsg).toMatchObject({ did: SELF, contact: '5415550199', direction: 'in', body: 'hey', ts: 10 })
|
||||
expect(inMsg.sender).toBeUndefined()
|
||||
expect(toNewMessage(sms('b', 11, S.MessageType.SMS_OUT, 'yo'), SELF, '5415550199', false)!.direction).toBe('out')
|
||||
expect(toNewMessage(sms('c', 12, S.MessageType.VOICEMAIL, ''), SELF, '5415550199', false)).toBeUndefined()
|
||||
|
||||
const photo = toNewMessage(
|
||||
sms('d', 13, S.MessageType.SMS_IN, '', {
|
||||
mms: {
|
||||
text: 'look',
|
||||
subject: '',
|
||||
senderPhoneNumber: '+15415550101',
|
||||
participants: [],
|
||||
attachments: [
|
||||
{ id: 'm1', mimeType: 'image/png', status: 1, metadata: [{ size: 2, width: 128, height: 96 }, { size: 1, width: 1280, height: 960 }] },
|
||||
{ id: 'm2', mimeType: 'video/mp4', status: 3, metadata: [] }
|
||||
]
|
||||
}
|
||||
}),
|
||||
SELF,
|
||||
'5415550101,5415550199',
|
||||
true
|
||||
)!
|
||||
expect(photo).toMatchObject({ body: 'look', kind: 'mms', sender: '5415550101' })
|
||||
expect(photo.media).toEqual([{ url: 'gv:m1', mime: 'image/png', width: 1280, height: 960 }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('GvSyncEngine', () => {
|
||||
let dir: string
|
||||
let db: MessageDb
|
||||
beforeEach(() => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'voipms-gv-'))
|
||||
db = new MessageDb(path.join(dir, 'messages.db'))
|
||||
})
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
// A fake GV account: threads listed newest first, each paged two messages at a time.
|
||||
function fakeGv(threads: S.GvThread[]) {
|
||||
return {
|
||||
listThreads: async (token = '') => {
|
||||
const start = Number(token || 0)
|
||||
const page = threads.slice(start, start + 1)
|
||||
return { threads: page.map((t) => ({ ...t, messages: t.messages.slice(0, 1) })), paginationToken: start + 1 < threads.length ? String(start + 1) : '' }
|
||||
},
|
||||
getThread: async (id: string, _count = 100, token = '') => {
|
||||
const t = threads.find((x) => x.id === id)!
|
||||
const start = Number(token || 0)
|
||||
return { ...t, messages: t.messages.slice(start, start + 2), paginationToken: start + 2 < t.messages.length ? String(start + 2) : '' }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it('imports history, groups included, and keeps polling', async () => {
|
||||
const one = thread('t.+15415550199', ['+15415550199'], [
|
||||
sms('1c', 30, S.MessageType.SMS_IN, 'third'),
|
||||
sms('1b', 20, S.MessageType.SMS_OUT, 'second'),
|
||||
sms('1a', 10, S.MessageType.SMS_IN, 'first')
|
||||
])
|
||||
const group = thread('g.abc', ['+15415550199', '+15415550101'], [
|
||||
sms('2a', 25, S.MessageType.SMS_IN, 'hi all', { mms: { text: 'hi all', subject: '', senderPhoneNumber: '+15415550101', participants: [], attachments: [] } })
|
||||
])
|
||||
const gv = fakeGv([one, group])
|
||||
const engine = new GvSyncEngine(db, gv as unknown as GVoice, { did: SELF, pollSeconds: 60, backfillFloor: '1970-01-01' })
|
||||
const done = new Promise<void>((resolve) => engine.on('status', (s) => s.backfillDone && resolve()))
|
||||
engine.start()
|
||||
await done
|
||||
engine.stop()
|
||||
|
||||
expect(db.getConversationMessages(SELF, '5415550199').map((m) => m.body)).toEqual(['first', 'second', 'third'])
|
||||
const g = db.getConversationMessages(SELF, '5415550101,5415550199')
|
||||
expect(g).toHaveLength(1)
|
||||
expect(g[0].sender).toBe('5415550101')
|
||||
expect(db.getGvThread(SELF, '5415550101,5415550199')).toBe('g.abc')
|
||||
const conv = db.listConversations().find((c) => c.contact.includes(','))!
|
||||
expect(conv.lastSender).toBe('5415550101')
|
||||
})
|
||||
|
||||
it('lets a polled copy of a sent message replace the pending one', async () => {
|
||||
const tempId = db.insertPending({ did: SELF, contact: '5415550199', direction: 'out', body: 'on my way', ts: 1000 })
|
||||
const t = thread('t.+15415550199', ['+15415550199'], [sms('x1', 1500, S.MessageType.SMS_OUT, 'on my way')])
|
||||
const engine = new GvSyncEngine(db, fakeGv([t]) as unknown as GVoice, { did: SELF, pollSeconds: 60, backfillFloor: '2100-01-01' })
|
||||
await engine.pollNow()
|
||||
expect(db.getMessage(tempId)).toBeUndefined()
|
||||
expect(db.getMessage(gvMessageId('x1'))?.status).toBe('delivered')
|
||||
})
|
||||
|
||||
it("carries over GV's read state on import", async () => {
|
||||
const read = thread('t.+15415550199', ['+15415550199'], [sms('r1', 10, S.MessageType.SMS_IN, 'seen')])
|
||||
const unread = { ...thread('t.+15415550198', ['+15415550198'], [sms('u1', 11, S.MessageType.SMS_IN, 'new')]), read: false }
|
||||
db.set('unread_floor', '0')
|
||||
const gv = { listThreads: async () => ({ threads: [read, unread], paginationToken: '' }) }
|
||||
const engine = new GvSyncEngine(db, gv as unknown as GVoice, { did: SELF, pollSeconds: 60, backfillFloor: '2100-01-01' })
|
||||
await engine.pollNow()
|
||||
const unreadOf = (contact: string): number => db.listConversations().find((c) => c.contact === contact)!.unread
|
||||
expect(unreadOf('5415550199')).toBe(0)
|
||||
expect(unreadOf('5415550198')).toBe(1)
|
||||
})
|
||||
|
||||
it('goes to signed-out on 401 and leaves the rest alone', async () => {
|
||||
const gv = { listThreads: async () => Promise.reject(new GVoiceError('signed out', 401)) }
|
||||
const engine = new GvSyncEngine(db, gv as unknown as GVoice, { did: SELF, pollSeconds: 60, backfillFloor: '2100-01-01' })
|
||||
await engine.pollNow()
|
||||
expect(engine.getStatus().phase).toBe('signedOut')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Google Voice sends', () => {
|
||||
it('fail for good when signed out, with the reason', async () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'voipms-gvsend-'))
|
||||
const db = new MessageDb(path.join(dir, 'messages.db'))
|
||||
const tempId = db.insertPending({ did: SELF, contact: '5415550199', direction: 'out', body: 'x', ts: 1 })
|
||||
let calls = 0
|
||||
await sendWithRetry(tempId, {
|
||||
db,
|
||||
attempt: async () => {
|
||||
calls++
|
||||
throw new GVoiceError('Google Voice signed out. Reconnect it in Settings.', 401)
|
||||
},
|
||||
checkSent: async () => undefined,
|
||||
sleep: async () => undefined,
|
||||
classify: classifyGvError,
|
||||
describe: gvErrorMessage
|
||||
})
|
||||
expect(calls).toBe(1)
|
||||
expect(db.getMessage(tempId)).toMatchObject({ status: 'failed', error: 'Google Voice signed out. Reconnect it in Settings.' })
|
||||
db.close()
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { compressionSteps, formatBytes } from '../src/renderer/src/media'
|
||||
import { guessMime, mediaKind } from '@shared/mime'
|
||||
import { previewText } from '../src/renderer/src/format'
|
||||
|
||||
describe('compressionSteps', () => {
|
||||
it('tries full size first, then shrinks toward an 640px long edge', () => {
|
||||
const steps = compressionSteps(4032, 3024)
|
||||
expect(steps[0]).toEqual({ scale: 1, quality: 0.85 })
|
||||
const scales = [...new Set(steps.map((s) => s.scale))]
|
||||
expect(scales).toEqual([1, 2048 / 4032, 1600 / 4032, 1280 / 4032, 1024 / 4032, 800 / 4032, 640 / 4032])
|
||||
expect(steps).toHaveLength(scales.length * 3)
|
||||
})
|
||||
it('never upscales small images', () => {
|
||||
const scales = [...new Set(compressionSteps(900, 700).map((s) => s.scale))]
|
||||
expect(scales).toEqual([1, 800 / 900, 640 / 900])
|
||||
})
|
||||
})
|
||||
|
||||
describe('media helpers', () => {
|
||||
it('guesses types from voip.ms URLs and file names', () => {
|
||||
expect(guessMime('https://voip.ms/media/MTc4/media.jpeg')).toBe('image/jpeg')
|
||||
expect(mediaKind({ url: 'https://voip.ms/media/x/media.mp4' })).toBe('video')
|
||||
expect(mediaKind({ file: 'abc.bin' })).toBe('file')
|
||||
expect(mediaKind({ mime: 'audio/amr' })).toBe('audio')
|
||||
})
|
||||
it('formats sizes', () => {
|
||||
expect(formatBytes(900 * 1024)).toBe('900 KB')
|
||||
expect(formatBytes(6.2 * 1024 * 1024)).toBe('6.2 MB')
|
||||
})
|
||||
it('labels media in conversation previews', () => {
|
||||
expect(previewText({ lastBody: '', lastMedia: { mime: 'image/jpeg' } })).toBe('📷 Photo')
|
||||
expect(previewText({ lastBody: 'look!', lastMedia: { url: 'x/media.jpeg' } })).toBe('📷 look!')
|
||||
expect(previewText({ lastBody: 'hi\nthere' })).toBe('hi there')
|
||||
})
|
||||
})
|
||||
+3
-18
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatNumber, normalizeNumber, splitMessage } from '@shared/phone'
|
||||
import { charCount, formatNumber, normalizeNumber } from '@shared/phone'
|
||||
|
||||
describe('phone numbers', () => {
|
||||
it('normalizes NANP numbers to 10 digits', () => {
|
||||
@@ -17,23 +17,8 @@ describe('phone numbers', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('splitMessage', () => {
|
||||
it('keeps short messages whole', () => {
|
||||
expect(splitMessage('hi there')).toEqual(['hi there'])
|
||||
})
|
||||
it('splits long messages on word boundaries under 160 chars', () => {
|
||||
const text = Array.from({ length: 80 }, (_, i) => `word${i}`).join(' ')
|
||||
const parts = splitMessage(text)
|
||||
expect(parts.length).toBeGreaterThan(1)
|
||||
for (const p of parts) expect([...p].length).toBeLessThanOrEqual(160)
|
||||
expect(parts.join(' ')).toBe(text)
|
||||
})
|
||||
it('hard-splits a long unbroken string', () => {
|
||||
const parts = splitMessage('x'.repeat(400))
|
||||
expect(parts.map((p) => p.length)).toEqual([160, 160, 80])
|
||||
})
|
||||
describe('charCount', () => {
|
||||
it('counts emoji as single characters', () => {
|
||||
const parts = splitMessage('😀'.repeat(200))
|
||||
expect(parts.map((p) => [...p].length)).toEqual([160, 40])
|
||||
expect(charCount('😀'.repeat(200))).toBe(200)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { foldReactions, parseReaction, reactionPreview } from '@shared/reactions'
|
||||
|
||||
let nextId = 1
|
||||
const msg = (body: string, opts: { out?: boolean; sender?: string; media?: boolean; ts?: number } = {}) => ({
|
||||
id: nextId++,
|
||||
body,
|
||||
ts: opts.ts ?? nextId * 1000,
|
||||
direction: (opts.out ? 'out' : 'in') as 'in' | 'out',
|
||||
contact: '5550001111,5550002222',
|
||||
...(opts.sender ? { sender: opts.sender } : {}),
|
||||
...(opts.media ? { media: [{ file: 'x.jpg' }] } : {})
|
||||
})
|
||||
|
||||
describe('parseReaction', () => {
|
||||
it('reads the classic tapbacks', () => {
|
||||
expect(parseReaction('Loved “see you at 9”')).toEqual({ emoji: '❤️', removed: false, target: { text: 'see you at 9' } })
|
||||
expect(parseReaction('Laughed at "lol ok"')?.emoji).toBe('😂')
|
||||
expect(parseReaction('Emphasized “Bring a jacket”')?.emoji).toBe('‼️')
|
||||
expect(parseReaction('Questioned “what time”')?.emoji).toBe('❓')
|
||||
expect(parseReaction('Disliked “Monday”')?.emoji).toBe('👎')
|
||||
expect(parseReaction('Liked “a quote with “nested” quotes”')?.target).toEqual({ text: 'a quote with “nested” quotes' })
|
||||
})
|
||||
|
||||
it('reads emoji reactions, removals and media', () => {
|
||||
expect(parseReaction('Reacted 🎉 to “we won”')).toEqual({ emoji: '🎉', removed: false, target: { text: 'we won' } })
|
||||
expect(parseReaction('Removed a heart from “see you at 9”')).toEqual({ emoji: '❤️', removed: true, target: { text: 'see you at 9' } })
|
||||
expect(parseReaction('Liked an image')).toEqual({ emoji: '👍', removed: false, target: { media: true } })
|
||||
expect(parseReaction('Loved a photo')?.target).toEqual({ media: true })
|
||||
})
|
||||
|
||||
it('leaves ordinary texts alone', () => {
|
||||
expect(parseReaction('Loved it, thanks!')).toBeNull()
|
||||
expect(parseReaction('Liked the movie a lot')).toBeNull()
|
||||
expect(parseReaction('see you at 9')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('foldReactions', () => {
|
||||
it('moves reactions onto the quoted message and hides their texts', () => {
|
||||
const a = msg('see you at 9', { out: true })
|
||||
const b = msg('Loved “see you at 9”', { sender: '5550001111' })
|
||||
const c = msg('Laughed at “see you at 9”', { sender: '5550002222' })
|
||||
const { shown, reactions } = foldReactions([a, b, c])
|
||||
expect(shown).toEqual([a])
|
||||
expect(reactions.get(a.id)?.map((r) => [r.emoji, r.from])).toEqual([
|
||||
['❤️', '5550001111'],
|
||||
['😂', '5550002222']
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps one reaction per person; a newer one replaces it, a removal clears it', () => {
|
||||
const a = msg('dinner?')
|
||||
const b = msg('Liked “dinner?”', { sender: '5550001111' })
|
||||
const c = msg('Loved “dinner?”', { sender: '5550001111' })
|
||||
const d = msg('Questioned “dinner?”', { sender: '5550002222' })
|
||||
const e = msg('Removed a question mark from “dinner?”', { sender: '5550002222' })
|
||||
const { shown, reactions } = foldReactions([a, b, c, d, e])
|
||||
expect(shown).toEqual([a])
|
||||
expect(reactions.get(a.id)?.map((r) => r.emoji)).toEqual(['❤️'])
|
||||
})
|
||||
|
||||
it('finds the nearest earlier match, photos, and cut-off quotes', () => {
|
||||
const old = msg('ok')
|
||||
const photo = msg('', { media: true, out: true })
|
||||
const recent = msg('ok')
|
||||
const long = msg('This is a long message that the other phone will only quote the start of')
|
||||
const r1 = msg('Liked “ok”', { sender: '5550001111' })
|
||||
const r2 = msg('Loved an image', { sender: '5550001111' })
|
||||
const r3 = msg('Emphasized “This is a long message that the other…”', { sender: '5550002222' })
|
||||
const { reactions } = foldReactions([old, photo, recent, long, r1, r2, r3])
|
||||
expect(reactions.has(old.id)).toBe(false)
|
||||
expect(reactions.get(recent.id)?.[0].emoji).toBe('👍')
|
||||
expect(reactions.get(photo.id)?.[0].emoji).toBe('❤️')
|
||||
expect(reactions.get(long.id)?.[0].emoji).toBe('‼️')
|
||||
})
|
||||
|
||||
it('ignores straight vs curly apostrophes', () => {
|
||||
const a = msg("I'll be there", { out: true })
|
||||
const r = msg('Loved “I’ll be there”', { sender: '5550001111' })
|
||||
expect(foldReactions([a, r]).reactions.get(a.id)?.[0].emoji).toBe('❤️')
|
||||
})
|
||||
|
||||
it("leaves a reaction it can't place as a normal message", () => {
|
||||
const a = msg('hello')
|
||||
const r = msg('Loved “something from last year”')
|
||||
const { shown, reactions } = foldReactions([a, r])
|
||||
expect(shown).toEqual([a, r])
|
||||
expect(reactions.size).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('reactionPreview', () => {
|
||||
it('summarises for the chat list', () => {
|
||||
expect(reactionPreview('Loved “see you at 9”')).toBe('❤️ to “see you at 9”')
|
||||
expect(reactionPreview('Liked an image')).toBe('👍 to a photo')
|
||||
expect(reactionPreview('just text')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { MessageDb } from '../src/main/db'
|
||||
import { sendWithRetry } from '../src/main/send'
|
||||
import { VoipMsError } from '../src/main/voipms'
|
||||
|
||||
let dir: string
|
||||
let db: MessageDb
|
||||
let tempId: number
|
||||
|
||||
const timeout = (): Error => new DOMException('The operation was aborted due to timeout', 'TimeoutError')
|
||||
const offline = (): Error => Object.assign(new TypeError('fetch failed'), { cause: { code: 'ENOTFOUND' } })
|
||||
const sleep = async (): Promise<void> => undefined
|
||||
|
||||
// An attempt that plays back `results` in order (errors are thrown).
|
||||
function attempts(...results: Array<number | Error>) {
|
||||
const fn = async (): Promise<number> => {
|
||||
fn.calls++
|
||||
const r = results.shift()!
|
||||
if (r instanceof Error) throw r
|
||||
return r
|
||||
}
|
||||
fn.calls = 0
|
||||
return fn
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'voipms-send-'))
|
||||
db = new MessageDb(path.join(dir, 'messages.db'))
|
||||
tempId = db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body: 'breakfast?', ts: 1000 })
|
||||
})
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('sendWithRetry', () => {
|
||||
it('confirms a message that sends first time', async () => {
|
||||
await sendWithRetry(tempId, { db, attempt: attempts(77), checkSent: async () => undefined, sleep })
|
||||
expect(db.getMessage(77)?.status).toBe('delivered')
|
||||
})
|
||||
|
||||
it('does not resend after a timeout when the listing shows it went out', async () => {
|
||||
const attempt = attempts(timeout(), 99)
|
||||
const checkSent = async (): Promise<void> => void db.reconcileSent(db.upsertMessages([{ id: 88, did: '5550001111', contact: 'a', direction: 'out', body: 'breakfast?', ts: 2000 }]))
|
||||
await sendWithRetry(tempId, { db, attempt, checkSent, sleep })
|
||||
expect(attempt.calls).toBe(1)
|
||||
expect(db.getConversationMessages('5550001111', 'a').map((m) => m.id)).toEqual([88])
|
||||
})
|
||||
|
||||
it('resends after a timeout once the listing shows it did not go out', async () => {
|
||||
const attempt = attempts(timeout(), 99)
|
||||
let checks = 0
|
||||
await sendWithRetry(tempId, { db, attempt, checkSent: async () => void checks++, sleep })
|
||||
expect(checks).toBe(2)
|
||||
expect(attempt.calls).toBe(2)
|
||||
expect(db.getConversationMessages('5550001111', 'a').map((m) => m.id)).toEqual([99])
|
||||
})
|
||||
|
||||
it('resends right away when the request never left', async () => {
|
||||
const attempt = attempts(offline(), 99)
|
||||
await sendWithRetry(tempId, { db, attempt, checkSent: async () => undefined, sleep })
|
||||
expect(attempt.calls).toBe(2)
|
||||
expect(db.getMessage(99)?.status).toBe('delivered')
|
||||
})
|
||||
|
||||
it('gives up after three attempts and says why', async () => {
|
||||
const attempt = attempts(offline(), offline(), offline(), 99)
|
||||
await sendWithRetry(tempId, { db, attempt, checkSent: async () => undefined, sleep })
|
||||
expect(attempt.calls).toBe(3)
|
||||
expect(db.getMessage(tempId)).toMatchObject({ status: 'failed', error: expect.stringMatching(/internet connection/) })
|
||||
})
|
||||
|
||||
it('does not retry a rejection', async () => {
|
||||
const attempt = attempts(new VoipMsError('invalid_dst'), 99)
|
||||
await sendWithRetry(tempId, { db, attempt, checkSent: async () => undefined, sleep })
|
||||
expect(attempt.calls).toBe(1)
|
||||
expect(db.getMessage(tempId)).toMatchObject({ status: 'failed', error: 'Invalid destination number.' })
|
||||
})
|
||||
})
|
||||
+37
-1
@@ -12,7 +12,7 @@ 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 }) {
|
||||
async getMessages({ 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)
|
||||
}
|
||||
@@ -41,6 +41,25 @@ describe('toNewMessage', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('toNewMessage (MMS)', () => {
|
||||
const mms = { ...raw(8, '2024-02-03'), message: '', col_media2: '', col_media3: '' }
|
||||
it('maps getMMS media to kind mms', () => {
|
||||
const url = 'https://voip.ms/media/abc/media.jpeg'
|
||||
expect(toNewMessage({ ...mms, col_media1: url, media: [url] })).toMatchObject({ kind: 'mms', media: [{ url }] })
|
||||
expect(toNewMessage({ ...mms, col_media1: url })).toMatchObject({ kind: 'mms', media: [{ url }] })
|
||||
})
|
||||
it('treats rows without media as plain texts', () => {
|
||||
const m = toNewMessage({ ...mms, message: 'long text', col_media1: '', media: [] })
|
||||
expect(m.kind).toBeUndefined()
|
||||
expect(m.media).toBeUndefined()
|
||||
})
|
||||
it('labels text too long for one SMS as a text-only MMS', () => {
|
||||
expect(toNewMessage({ ...mms, message: 'x'.repeat(161) })).toMatchObject({ kind: 'mms' })
|
||||
expect(toNewMessage({ ...mms, message: '😀'.repeat(160) }).kind).toBeUndefined()
|
||||
expect(toNewMessage({ ...mms, message: 'x'.repeat(161) }).media).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
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)))
|
||||
@@ -74,3 +93,20 @@ describe('SyncEngine backfill', () => {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}, 20_000)
|
||||
})
|
||||
|
||||
describe('SyncEngine poll', () => {
|
||||
it('replaces a failed local copy of a text that voip.ms did send', async () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'voipms-sync-'))
|
||||
const db = new MessageDb(path.join(dir, 'm.db'))
|
||||
db.set('backfill_done', '1')
|
||||
const sent = { ...raw(42, ymd(Date.now()), '0'), message: 'see you at 8' }
|
||||
const t = db.insertPending({ did: '5550001111', contact: '5415550142', direction: 'out', body: 'see you at 8', ts: toNewMessage(sent).ts })
|
||||
db.markFailed(t, "voip.ms didn't respond in time.")
|
||||
const engine = new SyncEngine(db, fakeApi([sent]) as unknown as VoipMs, { pollSeconds: 3600, dids: [], backfillFloor: '2010-01-01' })
|
||||
await engine.pollNow()
|
||||
expect(db.getMessage(t)).toBeUndefined()
|
||||
expect(db.getConversationMessages('5550001111', '5415550142').map((m) => [m.id, m.status])).toEqual([[42, 'delivered']])
|
||||
db.close()
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { classifySendError, fixVoipDst, parseVoipDate, sendErrorMessage, VoipMsError } from '../src/main/voipms'
|
||||
|
||||
describe('parseVoipDate', () => {
|
||||
// Real cases checked against the live API (timezone=0).
|
||||
it('undoes the extra hour voip.ms adds during US daylight time', () => {
|
||||
// Sent 2026-09-18 06:35:47 UTC; voip.ms reported 07:35:47.
|
||||
expect(parseVoipDate('2026-09-18 07:35:47')).toBe(Date.UTC(2026, 8, 18, 6, 35, 47))
|
||||
// March 12 2026: US DST (from Mar 8) but not UK summer time (from Mar 29).
|
||||
expect(parseVoipDate('2026-03-12 19:16:41')).toBe(Date.UTC(2026, 2, 12, 18, 16, 41))
|
||||
})
|
||||
it('leaves winter times alone', () => {
|
||||
expect(parseVoipDate('2026-01-20 02:44:49')).toBe(Date.UTC(2026, 0, 20, 2, 44, 49))
|
||||
expect(fixVoipDst(Date.UTC(2025, 11, 25, 12))).toBe(Date.UTC(2025, 11, 25, 12))
|
||||
})
|
||||
})
|
||||
|
||||
const netError = (code: string): Error => Object.assign(new TypeError('fetch failed'), { cause: Object.assign(new Error(code), { code }) })
|
||||
const timeout = (): Error => new DOMException('The operation was aborted due to timeout', 'TimeoutError')
|
||||
|
||||
describe('classifySendError', () => {
|
||||
it('never resends blindly when the message may have gone out', () => {
|
||||
expect(classifySendError(timeout())).toBe('unknown')
|
||||
expect(classifySendError(netError('ECONNRESET'))).toBe('unknown')
|
||||
expect(classifySendError(new Error('voip.ms HTTP 502'))).toBe('unknown')
|
||||
expect(classifySendError(new SyntaxError('Unexpected token <'))).toBe('unknown')
|
||||
})
|
||||
it('resends when the request never reached voip.ms or voip.ms says it failed', () => {
|
||||
expect(classifySendError(netError('ENOTFOUND'))).toBe('safe')
|
||||
expect(classifySendError(netError('ECONNREFUSED'))).toBe('safe')
|
||||
expect(classifySendError(new VoipMsError('sms_failed'))).toBe('safe')
|
||||
})
|
||||
it('gives up on rejections', () => {
|
||||
expect(classifySendError(new VoipMsError('invalid_dst'))).toBe('fatal')
|
||||
expect(classifySendError(new VoipMsError('not_signed_in'))).toBe('fatal')
|
||||
})
|
||||
})
|
||||
|
||||
describe('sendErrorMessage', () => {
|
||||
it('explains failures in plain words', () => {
|
||||
expect(sendErrorMessage(timeout())).toBe("voip.ms didn't respond in time.")
|
||||
expect(sendErrorMessage(netError('ENOTFOUND'))).toMatch(/internet connection/)
|
||||
expect(sendErrorMessage(new VoipMsError('invalid_dst'))).toBe('Invalid destination number.')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user