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:
@@ -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())
|
||||
Reference in New Issue
Block a user