Files
bubble/src/main/index.ts
T
trav bd10daeb8b v0.9.0: the history lives in ~/Documents/bubble-data
On its first launch bubble copies ~/Documents/voipms-desktop-data to ~/Documents/bubble-data (through a .partial folder, renamed only once the copy is whole) and uses that. The old folder stays as a backup with a "MOVED TO bubble-data.txt" note, to delete once everything looks right. A data folder chosen in Settings elsewhere stays put; if the copy fails, bubble keeps using the old folder rather than starting empty.

Tried with a throwaway home holding the sandbox's made-up history: the copy, the note, the chats loading from the new folder, no second copy on the next launch, and a saved pointer to the old folder moving along with it.
2026-11-13 12:15:09 -08:00

854 lines
35 KiB
TypeScript

// First: in sandbox mode this moves every path the app uses (see sandbox.ts).
import { SANDBOX, seedDemo } from './sandbox'
import { app, BrowserWindow, clipboard, ClipboardItem, dialog, ipcMain, nativeTheme, net, protocol, safeStorage, screen, shell } from 'electron'
import { execFileSync } from 'node:child_process'
import crypto from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
import os from 'node:os'
import { pathToFileURL } from 'node:url'
import { charCount, groupMembers, isGroup, normalizeNumber, SMS_TEXT_LIMIT } from '@shared/phone'
import type { ChatExport, IconStyle, Credentials, Did, MediaRef, Message, NewContact, OutgoingAttachment, Provider, Settings, SyncStatus, Theme } from '@shared/types'
import type { AppState, WindowAction, WindowState } from '@shared/api'
import { addToAddressBook, ContactDirectory, listAddressBooks } from './contacts'
import { localDay, MessageDb, type NewMessage } from './db'
import { MediaStore } from './media'
import { exportHtml, exportText, inRange, rangeLabel } from './export'
import { extFor, guessMime } from '@shared/mime'
import { clearCredentials, loadCredentials, saveCredentials } from './secrets'
import { getDataDir, loadSettings, moveToBubbleData, saveSettings, setDataDir } from './settings'
import { SyncEngine } from './sync'
import { loadZoom, saveZoom } from './uistate'
import { sendWithRetry } from './send'
import { VoipMs, VoipMsError } from './voipms'
import { classifyGvError, gvErrorMessage, GVoice, GVoiceError, toE164, transactionId } from './gvoice/client'
import { SendMediaType } from './gvoice/schema'
import { clearGvSession, exportCookies, gvTransport, hasGvSession, importCookies, parseCookies, signInWindow } from './gvoice/session'
import { gvMessageId, GvSyncEngine } from './gvoice/sync'
import { WaaSigner } from './gvoice/waa'
import { clearNotifications, notifyNew } from './notify'
import * as rabbit from './rabbit'
import { checkUrl, clearRelayConfig, loadRelayConfig, newKey, RelayEngine, saveRelayConfig, SIM_DID } from './relay'
protocol.registerSchemesAsPrivileged([
{ scheme: 'contact-photo', privileges: { standard: true, secure: true, supportFetchAPI: true } },
{ scheme: 'mms-media', privileges: { standard: true, secure: true, supportFetchAPI: true, stream: true } }
])
if (!app.requestSingleInstanceLock()) app.quit()
let win: BrowserWindow | undefined
let db: MessageDb
let contacts: ContactDirectory
let media: MediaStore
let settings: Settings
let api: VoipMs | undefined
let sync: SyncEngine | undefined
let dids: Did[] = []
// Google Voice: optional, alongside voip.ms. Its number is cached in the DB.
let gv: GVoice | undefined
let gvSync: GvSyncEngine | undefined
let waa: WaaSigner | undefined
// The relay through jai: the Rabbit's SIM, names and read state (relay.ts).
let relay: RelayEngine | undefined
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', onNewMessages)
sync.on('status', () => send('syncStatus', syncStatus()))
sync.start()
api
.getDids()
.then(setDids)
.catch(() => undefined)
}
// The account's numbers, cached in the DB: voip.ms takes seconds to answer, so
// startup uses the cached list and refreshes it in the background.
function setDids(next: Did[]): void {
const changed = JSON.stringify(next) !== JSON.stringify(dids)
dids = next
db.set('dids', JSON.stringify(next))
if (changed) send('stateChanged')
}
// Fresh messages from either provider.
function onNewMessages(msgs: NewMessage[]): void {
media.prefetch(msgs)
send('messages', msgs)
send('conversationsChanged')
// While the window has focus you're looking at them already.
if (settings.notifications && !win?.isFocused()) notifyNew(msgs, { db, contacts, onClick: openFromNotification })
}
function openFromNotification(key: { did: string; contact: string }): void {
if (!win || win.isDestroyed()) return
if (win.isMinimized()) win.restore()
win.show()
win.focus()
send('openConversation', key)
}
const gvNumber = (): string | undefined => db.get('gv_number') || undefined
// Every number we can text from: voip.ms's DIDs, then Google Voice's, then
// the Rabbit's SIM (through jai).
function allDids(): Did[] {
const n = gvNumber()
const out: Did[] = n ? [...dids, { did: n, description: 'Google Voice', smsEnabled: true, provider: 'gvoice' }] : [...dids]
if (relay) out.push({ did: SIM_DID, description: 'Rabbit SIM', smsEnabled: true, provider: 'sim' })
return out
}
const providerOf = (did: string): Provider => (did === SIM_DID ? 'sim' : did === gvNumber() ? 'gvoice' : 'voipms')
function startRelay(): void {
relay?.stop()
relay = undefined
const cfg = loadRelayConfig()
if (!cfg) return
relay = new RelayEngine(db, media, cfg, settings.pollSeconds)
relay.on('messages', onNewMessages)
relay.on('changed', () => send('conversationsChanged'))
relay.on('status', () => send('relayStatus', relay?.status()))
relay.start()
}
// A text over the Rabbit's SIM: pending here until the Rabbit's next check
// sends it and says how it went (relay.ts).
function relaySend(contact: string, text: string, refs: MediaRef[]): void {
if (!relay) throw new Error('The Rabbit relay is off: connect it in Settings → jai.')
const kind = refs.length || isGroup(contact) ? 'mms' : 'sms'
const tempId = db.insertPending({ did: SIM_DID, contact, direction: 'out', body: text, ts: Date.now(), kind, ...(refs.length ? { media: refs } : {}) })
relay.send(tempId, contact, text, refs)
send('conversationsChanged')
}
function syncStatus(): SyncStatus {
const base: SyncStatus = sync?.getStatus() ?? { phase: 'unconfigured', backfillDone: false, total: db.count() }
return { ...base, total: db.count(), ...(gvSync ? { gvoice: gvSync.getStatus() } : {}) }
}
function startGvSync(): void {
const did = gvNumber()
if (!did) return
gvSync?.stop()
waa?.close()
gv = new GVoice(gvTransport())
waa = new WaaSigner(gv)
gvSync = new GvSyncEngine(db, gv, { did, pollSeconds: settings.pollSeconds, backfillFloor: settings.backfillFloor })
gvSync.on('messages', onNewMessages)
gvSync.on('status', () => send('syncStatus', syncStatus()))
gvSync.on('readChanged', () => send('conversationsChanged'))
gvSync.start()
}
// After signing in (either way): learn the number and start syncing.
async function finishGvConnect(): Promise<void> {
const number = normalizeNumber(await new GVoice(gvTransport()).getAccount())
db.set('gv_number', number)
startGvSync()
send('stateChanged')
}
function stopGv(): void {
gvSync?.stop()
waa?.close()
gvSync = undefined
waa = undefined
gv = undefined
}
// ---- the Rabbit (Android app) ----
// In the sandbox this targets the separate dev app with made-up data, so
// trying the installer never puts anything real on the device.
const RABBIT_PKG = SANDBOX ? 'me.teafry.voipmessages.dev' : 'me.teafry.voipmessages'
function rabbitTarget(): rabbit.RabbitTarget {
const apk = SANDBOX ? path.join(app.getAppPath(), 'android/build/dev/DevVoipMessages.apk') : rabbit.bundledApk()?.apk
if (!apk || !fs.existsSync(apk)) throw new Error("This build doesn't include the Android app. Run: python3 android/build.py --ship")
return { pkg: RABBIT_PKG, apk }
}
async function rabbitConfig(): Promise<rabbit.RabbitConfig> {
const chosen = settings.dids
const voipDids = dids.filter((d) => d.smsEnabled && (!chosen.length || chosen.includes(d.did)))
const gv = gvNumber()
const creds = loadCredentials()
return {
...(SANDBOX ? { sandbox: true } : {}),
voipms: SANDBOX ? { username: 'sandbox', password: 'sandbox' } : creds ? { username: creds.username, password: creds.password } : null,
gvoice: gv ? { number: gv, cookies: SANDBOX ? {} : await exportCookies() } : null,
relay: (() => {
const r = loadRelayConfig()
return r ? { url: r.url, token: r.token, key: r.key } : null
})(),
dids: voipDids.map((d) => ({ did: d.did, description: d.description })),
defaultDid: settings.defaultDid ?? voipDids[0]?.did ?? gv
}
}
function rabbitDeps(): Omit<rabbit.InstallDeps, 'mediaDir'> {
return { db, target: rabbitTarget(), config: rabbitConfig, progress: (step) => send('rabbitProgress', step) }
}
// ---- 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 })
}
}
// ---- MMS attachments: mms-media://m/<messageId>/<index>[?thumb] ----
// ?thumb: a smaller copy of a still picture, for the chat and Get info.
async function serveMedia(req: Request): Promise<Response> {
const url = new URL(req.url)
const [id, index] = url.pathname.slice(1).split('/').map(Number)
const ref = await media.resolve(id, index)
if (!ref?.file) return new Response(null, { status: 404 })
const thumb = url.searchParams.has('thumb') ? await media.thumb(ref).catch(() => undefined) : undefined
const file = thumb ?? media.filePath(ref.file)
const mime = thumb ? (thumb.endsWith('.png') ? 'image/png' : 'image/jpeg') : (ref.mime ?? guessMime(ref.file) ?? 'application/octet-stream')
return new Response(await fs.promises.readFile(file), { headers: { 'content-type': mime } })
}
async function saveMediaAs(id: number, index: number): Promise<void> {
const m = db.getMessage(id)
const ref = await media.resolve(id, index)
if (!m || !ref?.file) throw new Error('That attachment is no longer available.')
const r = await dialog.showSaveDialog(win!, {
defaultPath: path.join(app.getPath('downloads'), `mms-${localDay(new Date(m.ts))}-${id}-${index + 1}.${extFor(ref.mime)}`)
})
if (!r.canceled && r.filePath) fs.copyFileSync(media.filePath(ref.file), r.filePath)
}
// ---- Export chat ----
async function exportChat(did: string, contact: string, opts: ChatExport): Promise<boolean> {
const msgs = inRange(db.getConversationMessages(did, contact), opts)
if (!msgs.length) throw new Error('There are no messages in those dates.')
const name = `${opts.title} - ${rangeLabel(opts)}`.replace(/[/\\:*?"<>|]/g, '-')
const r = await dialog.showSaveDialog(win!, {
defaultPath: path.join(app.getPath('documents'), `${name}.${opts.format}`),
filters: [opts.format === 'pdf' ? { name: 'PDF', extensions: ['pdf'] } : { name: 'Text', extensions: ['txt'] }]
})
if (r.canceled || !r.filePath) return false
if (opts.format === 'txt') {
fs.writeFileSync(r.filePath, exportText(contact, msgs, opts))
return true
}
// Photos as local files (fetching any not downloaded yet, a few at a time).
const photos = new Map<string, string>()
if (opts.attachments) {
const wanted = msgs.flatMap((m) => (m.media ?? []).flatMap((ref, i) => (ref.mime?.startsWith('image/') ? [[m.id, i] as const] : [])))
for (let k = 0; k < wanted.length; k += 4) {
await Promise.all(
wanted.slice(k, k + 4).map(async ([id, i]) => {
const ref = await media.resolve(id, i).catch(() => undefined)
if (ref?.file) photos.set(`${id}/${i}`, pathToFileURL(media.filePath(ref.file)).href)
})
)
}
}
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bubble-export-'))
const page = new BrowserWindow({ show: false, webPreferences: { javascript: false } })
try {
const html = path.join(dir, 'chat.html')
fs.writeFileSync(html, exportHtml(contact, msgs, opts, (m, i) => photos.get(`${m.id}/${i}`)))
await page.loadFile(html)
fs.writeFileSync(r.filePath, await page.webContents.printToPDF({ pageSize: 'Letter', printBackground: true }))
} finally {
page.destroy()
fs.rmSync(dir, { recursive: true, force: true })
}
return true
}
// For "Copy image": the renderer decodes the bytes (any format Chromium reads)
// and hands back a PNG, the one image format every clipboard consumer takes.
async function readMedia(id: number, index: number): Promise<{ mime: string; data: Uint8Array<ArrayBuffer> }> {
const ref = await media.resolve(id, index)
if (!ref?.file) throw new Error('That attachment is no longer available.')
return { mime: ref.mime ?? guessMime(ref.file) ?? 'application/octet-stream', data: new Uint8Array(fs.readFileSync(media.filePath(ref.file))) }
}
// ---- icon: the dark original or its negative (Settings → Appearance) ----
const iconFile = (style: IconStyle | undefined): string =>
path.join(__dirname, '../../resources', style === 'inverted' ? 'icon-inverted.png' : 'icon.png')
// The window's icon, and the launcher's (the copy scripts/install-desktop.sh
// put in ~/.local/share/icons), so the dash and Alt+Tab match too.
function applyIcon(): void {
const file = iconFile(settings.icon)
win?.setIcon(file)
if (SANDBOX || !app.isPackaged) return
const installed = path.join(os.homedir(), '.local/share/icons/hicolor/512x512/apps/voipms-desktop.png')
try {
if (!fs.existsSync(installed)) return
const want = fs.readFileSync(file)
if (Buffer.compare(want, fs.readFileSync(installed)) === 0) return
fs.writeFileSync(installed, want)
// GNOME caches icons by name: nudge it to look again.
const now = new Date()
fs.utimesSync(path.join(os.homedir(), '.local/share/icons/hicolor'), now, now)
} catch (e) {
console.warn('[icon] could not update the launcher icon:', (e as Error).message)
}
}
// ---- theme + zoom ----
function applyTheme(): void {
nativeTheme.themeSource = settings.theme
win?.setBackgroundColor(windowBackground())
}
// The window itself stays transparent: the page paints its rounded tile.
function windowBackground(): string {
return '#00000000'
}
// ---- the window's own frame (design.html#window, #titlebar) ----
// Square corners when maximized, fullscreen or tiled. Wayland doesn't tell
// us about tiling, so a window within 64 px of the screen's full height
// counts as tiled.
function windowState(): WindowState {
if (!win) return { square: false, maximized: false, focused: true }
const maximized = win.isMaximized()
const full = screen.getDisplayMatching(win.getBounds()).bounds
const tiled = full.height - win.getBounds().height <= 64
return { square: maximized || win.isFullScreen() || tiled, maximized, focused: win.isFocused() }
}
function sendWindowState(): void {
if (win && !win.isDestroyed()) win.webContents.send('windowState', windowState())
}
// GNOME's button-layout ("appmenu:minimize,maximize,close"): which side
// the window buttons go on, and in what order.
let buttonLayout: string | undefined
function windowButtons(): string {
if (buttonLayout === undefined) {
try {
buttonLayout = execFileSync('gsettings', ['get', 'org.gnome.desktop.wm.preferences', 'button-layout'], { encoding: 'utf8' })
.trim()
.replace(/^'|'$/g, '')
} catch {
buttonLayout = ''
}
if (!buttonLayout.includes(':')) buttonLayout = 'appmenu:minimize,maximize,close'
}
return buttonLayout
}
const ZOOM_STEP = 0.5
const ZOOM_MIN = -3
const ZOOM_MAX = 4
function setZoom(level: number): void {
if (!win) return
const z = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, level))
win.webContents.setZoomLevel(z)
saveZoom(z)
}
// ---- sending ----
// voip.ms can take half a minute to accept a message, so sends to one
// conversation go out one at a time, in the order they were typed; otherwise a
// quick follow-up overtakes a slow message on the recipient's phone.
const sendQueues = new Map<string, Promise<void>>()
function enqueue<T>(key: string, job: () => Promise<T>): Promise<T> {
const run = (sendQueues.get(key) ?? Promise.resolve()).then(job)
const tail = run.then(
() => undefined,
() => undefined
)
sendQueues.set(key, tail)
void tail.then(() => sendQueues.get(key) === tail && sendQueues.delete(key))
return run
}
// The pending bubble shows up right away; the voip.ms call waits its turn.
// Resolves once the message is sent or marked failed (the failure shows on the
// message, with a Retry button).
async function deliver(m: Omit<NewMessage, 'id'>, attempt: () => Promise<number>): Promise<void> {
const engine = providerOf(m.did) === 'gvoice' ? gvSync : sync
const tempId = db.insertPending(m)
send('conversationsChanged')
try {
await enqueue(`${m.did}:${m.contact}`, () =>
sendWithRetry(tempId, {
db,
attempt,
checkSent: () => engine?.pollNow() ?? Promise.resolve(),
...(engine === gvSync ? { classify: classifyGvError, describe: gvErrorMessage } : {})
})
)
} finally {
send('conversationsChanged')
engine?.burst()
}
}
const voipAttempt = (call: (api: VoipMs) => Promise<number>) => (): Promise<number> => {
if (!api) throw new VoipMsError('not_signed_in')
return call(api)
}
// One Google Voice send: text and at most one photo. Resolves with the id the
// message has in GV's own listing, so the next sync recognises it.
async function gvSend(did: string, contact: string, text: string, ref?: MediaRef): Promise<number> {
if (!gv) throw new GVoiceError('Google Voice is not connected. Connect it in Settings.', 401)
const recipients = groupMembers(contact).map(toE164)
let threadId = db.getGvThread(did, contact) ?? ''
if (!threadId && !isGroup(contact)) {
// A 1:1 thread's id is predictable, but it only exists once either side
// has texted; otherwise start one from the recipient list.
try {
threadId = (await gv.getThread(`t.${recipients[0]}`, 1)).id
} catch (e) {
if (!(e instanceof GVoiceError && e.status === 404)) throw e
}
}
const txn = transactionId()
const trackingData = await waa?.sign(threadId, recipients, txn)
const photo = ref && { mime: ref.mime!, data: new Uint8Array(fs.readFileSync(media.filePath(ref.file!))) }
const r = await gv.sendSms({ threadId, recipients, text, media: photo, transactionId: txn, trackingData })
const thread = r.threadId || threadId
if (thread) db.setGvThread(did, contact, thread)
// Find our message by transaction id: the listing is what later syncs see.
const listed = thread ? (await gv.getThread(thread, 10).catch(() => undefined))?.messages.find((m) => m.transactionId === txn) : undefined
return gvMessageId(listed?.id ?? r.threadItemId)
}
// Anything longer than one SMS goes out as a single text-only MMS (voip.ms;
// Google Voice has no such limit).
async function sendText(did: string, contact: string, text: string): Promise<void> {
if (did === SIM_DID) return relaySend(contact, text, [])
const from = normalizeNumber(did)
const m: Omit<NewMessage, 'id'> = { did: from, contact, direction: 'out', body: text, ts: Date.now() }
if (providerOf(from) === 'gvoice') return deliver(m, () => gvSend(from, contact, text))
if (charCount(text) > SMS_TEXT_LIMIT) return sendMmsRefs(did, contact, text, [])
if (!api) throw new Error('Not signed in')
const dst = normalizeNumber(contact)
await deliver({ ...m, contact: dst }, voipAttempt((api) => api.sendSms(from, dst, text)))
}
// One MMS: text (up to 2048 chars) plus up to three attachments, each already
// small enough for voip.ms (the renderer compresses before handing them over).
async function sendMms(did: string, contact: string, text: string, attachments: OutgoingAttachment[]): Promise<void> {
const refs: MediaRef[] = attachments.map((a) => ({ file: media.save(a.data, a.mime), mime: a.mime, width: a.width, height: a.height }))
await sendMmsRefs(did, contact, text, refs)
}
async function sendMmsRefs(did: string, contact: string, text: string, refs: MediaRef[]): Promise<void> {
if (did === SIM_DID) return relaySend(contact, text, refs)
const from = normalizeNumber(did)
if (providerOf(from) === 'gvoice') {
if (refs.some((r) => !SendMediaType[r.mime ?? ''])) throw new Error('Google Voice can only send photos.')
// GV carries one photo per message: the text rides with the first.
await Promise.all(
refs.map((ref, i) => {
const body = i === 0 ? text : ''
const m: Omit<NewMessage, 'id'> = { did: from, contact, direction: 'out', body, ts: Date.now() + i, kind: 'mms', media: [ref] }
return deliver(m, () => gvSend(from, contact, body, ref))
})
)
return
}
if (!api) throw new Error('Not signed in')
const dst = normalizeNumber(contact)
await deliver(
{ did: from, contact: dst, direction: 'out', body: text, ts: Date.now(), kind: 'mms', media: refs },
voipAttempt((api) => {
const payload = refs.map((r) => `data:${r.mime};base64,${fs.readFileSync(media.filePath(r.file!)).toString('base64')}`)
return api.sendMms(from, dst, text, payload)
})
)
}
function registerIpc(): void {
ipcMain.handle('getState', (): AppState => {
const creds = loadCredentials()
return {
// Sandbox: show the main UI without an account (made-up data).
configured: !!creds || !!gvNumber() || !!SANDBOX,
username: creds?.username,
settings,
dataDir: getDataDir(),
dids: allDids(),
keyringBackend: safeBackend(),
gvoiceNumber: gvNumber()
}
})
ipcMain.handle('rabbitStatus', async () => {
const bundled = SANDBOX ? undefined : rabbit.bundledApk()
const device = await rabbit.status(RABBIT_PKG)
return { adb: !!rabbit.findAdb(), bundledVersion: bundled?.version, ...(device ? { device } : {}) }
})
ipcMain.handle('rabbitInstall', async (_e, mode: 'full' | 'update' = 'full') => {
const names = await rabbit.install({ ...rabbitDeps(), mediaDir: path.join(getDataDir(), 'media'), mode })
if (names) send('conversationsChanged')
})
ipcMain.handle('rabbitSync', async () => {
const names = await rabbit.sync(rabbitDeps())
if (names) send('conversationsChanged')
})
ipcMain.handle('connectGoogleVoice', async () => {
await signInWindow(win)
await finishGvConnect()
})
ipcMain.handle('connectGoogleVoiceCookies', async (_e, text: string) => {
await importCookies(parseCookies(text))
await finishGvConnect()
})
ipcMain.handle('disconnectGoogleVoice', async () => {
stopGv()
db.db.prepare(`DELETE FROM kv WHERE key = 'gv_number'`).run()
await clearGvSession()
send('stateChanged')
send('syncStatus', syncStatus())
})
ipcMain.handle('testCredentials', async (_e, creds: Credentials) => {
setDids(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
const syncChanged = floorChanged || s.pollSeconds !== settings.pollSeconds || s.dids.join() !== settings.dids.join()
settings = s
saveSettings(s)
applyTheme()
const creds = loadCredentials()
if (creds && syncChanged) startSync(creds)
if (syncChanged && gvSync) startGvSync()
if (floorChanged) {
sync?.resetBackfill()
gvSync?.resetBackfill()
}
})
ipcMain.handle('windowState', () => windowState())
ipcMain.handle('windowButtons', () => windowButtons())
ipcMain.handle('windowControl', (_e, action: WindowAction) => {
if (!win) return
if (action === 'zoomIn') setZoom(win.webContents.getZoomLevel() + ZOOM_STEP)
else if (action === 'zoomOut') setZoom(win.webContents.getZoomLevel() - ZOOM_STEP)
else if (action === 'zoomReset') setZoom(0)
else if (action === 'minimize') win.minimize()
else if (action === 'maximize') {
if (win.isMaximized()) win.unmaximize()
else win.maximize()
} else if (action === 'close') win.close()
else app.quit()
})
ipcMain.handle('setIcon', (_e, icon: IconStyle) => {
settings = { ...settings, icon }
saveSettings(settings)
applyIcon()
})
// Theme takes effect (and is saved) immediately, without the dialog's Save.
ipcMain.handle('setTheme', (_e, theme: Theme) => {
settings = { ...settings, theme }
saveSettings(settings)
applyTheme()
})
ipcMain.handle('signOut', () => {
sync?.stop()
sync = undefined
api = undefined
clearCredentials()
setDids([])
send('syncStatus', syncStatus())
})
ipcMain.handle('listContacts', () => contacts.list())
// The sandbox never touches the real address books: pretend.
ipcMain.handle('listAddressBooks', () =>
SANDBOX ? { books: [{ uid: 'sandbox', name: 'Contacts', account: 'Sandbox' }], default: 'sandbox' } : listAddressBooks()
)
ipcMain.handle('addContact', async (_e, c: NewContact) => {
const book = SANDBOX ? 'Contacts (sandbox)' : await addToAddressBook({ ...c, book: c.book ?? settings.contactBook })
const name = [c.first, c.last].filter(Boolean).join(' ') || c.org
contacts.addLocal({ name, number: normalizeNumber(c.number), label: 'cell', book })
return book
})
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) => {
// Clear the unread badge on the phone too.
const thread = providerOf(did) === 'gvoice' && db.hasUnread(did, contact) ? db.getGvThread(did, contact) : undefined
if (thread) gv?.markRead(thread).catch((e: Error) => console.warn('[gvoice] mark read failed:', e.message))
const had = db.hasUnread(did, contact)
db.markRead(did, contact)
clearNotifications(did, contact)
if (had) relay?.stateChanged()
send('conversationsChanged')
})
ipcMain.handle('markUnread', (_e, did: string, contact: string) => {
db.markUnread(did, contact)
relay?.stateChanged()
send('conversationsChanged')
})
ipcMain.handle('setArchived', (_e, did: string, contact: string, archived: boolean) => {
db.setArchived(did, contact, archived)
relay?.stateChanged()
send('conversationsChanged')
})
ipcMain.handle('setName', (_e, did: string, contact: string, name: string | null) => {
db.setName(did, contact, name)
relay?.stateChanged()
send('conversationsChanged')
})
ipcMain.handle('getDrafts', () => db.getDrafts())
ipcMain.handle('setDraft', (_e, contact: string, text: string) => db.setDraft(contact, text))
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, attachments?: OutgoingAttachment[]) =>
attachments?.length ? sendMms(did, contact, text, attachments) : 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)
if (m.kind === 'mms' && m.media?.length) await sendMmsRefs(m.did, m.contact, m.body, m.media)
else await sendText(m.did, m.contact, m.body)
})
ipcMain.handle('saveMedia', (_e, id: number, index: number) => saveMediaAs(id, index))
ipcMain.handle('exportChat', (_e, did: string, contact: string, opts: ChatExport) => exportChat(did, contact, opts))
ipcMain.handle('readMedia', (_e, id: number, index: number) => readMedia(id, index))
ipcMain.handle('copyImage', (_e, png: Uint8Array<ArrayBuffer>) =>
clipboard.write([new ClipboardItem({ 'image/png': new Blob([png], { type: 'image/png' }) })])
)
ipcMain.handle('relayStatus', () => relay?.status() ?? { connected: false, waiting: 0, url: loadRelayConfig()?.url })
ipcMain.handle('relayConnect', async (_e, url: string, token: string) => {
const origin = checkUrl(url)
const tok = token.trim()
if (!/^[A-Za-z0-9_-]{20,200}$/.test(tok)) throw new Error("That doesn't look like the relay's token.")
// A harmless call that needs the token: acknowledges nothing, posts nothing.
const res = await fetch(`${origin}/sync`, {
method: 'POST',
headers: { Authorization: `Bearer ${tok}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ device: 'desktop', since: Number(db.get('relay_cursor') ?? 0), push: [] }),
signal: AbortSignal.timeout(15_000)
}).catch(() => undefined)
if (!res) throw new Error(`Couldn't reach ${origin}. Is tailscale up?`)
if (res.status === 401) throw new Error('jai turned down that token.')
if (!res.ok) throw new Error(`jai answered ${res.status}.`)
// Keep the key across reconnects so the Rabbit's copy stays good.
saveRelayConfig({ url: origin, token: tok, key: loadRelayConfig()?.key ?? newKey() })
startRelay()
send('stateChanged')
})
ipcMain.handle('relayDisconnect', () => {
relay?.stop()
relay = undefined
clearRelayConfig()
send('stateChanged')
})
ipcMain.handle('syncStatus', () => syncStatus())
ipcMain.handle('pollNow', () => Promise.all([sync?.pollNow(), gvSync?.pollNow(), relay?.syncNow()]))
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: SANDBOX ? 'bubble (sandbox)' : 'bubble',
// design.html#window: frameless and see-through; the page paints the
// rounded tile, its own title bar (#titlebar) and menu bar (#menubar).
frame: false,
transparent: true,
backgroundColor: '#00000000',
icon: iconFile(settings.icon),
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)
}
})
// Ctrl +/-/0 zoom (handled here so Ctrl+= works without Shift, and the
// default menu's accelerators don't double-step).
win.webContents.on('before-input-event', (e, input) => {
if (input.type !== 'keyDown' || !(input.control || input.meta) || input.alt) return
const level = win!.webContents.getZoomLevel()
if (input.key === '=' || input.key === '+' || input.code === 'NumpadAdd') setZoom(level + ZOOM_STEP)
else if (input.key === '-' || input.key === '_' || input.code === 'NumpadSubtract') setZoom(level - ZOOM_STEP)
else if (input.key === '0' || input.code === 'Numpad0') setZoom(0)
else return
e.preventDefault()
})
// Ctrl+scroll wheel / pinch.
win.webContents.on('zoom-changed', (_e, dir) => setZoom(win!.webContents.getZoomLevel() + (dir === 'in' ? ZOOM_STEP : -ZOOM_STEP)))
win.webContents.on('did-finish-load', () => win!.webContents.setZoomLevel(loadZoom()))
// The hidden Google Voice window would otherwise keep 'window-all-closed'
// from firing, leaving a windowless process holding the single-instance lock.
for (const ev of ['maximize', 'unmaximize', 'enter-full-screen', 'leave-full-screen', 'resize', 'focus', 'blur'] as const)
win.on(ev as 'resize', sendWindowState)
win.on('closed', () => {
win = undefined
app.quit()
})
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 && !win.isDestroyed()) {
if (win.isMinimized()) win.restore()
win.focus()
}
})
app.whenReady().then(async () => {
moveToBubbleData()
settings = loadSettings()
db = new MessageDb(path.join(getDataDir(), 'messages.db'))
if (SANDBOX) seedDemo(db)
dids = JSON.parse(db.get('dids') ?? '[]') as Did[]
media = new MediaStore(path.join(getDataDir(), 'media'), db, (url, at) => {
if (url.startsWith('mmspart:')) {
// On the Rabbit: ask for it; it shows up after the Rabbit's next check.
if (at) relay?.want(at.id, at.index, url)
return Promise.reject(new Error('on the Rabbit'))
}
if (!url.startsWith('gv:')) return net.fetch(url)
if (!gv) return Promise.reject(new Error('Google Voice is not connected'))
return gv.downloadMedia(url.slice(3))
})
applyTheme()
contacts = new ContactDirectory()
contacts.on('changed', () => send('contactsChanged'))
protocol.handle('contact-photo', servePhoto)
protocol.handle('mms-media', serveMedia)
registerIpc()
createWindow()
applyIcon()
// The sandbox stays away from the real address book.
if (!SANDBOX) void contacts.load()
const creds = loadCredentials()
if (creds) startSync(creds)
if (gvNumber() && (await hasGvSession())) startGvSync()
startRelay()
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()
stopGv()
relay?.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())