voip.ms Messages: Signal-style desktop SMS client

Electron + React app that imports the full voip.ms SMS history into a
local SQLite/FTS5 database, polls for new messages, sends SMS, resolves
names/photos from GNOME EDS address books, and supports global and
per-chat search with jump-to-message.

Data lives in ~/Documents/voipms-desktop-data (covered by Deja Dup) with
daily consistent snapshots.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-17 21:25:12 -07:00
co-authored by Claude Opus 5
commit 241a44f0ee
47 changed files with 10956 additions and 0 deletions
+237
View File
@@ -0,0 +1,237 @@
// Local message store: SQLite (WAL) with an FTS5 index for search.
import Database from 'better-sqlite3'
import fs from 'node:fs'
import path from 'node:path'
import type { Conversation, Direction, Message, MessageStatus, SearchHit } from '@shared/types'
import { SNIPPET_END, SNIPPET_START } from '@shared/types'
const SCHEMA_VERSION = 1
export interface NewMessage {
id: number
did: string
contact: string
direction: Direction
body: string
ts: number
status?: MessageStatus
}
interface MessageRow {
id: number
did: string
contact: string
direction: Direction
body: string
ts: number
kind: 'sms' | 'mms'
status: MessageStatus
}
export class MessageDb {
readonly db: Database.Database
constructor(private file: string) {
fs.mkdirSync(path.dirname(file), { recursive: true })
this.db = new Database(file)
this.db.pragma('journal_mode = WAL')
this.db.pragma('synchronous = NORMAL')
this.db.pragma('foreign_keys = ON')
this.migrate()
}
private migrate(): void {
const version = this.db.pragma('user_version', { simple: true }) as number
if (version >= SCHEMA_VERSION) return
this.db.exec(`
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY, -- voip.ms id (negative = local pending)
did TEXT NOT NULL,
contact TEXT NOT NULL,
direction TEXT NOT NULL CHECK (direction IN ('in','out')),
body TEXT NOT NULL,
ts INTEGER NOT NULL, -- epoch ms UTC
kind TEXT NOT NULL DEFAULT 'sms', -- 'sms' | 'mms' (future)
status TEXT NOT NULL DEFAULT 'delivered',
media_json TEXT -- MMS attachments (future)
);
CREATE INDEX IF NOT EXISTS messages_conv ON messages (did, contact, ts);
CREATE INDEX IF NOT EXISTS messages_ts ON messages (ts);
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5 (
body, content='messages', content_rowid='id', tokenize='unicode61 remove_diacritics 2'
);
CREATE TRIGGER IF NOT EXISTS messages_ai AFTER INSERT ON messages BEGIN
INSERT INTO messages_fts(rowid, body) VALUES (new.id, new.body);
END;
CREATE TRIGGER IF NOT EXISTS messages_ad AFTER DELETE ON messages BEGIN
INSERT INTO messages_fts(messages_fts, rowid, body) VALUES ('delete', old.id, old.body);
END;
CREATE TRIGGER IF NOT EXISTS messages_au AFTER UPDATE OF id, body ON messages BEGIN
INSERT INTO messages_fts(messages_fts, rowid, body) VALUES ('delete', old.id, old.body);
INSERT INTO messages_fts(rowid, body) VALUES (new.id, new.body);
END;
CREATE TABLE IF NOT EXISTS read_state (
did TEXT NOT NULL, contact TEXT NOT NULL, last_read_ts INTEGER NOT NULL,
PRIMARY KEY (did, contact)
);
CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL);
`)
this.db.pragma(`user_version = ${SCHEMA_VERSION}`)
}
// ---- key/value state ----
get(key: string): string | undefined {
const r = this.db.prepare('SELECT value FROM kv WHERE key = ?').get(key) as { value: string } | undefined
return r?.value
}
set(key: string, value: string): void {
this.db.prepare('INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, value)
}
// ---- messages ----
// Inserts messages we haven't seen; returns the ones that were new.
upsertMessages(msgs: NewMessage[]): NewMessage[] {
const insert = this.db.prepare(
`INSERT OR IGNORE INTO messages (id, did, contact, direction, body, ts, status)
VALUES (@id, @did, @contact, @direction, @body, @ts, @status)`
)
const added: NewMessage[] = []
this.db.transaction(() => {
for (const m of msgs) {
if (insert.run({ ...m, status: m.status ?? 'delivered' }).changes) added.push(m)
}
})()
return added
}
insertPending(m: Omit<NewMessage, 'id'>): number {
const row = this.db.prepare('SELECT MIN(id) AS min FROM messages').get() as { min: number | null }
const id = Math.min(-1, (row.min ?? 0) - 1)
this.upsertMessages([{ ...m, id, status: 'pending' }])
return id
}
// Replace a local pending row with the id voip.ms assigned.
confirmPending(tempId: number, realId: number): void {
this.db.transaction(() => {
const exists = this.db.prepare('SELECT 1 FROM messages WHERE id = ?').get(realId)
if (exists) {
this.db.prepare('DELETE FROM messages WHERE id = ?').run(tempId)
} else {
this.db.prepare(`UPDATE messages SET id = ?, status = 'delivered' WHERE id = ?`).run(realId, tempId)
}
})()
}
markFailed(tempId: number): void {
this.db.prepare(`UPDATE messages SET status = 'failed' WHERE id = ?`).run(tempId)
}
deleteMessage(id: number): void {
this.db.prepare('DELETE FROM messages WHERE id = ?').run(id)
}
getMessage(id: number): Message | undefined {
return this.db.prepare('SELECT id, did, contact, direction, body, ts, kind, status FROM messages WHERE id = ?').get(id) as
| MessageRow
| undefined
}
getConversationMessages(did: string, contact: string): Message[] {
return this.db
.prepare(
`SELECT id, did, contact, direction, body, ts, kind, status FROM messages
WHERE did = ? AND contact = ? ORDER BY ts, id`
)
.all(did, contact) as MessageRow[]
}
count(): number {
return (this.db.prepare('SELECT COUNT(*) AS n FROM messages').get() as { n: number }).n
}
// ---- conversations ----
listConversations(): Conversation[] {
// Messages from before the initial history import never count as unread.
const floor = Number(this.get('unread_floor') ?? 0)
return this.db
.prepare(
`WITH latest AS (
SELECT did, contact, MAX(ts) AS mts FROM messages GROUP BY did, contact
)
SELECT l.did, l.contact, l.mts AS lastTs,
(SELECT body FROM messages m WHERE m.did = l.did AND m.contact = l.contact ORDER BY ts DESC, id DESC LIMIT 1) AS lastBody,
(SELECT direction FROM messages m WHERE m.did = l.did AND m.contact = l.contact ORDER BY ts DESC, id DESC LIMIT 1) AS lastDirection,
(SELECT COUNT(*) FROM messages m WHERE m.did = l.did AND m.contact = l.contact AND m.direction = 'in'
AND m.ts > MAX(COALESCE(r.last_read_ts, 0), @floor)) AS unread
FROM latest l
LEFT JOIN read_state r ON r.did = l.did AND r.contact = l.contact
ORDER BY l.mts DESC`
)
.all({ floor }) as Conversation[]
}
markRead(did: string, contact: string): void {
this.db
.prepare(
`INSERT INTO read_state (did, contact, last_read_ts)
SELECT @did, @contact, COALESCE(MAX(ts), 0) FROM messages WHERE did = @did AND contact = @contact
ON CONFLICT(did, contact) DO UPDATE SET last_read_ts = excluded.last_read_ts`
)
.run({ did, contact })
}
// ---- search ----
search(query: string, scope?: { did: string; contact: string }, limit = 300): SearchHit[] {
const match = toFtsQuery(query)
if (!match) return []
const where = scope ? 'AND m.did = @did AND m.contact = @contact' : ''
return this.db
.prepare(
`SELECT m.id, m.did, m.contact, m.ts, m.direction,
snippet(messages_fts, 0, @s, @e, '…', 14) AS snippet
FROM messages_fts JOIN messages m ON m.id = messages_fts.rowid
WHERE messages_fts MATCH @match ${where}
ORDER BY m.ts DESC LIMIT @limit`
)
.all({ match, s: SNIPPET_START, e: SNIPPET_END, limit, did: scope?.did, contact: scope?.contact }) as SearchHit[]
}
// ---- backups ----
// Write a consistent copy to dir/messages-YYYY-MM-DD.db and prune old ones.
async snapshot(dir: string, keep = 7): Promise<string> {
fs.mkdirSync(dir, { recursive: true })
const dest = path.join(dir, `messages-${localDay()}.db`)
const tmp = dest + '.tmp'
await this.db.backup(tmp)
fs.renameSync(tmp, dest)
const old = fs
.readdirSync(dir)
.filter((f) => /^messages-\d{4}-\d{2}-\d{2}\.db$/.test(f))
.sort()
.reverse()
.slice(keep)
for (const f of old) fs.rmSync(path.join(dir, f), { force: true })
return dest
}
close(): void {
this.db.close()
}
}
// Today's date as YYYY-MM-DD in local time (snapshot file names).
export function localDay(d = new Date()): string {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}
// Turn free text into a safe FTS5 query: every word must appear (prefix match).
export function toFtsQuery(input: string): string {
const words = input
.normalize('NFKC')
.split(/[^\p{L}\p{N}]+/u)
.filter(Boolean)
return words.map((w) => `"${w.replace(/"/g, '""')}"*`).join(' ')
}