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 a2b8f764db
47 changed files with 10956 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
node_modules/
out/
dist/
*.log
+70
View File
@@ -0,0 +1,70 @@
# voip.ms Messages
A Signal Desktop–style SMS client for [voip.ms](https://voip.ms). It keeps your full message history on your own machine, lets you search it, and shows your GNOME contacts' names and photos.
## Features
- A conversation list on the left, with contact photos, previews, times, and unread badges. The chat opens on the right.
- A **full local copy of your history.** On first run the app imports everything from voip.ms, working backwards in 90-day windows, and picks up where it left off if interrupted. After that it checks for new messages every 30 seconds (you can change this).
- **Search** everything from the sidebar (Ctrl+F). Results show a highlighted preview, and clicking one jumps to that exact message. You can also search inside a single chat (Ctrl+Shift+F), using Enter and Shift+Enter to step through the matches.
- **New chat** (Ctrl+N), with autocomplete from your contacts by name or number.
- Contacts are read-only, straight from GNOME's Evolution Data Server caches: your Nextcloud CardDAV books and anything else GNOME Contacts shows. They reload automatically when the books sync.
- Messages longer than 160 characters are split automatically. If a send fails, it's marked with Retry and Delete options.
- Alt+↑/↓ moves between conversations.
## Where your data lives
| What | Where | Backed up? |
|---|---|---|
| Message database | `~/Documents/voipms-desktop-data/messages.db` | ✅ Déjà Dup covers `~/Documents` |
| Daily snapshots, last 7 kept | `~/Documents/voipms-desktop-data/snapshots/` | ✅ |
| Settings | `~/Documents/voipms-desktop-data/settings.json` | ✅ |
| API password | GNOME Keyring (via Electron `safeStorage`) → `~/.config/voipms-desktop/credentials.bin` | ❌ on purpose; you re-enter it after a restore |
| Contact photo cache | `~/.config/voipms-desktop/photo-cache/` | ❌ not needed |
The snapshots are consistent SQLite copies, made daily and whenever you quit. So even if a backup catches the live database halfway through a write, the backup still holds a clean, restorable copy. To move the data folder, go to Settings → Storage → Move…. If you point it at a folder that already holds a `messages.db`, for example one restored from backup, the app uses that history.
## Setup
In the voip.ms portal, go to **Main Menu → SOAP & REST/JSON API** and:
1. Enable the API.
2. Set an **API password**. This is separate from your login password.
3. Add your IP address under **Enable IP Addresses**.
Then launch the app and enter your account email and API password.
## Development
```bash
npm install
npm run dev # run with hot reload
npm test # unit tests (run under Electron's Node for better-sqlite3)
npm run test:live # also reads your real EDS address books (read-only)
npm run typecheck
npm run install-desktop # build the AppImage and add a GNOME launcher
```
To work on the UI against fake data, without touching your real history, run:
```bash
VOIPMS_DEMO=1 VOIPMS_DATA_DIR=/tmp/voipms-demo npm run dev
```
### Layout
```
src/main/ Electron main process
voipms.ts REST client (getDIDsInfo, getSMS, sendSMS)
sync.ts history backfill + polling
db.ts SQLite schema, FTS5 search, snapshots
contacts.ts EDS cache reader + vCard parser
secrets.ts keyring-encrypted credentials
settings.ts data folder + preferences
src/preload/ typed IPC bridge (window.api)
src/renderer/ React UI
src/shared/ types + phone-number helpers shared by both sides
resources/ icon, eds-sources.py (lists live EDS address books)
```
The message table already reserves `kind` and `media_json` columns for MMS support.
+18
View File
@@ -0,0 +1,18 @@
import { resolve } from 'node:path'
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
main: {
plugins: [externalizeDepsPlugin()],
resolve: { alias: { '@shared': resolve('src/shared') } }
},
preload: {
plugins: [externalizeDepsPlugin()],
resolve: { alias: { '@shared': resolve('src/shared') } }
},
renderer: {
plugins: [react()],
resolve: { alias: { '@shared': resolve('src/shared') } }
}
})
+6796
View File
File diff suppressed because it is too large Load Diff
+76
View File
@@ -0,0 +1,76 @@
{
"name": "voipms-desktop",
"productName": "voip.ms Messages",
"version": "0.1.0",
"description": "Signal-style desktop SMS client for voip.ms",
"author": "trav <trav@teafry.me>",
"private": true,
"main": "out/main/index.js",
"scripts": {
"dev": "electron-vite dev",
"build": "electron-vite build",
"start": "electron-vite preview",
"typecheck": "tsc --noEmit -p tsconfig.node.json && tsc --noEmit -p tsconfig.web.json",
"test": "ELECTRON_RUN_AS_NODE=1 electron node_modules/vitest/vitest.mjs run",
"postinstall": "electron-builder install-app-deps",
"dist": "electron-vite build && electron-builder --linux AppImage",
"install-desktop": "npm run dist && ./scripts/install-desktop.sh",
"test:live": "LIVE=1 npm test"
},
"dependencies": {
"better-sqlite3": "^13.0.3"
},
"devDependencies": {
"@types/better-sqlite3": "^9.6.0",
"@types/node": "^26.6.1",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^5.2.0",
"electron": "^44.4.2",
"electron-builder": "^26.15.3",
"electron-vite": "^5.0.0",
"react": "^19.3.0",
"react-dom": "^19.3.0",
"react-virtuoso": "^4.18.13",
"typescript": "^7.0.2",
"vite": "^7.3.6",
"vitest": "^3.2.7"
},
"build": {
"appId": "me.teafry.voipms-desktop",
"productName": "voip.ms Messages",
"directories": {
"output": "dist",
"buildResources": "resources"
},
"files": [
"out/**",
"resources/icon.png",
"package.json"
],
"extraResources": [
{
"from": "resources/eds-sources.py",
"to": "eds-sources.py"
}
],
"linux": {
"target": [
"AppImage"
],
"icon": "resources/icon.png",
"category": "Network",
"executableName": "voipms-desktop",
"desktop": {
"entry": {
"Name": "voip.ms Messages",
"Comment": "Text messages via voip.ms",
"StartupWMClass": "voip.ms Messages"
}
},
"syncDesktopName": true,
"artifactName": "voipms-desktop-${version}.${ext}"
}
},
"desktopName": "voipms-desktop.desktop"
}
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""List the enabled Evolution Data Server address books as JSON.
Only reads the source registry (no book connections), so it's fast. The app
uses this to know which ~/.cache/evolution/addressbook/<uid>/cache.db files
are live, and what they're called.
"""
import json
import sys
import gi
gi.require_version("EDataServer", "1.2")
from gi.repository import EDataServer as EDS # noqa: E402
reg = EDS.SourceRegistry.new_sync(None)
out = []
for s in reg.list_enabled(EDS.SOURCE_EXTENSION_ADDRESS_BOOK):
ext = s.get_extension(EDS.SOURCE_EXTENSION_ADDRESS_BOOK)
parent = reg.ref_source(s.get_parent()) if s.get_parent() else None
out.append({
"uid": s.get_uid(),
"name": s.get_display_name(),
"backend": ext.get_backend_name(),
"account": parent.get_display_name() if parent else "",
})
json.dump(out, sys.stdout)
Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

+13
View File
@@ -0,0 +1,13 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
<defs>
<linearGradient id="g" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#3a78f2"/>
<stop offset="1" stop-color="#2257d6"/>
</linearGradient>
</defs>
<rect x="32" y="32" width="448" height="448" rx="104" fill="url(#g)"/>
<path d="M256 120c-86 0-150 55-150 124 0 38 19 71 50 94l-12 58 60-32c16 4 34 6 52 6 86 0 150-55 150-126S342 120 256 120z" fill="#fff"/>
<circle cx="196" cy="246" r="18" fill="#2c6bed"/>
<circle cx="256" cy="246" r="18" fill="#2c6bed"/>
<circle cx="316" cy="246" r="18" fill="#2c6bed"/>
</svg>

After

Width:  |  Height:  |  Size: 651 B

+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Install the built AppImage + a GNOME launcher for the current user.
# Usage: npm run dist && ./scripts/install-desktop.sh
set -euo pipefail
cd "$(dirname "$0")/.."
appimage=$(ls -t dist/voipms-desktop-*.AppImage | head -1)
bin="$HOME/.local/bin/voipms-desktop.AppImage"
icon="$HOME/.local/share/icons/hicolor/512x512/apps/voipms-desktop.png"
desktop="$HOME/.local/share/applications/voipms-desktop.desktop"
install -Dm755 "$appimage" "$bin"
install -Dm644 resources/icon.png "$icon"
mkdir -p "$(dirname "$desktop")"
cat > "$desktop" <<DESKTOP
[Desktop Entry]
Type=Application
Name=voip.ms Messages
Comment=Text messages via voip.ms
Exec=$bin %U
Icon=voipms-desktop
Terminal=false
Categories=Network;InstantMessaging;
StartupWMClass=voip.ms Messages
DESKTOP
update-desktop-database "$(dirname "$desktop")" 2>/dev/null || true
echo "Installed: $bin"
echo "Launcher: $desktop"
+291
View File
@@ -0,0 +1,291 @@
// Reads contacts from GNOME's Evolution Data Server caches (read-only) and maps
// phone numbers to names + photos.
import Database from 'better-sqlite3'
import { execFile } from 'node:child_process'
import { EventEmitter } from 'node:events'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { normalizeNumber } from '@shared/phone'
import type { ContactInfo } from '@shared/types'
export interface BookSource {
uid: string
name: string
backend: string
account: string
}
export interface VCardContact {
name: string
tels: Array<{ number: string; label?: string }>
photo?: PhotoRef
}
export type PhotoRef = { kind: 'file'; path: string } | { kind: 'url'; url: string } | { kind: 'inline'; mime: string; data: string }
const HOME = os.homedir()
const CACHE_ROOT = path.join(HOME, '.cache/evolution/addressbook')
const LOCAL_ROOT = path.join(HOME, '.local/share/evolution/addressbook')
// ---------- vCard parsing ----------
interface Prop {
name: string
params: Record<string, string>
value: string
}
function unfold(vcard: string): string[] {
return vcard.replace(/\r\n/g, '\n').replace(/\n[ \t]/g, '').split('\n')
}
function parseLine(line: string): Prop | null {
// Find the first ':' that isn't inside a quoted parameter value.
let inQuote = false
let colon = -1
for (let i = 0; i < line.length; i++) {
const c = line[i]
if (c === '"') inQuote = !inQuote
else if (c === ':' && !inQuote) {
colon = i
break
}
}
if (colon < 0) return null
const [rawName, ...rawParams] = line.slice(0, colon).split(';')
const params: Record<string, string> = {}
for (const p of rawParams) {
const eq = p.indexOf('=')
if (eq < 0) params[p.toUpperCase()] = (params['TYPE'] ? params['TYPE'] + ',' : '') + p
else {
const k = p.slice(0, eq).toUpperCase()
const v = p.slice(eq + 1).replace(/^"|"$/g, '')
params[k] = params[k] ? `${params[k]},${v}` : v
}
}
// Strip any "item1." group prefix.
const name = rawName.replace(/^[^.]+\./, '').toUpperCase()
return { name, params, value: line.slice(colon + 1) }
}
function unescapeText(v: string): string {
return v.replace(/\\n/gi, '\n').replace(/\\([,;\\])/g, '$1')
}
export function parseVCard(vcard: string): VCardContact {
let fn = ''
let n = ''
let org = ''
const tels: VCardContact['tels'] = []
let photo: PhotoRef | undefined
for (const line of unfold(vcard)) {
const p = parseLine(line)
if (!p) continue
switch (p.name) {
case 'FN':
fn = unescapeText(p.value).trim()
break
case 'N': {
const [family, given] = p.value.split(';').map(unescapeText)
n = [given, family].filter(Boolean).join(' ').trim()
break
}
case 'ORG':
org = unescapeText(p.value.split(';')[0]).trim()
break
case 'TEL': {
const raw = p.value.replace(/^tel:/i, '')
const number = normalizeNumber(raw)
if (number.length >= 3) {
const label = (p.params['TYPE'] ?? '')
.split(',')
.map((t) => t.toLowerCase())
.find((t) => ['cell', 'mobile', 'home', 'work', 'main', 'iphone', 'other'].includes(t))
tels.push({ number, label: label === 'mobile' || label === 'iphone' ? 'cell' : label })
}
break
}
case 'PHOTO': {
if (photo) break
const v = p.value.trim()
const encoding = (p.params['ENCODING'] ?? '').toLowerCase()
if (v.startsWith('data:')) {
const m = /^data:([^;,]+)?(?:;base64)?,(.*)$/s.exec(v)
if (m) photo = { kind: 'inline', mime: m[1] ?? 'image/jpeg', data: m[2] }
} else if (encoding === 'b' || encoding === 'base64') {
const type = (p.params['TYPE'] ?? 'jpeg').toLowerCase()
photo = { kind: 'inline', mime: type.includes('/') ? type : `image/${type}`, data: v.replace(/\s/g, '') }
} else if (/^file:\/\//i.test(v)) {
photo = { kind: 'file', path: decodeURIComponent(v.replace(/^file:\/\//i, '')) }
} else if (/^https?:\/\//i.test(v)) {
photo = { kind: 'url', url: v }
}
break
}
}
}
return { name: fn || n || org, tels, photo }
}
// ---------- EDS sources ----------
function helperPath(): string {
// In a packaged app the helper ships in resources/, in dev it's in the repo.
const packaged = path.join(process.resourcesPath ?? '', 'eds-sources.py')
return fs.existsSync(packaged) ? packaged : path.join(__dirname, '../../resources/eds-sources.py')
}
export function listSources(): Promise<BookSource[]> {
return new Promise((resolve) => {
execFile('python3', [helperPath()], { timeout: 20_000 }, (err, stdout) => {
if (!err) {
try {
return resolve(JSON.parse(stdout) as BookSource[])
} catch {
/* fall through */
}
}
// Fallback: every cache dir we can find.
console.warn('[contacts] EDS registry helper failed, scanning caches instead:', err?.message)
const dirs = fs.existsSync(CACHE_ROOT) ? fs.readdirSync(CACHE_ROOT).filter((d) => d !== 'trash') : []
resolve([
...dirs.map((uid) => ({ uid, name: uid.slice(0, 8), backend: 'carddav', account: '' })),
{ uid: 'system-address-book', name: 'Personal', backend: 'local', account: '' }
])
})
})
}
function bookDbPath(src: BookSource): string | undefined {
const candidates =
src.uid === 'system-address-book'
? [path.join(LOCAL_ROOT, 'system/contacts.db')]
: [path.join(CACHE_ROOT, src.uid, 'cache.db'), path.join(LOCAL_ROOT, src.uid, 'contacts.db')]
return candidates.find((f) => fs.existsSync(f))
}
function readBook(file: string): string[] {
const db = new Database(file, { readonly: true, fileMustExist: true })
try {
const tables = new Set((db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table'`).all() as { name: string }[]).map((t) => t.name))
if (tables.has('ECacheObjects')) {
// ECacheState 3 = locally deleted, not yet synced.
return (db.prepare('SELECT ECacheOBJ AS v FROM ECacheObjects WHERE ECacheState != 3').all() as { v: string }[]).map((r) => r.v)
}
if (tables.has('folder_id')) {
return (db.prepare('SELECT vcard AS v FROM folder_id WHERE vcard IS NOT NULL').all() as { v: string }[]).map((r) => r.v)
}
return []
} finally {
db.close()
}
}
// Main "Contacts"-style books win over auto-generated ones like Nextcloud's
// server "Accounts" list or "Recently contacted".
function bookRank(src: BookSource): number {
const n = src.name.toLowerCase()
if (n === 'contacts' && src.account) return 0
if (n === 'personal') return 1
if (n === 'accounts') return 3
if (n.includes('recent')) return 4
return 2
}
// ---------- Directory ----------
interface Entry {
info: ContactInfo
photo?: PhotoRef
rank: number
}
export class ContactDirectory extends EventEmitter {
private byNumber = new Map<string, Entry>()
private all: ContactInfo[] = []
private watchers: fs.FSWatcher[] = []
private reloadTimer?: NodeJS.Timeout
async load(): Promise<void> {
const sources = (await listSources()).sort((a, b) => bookRank(a) - bookRank(b))
const byNumber = new Map<string, Entry>()
const all: ContactInfo[] = []
for (const src of sources) {
const file = bookDbPath(src)
if (!file) continue
let cards: string[]
try {
cards = readBook(file)
} catch (e) {
console.warn(`[contacts] couldn't read ${src.name}:`, (e as Error).message)
continue
}
const rank = bookRank(src)
for (const card of cards) {
const c = parseVCard(card)
if (!c.name || !c.tels.length) continue
for (const tel of c.tels) {
const existing = byNumber.get(tel.number)
if (!existing) {
const info: ContactInfo = { name: c.name, number: tel.number, label: tel.label, book: src.name }
byNumber.set(tel.number, { info, photo: c.photo, rank })
all.push(info)
} else if (!existing.photo && c.photo) {
// Borrow a photo from a lower-priority book for the same number.
existing.photo = c.photo
}
}
}
}
for (const e of byNumber.values()) if (e.photo) e.info.photo = photoUrl(e.info.number)
this.byNumber = byNumber
this.all = all.sort((a, b) => a.name.localeCompare(b.name))
this.watch(sources)
this.emit('changed')
}
private watch(sources: BookSource[]): void {
for (const w of this.watchers) w.close()
this.watchers = []
const files = sources.map(bookDbPath).filter((f): f is string => !!f)
// Only reload when a book's database actually changed (our own read-only
// opens can touch -shm files and would otherwise trigger reload loops).
const stamp = (): string =>
files.flatMap((f) => [f, f + '-wal']).map((f) => (fs.existsSync(f) ? fs.statSync(f).mtimeMs : 0)).join('/')
const last = stamp()
for (const file of files) {
try {
const w = fs.watch(path.dirname(file), () => {
clearTimeout(this.reloadTimer)
this.reloadTimer = setTimeout(() => {
if (stamp() !== last) void this.load()
}, 3000)
})
this.watchers.push(w)
} catch {
/* not fatal */
}
}
}
list(): ContactInfo[] {
return this.all
}
lookup(number: string): ContactInfo | undefined {
return this.byNumber.get(normalizeNumber(number))?.info
}
photoFor(number: string): PhotoRef | undefined {
return this.byNumber.get(normalizeNumber(number))?.photo
}
close(): void {
for (const w of this.watchers) w.close()
}
}
export function photoUrl(number: string): string {
return `contact-photo://n/${number}`
}
+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(' ')
}
+281
View File
@@ -0,0 +1,281 @@
import { app, BrowserWindow, dialog, ipcMain, net, protocol, safeStorage, shell } from 'electron'
import crypto from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { splitMessage, normalizeNumber } from '@shared/phone'
import type { Credentials, Did, Message, Settings } from '@shared/types'
import type { AppState } from '@shared/api'
import { ContactDirectory } from './contacts'
import { localDay, MessageDb, type NewMessage } from './db'
import { clearCredentials, loadCredentials, saveCredentials } from './secrets'
import { getDataDir, loadSettings, saveSettings, setDataDir } from './settings'
import { SyncEngine } from './sync'
import { VoipMs } from './voipms'
protocol.registerSchemesAsPrivileged([{ scheme: 'contact-photo', privileges: { standard: true, secure: true, supportFetchAPI: true } }])
if (!app.requestSingleInstanceLock()) app.quit()
let win: BrowserWindow | undefined
let db: MessageDb
let contacts: ContactDirectory
let settings: Settings
let api: VoipMs | undefined
let sync: SyncEngine | undefined
let dids: Did[] = []
const send = (channel: string, ...args: unknown[]): void => {
if (win && !win.isDestroyed()) win.webContents.send(channel, ...args)
}
function snapshotDir(): string {
return path.join(getDataDir(), 'snapshots')
}
async function dailySnapshot(): Promise<void> {
const today = path.join(snapshotDir(), `messages-${localDay()}.db`)
if (fs.existsSync(today)) return
try {
await db.snapshot(snapshotDir())
} catch (e) {
console.error('[snapshot] failed:', e)
}
}
function startSync(creds: Credentials): void {
sync?.stop()
api = new VoipMs(creds)
sync = new SyncEngine(db, api, settings)
sync.on('messages', (msgs: NewMessage[]) => {
send('messages', msgs)
send('conversationsChanged')
})
sync.on('status', (s) => send('syncStatus', s))
sync.start()
api
.getDids()
.then((d) => (dids = d))
.catch(() => undefined)
}
// ---- contact photos: contact-photo://n/<number> ----
async function servePhoto(req: Request): Promise<Response> {
const number = decodeURIComponent(new URL(req.url).pathname.slice(1))
const ref = contacts.photoFor(number)
if (!ref) return new Response(null, { status: 404 })
try {
if (ref.kind === 'inline') return new Response(Buffer.from(ref.data, 'base64'), { headers: { 'content-type': ref.mime } })
if (ref.kind === 'file') return await net.fetch(pathToFileURL(ref.path).toString())
// Remote photo URL: cache on disk so we only fetch it once.
const dir = path.join(app.getPath('userData'), 'photo-cache')
const file = path.join(dir, crypto.createHash('sha1').update(ref.url).digest('hex'))
if (!fs.existsSync(file)) {
if (fs.existsSync(file + '.missing')) return new Response(null, { status: 404 })
const res = await net.fetch(ref.url)
fs.mkdirSync(dir, { recursive: true })
if (!res.ok) {
fs.writeFileSync(file + '.missing', String(res.status))
return new Response(null, { status: 404 })
}
fs.writeFileSync(file, Buffer.from(await res.arrayBuffer()))
}
return new Response(fs.readFileSync(file), { headers: { 'content-type': 'image/jpeg' } })
} catch {
return new Response(null, { status: 404 })
}
}
// ---- sending ----
async function sendText(did: string, contact: string, text: string): Promise<void> {
if (!api) throw new Error('Not signed in')
const dst = normalizeNumber(contact)
const from = normalizeNumber(did)
let failed: Error | undefined
for (const part of splitMessage(text)) {
const tempId = db.insertPending({ did: from, contact: dst, direction: 'out', body: part, ts: Date.now() })
send('conversationsChanged')
try {
const realId = await api.sendSms(from, dst, part)
db.confirmPending(tempId, realId)
} catch (e) {
db.markFailed(tempId)
failed = e as Error
}
send('conversationsChanged')
if (failed) break
}
sync?.burst()
if (failed) throw failed
}
function registerIpc(): void {
ipcMain.handle('getState', async (): Promise<AppState> => {
const creds = loadCredentials()
if (api && !dids.length) dids = await api.getDids().catch(() => [])
if (process.env['VOIPMS_DEMO'] && !dids.length) dids = [{ did: '5415550100', description: 'Demo', smsEnabled: true }]
return {
// VOIPMS_DEMO: show the main UI without an account (for UI work on seeded data).
configured: !!creds || !!process.env['VOIPMS_DEMO'],
username: creds?.username,
settings,
dataDir: getDataDir(),
dids,
keyringBackend: safeBackend()
}
})
ipcMain.handle('testCredentials', async (_e, creds: Credentials) => {
dids = await new VoipMs(creds).getDids()
return dids
})
ipcMain.handle('saveSetup', (_e, creds: Credentials, s: Settings) => {
saveCredentials(creds)
settings = s
saveSettings(s)
startSync(creds)
})
ipcMain.handle('updateSettings', (_e, s: Settings) => {
const floorChanged = s.backfillFloor !== settings.backfillFloor
settings = s
saveSettings(s)
const creds = loadCredentials()
if (creds) startSync(creds)
if (floorChanged) sync?.resetBackfill()
})
ipcMain.handle('signOut', () => {
sync?.stop()
sync = undefined
api = undefined
clearCredentials()
})
ipcMain.handle('listContacts', () => contacts.list())
ipcMain.handle('listConversations', () => db.listConversations())
ipcMain.handle('getMessages', (_e, did: string, contact: string) => db.getConversationMessages(did, contact))
ipcMain.handle('markRead', (_e, did: string, contact: string) => {
db.markRead(did, contact)
send('conversationsChanged')
})
ipcMain.handle('search', (_e, q: string, scope?: { did: string; contact: string }) => db.search(q, scope))
ipcMain.handle('send', (_e, did: string, contact: string, text: string) => sendText(did, contact, text))
ipcMain.handle('deleteFailed', (_e, id: number) => {
db.deleteMessage(id)
send('conversationsChanged')
})
ipcMain.handle('retryFailed', async (_e, id: number) => {
const m: Message | undefined = db.getMessage(id)
if (!m || m.status !== 'failed') return
db.deleteMessage(id)
await sendText(m.did, m.contact, m.body)
})
ipcMain.handle('syncStatus', () => sync?.getStatus() ?? { phase: 'unconfigured', backfillDone: false, total: db.count() })
ipcMain.handle('pollNow', () => sync?.pollNow())
ipcMain.handle('openDataFolder', () => shell.openPath(getDataDir()))
ipcMain.handle('snapshotNow', () => db.snapshot(snapshotDir()))
ipcMain.handle('chooseDataDir', async () => {
const r = await dialog.showOpenDialog(win!, {
title: 'Choose where to keep your message history',
defaultPath: getDataDir(),
properties: ['openDirectory', 'createDirectory']
})
const dir = r.filePaths[0]
if (r.canceled || !dir || path.resolve(dir) === path.resolve(getDataDir())) return undefined
// Copy the database + settings to the new place, then restart there. If the
// folder already holds a history (e.g. restored from backup), use it as-is.
sync?.stop()
fs.mkdirSync(dir, { recursive: true })
if (!fs.existsSync(path.join(dir, 'messages.db'))) {
await db.db.backup(path.join(dir, 'messages.db'))
saveSettingsTo(dir)
}
setDataDir(dir)
app.relaunch()
app.exit(0)
return dir
})
}
function saveSettingsTo(dir: string): void {
fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify(settings, null, 2))
}
function safeBackend(): string {
try {
return safeStorage.getSelectedStorageBackend()
} catch {
return 'unknown'
}
}
function createWindow(): void {
win = new BrowserWindow({
width: 1180,
height: 800,
minWidth: 760,
minHeight: 480,
title: 'voip.ms Messages',
backgroundColor: '#1b1b1d',
autoHideMenuBar: true,
icon: path.join(__dirname, '../../resources/icon.png'),
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true,
sandbox: false,
nodeIntegration: false
}
})
win.webContents.setWindowOpenHandler(({ url }) => {
if (/^https?:/.test(url)) void shell.openExternal(url)
return { action: 'deny' }
})
win.webContents.on('will-navigate', (e, url) => {
if (url !== win!.webContents.getURL()) {
e.preventDefault()
if (/^https?:/.test(url)) void shell.openExternal(url)
}
})
if (process.env['ELECTRON_RENDERER_URL']) void win.loadURL(process.env['ELECTRON_RENDERER_URL'])
else void win.loadFile(path.join(__dirname, '../renderer/index.html'))
}
app.on('second-instance', () => {
if (win) {
if (win.isMinimized()) win.restore()
win.focus()
}
})
app.whenReady().then(async () => {
settings = loadSettings()
db = new MessageDb(path.join(getDataDir(), 'messages.db'))
contacts = new ContactDirectory()
contacts.on('changed', () => send('contactsChanged'))
protocol.handle('contact-photo', servePhoto)
registerIpc()
createWindow()
void contacts.load()
const creds = loadCredentials()
if (creds) startSync(creds)
void dailySnapshot()
setInterval(() => void dailySnapshot(), 60 * 60 * 1000)
})
let quitting = false
app.on('before-quit', (e) => {
if (quitting || !db) return
e.preventDefault()
quitting = true
sync?.stop()
contacts?.close()
db.snapshot(snapshotDir())
.catch((err) => console.error('[snapshot] on quit failed:', err))
.finally(() => {
db.close()
app.quit()
})
})
app.on('window-all-closed', () => app.quit())
+28
View File
@@ -0,0 +1,28 @@
// API credentials, encrypted with Electron safeStorage (GNOME Keyring/libsecret).
// Stored in Electron's userData dir, deliberately outside the backed-up data
// folder: the blob is useless without this machine's keyring anyway.
import { app, safeStorage } from 'electron'
import fs from 'node:fs'
import path from 'node:path'
import type { Credentials } from '@shared/types'
const file = (): string => path.join(app.getPath('userData'), 'credentials.bin')
export function loadCredentials(): Credentials | undefined {
try {
const blob = fs.readFileSync(file())
return JSON.parse(safeStorage.decryptString(blob)) as Credentials
} catch {
return undefined
}
}
export function saveCredentials(creds: Credentials): void {
if (!safeStorage.isEncryptionAvailable()) throw new Error('No system keyring available to store the API password securely.')
fs.mkdirSync(path.dirname(file()), { recursive: true })
fs.writeFileSync(file(), safeStorage.encryptString(JSON.stringify(creds)), { mode: 0o600 })
}
export function clearCredentials(): void {
fs.rmSync(file(), { force: true })
}
+52
View File
@@ -0,0 +1,52 @@
// Where the data lives + non-secret preferences.
//
// The message database defaults to ~/Documents/voipms-desktop-data so Déjà Dup
// backs it up (it excludes ~/.config, ~/.local and ~/.cache). A small pointer
// file in Electron's userData remembers a custom location if one is chosen.
import { app } from 'electron'
import fs from 'node:fs'
import path from 'node:path'
import type { Settings } from '@shared/types'
const DEFAULTS: Settings = {
pollSeconds: 30,
dids: [],
backfillFloor: '2010-01-01'
}
const pointerFile = (): string => path.join(app.getPath('userData'), 'data-location.json')
export function defaultDataDir(): string {
return path.join(app.getPath('documents'), 'voipms-desktop-data')
}
export function getDataDir(): string {
if (process.env['VOIPMS_DATA_DIR']) return process.env['VOIPMS_DATA_DIR']
try {
const { dataDir } = JSON.parse(fs.readFileSync(pointerFile(), 'utf8')) as { dataDir: string }
if (dataDir) return dataDir
} catch {
/* default */
}
return defaultDataDir()
}
export function setDataDir(dir: string): void {
fs.mkdirSync(path.dirname(pointerFile()), { recursive: true })
fs.writeFileSync(pointerFile(), JSON.stringify({ dataDir: dir }, null, 2))
}
const settingsFile = (): string => path.join(getDataDir(), 'settings.json')
export function loadSettings(): Settings {
try {
return { ...DEFAULTS, ...(JSON.parse(fs.readFileSync(settingsFile(), 'utf8')) as Partial<Settings>) }
} catch {
return { ...DEFAULTS }
}
}
export function saveSettings(s: Settings): void {
fs.mkdirSync(getDataDir(), { recursive: true })
fs.writeFileSync(settingsFile(), JSON.stringify(s, null, 2))
}
+172
View File
@@ -0,0 +1,172 @@
// History backfill + incremental polling against voip.ms.
import { EventEmitter } from 'node:events'
import type { MessageDb, NewMessage } from './db'
import { parseVoipDate, type RawSms, type VoipMs } from './voipms'
import { normalizeNumber } from '@shared/phone'
import type { SyncStatus } from '@shared/types'
const WINDOW_DAYS = 90
const PAGE_LIMIT = 10000
// Stop walking back after this many consecutive empty 90-day windows (~2 years).
const MAX_EMPTY_WINDOWS = 8
const DAY = 86_400_000
export function ymd(ms: number): string {
return new Date(ms).toISOString().slice(0, 10)
}
function parseYmd(s: string): number {
return Date.parse(s + 'T00:00:00Z')
}
export function toNewMessage(r: RawSms): NewMessage {
return {
id: Number(r.id),
did: normalizeNumber(r.did),
contact: normalizeNumber(r.contact),
direction: r.type === '1' ? 'in' : 'out',
body: r.message ?? '',
ts: parseVoipDate(r.date)
}
}
// Fetch every message in [from, to] (inclusive days), halving the range if a
// single call comes back full so nothing gets truncated.
export async function fetchRange(api: Pick<VoipMs, 'getSms'>, from: number, to: number, limit = PAGE_LIMIT): Promise<RawSms[]> {
const rows = await api.getSms({ from: ymd(from), to: ymd(to), limit })
if (rows.length < limit || to - from < DAY) return rows
const mid = from + Math.floor((to - from) / DAY / 2) * DAY
const a = await fetchRange(api, from, mid, limit)
const b = await fetchRange(api, mid + DAY, to, limit)
return [...a, ...b]
}
export interface SyncOptions {
pollSeconds: number
dids: string[] // empty = all
backfillFloor: string
}
export class SyncEngine extends EventEmitter {
private pollTimer?: NodeJS.Timeout
private burstUntil = 0
private running = false
private backfilling = false
private polling = false
private status: SyncStatus
constructor(
private db: MessageDb,
private api: VoipMs,
private opts: SyncOptions
) {
super()
this.status = {
phase: 'idle',
backfillDone: db.get('backfill_done') === '1',
backfillCursor: db.get('backfill_cursor'),
total: db.count()
}
}
getStatus(): SyncStatus {
return this.status
}
private setStatus(patch: Partial<SyncStatus>): void {
this.status = { ...this.status, ...patch, total: this.db.count() }
this.emit('status', this.status)
}
private store(raw: RawSms[]): void {
const wanted = new Set(this.opts.dids.map(normalizeNumber))
const msgs = raw.map(toNewMessage).filter((m) => wanted.size === 0 || wanted.has(m.did))
const added = this.db.upsertMessages(msgs)
if (added.length) this.emit('messages', added)
}
start(): void {
if (this.running) return
this.running = true
if (!this.db.get('unread_floor')) this.db.set('unread_floor', String(Date.now()))
void this.poll().finally(() => this.scheduleNextPoll())
if (!this.status.backfillDone) void this.backfill()
}
stop(): void {
this.running = false
clearTimeout(this.pollTimer)
}
// Poll faster for a couple of minutes (e.g. right after sending).
burst(): void {
this.burstUntil = Date.now() + 2 * 60_000
clearTimeout(this.pollTimer)
this.scheduleNextPoll(3000)
}
private scheduleNextPoll(delay?: number): void {
if (!this.running) return
const d = delay ?? (Date.now() < this.burstUntil ? 5000 : this.opts.pollSeconds * 1000)
this.pollTimer = setTimeout(() => {
void this.poll().finally(() => this.scheduleNextPoll())
}, d)
}
async pollNow(): Promise<void> {
await this.poll()
}
private async poll(): Promise<void> {
if (this.polling) return
this.polling = true
try {
const now = Date.now()
const rows = await this.api.getSms({ from: ymd(now - DAY), to: ymd(now + DAY), limit: PAGE_LIMIT })
this.store(rows)
this.setStatus({ lastPoll: Date.now(), error: undefined, phase: this.backfilling ? 'backfill' : 'polling' })
} catch (e) {
this.setStatus({ phase: 'error', error: (e as Error).message })
} finally {
this.polling = false
}
}
private async backfill(): Promise<void> {
if (this.backfilling) return
this.backfilling = true
this.setStatus({ phase: 'backfill' })
const floor = parseYmd(this.opts.backfillFloor)
let end = this.db.get('backfill_cursor') ? parseYmd(this.db.get('backfill_cursor')!) : parseYmd(ymd(Date.now() + DAY))
let empty = Number(this.db.get('backfill_empty') ?? 0)
try {
while (this.running && end >= floor && empty < MAX_EMPTY_WINDOWS) {
const start = Math.max(floor, end - (WINDOW_DAYS - 1) * DAY)
const rows = await fetchRange(this.api, start, end)
this.store(rows)
empty = rows.length ? 0 : empty + 1
end = start - DAY
this.db.set('backfill_cursor', ymd(end))
this.db.set('backfill_empty', String(empty))
this.setStatus({ phase: 'backfill', backfillCursor: ymd(end), error: undefined })
await new Promise((r) => setTimeout(r, 250))
}
if (this.running) {
this.db.set('backfill_done', '1')
this.setStatus({ phase: 'polling', backfillDone: true })
}
} catch (e) {
this.setStatus({ phase: 'error', error: (e as Error).message })
// Try again shortly; progress is saved so it resumes where it left off.
setTimeout(() => this.running && void this.backfill(), 30_000)
} finally {
this.backfilling = false
}
}
// Start the history import over (e.g. after changing the floor date).
resetBackfill(): void {
for (const k of ['backfill_cursor', 'backfill_empty', 'backfill_done']) this.db.db.prepare('DELETE FROM kv WHERE key = ?').run(k)
this.status.backfillDone = false
if (this.running) void this.backfill()
}
}
+85
View File
@@ -0,0 +1,85 @@
// Minimal voip.ms REST client. Docs: https://voip.ms/m/apidocs.php
import type { Credentials, Did } from '@shared/types'
const ENDPOINT = 'https://voip.ms/api/v1/rest.php'
export interface RawSms {
id: string
date: string // "YYYY-MM-DD HH:MM:SS" in the requested timezone (we ask for UTC)
type: string // "1" received, "0" sent
did: string
contact: string
message: string
}
const FRIENDLY_ERRORS: Record<string, string> = {
invalid_credentials: 'Invalid API username or password. Use the API password set under Main Menu → SOAP & REST/JSON API, not your login password.',
missing_credentials: 'Missing API username or password.',
ip_not_enabled: "This computer's IP address isn't allowed. Add it under Main Menu → SOAP & REST/JSON API → Enable IP Addresses.",
api_not_enabled: 'The API is not enabled on your voip.ms account. Enable it under Main Menu → SOAP & REST/JSON API.',
sms_toolong: 'Message is too long.',
invalid_dst: 'Invalid destination number.',
invalid_did: 'That DID is not valid on your account.',
sms_failed: 'voip.ms failed to send the message.'
}
export class VoipMsError extends Error {
constructor(public status: string) {
super(FRIENDLY_ERRORS[status] ?? `voip.ms error: ${status}`)
}
}
export class VoipMs {
constructor(private creds: Credentials) {}
private async call<T>(method: string, params: Record<string, string | number | undefined> = {}): Promise<T> {
const url = new URL(ENDPOINT)
url.searchParams.set('api_username', this.creds.username)
url.searchParams.set('api_password', this.creds.password)
url.searchParams.set('method', method)
for (const [k, v] of Object.entries(params)) {
if (v !== undefined && v !== '') url.searchParams.set(k, String(v))
}
const res = await fetch(url, { signal: AbortSignal.timeout(60_000) })
if (!res.ok) throw new Error(`voip.ms HTTP ${res.status}`)
const json = (await res.json()) as { status: string } & T
if (json.status !== 'success') throw new VoipMsError(json.status)
return json
}
async getDids(): Promise<Did[]> {
const r = await this.call<{ dids: Array<Record<string, string>> }>('getDIDsInfo')
return r.dids.map((d) => ({
did: d.did,
description: d.description ?? '',
smsEnabled: d.sms_enabled === '1'
}))
}
// Returns [] when voip.ms reports no messages for the range.
async getSms(opts: { from: string; to: string; did?: string; limit?: number }): Promise<RawSms[]> {
try {
const r = await this.call<{ sms: RawSms[] }>('getSMS', {
from: opts.from,
to: opts.to,
did: opts.did,
limit: opts.limit ?? 10000,
timezone: 0
})
return r.sms ?? []
} catch (e) {
if (e instanceof VoipMsError && e.status === 'no_sms') return []
throw e
}
}
async sendSms(did: string, dst: string, message: string): Promise<number> {
const r = await this.call<{ sms: number | string }>('sendSMS', { did, dst, message })
return Number(r.sms)
}
}
// "2024-01-02 03:04:05" (UTC) -> epoch ms
export function parseVoipDate(s: string): number {
return Date.parse(s.replace(' ', 'T') + 'Z')
}
+7
View File
@@ -0,0 +1,7 @@
import type { Api } from '../shared/api'
declare global {
interface Window {
api: Api
}
}
+38
View File
@@ -0,0 +1,38 @@
import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'
import type { Api } from '@shared/api'
function on<T extends unknown[]>(channel: string, cb: (...args: T) => void): () => void {
const listener = (_e: IpcRendererEvent, ...args: unknown[]): void => cb(...(args as T))
ipcRenderer.on(channel, listener)
return () => ipcRenderer.removeListener(channel, listener)
}
const api: Api = {
getState: () => ipcRenderer.invoke('getState'),
testCredentials: (creds) => ipcRenderer.invoke('testCredentials', creds),
saveSetup: (creds, settings) => ipcRenderer.invoke('saveSetup', creds, settings),
updateSettings: (settings) => ipcRenderer.invoke('updateSettings', settings),
signOut: () => ipcRenderer.invoke('signOut'),
listContacts: () => ipcRenderer.invoke('listContacts'),
listConversations: () => ipcRenderer.invoke('listConversations'),
getMessages: (did, contact) => ipcRenderer.invoke('getMessages', did, contact),
markRead: (did, contact) => ipcRenderer.invoke('markRead', did, contact),
search: (query, scope) => ipcRenderer.invoke('search', query, scope),
send: (did, contact, text) => ipcRenderer.invoke('send', did, contact, text),
deleteFailed: (id) => ipcRenderer.invoke('deleteFailed', id),
retryFailed: (id) => ipcRenderer.invoke('retryFailed', id),
syncStatus: () => ipcRenderer.invoke('syncStatus'),
pollNow: () => ipcRenderer.invoke('pollNow'),
openDataFolder: () => ipcRenderer.invoke('openDataFolder'),
snapshotNow: () => ipcRenderer.invoke('snapshotNow'),
chooseDataDir: () => ipcRenderer.invoke('chooseDataDir'),
onMessages: (cb) => on('messages', cb),
onConversationsChanged: (cb) => on('conversationsChanged', cb),
onSyncStatus: (cb) => on('syncStatus', cb),
onContactsChanged: (cb) => on('contactsChanged', cb)
}
contextBridge.exposeInMainWorld('api', api)
+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>voip.ms Messages</title>
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: contact-photo:; connect-src 'self' ws://localhost:*"
/>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+138
View File
@@ -0,0 +1,138 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import type { AppState } from '@shared/api'
import type { ContactInfo, Conversation, SyncStatus } from '@shared/types'
import { Sidebar, type SidebarMode } from './components/Sidebar'
import { ChatView } from './components/ChatView'
import { Setup } from './components/Setup'
import { SettingsDialog } from './components/SettingsDialog'
export interface ConvKey {
did: string
contact: string
}
export interface Jump {
id: number
nonce: number
}
export const sameConv = (a?: ConvKey | null, b?: ConvKey | null): boolean =>
!!a && !!b && a.did === b.did && a.contact === b.contact
export function App() {
const [state, setState] = useState<AppState>()
const [contacts, setContacts] = useState<ContactInfo[]>([])
const [conversations, setConversations] = useState<Conversation[]>([])
const [selected, setSelected] = useState<ConvKey | null>(null)
const [jump, setJump] = useState<Jump>()
const [mode, setMode] = useState<SidebarMode>('chats')
const [query, setQuery] = useState('')
const [sync, setSync] = useState<SyncStatus>()
const [settingsOpen, setSettingsOpen] = useState(false)
const [msgVersion, setMsgVersion] = useState(0)
const refreshState = useCallback(() => void window.api.getState().then(setState), [])
const refreshConversations = useCallback(() => {
void window.api.listConversations().then(setConversations)
setMsgVersion((v) => v + 1)
}, [])
const refreshContacts = useCallback(() => void window.api.listContacts().then(setContacts), [])
useEffect(() => {
refreshState()
refreshConversations()
refreshContacts()
void window.api.syncStatus().then(setSync)
const offs = [
window.api.onConversationsChanged(refreshConversations),
window.api.onContactsChanged(refreshContacts),
window.api.onSyncStatus(setSync)
]
return () => offs.forEach((off) => off())
}, [refreshState, refreshConversations, refreshContacts])
const contactMap = useMemo(() => new Map(contacts.map((c) => [c.number, c])), [contacts])
const smsDids = useMemo(() => {
const all = state?.dids.filter((d) => d.smsEnabled) ?? []
const chosen = state?.settings.dids ?? []
return chosen.length ? all.filter((d) => chosen.includes(d.did)) : all
}, [state])
const open = useCallback((key: ConvKey, jumpTo?: number) => {
setSelected(key)
setJump(jumpTo !== undefined ? { id: jumpTo, nonce: Date.now() } : undefined)
}, [])
// Keyboard shortcuts (Signal-like).
useEffect(() => {
const onKey = (e: KeyboardEvent): void => {
const mod = e.ctrlKey || e.metaKey
if (mod && !e.shiftKey && e.key.toLowerCase() === 'f') {
e.preventDefault()
setMode('search')
document.getElementById('sidebar-search')?.focus()
} else if (mod && e.key.toLowerCase() === 'n') {
e.preventDefault()
setMode('compose')
} else if (e.altKey && (e.key === 'ArrowDown' || e.key === 'ArrowUp') && conversations.length) {
e.preventDefault()
const i = conversations.findIndex((c) => sameConv(c, selected))
const next = e.key === 'ArrowDown' ? Math.min(conversations.length - 1, i + 1) : Math.max(0, i - 1)
open(conversations[i < 0 ? 0 : next])
}
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [conversations, selected, open])
if (!state) return <div className="app loading" />
if (!state.configured) return <Setup initial={state} onDone={refreshState} />
return (
<div className="app">
<Sidebar
mode={mode}
setMode={setMode}
query={query}
setQuery={setQuery}
conversations={conversations}
contacts={contacts}
contactMap={contactMap}
selected={selected}
onOpen={open}
sync={sync}
multiDid={smsDids.length > 1}
defaultDid={state.settings.defaultDid ?? smsDids[0]?.did}
onSettings={() => setSettingsOpen(true)}
/>
{selected ? (
<ChatView
key={`${selected.did}:${selected.contact}`}
conv={selected}
contact={contactMap.get(selected.contact)}
jump={jump}
highlight={mode === 'search' ? query : ''}
version={msgVersion}
smsDids={smsDids}
onChangeDid={(did) => setSelected({ ...selected, did })}
/>
) : (
<main className="chat empty">
<div className="empty-hint">
<div className="empty-title">voip.ms Messages</div>
<div>Pick a conversation, or press Ctrl+N to start a new one.</div>
</div>
</main>
)}
{settingsOpen && (
<SettingsDialog
state={state}
sync={sync}
onClose={() => setSettingsOpen(false)}
onChanged={refreshState}
/>
)}
</div>
)
}
+26
View File
@@ -0,0 +1,26 @@
import { useState } from 'react'
import type { ContactInfo } from '@shared/types'
import { avatarColors, initials } from '../format'
export function Avatar({ number, contact, size = 40 }: { number: string; contact?: ContactInfo; size?: number }) {
const [broken, setBroken] = useState<string>()
const { bg, fg } = avatarColors(contact?.name ?? number)
const style = { width: size, height: size, fontSize: size * 0.4, background: bg, color: fg }
if (contact?.photo && broken !== contact.photo) {
return (
<div className="avatar" style={style}>
<img src={contact.photo} alt="" draggable={false} onError={() => setBroken(contact.photo)} />
</div>
)
}
const text = contact ? initials(contact.name) : ''
return (
<div className="avatar" style={style}>
{text || (
<svg viewBox="0 0 24 24" width={size * 0.55} height={size * 0.55} fill="currentColor" aria-hidden>
<path d="M12 12a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9Zm0 2c-4.4 0-8 2.2-8 5v1.5h16V19c0-2.8-3.6-5-8-5Z" />
</svg>
)}
</div>
)
}
+244
View File
@@ -0,0 +1,244 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Virtuoso, type VirtuosoHandle } from 'react-virtuoso'
import { formatNumber } from '@shared/phone'
import type { ContactInfo, Did, Message, SearchHit } from '@shared/types'
import type { ConvKey, Jump } from '../App'
import { dayLabel, displayName, sameDay } from '../format'
import { Avatar } from './Avatar'
import { Composer } from './Composer'
import { CloseIcon, DownIcon, SearchIcon, UpIcon } from './Icons'
import { MessageBubble } from './MessageBubble'
type Row = { kind: 'day'; key: string; ts: number } | { kind: 'msg'; key: string; m: Message; groupStart: boolean; groupEnd: boolean }
const GROUP_GAP = 5 * 60_000
function buildRows(msgs: Message[]): Row[] {
const rows: Row[] = []
msgs.forEach((m, i) => {
const prev = msgs[i - 1]
const next = msgs[i + 1]
const newDay = !prev || !sameDay(prev.ts, m.ts)
if (newDay) rows.push({ kind: 'day', key: `d${m.ts}`, ts: m.ts })
const groupStart = newDay || prev.direction !== m.direction || m.ts - prev.ts > GROUP_GAP
const groupEnd = !next || !sameDay(m.ts, next.ts) || next.direction !== m.direction || next.ts - m.ts > GROUP_GAP
rows.push({ kind: 'msg', key: String(m.id), m, groupStart, groupEnd })
})
return rows
}
interface Props {
conv: ConvKey
contact?: ContactInfo
jump?: Jump
highlight: string
version: number
smsDids: Did[]
onChangeDid: (did: string) => void
}
export function ChatView({ conv, contact, jump, highlight, version, smsDids, onChangeDid }: Props) {
const [messages, setMessages] = useState<Message[]>()
const [flashId, setFlashId] = useState<number>()
const [searchOpen, setSearchOpen] = useState(false)
const [q, setQ] = useState('')
const [hits, setHits] = useState<SearchHit[]>([])
const [hitIdx, setHitIdx] = useState(0)
const virtuoso = useRef<VirtuosoHandle>(null)
const searchInput = useRef<HTMLInputElement>(null)
// Load (and reload on any change) the whole conversation.
useEffect(() => {
let cancelled = false
void window.api.getMessages(conv.did, conv.contact).then((m) => {
if (cancelled) return
setMessages(m)
if (document.hasFocus()) void window.api.markRead(conv.did, conv.contact)
})
return () => {
cancelled = true
}
}, [conv.did, conv.contact, version])
useEffect(() => {
const onFocus = (): void => void window.api.markRead(conv.did, conv.contact)
window.addEventListener('focus', onFocus)
return () => window.removeEventListener('focus', onFocus)
}, [conv.did, conv.contact])
const rows = useMemo(() => buildRows(messages ?? []), [messages])
const indexOf = useCallback((id: number) => rows.findIndex((r) => r.kind === 'msg' && r.m.id === id), [rows])
const flash = useCallback((id: number) => {
setFlashId(id)
setTimeout(() => setFlashId((cur) => (cur === id ? undefined : cur)), 2200)
}, [])
const scrollTo = useCallback(
(id: number) => {
const index = indexOf(id)
if (index < 0) return
virtuoso.current?.scrollToIndex({ index, align: 'center' })
flash(id)
},
[indexOf, flash]
)
// Jump requests from the sidebar search (including repeat clicks).
const initialJump = useRef(jump)
useEffect(() => {
if (!jump || !messages) return
if (jump === initialJump.current) {
flash(jump.id) // initial mount already positioned us
initialJump.current = undefined
return
}
scrollTo(jump.id)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [jump, messages !== undefined])
// ---- in-chat search ----
useEffect(() => {
if (!searchOpen || !q.trim()) {
setHits([])
return
}
let cancelled = false
const t = setTimeout(() => {
void window.api.search(q, conv).then((h) => {
if (cancelled) return
setHits(h)
setHitIdx(0)
if (h[0]) scrollTo(h[0].id)
})
}, 200)
return () => {
cancelled = true
clearTimeout(t)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [q, searchOpen])
const stepHit = (dir: 1 | -1): void => {
if (!hits.length) return
const next = (hitIdx + dir + hits.length) % hits.length
setHitIdx(next)
scrollTo(hits[next].id)
}
const openSearch = (): void => {
setSearchOpen(true)
setTimeout(() => searchInput.current?.focus(), 0)
}
useEffect(() => {
const onKey = (e: KeyboardEvent): void => {
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === 'f') {
e.preventDefault()
openSearch()
}
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [])
const mark = searchOpen && q.trim() ? q : highlight
const isNew = messages !== undefined && messages.length === 0
const initialIndex = jump && messages ? Math.max(0, indexOf(jump.id)) : rows.length - 1
return (
<main className="chat">
<header className="chat-header">
<Avatar number={conv.contact} contact={contact} size={36} />
<div className="chat-title">
<div className="chat-name">{displayName(conv.contact, contact)}</div>
<div className="chat-sub">
{contact ? formatNumber(conv.contact) : ''}
{smsDids.length > 1 && (
<span className="chat-via">
{contact ? ' · ' : ''}via {formatNumber(conv.did)}
</span>
)}
</div>
</div>
<button className="icon-btn" title="Search in chat (Ctrl+Shift+F)" onClick={openSearch}>
<SearchIcon />
</button>
</header>
{searchOpen && (
<div className="chat-search">
<SearchIcon size={16} />
<input
ref={searchInput}
value={q}
placeholder={`Search in ${displayName(conv.contact, contact)}`}
onChange={(e) => setQ(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') stepHit(e.shiftKey ? -1 : 1)
else if (e.key === 'Escape') {
setSearchOpen(false)
setQ('')
}
}}
/>
<span className="hit-count">{q.trim() ? (hits.length ? `${hitIdx + 1} of ${hits.length}` : 'No results') : ''}</span>
<button className="icon-btn small" title="Older (Enter)" disabled={!hits.length} onClick={() => stepHit(1)}>
<UpIcon />
</button>
<button className="icon-btn small" title="Newer (Shift+Enter)" disabled={!hits.length} onClick={() => stepHit(-1)}>
<DownIcon />
</button>
<button
className="icon-btn small"
title="Close"
onClick={() => {
setSearchOpen(false)
setQ('')
}}
>
<CloseIcon />
</button>
</div>
)}
<div className="messages">
{messages === undefined ? null : isNew ? (
<div className="new-conv">
<Avatar number={conv.contact} contact={contact} size={80} />
<div className="new-conv-name">{displayName(conv.contact, contact)}</div>
{contact && <div className="new-conv-sub">{formatNumber(conv.contact)}</div>}
</div>
) : (
<Virtuoso
ref={virtuoso}
data={rows}
className="message-scroller"
computeItemKey={(_, r) => r.key}
initialTopMostItemIndex={{ index: initialIndex, align: jump ? 'center' : 'end' }}
followOutput={(atBottom) => (atBottom ? 'smooth' : false)}
alignToBottom
increaseViewportBy={{ top: 800, bottom: 800 }}
itemContent={(_, r) =>
r.kind === 'day' ? (
<div className="day-sep">
<span>{dayLabel(r.ts)}</span>
</div>
) : (
<MessageBubble
m={r.m}
groupStart={r.groupStart}
groupEnd={r.groupEnd}
flash={flashId === r.m.id}
highlight={mark}
/>
)
}
/>
)}
</div>
<Composer conv={conv} isNew={isNew} smsDids={smsDids} onChangeDid={onChangeDid} />
</main>
)
}
+92
View File
@@ -0,0 +1,92 @@
import { useEffect, useRef, useState } from 'react'
import { formatNumber, splitMessage } from '@shared/phone'
import type { Did } from '@shared/types'
import type { ConvKey } from '../App'
import { SendIcon } from './Icons'
// Drafts survive switching conversations (not app restarts).
const drafts = new Map<string, string>()
interface Props {
conv: ConvKey
isNew: boolean
smsDids: Did[]
onChangeDid: (did: string) => void
}
export function Composer({ conv, isNew, smsDids, onChangeDid }: Props) {
const key = conv.contact
const [text, setText] = useState(() => drafts.get(key) ?? '')
const [error, setError] = useState<string>()
const ref = useRef<HTMLTextAreaElement>(null)
useEffect(() => {
ref.current?.focus()
}, [])
useEffect(() => {
drafts.set(key, text)
const el = ref.current
if (el) {
el.style.height = 'auto'
el.style.height = `${Math.min(el.scrollHeight, 200)}px`
}
}, [text, key])
const submit = (): void => {
const body = text.trim()
if (!body) return
setText('')
setError(undefined)
window.api.send(conv.did, conv.contact, body).catch((e: Error) => setError(e.message.replace(/^Error invoking remote method '\w+': (Error: )?/, '')))
}
const len = [...text.trim()].length
const parts = len ? splitMessage(text).length : 0
return (
<footer className="composer">
{error && (
<div className="composer-error" onClick={() => setError(undefined)}>
{error}
</div>
)}
{isNew && smsDids.length > 1 && (
<label className="from-picker">
From
<select value={conv.did} onChange={(e) => onChangeDid(e.target.value)}>
{smsDids.map((d) => (
<option key={d.did} value={d.did}>
{formatNumber(d.did)}
{d.description ? ` — ${d.description}` : ''}
</option>
))}
</select>
</label>
)}
<div className="composer-row">
<textarea
ref={ref}
rows={1}
value={text}
placeholder="Message"
onChange={(e) => setText(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault()
submit()
}
}}
/>
{len > 0 && (
<span className={`counter${parts > 1 ? ' multi' : ''}`} title="voip.ms sends up to 160 characters per message">
{parts > 1 ? `${parts} msgs` : `${len}/160`}
</span>
)}
<button className="send-btn" title="Send (Enter)" disabled={!len} onClick={submit}>
<SendIcon />
</button>
</div>
</footer>
)
}
@@ -0,0 +1,75 @@
import { memo, useEffect, useState } from 'react'
import { Virtuoso } from 'react-virtuoso'
import { formatNumber } from '@shared/phone'
import type { ContactInfo, Conversation } from '@shared/types'
import { sameConv, type ConvKey } from '../App'
import { displayName, shortTime } from '../format'
import { Avatar } from './Avatar'
interface Props {
conversations: Conversation[]
contactMap: Map<string, ContactInfo>
selected: ConvKey | null
multiDid: boolean
onOpen: (key: ConvKey) => void
}
export function ConversationList({ conversations, contactMap, selected, multiDid, onOpen }: Props) {
// Re-render every minute so relative times ("5m") stay fresh.
const [, tick] = useState(0)
useEffect(() => {
const t = setInterval(() => tick((n) => n + 1), 60_000)
return () => clearInterval(t)
}, [])
if (!conversations.length) return <div className="list-empty">No conversations yet.</div>
return (
<Virtuoso
className="conv-list"
data={conversations}
computeItemKey={(_, c) => `${c.did}:${c.contact}`}
itemContent={(_, c) => (
<ConversationRow
conv={c}
contact={contactMap.get(c.contact)}
active={sameConv(c, selected)}
multiDid={multiDid}
onOpen={onOpen}
/>
)}
/>
)
}
const ConversationRow = memo(function ConversationRow({
conv,
contact,
active,
multiDid,
onOpen
}: {
conv: Conversation
contact?: ContactInfo
active: boolean
multiDid: boolean
onOpen: (key: ConvKey) => void
}) {
const preview = (conv.lastDirection === 'out' ? 'You: ' : '') + conv.lastBody.replace(/\s+/g, ' ')
return (
<button className={`row${active ? ' active' : ''}${conv.unread ? ' unread' : ''}`} onClick={() => onOpen(conv)}>
<Avatar number={conv.contact} contact={contact} size={48} />
<div className="row-main">
<div className="row-top">
<span className="row-name">{displayName(conv.contact, contact)}</span>
<span className="row-time">{shortTime(conv.lastTs)}</span>
</div>
<div className="row-bottom">
<span className="row-preview">{preview}</span>
{conv.unread > 0 && <span className="badge">{conv.unread > 99 ? '99+' : conv.unread}</span>}
</div>
{multiDid && <div className="row-via">via {formatNumber(conv.did)}</div>}
</div>
</button>
)
})
+58
View File
@@ -0,0 +1,58 @@
// Small inline icons (stroke style, inherit currentColor).
const base = { width: 20, height: 20, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round' } as const
export const ComposeIcon = () => (
<svg {...base}>
<path d="M12 20h9" />
<path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" />
</svg>
)
export const SearchIcon = ({ size = 20 }: { size?: number }) => (
<svg {...base} width={size} height={size}>
<circle cx="11" cy="11" r="7" />
<path d="m20 20-3.5-3.5" />
</svg>
)
export const GearIcon = () => (
<svg {...base}>
<circle cx="12" cy="12" r="3" />
<path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z" />
</svg>
)
export const CloseIcon = ({ size = 18 }: { size?: number }) => (
<svg {...base} width={size} height={size}>
<path d="M18 6 6 18M6 6l12 12" />
</svg>
)
export const BackIcon = () => (
<svg {...base}>
<path d="M15 18l-6-6 6-6" />
</svg>
)
export const UpIcon = () => (
<svg {...base} width={18} height={18}>
<path d="m18 15-6-6-6 6" />
</svg>
)
export const DownIcon = () => (
<svg {...base} width={18} height={18}>
<path d="m6 9 6 6 6-6" />
</svg>
)
export const SendIcon = () => (
<svg width={20} height={20} viewBox="0 0 24 24" fill="currentColor">
<path d="M3.4 20.4 21 12 3.4 3.6 3.4 10l12.6 2-12.6 2z" />
</svg>
)
export const ClockIcon = () => (
<svg {...base} width={12} height={12} strokeWidth={2.2}>
<circle cx="12" cy="12" r="9" />
<path d="M12 7v5l3 2" />
</svg>
)
export const AlertIcon = () => (
<svg {...base} width={14} height={14} strokeWidth={2.2}>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v5M12 16h.01" />
</svg>
)
@@ -0,0 +1,70 @@
import { memo, type ReactNode } from 'react'
import type { Message } from '@shared/types'
import { highlightChunks, timeOfDay } from '../format'
import { AlertIcon, ClockIcon } from './Icons'
const URL_RE = /\b((?:https?:\/\/|www\.)[^\s<>"']+[^\s<>"'.,;:!?)\]])/gi
function renderText(text: string, highlight: string): ReactNode[] {
const out: ReactNode[] = []
let key = 0
const pushHighlighted = (s: string): void => {
for (const c of highlightChunks(s, highlight)) out.push(c.hit ? <mark key={key++}>{c.text}</mark> : c.text)
}
let last = 0
for (const m of text.matchAll(URL_RE)) {
if (m.index! > last) pushHighlighted(text.slice(last, m.index))
const href = m[0].startsWith('www.') ? `https://${m[0]}` : m[0]
out.push(
<a key={key++} href={href} target="_blank" rel="noreferrer">
{m[0]}
</a>
)
last = m.index! + m[0].length
}
if (last < text.length) pushHighlighted(text.slice(last))
return out
}
interface Props {
m: Message
groupStart: boolean
groupEnd: boolean
flash: boolean
highlight: string
}
export const MessageBubble = memo(function MessageBubble({ m, groupStart, groupEnd, flash, highlight }: Props) {
const cls = [
'msg',
m.direction,
groupStart ? 'g-start' : '',
groupEnd ? 'g-end' : '',
flash ? 'flash' : '',
m.status === 'failed' ? 'failed' : ''
]
.filter(Boolean)
.join(' ')
return (
<div className={cls} data-id={m.id}>
<div className="bubble" title={new Date(m.ts).toLocaleString()}>
<span className="text">{renderText(m.body, highlight)}</span>
<span className="meta">
{timeOfDay(m.ts)}
{m.status === 'pending' && (
<span className="status" title="Sending…">
<ClockIcon />
</span>
)}
</span>
</div>
{m.status === 'failed' && (
<div className="failed-row">
<AlertIcon /> Not sent ·
<button onClick={() => void window.api.retryFailed(m.id).catch(() => undefined)}>Retry</button>·
<button onClick={() => void window.api.deleteFailed(m.id)}>Delete</button>
</div>
)}
</div>
)
})
+110
View File
@@ -0,0 +1,110 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { formatNumber, normalizeNumber } from '@shared/phone'
import type { ContactInfo, Conversation } from '@shared/types'
import type { ConvKey } from '../App'
import { Avatar } from './Avatar'
import { BackIcon } from './Icons'
import { matchesContact } from './SearchResults'
interface Props {
contacts: ContactInfo[]
conversations: Conversation[]
defaultDid?: string
onPick: (key: ConvKey) => void
onCancel: () => void
}
export function NewChat({ contacts, conversations, defaultDid, onPick, onCancel }: Props) {
const [q, setQ] = useState('')
const [cursor, setCursor] = useState(0)
const inputRef = useRef<HTMLInputElement>(null)
const listRef = useRef<HTMLDivElement>(null)
useEffect(() => inputRef.current?.focus(), [])
// Most recently used contacts first, then alphabetical.
const recency = useMemo(() => {
const m = new Map<string, number>()
for (const c of conversations) m.set(c.contact, Math.max(m.get(c.contact) ?? 0, c.lastTs))
return m
}, [conversations])
const matches = useMemo(() => {
const list = q.trim() ? contacts.filter((c) => matchesContact(q, c.name, c.number)) : contacts
return [...list].sort((a, b) => (recency.get(b.number) ?? 0) - (recency.get(a.number) ?? 0) || a.name.localeCompare(b.name)).slice(0, 100)
}, [q, contacts, recency])
const typed = normalizeNumber(q)
const typedIsNumber = /^[\d\s()+.-]+$/.test(q.trim()) && (typed.length === 10 || (typed.length >= 3 && typed.length <= 6))
const options: Array<{ number: string; contact?: ContactInfo }> = [
...(typedIsNumber && !matches.some((m) => m.number === typed) ? [{ number: typed }] : []),
...matches.map((c) => ({ number: c.number, contact: c }))
]
useEffect(() => setCursor(0), [q])
useEffect(() => {
listRef.current?.querySelector<HTMLElement>(`[data-i="${cursor}"]`)?.scrollIntoView({ block: 'nearest' })
}, [cursor])
const pick = (number: string): void => {
if (!defaultDid) return
// Reuse an existing conversation with this person if there is one.
const existing = conversations.find((c) => c.contact === number)
onPick({ did: existing?.did ?? defaultDid, contact: number })
}
return (
<>
<header className="sidebar-header compose">
<button className="icon-btn" title="Back" onClick={onCancel}>
<BackIcon />
</button>
<span className="compose-title">New chat</span>
</header>
<div className="to-field">
<span>To:</span>
<input
ref={inputRef}
value={q}
placeholder="Name or number"
onChange={(e) => setQ(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Escape') onCancel()
else if (e.key === 'ArrowDown') {
e.preventDefault()
setCursor((c) => Math.min(options.length - 1, c + 1))
} else if (e.key === 'ArrowUp') {
e.preventDefault()
setCursor((c) => Math.max(0, c - 1))
} else if (e.key === 'Enter' && options[cursor]) pick(options[cursor].number)
}}
/>
</div>
{!defaultDid && <div className="list-empty">No SMS-enabled number to send from. Check Settings.</div>}
<div className="sidebar-body search-results" ref={listRef}>
{options.map((o, i) => (
<button
key={o.number + (o.contact ? '' : ':typed')}
data-i={i}
className={`row${i === cursor ? ' active' : ''}`}
onMouseEnter={() => setCursor(i)}
onClick={() => pick(o.number)}
>
<Avatar number={o.number} contact={o.contact} size={40} />
<div className="row-main">
<div className="row-top">
<span className="row-name">{o.contact?.name ?? formatNumber(o.number)}</span>
</div>
<div className="row-bottom">
<span className="row-preview">
{o.contact ? formatNumber(o.number) + (o.contact.label ? ` · ${o.contact.label}` : '') : 'Send to this number'}
</span>
</div>
</div>
</button>
))}
{q && !options.length && <div className="list-empty">No matching contacts. Type a 10-digit number.</div>}
</div>
</>
)
}
@@ -0,0 +1,143 @@
import { useEffect, useMemo, useState } from 'react'
import { formatNumber } from '@shared/phone'
import { SNIPPET_END, SNIPPET_START, type ContactInfo, type Conversation, type SearchHit } from '@shared/types'
import type { ConvKey } from '../App'
import { displayName, shortTime } from '../format'
import { Avatar } from './Avatar'
interface Props {
query: string
conversations: Conversation[]
contacts: ContactInfo[]
contactMap: Map<string, ContactInfo>
defaultDid?: string
onOpen: (key: ConvKey, jumpTo?: number) => void
}
export function matchesContact(query: string, name: string, number: string): boolean {
const q = query.trim().toLowerCase()
if (!q) return false
const digits = q.replace(/\D/g, '')
if (digits.length >= 3 && /^[\d\s()+.-]+$/.test(q) && number.includes(digits.replace(/^1(?=\d{10}$)/, ''))) return true
const n = name.toLowerCase()
return q.split(/\s+/).every((w) => n.split(/\s+/).some((part) => part.startsWith(w)) || n.includes(w))
}
export function SearchResults({ query, conversations, contacts, contactMap, defaultDid, onOpen }: Props) {
const [hits, setHits] = useState<SearchHit[]>([])
const [activeId, setActiveId] = useState<number>()
useEffect(() => {
let cancelled = false
const t = setTimeout(() => {
void window.api.search(query).then((h) => !cancelled && setHits(h))
}, 150)
return () => {
cancelled = true
clearTimeout(t)
}
}, [query])
const chats = useMemo(
() => conversations.filter((c) => matchesContact(query, contactMap.get(c.contact)?.name ?? '', c.contact)).slice(0, 8),
[query, conversations, contactMap]
)
const otherContacts = useMemo(() => {
const inChats = new Set(conversations.map((c) => c.contact))
return contacts.filter((c) => !inChats.has(c.number) && matchesContact(query, c.name, c.number)).slice(0, 8)
}, [query, contacts, conversations])
if (!chats.length && !otherContacts.length && !hits.length) {
return <div className="list-empty">No results for “{query}”</div>
}
return (
<div className="search-results">
{chats.length > 0 && <div className="section-label">Chats</div>}
{chats.map((c) => {
const contact = contactMap.get(c.contact)
return (
<button key={`${c.did}:${c.contact}`} className="row" onClick={() => onOpen(c)}>
<Avatar number={c.contact} contact={contact} size={40} />
<div className="row-main">
<div className="row-top">
<span className="row-name">{displayName(c.contact, contact)}</span>
</div>
<div className="row-bottom">
<span className="row-preview">{formatNumber(c.contact)}</span>
</div>
</div>
</button>
)
})}
{otherContacts.length > 0 && <div className="section-label">Contacts</div>}
{otherContacts.map((c) => (
<button
key={c.number}
className="row"
disabled={!defaultDid}
onClick={() => defaultDid && onOpen({ did: defaultDid, contact: c.number })}
>
<Avatar number={c.number} contact={c} size={40} />
<div className="row-main">
<div className="row-top">
<span className="row-name">{c.name}</span>
</div>
<div className="row-bottom">
<span className="row-preview">
{formatNumber(c.number)}
{c.label ? ` · ${c.label}` : ''}
</span>
</div>
</div>
</button>
))}
{hits.length > 0 && (
<div className="section-label">
Messages <span className="count">{hits.length >= 300 ? '300+' : hits.length}</span>
</div>
)}
{hits.map((h) => {
const contact = contactMap.get(h.contact)
return (
<button
key={h.id}
className={`row hit${activeId === h.id ? ' active' : ''}`}
onClick={() => {
setActiveId(h.id)
onOpen({ did: h.did, contact: h.contact }, h.id)
}}
>
<Avatar number={h.contact} contact={contact} size={40} />
<div className="row-main">
<div className="row-top">
<span className="row-name">{displayName(h.contact, contact)}</span>
<span className="row-time">{shortTime(h.ts)}</span>
</div>
<div className="row-snippet">
{h.direction === 'out' && <span className="you">You: </span>}
<Snippet text={h.snippet} />
</div>
</div>
</button>
)
})}
</div>
)
}
function Snippet({ text }: { text: string }) {
const parts: React.ReactNode[] = []
const re = new RegExp(`${SNIPPET_START}([\\s\\S]*?)${SNIPPET_END}`, 'g')
let last = 0
let i = 0
for (const m of text.matchAll(re)) {
if (m.index! > last) parts.push(text.slice(last, m.index))
parts.push(<mark key={i++}>{m[1]}</mark>)
last = m.index! + m[0].length
}
if (last < text.length) parts.push(text.slice(last))
return <>{parts}</>
}
@@ -0,0 +1,148 @@
import { useEffect, useState } from 'react'
import type { AppState } from '@shared/api'
import { formatNumber } from '@shared/phone'
import type { Settings, SyncStatus } from '@shared/types'
import { CloseIcon } from './Icons'
interface Props {
state: AppState
sync?: SyncStatus
onClose: () => void
onChanged: () => void
}
export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
const [s, setS] = useState<Settings>(state.settings)
const [note, setNote] = useState<string>()
const smsDids = state.dids.filter((d) => d.smsEnabled)
const dirty = JSON.stringify(s) !== JSON.stringify(state.settings)
useEffect(() => {
const onKey = (e: KeyboardEvent): void => {
if (e.key === 'Escape') onClose()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const save = async (): Promise<void> => {
await window.api.updateSettings(s)
onChanged()
onClose()
}
const synced = s.dids.length ? s.dids : smsDids.map((d) => d.did)
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal" role="dialog" aria-label="Settings">
<header>
<h2>Settings</h2>
<button className="icon-btn" onClick={onClose} title="Close">
<CloseIcon />
</button>
</header>
<section>
<h3>Account</h3>
<div className="kv">
<span>voip.ms user</span>
<span>{state.username}</span>
</div>
<div className="kv">
<span>Messages stored</span>
<span>{sync?.total.toLocaleString() ?? '—'}</span>
</div>
<div className="kv">
<span>History import</span>
<span>{sync?.backfillDone ? 'Complete' : sync?.backfillCursor ? `In progress (back to ${sync.backfillCursor})` : 'Pending'}</span>
</div>
<div className="kv">
<span>Password stored in</span>
<span>{state.keyringBackend.startsWith('gnome') || state.keyringBackend.includes('libsecret') ? 'GNOME Keyring' : state.keyringBackend}</span>
</div>
<button
className="danger"
onClick={() => {
void window.api.signOut().then(onChanged)
}}
>
Sign out
</button>
</section>
{smsDids.length > 0 && (
<section>
<h3>Numbers</h3>
{smsDids.map((d) => (
<label key={d.did} className="did">
<input
type="checkbox"
checked={synced.includes(d.did)}
onChange={(e) => {
const next = e.target.checked ? [...synced, d.did] : synced.filter((x) => x !== d.did)
setS({ ...s, dids: next.length === smsDids.length ? [] : next })
}}
/>
<span>{formatNumber(d.did)}</span>
<span className="muted">{d.description}</span>
</label>
))}
{smsDids.length > 1 && (
<label className="field">
Send new chats from
<select value={s.defaultDid ?? synced[0]} onChange={(e) => setS({ ...s, defaultDid: e.target.value })}>
{synced.map((d) => (
<option key={d} value={d}>
{formatNumber(d)}
</option>
))}
</select>
</label>
)}
</section>
)}
<section>
<h3>Sync</h3>
<label className="field">
Check for new messages every
<select value={s.pollSeconds} onChange={(e) => setS({ ...s, pollSeconds: Number(e.target.value) })}>
{[10, 15, 30, 60, 120, 300].map((n) => (
<option key={n} value={n}>
{n < 60 ? `${n} seconds` : `${n / 60} minute${n > 60 ? 's' : ''}`}
</option>
))}
</select>
</label>
<label className="field">
Import history back to
<input type="date" value={s.backfillFloor} onChange={(e) => e.target.value && setS({ ...s, backfillFloor: e.target.value })} />
</label>
</section>
<section>
<h3>Storage &amp; backups</h3>
<p className="muted small">
Your message history lives here. A dated snapshot is written daily and on quit (last 7 kept in <code>snapshots/</code>) so
backups always contain a clean copy.
</p>
<code className="path">{state.dataDir}</code>
<div className="btn-row">
<button onClick={() => void window.api.openDataFolder()}>Open folder</button>
<button onClick={() => void window.api.snapshotNow().then((p) => setNote(`Snapshot saved: ${p}`))}>Snapshot now</button>
<button onClick={() => void window.api.chooseDataDir()}>Move…</button>
</div>
{note && <p className="muted small">{note}</p>}
</section>
<footer>
<button onClick={onClose}>Cancel</button>
<button className="primary" disabled={!dirty} onClick={() => void save()}>
Save
</button>
</footer>
</div>
</div>
)
}
+118
View File
@@ -0,0 +1,118 @@
import { useState } from 'react'
import type { AppState } from '@shared/api'
import { formatNumber } from '@shared/phone'
import type { Did } from '@shared/types'
function cleanError(e: unknown): string {
return String((e as Error).message ?? e).replace(/^Error invoking remote method '\w+': (Error: )?/, '')
}
export function Setup({ initial, onDone }: { initial: AppState; onDone: () => void }) {
const [username, setUsername] = useState(initial.username ?? '')
const [password, setPassword] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string>()
const [dids, setDids] = useState<Did[]>()
const [chosen, setChosen] = useState<string[]>([])
const test = async (): Promise<void> => {
setBusy(true)
setError(undefined)
try {
const d = await window.api.testCredentials({ username: username.trim(), password })
setDids(d)
setChosen(d.filter((x) => x.smsEnabled).map((x) => x.did))
} catch (e) {
setError(cleanError(e))
} finally {
setBusy(false)
}
}
const finish = async (): Promise<void> => {
setBusy(true)
try {
const allSms = dids!.filter((d) => d.smsEnabled).map((d) => d.did)
const syncAll = chosen.length === allSms.length
await window.api.saveSetup(
{ username: username.trim(), password },
{ ...initial.settings, dids: syncAll ? [] : chosen, defaultDid: chosen[0] }
)
onDone()
} catch (e) {
setError(cleanError(e))
setBusy(false)
}
}
return (
<div className="setup">
<div className="setup-card">
<h1>voip.ms Messages</h1>
{!dids ? (
<>
<p className="muted">
Connect your voip.ms account. In the voip.ms portal, go to <b>Main Menu → SOAP &amp; REST/JSON API</b> and:
</p>
<ol className="muted">
<li>
<b>Enable API</b>
</li>
<li>
Set an <b>API password</b> (this is separate from your login password)
</li>
<li>
Add this computer's IP under <b>Enable IP Addresses</b>
</li>
</ol>
<form
onSubmit={(e) => {
e.preventDefault()
void test()
}}
>
<label>
Account email
<input value={username} onChange={(e) => setUsername(e.target.value)} autoFocus type="email" required />
</label>
<label>
API password
<input value={password} onChange={(e) => setPassword(e.target.value)} type="password" required />
</label>
{error && <div className="form-error">{error}</div>}
<button className="primary" disabled={busy || !username || !password}>
{busy ? 'Connecting…' : 'Connect'}
</button>
</form>
</>
) : (
<>
<p className="muted">Connected! Choose which numbers to sync messages for:</p>
<div className="did-list">
{dids.map((d) => (
<label key={d.did} className={`did${d.smsEnabled ? '' : ' disabled'}`}>
<input
type="checkbox"
disabled={!d.smsEnabled}
checked={chosen.includes(d.did)}
onChange={(e) => setChosen(e.target.checked ? [...chosen, d.did] : chosen.filter((x) => x !== d.did))}
/>
<span>{formatNumber(d.did)}</span>
<span className="muted">{d.smsEnabled ? d.description : 'SMS not enabled'}</span>
</label>
))}
</div>
<p className="muted small">
Your full message history will be imported and stored in <code>{initial.dataDir}</code>, which your Déjà Dup backups
already cover.
</p>
{error && <div className="form-error">{error}</div>}
<button className="primary" disabled={busy || !chosen.length} onClick={() => void finish()}>
Start syncing
</button>
</>
)}
</div>
</div>
)
}
+142
View File
@@ -0,0 +1,142 @@
import { useEffect, useRef } from 'react'
import type { ContactInfo, Conversation, SyncStatus } from '@shared/types'
import type { ConvKey } from '../App'
import { ConversationList } from './ConversationList'
import { SearchResults } from './SearchResults'
import { NewChat } from './NewChat'
import { BackIcon, CloseIcon, ComposeIcon, GearIcon, SearchIcon } from './Icons'
export type SidebarMode = 'chats' | 'search' | 'compose'
interface Props {
mode: SidebarMode
setMode: (m: SidebarMode) => void
query: string
setQuery: (q: string) => void
conversations: Conversation[]
contacts: ContactInfo[]
contactMap: Map<string, ContactInfo>
selected: ConvKey | null
onOpen: (key: ConvKey, jumpTo?: number) => void
sync?: SyncStatus
multiDid: boolean
defaultDid?: string
onSettings: () => void
}
export function Sidebar(p: Props) {
const searchRef = useRef<HTMLInputElement>(null)
useEffect(() => {
if (p.mode === 'search') searchRef.current?.focus()
}, [p.mode])
const clearSearch = (): void => {
p.setQuery('')
p.setMode('chats')
}
return (
<aside className="sidebar">
{p.mode === 'compose' ? (
<NewChat
contacts={p.contacts}
conversations={p.conversations}
defaultDid={p.defaultDid}
onCancel={() => p.setMode('chats')}
onPick={(key) => {
p.setMode('chats')
p.onOpen(key)
}}
/>
) : (
<>
<header className="sidebar-header">
<div className="search-box">
{p.mode === 'search' ? (
<button className="icon-btn inline" title="Back" onClick={clearSearch}>
<BackIcon />
</button>
) : (
<span className="search-glyph">
<SearchIcon size={16} />
</span>
)}
<input
id="sidebar-search"
ref={searchRef}
placeholder="Search"
value={p.query}
onFocus={() => p.setMode('search')}
onChange={(e) => {
p.setQuery(e.target.value)
p.setMode('search')
}}
onKeyDown={(e) => {
if (e.key === 'Escape') {
clearSearch()
e.currentTarget.blur()
}
}}
/>
{p.query && (
<button className="icon-btn inline" title="Clear" onClick={() => p.setQuery('')}>
<CloseIcon size={16} />
</button>
)}
</div>
<button className="icon-btn" title="New chat (Ctrl+N)" onClick={() => p.setMode('compose')}>
<ComposeIcon />
</button>
<button className="icon-btn" title="Settings" onClick={p.onSettings}>
<GearIcon />
</button>
</header>
<div className="sidebar-body">
{p.mode === 'search' && p.query.trim() ? (
<SearchResults
query={p.query}
conversations={p.conversations}
contacts={p.contacts}
contactMap={p.contactMap}
defaultDid={p.defaultDid}
onOpen={p.onOpen}
/>
) : (
<ConversationList
conversations={p.conversations}
contactMap={p.contactMap}
selected={p.selected}
multiDid={p.multiDid}
onOpen={p.onOpen}
/>
)}
</div>
</>
)}
<SyncFooter sync={p.sync} />
</aside>
)
}
function SyncFooter({ sync }: { sync?: SyncStatus }) {
if (!sync) return null
let text = ''
let cls = 'sync-footer'
if (sync.phase === 'error') {
text = `⚠ ${sync.error ?? 'Sync error'}`
cls += ' error'
} else if (!sync.backfillDone && sync.backfillCursor) {
const d = new Date(sync.backfillCursor + 'T12:00:00Z')
text = `Importing history… back to ${d.toLocaleDateString([], { month: 'short', year: 'numeric' })} · ${sync.total.toLocaleString()} messages`
} else if (!sync.backfillDone && sync.phase === 'backfill') {
text = 'Importing history…'
} else {
return null
}
return (
<div className={cls} title={text}>
{text}
</div>
)
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+84
View File
@@ -0,0 +1,84 @@
import { formatNumber } from '@shared/phone'
import type { ContactInfo } from '@shared/types'
const DAY = 86_400_000
function startOfDay(ms: number): number {
const d = new Date(ms)
d.setHours(0, 0, 0, 0)
return d.getTime()
}
export function timeOfDay(ms: number): string {
return new Date(ms).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })
}
// Conversation list: "Now", "5m", "3:04 PM", "Tue", "Mar 3", "3/3/22"
export function shortTime(ms: number, now = Date.now()): string {
const diff = now - ms
if (diff < 60_000) return 'Now'
if (diff < 60 * 60_000) return `${Math.floor(diff / 60_000)}m`
if (ms >= startOfDay(now)) return timeOfDay(ms)
if (ms >= startOfDay(now) - 6 * DAY) return new Date(ms).toLocaleDateString([], { weekday: 'short' })
if (new Date(ms).getFullYear() === new Date(now).getFullYear())
return new Date(ms).toLocaleDateString([], { month: 'short', day: 'numeric' })
return new Date(ms).toLocaleDateString([], { year: '2-digit', month: 'numeric', day: 'numeric' })
}
// Chat date separators: "Today", "Yesterday", "Tuesday", "Mon, Mar 3, 2024"
export function dayLabel(ms: number, now = Date.now()): string {
const today = startOfDay(now)
const day = startOfDay(ms)
if (day === today) return 'Today'
if (day === today - DAY) return 'Yesterday'
if (day > today - 7 * DAY) return new Date(ms).toLocaleDateString([], { weekday: 'long' })
return new Date(ms).toLocaleDateString([], {
weekday: 'short',
month: 'short',
day: 'numeric',
year: new Date(ms).getFullYear() === new Date(now).getFullYear() ? undefined : 'numeric'
})
}
export function sameDay(a: number, b: number): boolean {
return startOfDay(a) === startOfDay(b)
}
export function displayName(number: string, contact?: ContactInfo): string {
return contact?.name ?? formatNumber(number)
}
const AVATAR_COLORS = ['#e3b5a4', '#a4c9e3', '#b5e3a4', '#e3a4d6', '#e3d6a4', '#a4e3d4', '#c2a4e3', '#e3a4a4', '#a4b0e3', '#d4e3a4']
const AVATAR_INK = ['#5c2a17', '#16405c', '#2a5c17', '#5c1750', '#5c4a17', '#175c4c', '#3c175c', '#5c1717', '#17245c', '#4a5c17']
export function avatarColors(key: string): { bg: string; fg: string } {
let h = 0
for (const c of key) h = (h * 31 + c.charCodeAt(0)) | 0
const i = Math.abs(h) % AVATAR_COLORS.length
return { bg: AVATAR_COLORS[i], fg: AVATAR_INK[i] }
}
export function initials(name: string): string {
const words = name.replace(/[^\p{L}\p{N}\s]/gu, '').trim().split(/\s+/).filter(Boolean)
if (!words.length) return ''
if (words.length === 1) return [...words[0]][0].toUpperCase()
return ([...words[0]][0] + [...words[words.length - 1]][0]).toUpperCase()
}
// Split text into plain + highlighted chunks for the given search words
// (prefix match, case-insensitive), mirroring the FTS query semantics.
export function highlightChunks(text: string, query: string): Array<{ text: string; hit: boolean }> {
const words = query.split(/[^\p{L}\p{N}]+/u).filter(Boolean)
if (!words.length) return [{ text, hit: false }]
const escaped = words.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
const re = new RegExp(`(?<![\\p{L}\\p{N}])(${escaped.join('|')})[\\p{L}\\p{N}]*`, 'giu')
const out: Array<{ text: string; hit: boolean }> = []
let last = 0
for (const m of text.matchAll(re)) {
if (m.index! > last) out.push({ text: text.slice(last, m.index), hit: false })
out.push({ text: m[0], hit: true })
last = m.index! + m[0].length
}
if (last < text.length) out.push({ text: text.slice(last), hit: false })
return out
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { App } from './App'
import './styles.css'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>
)
+777
View File
@@ -0,0 +1,777 @@
/* Signal Desktop–inspired theme. Light + dark follow the system setting. */
:root {
--accent: #2c6bed;
--accent-hover: #1f5ad6;
--bg: #ffffff;
--sidebar: #ffffff;
--panel: #f6f6f6;
--border: #e9e9e9;
--text: #1b1b1b;
--muted: #6b6b6b;
--faint: #8f8f8f;
--row-hover: #f2f2f2;
--row-active: #dedede;
--bubble-in: #e9e9e9;
--bubble-in-text: #1b1b1b;
--bubble-out: var(--accent);
--bubble-out-text: #ffffff;
--input-bg: #f0f0f0;
--mark: #ffe36a;
--mark-text: #1b1b1b;
--danger: #d62828;
--flash: rgba(44, 107, 237, 0.18);
--shadow: 0 8px 30px rgba(0, 0, 0, 0.18);
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #121212;
--sidebar: #1b1b1d;
--panel: #242426;
--border: #2e2e30;
--text: #e9e9e9;
--muted: #a3a3a3;
--faint: #7c7c7c;
--row-hover: #262628;
--row-active: #333336;
--bubble-in: #3b3b3b;
--bubble-in-text: #e9e9e9;
--input-bg: #2e2e30;
--mark: #f2c94c;
--mark-text: #121212;
--flash: rgba(44, 107, 237, 0.3);
--shadow: 0 8px 30px rgba(0, 0, 0, 0.6);
color-scheme: dark;
}
}
* {
box-sizing: border-box;
}
html,
body,
#root {
height: 100%;
margin: 0;
}
body {
font-family: Inter, 'Cantarell', system-ui, -apple-system, 'Segoe UI', sans-serif;
font-size: 14px;
background: var(--bg);
color: var(--text);
-webkit-font-smoothing: antialiased;
overflow: hidden;
user-select: none;
}
button {
font: inherit;
color: inherit;
cursor: pointer;
}
input,
textarea,
select {
font: inherit;
color: inherit;
}
code {
font-family: ui-monospace, 'JetBrains Mono', monospace;
font-size: 12px;
}
mark {
background: var(--mark);
color: var(--mark-text);
border-radius: 3px;
padding: 0 1px;
}
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-thumb {
background: color-mix(in srgb, var(--text) 22%, transparent);
border-radius: 10px;
border: 3px solid transparent;
background-clip: content-box;
}
.app {
display: flex;
height: 100%;
}
/* ---------- sidebar ---------- */
.sidebar {
width: 340px;
min-width: 280px;
display: flex;
flex-direction: column;
background: var(--sidebar);
border-right: 1px solid var(--border);
}
.sidebar-header {
display: flex;
align-items: center;
gap: 4px;
padding: 12px 10px 8px 12px;
}
.sidebar-header.compose {
gap: 8px;
}
.compose-title {
font-weight: 600;
font-size: 15px;
}
.search-box {
flex: 1;
display: flex;
align-items: center;
background: var(--input-bg);
border-radius: 8px;
height: 32px;
padding: 0 4px 0 8px;
min-width: 0;
}
.search-glyph {
color: var(--faint);
display: flex;
padding-right: 6px;
}
.search-box input {
flex: 1;
min-width: 0;
border: 0;
outline: 0;
background: transparent;
}
.icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border: 0;
background: transparent;
border-radius: 50%;
color: var(--muted);
flex: none;
}
.icon-btn:hover:not(:disabled) {
background: var(--row-hover);
color: var(--text);
}
.icon-btn:disabled {
opacity: 0.4;
cursor: default;
}
.icon-btn.inline {
width: 24px;
height: 24px;
margin-left: -4px;
margin-right: 2px;
}
.icon-btn.small {
width: 28px;
height: 28px;
}
.sidebar-body {
flex: 1;
min-height: 0;
overflow-y: auto;
}
.conv-list {
height: 100%;
}
.list-empty {
padding: 24px 16px;
color: var(--muted);
text-align: center;
}
.section-label {
padding: 14px 16px 6px;
font-weight: 600;
font-size: 13px;
color: var(--text);
}
.section-label .count {
color: var(--faint);
font-weight: 400;
margin-left: 4px;
}
.row {
display: flex;
align-items: center;
gap: 12px;
width: calc(100% - 16px);
margin: 0 8px;
padding: 10px 8px;
border: 0;
border-radius: 10px;
background: transparent;
text-align: left;
}
.row:hover {
background: var(--row-hover);
}
.row.active {
background: var(--row-active);
}
.row:disabled {
opacity: 0.5;
}
.row-main {
flex: 1;
min-width: 0;
}
.row-top,
.row-bottom {
display: flex;
align-items: baseline;
gap: 8px;
}
.row-name {
flex: 1;
font-weight: 600;
font-size: 14px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.row-time {
font-size: 12px;
color: var(--faint);
flex: none;
}
.row-preview {
flex: 1;
color: var(--muted);
font-size: 13px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-top: 2px;
}
.row.unread .row-preview {
color: var(--text);
}
.row.unread .row-time {
color: var(--text);
font-weight: 600;
}
.row-via {
font-size: 11px;
color: var(--faint);
margin-top: 2px;
}
.row-snippet {
color: var(--muted);
font-size: 13px;
margin-top: 2px;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
word-break: break-word;
}
.row-snippet .you {
color: var(--faint);
}
.badge {
background: var(--accent);
color: #fff;
border-radius: 10px;
font-size: 11px;
font-weight: 600;
min-width: 20px;
height: 20px;
line-height: 20px;
padding: 0 6px;
text-align: center;
flex: none;
}
.search-results {
padding-bottom: 12px;
}
.to-field {
display: flex;
align-items: center;
gap: 8px;
margin: 0 12px 8px;
padding: 0 10px;
height: 36px;
background: var(--input-bg);
border-radius: 8px;
}
.to-field span {
color: var(--muted);
}
.to-field input {
flex: 1;
border: 0;
outline: 0;
background: transparent;
}
.sync-footer {
font-size: 12px;
color: var(--muted);
padding: 8px 14px;
border-top: 1px solid var(--border);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.sync-footer.error {
color: var(--danger);
white-space: normal;
}
/* ---------- avatar ---------- */
.avatar {
flex: none;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-weight: 600;
overflow: hidden;
letter-spacing: 0.02em;
}
.avatar img {
width: 100%;
height: 100%;
object-fit: cover;
}
/* ---------- chat ---------- */
.chat {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
background: var(--bg);
}
.chat.empty {
align-items: center;
justify-content: center;
}
.empty-hint {
text-align: center;
color: var(--muted);
}
.empty-title {
font-size: 20px;
font-weight: 600;
color: var(--text);
margin-bottom: 6px;
}
.chat-header {
display: flex;
align-items: center;
gap: 12px;
height: 60px;
padding: 0 12px 0 16px;
border-bottom: 1px solid var(--border);
flex: none;
}
.chat-title {
flex: 1;
min-width: 0;
}
.chat-name {
font-weight: 600;
font-size: 15px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.chat-sub {
font-size: 12px;
color: var(--muted);
user-select: text;
}
.chat-search {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 12px 8px 16px;
border-bottom: 1px solid var(--border);
color: var(--faint);
}
.chat-search input {
flex: 1;
border: 0;
outline: 0;
background: transparent;
color: var(--text);
}
.hit-count {
font-size: 12px;
color: var(--muted);
margin-right: 4px;
white-space: nowrap;
}
.messages {
flex: 1;
min-height: 0;
position: relative;
}
.message-scroller {
height: 100%;
}
.day-sep {
text-align: center;
padding: 18px 0 8px;
}
.day-sep span {
font-size: 12px;
font-weight: 600;
color: var(--muted);
}
.new-conv {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
}
.new-conv-name {
font-size: 18px;
font-weight: 600;
margin-top: 8px;
}
.new-conv-sub {
color: var(--muted);
}
.msg {
display: flex;
flex-direction: column;
padding: 1px 20px;
transition: background-color 0.6s;
}
.msg.g-start {
padding-top: 8px;
}
.msg.out {
align-items: flex-end;
}
.msg.in {
align-items: flex-start;
}
.msg.flash {
background: var(--flash);
transition: none;
}
.bubble {
max-width: min(70%, 560px);
padding: 7px 12px 6px;
border-radius: 18px;
font-size: 14px;
line-height: 1.4;
white-space: pre-wrap;
word-wrap: break-word;
overflow-wrap: anywhere;
user-select: text;
}
.msg.in .bubble {
background: var(--bubble-in);
color: var(--bubble-in-text);
}
.msg.out .bubble {
background: var(--bubble-out);
color: var(--bubble-out-text);
}
/* Signal-style grouped corners */
.msg.in:not(.g-start) .bubble {
border-top-left-radius: 4px;
}
.msg.in:not(.g-end) .bubble {
border-bottom-left-radius: 4px;
}
.msg.out:not(.g-start) .bubble {
border-top-right-radius: 4px;
}
.msg.out:not(.g-end) .bubble {
border-bottom-right-radius: 4px;
}
.msg.failed .bubble {
opacity: 0.6;
}
.bubble a {
color: inherit;
text-decoration: underline;
}
.meta {
float: right;
margin: 6px 0 -3px 10px;
font-size: 11px;
opacity: 0.7;
display: inline-flex;
align-items: center;
gap: 3px;
user-select: none;
}
.msg.out .bubble mark {
background: rgba(255, 255, 255, 0.9);
color: #1b1b1b;
}
.failed-row {
display: flex;
align-items: center;
gap: 4px;
font-size: 12px;
color: var(--danger);
margin-top: 3px;
}
.failed-row button {
border: 0;
background: none;
color: var(--danger);
text-decoration: underline;
padding: 0 2px;
}
/* ---------- composer ---------- */
.composer {
flex: none;
padding: 10px 16px 14px;
border-top: 1px solid var(--border);
}
.composer-row {
display: flex;
align-items: flex-end;
gap: 8px;
}
.composer textarea {
flex: 1;
resize: none;
border: 0;
outline: 0;
border-radius: 18px;
background: var(--input-bg);
padding: 8px 14px;
line-height: 1.4;
max-height: 200px;
user-select: text;
}
.counter {
font-size: 11px;
color: var(--faint);
padding-bottom: 10px;
white-space: nowrap;
}
.counter.multi {
color: var(--accent);
}
.send-btn {
width: 36px;
height: 36px;
border-radius: 50%;
border: 0;
background: var(--accent);
color: #fff;
display: flex;
align-items: center;
justify-content: center;
flex: none;
}
.send-btn:disabled {
background: var(--input-bg);
color: var(--faint);
cursor: default;
}
.composer-error {
color: var(--danger);
font-size: 12px;
margin-bottom: 6px;
cursor: pointer;
}
.from-picker {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: var(--muted);
margin-bottom: 8px;
}
.from-picker select,
.field select,
.field input {
background: var(--input-bg);
border: 1px solid var(--border);
border-radius: 6px;
padding: 4px 8px;
}
/* ---------- setup + settings ---------- */
.setup {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: var(--panel);
user-select: text;
}
.setup-card {
width: 440px;
max-width: calc(100% - 32px);
background: var(--bg);
border-radius: 14px;
padding: 28px 32px;
box-shadow: var(--shadow);
}
.setup-card h1 {
margin: 0 0 12px;
font-size: 22px;
}
.setup-card ol {
padding-left: 20px;
line-height: 1.6;
}
.setup-card form,
.setup-card label {
display: flex;
flex-direction: column;
gap: 6px;
}
.setup-card form {
gap: 14px;
margin-top: 16px;
}
.setup-card input[type='email'],
.setup-card input[type='password'] {
padding: 9px 12px;
border-radius: 8px;
border: 1px solid var(--border);
background: var(--input-bg);
outline: none;
}
.setup-card input:focus {
border-color: var(--accent);
}
.muted {
color: var(--muted);
}
.small {
font-size: 12px;
}
.form-error {
color: var(--danger);
font-size: 13px;
}
button.primary {
background: var(--accent);
color: #fff;
border: 0;
border-radius: 8px;
padding: 9px 16px;
font-weight: 600;
}
button.primary:hover:not(:disabled) {
background: var(--accent-hover);
}
button.primary:disabled {
opacity: 0.5;
cursor: default;
}
.did-list {
display: flex;
flex-direction: column;
gap: 4px;
margin: 12px 0;
}
label.did {
display: flex !important;
flex-direction: row !important;
align-items: center;
gap: 10px !important;
padding: 6px 0;
}
label.did.disabled {
opacity: 0.5;
}
.modal-backdrop {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.45);
display: flex;
align-items: center;
justify-content: center;
z-index: 10;
}
.modal {
width: 520px;
max-width: calc(100% - 32px);
max-height: calc(100% - 48px);
overflow-y: auto;
background: var(--bg);
border-radius: 14px;
box-shadow: var(--shadow);
user-select: text;
}
.modal > header,
.modal > footer {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 16px 6px 24px;
}
.modal > footer {
justify-content: flex-end;
gap: 8px;
padding: 12px 24px 20px;
}
.modal h2 {
margin: 0;
font-size: 18px;
}
.modal section {
padding: 8px 24px 14px;
border-bottom: 1px solid var(--border);
}
.modal h3 {
font-size: 13px;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--muted);
margin: 8px 0 10px;
}
.modal button:not(.icon-btn):not(.primary) {
background: var(--input-bg);
border: 1px solid var(--border);
border-radius: 8px;
padding: 6px 12px;
}
.modal button.danger {
color: var(--danger);
margin-top: 8px;
}
.kv {
display: flex;
justify-content: space-between;
padding: 3px 0;
}
.kv span:first-child {
color: var(--muted);
}
.field {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 6px 0;
}
.path {
display: block;
padding: 8px 10px;
background: var(--input-bg);
border-radius: 6px;
word-break: break-all;
}
.btn-row {
display: flex;
gap: 8px;
margin-top: 10px;
}
+39
View File
@@ -0,0 +1,39 @@
// The typed bridge exposed to the renderer as window.api.
import type { ContactInfo, Conversation, Credentials, Did, Message, SearchHit, Settings, SyncStatus } from './types'
export interface AppState {
configured: boolean
username?: string
settings: Settings
dataDir: string
dids: Did[]
keyringBackend: string
}
export interface Api {
getState(): Promise<AppState>
testCredentials(creds: Credentials): Promise<Did[]>
saveSetup(creds: Credentials, settings: Settings): Promise<void>
updateSettings(settings: Settings): Promise<void>
signOut(): Promise<void>
listContacts(): Promise<ContactInfo[]>
listConversations(): Promise<Conversation[]>
getMessages(did: string, contact: string): Promise<Message[]>
markRead(did: string, contact: string): Promise<void>
search(query: string, scope?: { did: string; contact: string }): Promise<SearchHit[]>
send(did: string, contact: string, text: string): Promise<void>
deleteFailed(id: number): Promise<void>
retryFailed(id: number): Promise<void>
syncStatus(): Promise<SyncStatus>
pollNow(): Promise<void>
openDataFolder(): Promise<void>
snapshotNow(): Promise<string>
chooseDataDir(): Promise<string | undefined>
onMessages(cb: (msgs: Message[]) => void): () => void
onConversationsChanged(cb: () => void): () => void
onSyncStatus(cb: (s: SyncStatus) => void): () => void
onContactsChanged(cb: () => void): () => void
}
+36
View File
@@ -0,0 +1,36 @@
// Phone number helpers. voip.ms uses bare 10-digit NANP numbers, so everything
// is normalized to that form where possible (short codes and international
// numbers are left as plain digits).
export function normalizeNumber(raw: string): string {
let digits = raw.replace(/\D/g, '')
if (digits.length === 11 && digits.startsWith('1')) digits = digits.slice(1)
return digits
}
export function formatNumber(n: string): string {
const d = normalizeNumber(n)
if (d.length === 10) return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`
return n
}
// Split text into voip.ms-sized parts (160 chars max per sendSMS call),
// preferring to break on whitespace.
export function splitMessage(text: string, max = 160): string[] {
const parts: string[] = []
let rest = text.trim()
while ([...rest].length > max) {
const chars = [...rest]
let cut = max
for (let i = max; i > max * 0.6; i--) {
if (/\s/.test(chars[i])) {
cut = i
break
}
}
parts.push(chars.slice(0, cut).join('').trimEnd())
rest = chars.slice(cut).join('').trimStart()
}
if (rest) parts.push(rest)
return parts
}
+71
View File
@@ -0,0 +1,71 @@
// Types shared between the main process, preload bridge and renderer.
export type Direction = 'in' | 'out'
export type MessageStatus = 'delivered' | 'pending' | 'failed'
export interface Message {
id: number
did: string
contact: string
direction: Direction
body: string
ts: number // epoch ms, UTC
kind: 'sms' | 'mms'
status: MessageStatus
}
export interface Conversation {
did: string
contact: string
lastBody: string
lastTs: number
lastDirection: Direction
unread: number
}
export interface ContactInfo {
name: string
number: string // normalized
label?: string // e.g. "cell", "work"
photo?: string // data: URL
book: string
}
export interface SearchHit {
id: number
did: string
contact: string
ts: number
direction: Direction
snippet: string // contains  /  markers around matched text
}
export interface Did {
did: string
description: string
smsEnabled: boolean
}
export interface SyncStatus {
phase: 'idle' | 'backfill' | 'polling' | 'error' | 'unconfigured'
backfillCursor?: string // YYYY-MM-DD the backfill has reached
backfillDone: boolean
lastPoll?: number
error?: string
total: number
}
export interface Settings {
pollSeconds: number
dids: string[] // DIDs to sync; empty = all SMS-enabled
defaultDid?: string
backfillFloor: string // YYYY-MM-DD, stop backfill here
}
export interface Credentials {
username: string
password: string
}
export const SNIPPET_START = ''
export const SNIPPET_END = ''
+29
View File
@@ -0,0 +1,29 @@
// Reads the real GNOME/EDS address books (read-only). Run with: LIVE=1 npm test
import { describe, expect, it } from 'vitest'
import { ContactDirectory, listSources } from '../src/main/contacts'
describe.skipIf(!process.env.LIVE)('live EDS contacts', () => {
it('lists enabled address books', async () => {
const sources = await listSources()
console.log(sources.map((s) => `${s.name} (${s.account})`).join('\n'))
expect(sources.length).toBeGreaterThan(0)
})
it('loads contacts with numbers and photos', async () => {
const dir = new ContactDirectory()
await dir.load()
const all = dir.list()
const withPhoto = all.filter((c) => c.photo)
const byBook = new Map<string, number>()
for (const c of all) byBook.set(c.book, (byBook.get(c.book) ?? 0) + 1)
console.log(`numbers: ${all.length}, with photo: ${withPhoto.length}`, Object.fromEntries(byBook))
const kinds = new Map<string, number>()
for (const c of withPhoto) {
const k = dir.photoFor(c.number)!.kind
kinds.set(k, (kinds.get(k) ?? 0) + 1)
}
console.log('photo kinds', Object.fromEntries(kinds))
expect(all.length).toBeGreaterThan(50)
dir.close()
})
})
+108
View File
@@ -0,0 +1,108 @@
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { SNIPPET_END, SNIPPET_START } from '@shared/types'
import { MessageDb, toFtsQuery, type NewMessage } from '../src/main/db'
let dir: string
let db: MessageDb
const msg = (id: number, contact: string, body: string, ts: number, direction: 'in' | 'out' = 'in'): NewMessage => ({
id,
did: '5550001111',
contact,
direction,
body,
ts
})
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'voipms-test-'))
db = new MessageDb(path.join(dir, 'messages.db'))
})
afterEach(() => {
db.close()
fs.rmSync(dir, { recursive: true, force: true })
})
describe('MessageDb', () => {
it('dedupes by voip.ms id', () => {
expect(db.upsertMessages([msg(1, 'a', 'hi', 1000), msg(2, 'a', 'yo', 2000)])).toHaveLength(2)
expect(db.upsertMessages([msg(2, 'a', 'yo', 2000), msg(3, 'a', 'new', 3000)]).map((m) => m.id)).toEqual([3])
expect(db.count()).toBe(3)
})
it('lists conversations newest first with previews and unread counts', () => {
db.set('unread_floor', '1500')
db.upsertMessages([msg(1, 'a', 'old', 1000), msg(2, 'b', 'hello b', 2000), msg(3, 'a', 'latest a', 3000), msg(4, 'a', 'me', 2500, 'out')])
const convs = db.listConversations()
expect(convs.map((c) => c.contact)).toEqual(['a', 'b'])
expect(convs[0]).toMatchObject({ lastBody: 'latest a', lastDirection: 'in', unread: 1 })
expect(convs[1]).toMatchObject({ unread: 1 })
db.markRead('5550001111', 'a')
expect(db.listConversations()[0].unread).toBe(0)
})
it('searches with prefix matching, snippets, and per-chat scope', () => {
db.upsertMessages([
msg(1, 'a', 'Want to grab pizza tonight?', 1000),
msg(2, 'b', 'The pizzeria on Main is closed', 2000),
msg(3, 'a', 'nothing here', 3000)
])
const all = db.search('piz')
expect(all.map((h) => h.id)).toEqual([2, 1])
expect(all[1].snippet).toContain(`${SNIPPET_START}pizza${SNIPPET_END}`)
expect(db.search('piz', { did: '5550001111', contact: 'a' }).map((h) => h.id)).toEqual([1])
expect(db.search('grab tonight').map((h) => h.id)).toEqual([1])
expect(db.search('"); DROP TABLE messages; --')).toEqual([])
expect(db.search('')).toEqual([])
})
it('handles pending sends: confirm, dedupe against poll, failure', () => {
const t1 = db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body: 'on my way', ts: 5000 })
expect(t1).toBeLessThan(0)
expect(db.getMessage(t1)?.status).toBe('pending')
db.confirmPending(t1, 99)
expect(db.getMessage(99)).toMatchObject({ status: 'delivered', body: 'on my way' })
// Poll got the real message before sendSMS returned.
const t2 = db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body: 'x', ts: 6000 })
db.upsertMessages([msg(100, 'a', 'x', 6001, 'out')])
db.confirmPending(t2, 100)
expect(db.getMessage(t2)).toBeUndefined()
expect(db.count()).toBe(2)
const t3 = db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body: 'fail', ts: 7000 })
db.markFailed(t3)
expect(db.getMessage(t3)?.status).toBe('failed')
expect(db.search('fail').map((h) => h.id)).toEqual([t3])
db.deleteMessage(t3)
expect(db.search('fail')).toEqual([])
})
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)
expect(db.search('unique').map((h) => h.id)).toEqual([555])
})
it('writes consistent snapshots and prunes to the last N', async () => {
db.upsertMessages([msg(1, 'a', 'backup me', 1000)])
const snaps = path.join(dir, 'snapshots')
fs.mkdirSync(snaps)
for (const d of ['2020-01-01', '2020-01-02', '2020-01-03']) fs.writeFileSync(path.join(snaps, `messages-${d}.db`), '')
const file = await db.snapshot(snaps, 2)
expect(fs.readdirSync(snaps).sort()).toEqual(['messages-2020-01-03.db', path.basename(file)].sort())
const copy = new MessageDb(file)
expect(copy.search('backup').length).toBe(1)
copy.close()
})
})
describe('toFtsQuery', () => {
it('quotes words as prefix terms', () => {
expect(toFtsQuery('hey "you" OR')).toBe('"hey"* "you"* "OR"*')
expect(toFtsQuery(' ')).toBe('')
})
})
+39
View File
@@ -0,0 +1,39 @@
import { describe, expect, it } from 'vitest'
import { formatNumber, normalizeNumber, splitMessage } from '@shared/phone'
describe('phone numbers', () => {
it('normalizes NANP numbers to 10 digits', () => {
expect(normalizeNumber('+1 (541) 555-0142')).toBe('5415550142')
expect(normalizeNumber('15415550142')).toBe('5415550142')
expect(normalizeNumber('541.555.0142')).toBe('5415550142')
expect(normalizeNumber('tel:+15415550142')).toBe('5415550142')
})
it('leaves short codes alone', () => {
expect(normalizeNumber('72975')).toBe('72975')
})
it('formats', () => {
expect(formatNumber('5415550142')).toBe('(541) 555-0142')
expect(formatNumber('72975')).toBe('72975')
})
})
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])
})
it('counts emoji as single characters', () => {
const parts = splitMessage('😀'.repeat(200))
expect(parts.map((p) => [...p].length)).toEqual([160, 40])
})
})
+76
View File
@@ -0,0 +1,76 @@
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<void>((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)
})
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, it } from 'vitest'
import { parseVCard } from '../src/main/contacts'
describe('parseVCard', () => {
it('parses EDS-style cards with E164 params and remote photos', () => {
const card = [
'BEGIN:VCARD',
'VERSION:3.0',
'FN:Alex Example',
'N:Example;Alex;;;',
'TEL;X-EVOLUTION-E164=4435550143,;VALUE=UNKNOWN;TYPE=CELL:(443) 555-0143',
'TEL;X-EVOLUTION-E164=5415550142,"+1";X-NC-SCOPE="v2-local";TYPE=VOICE:+1541',
' 5550142',
'PHOTO;VALUE=BINARY:https://lh5.googleusercontent.com/-abc/photo.jpg',
'END:VCARD'
].join('\r\n')
const c = parseVCard(card)
expect(c.name).toBe('Alex Example')
expect(c.tels).toEqual([
{ number: '4435550143', label: 'cell' },
{ number: '5415550142', label: undefined }
])
expect(c.photo).toEqual({ kind: 'url', url: 'https://lh5.googleusercontent.com/-abc/photo.jpg' })
})
it('parses file photos and falls back to N when FN is missing', () => {
const c = parseVCard(
'BEGIN:VCARD\nN:Doe;Jane;;;\nTEL;TYPE=work:555-123-4567\nPHOTO;VALUE=uri:file:///home/x/.cache/evolution/addressbook/abc/PHOTO-1.image%2Fpng\nEND:VCARD'
)
expect(c.name).toBe('Jane Doe')
expect(c.tels).toEqual([{ number: '5551234567', label: 'work' }])
expect(c.photo).toEqual({ kind: 'file', path: '/home/x/.cache/evolution/addressbook/abc/PHOTO-1.image/png' })
})
it('parses inline base64 photos (vCard 3 and 4)', () => {
const v3 = parseVCard('BEGIN:VCARD\nFN:A\nTEL:5551234567\nPHOTO;ENCODING=b;TYPE=PNG:iVBORw0KGgo\n AAAA\nEND:VCARD')
expect(v3.photo).toEqual({ kind: 'inline', mime: 'image/png', data: 'iVBORw0KGgoAAAA' })
const v4 = parseVCard('BEGIN:VCARD\nFN:A\nTEL:5551234567\nPHOTO:data:image/jpeg;base64,/9j/4AAQ\nEND:VCARD')
expect(v4.photo).toEqual({ kind: 'inline', mime: 'image/jpeg', data: '/9j/4AAQ' })
})
it('handles grouped properties and escaped text', () => {
const c = parseVCard('BEGIN:VCARD\nitem1.FN:Smith\\, John\nitem1.TEL;type=CELL:+1 541 555 0142\nEND:VCARD')
expect(c.name).toBe('Smith, John')
expect(c.tels[0]).toEqual({ number: '5415550142', label: 'cell' })
})
})
+4
View File
@@ -0,0 +1,4 @@
{
"files": [],
"references": [{ "path": "./tsconfig.node.json" }, { "path": "./tsconfig.web.json" }]
}
+13
View File
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2023",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"types": ["node"],
"paths": { "@shared/*": ["./src/shared/*"] }
},
"include": ["electron.vite.config.ts", "src/main/**/*", "src/preload/**/*", "src/shared/**/*", "test/**/*"]
}
+13
View File
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2023",
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"skipLibCheck": true,
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"paths": { "@shared/*": ["./src/shared/*"] }
},
"include": ["src/renderer/**/*", "src/shared/**/*", "src/preload/index.d.ts"]
}
+7
View File
@@ -0,0 +1,7 @@
import { resolve } from 'node:path'
import { defineConfig } from 'vitest/config'
export default defineConfig({
resolve: { alias: { '@shared': resolve(__dirname, 'src/shared') } },
test: { include: ['test/**/*.test.ts'] }
})