v0.2.0: bubble for Android 0.2.0 — chat search, swipe for unread, faster chat opening
Desktop: - Search lists chats whose own name matches first, so a named group isn't pushed out of the top 8 by chats that merely include a member. Android (Rabbit R1) app, 0.2.0: - Pull the chat list past its top for a search box (name, person, number, then group members; archived chats too; Back clears it). - Swipe right to left marks a chat unread / read over a magenta band; left to right still archives (SwipeActions replaces SwipeArchive). - Google Voice chats don't offer voice notes in the paperclip bubble. - Chats open with their newest 60 messages, then the full history; marking read (and the Google Voice network call) waits until they're on screen. Cached pictures show at once, and one slow download no longer blocks the other images. Fixed a contacts reload race. - Sandbox data gains filler chats, a named group and a 4,000-message chat. Also: the Android app, Google Voice support, media, export, emoji and the other work since the first commit, and a CLAUDE.md carrying the privacy rule.
This commit is contained in:
+456
-45
@@ -1,29 +1,52 @@
|
||||
import { app, BrowserWindow, dialog, ipcMain, net, protocol, safeStorage, shell } from 'electron'
|
||||
// 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, shell } from 'electron'
|
||||
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 { splitMessage, normalizeNumber } from '@shared/phone'
|
||||
import type { Credentials, Did, Message, Settings } from '@shared/types'
|
||||
import { charCount, groupMembers, isGroup, normalizeNumber, SMS_TEXT_LIMIT } from '@shared/phone'
|
||||
import type { ChatExport, Credentials, Did, MediaRef, Message, NewContact, OutgoingAttachment, Provider, Settings, SyncStatus, Theme } from '@shared/types'
|
||||
import type { AppState } from '@shared/api'
|
||||
import { ContactDirectory } from './contacts'
|
||||
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, saveSettings, setDataDir } from './settings'
|
||||
import { SyncEngine } from './sync'
|
||||
import { VoipMs } from './voipms'
|
||||
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'
|
||||
|
||||
protocol.registerSchemesAsPrivileged([{ scheme: 'contact-photo', privileges: { standard: true, secure: true, supportFetchAPI: true } }])
|
||||
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
|
||||
|
||||
const send = (channel: string, ...args: unknown[]): void => {
|
||||
if (win && !win.isDestroyed()) win.webContents.send(channel, ...args)
|
||||
@@ -47,18 +70,115 @@ 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.on('messages', onNewMessages)
|
||||
sync.on('status', () => send('syncStatus', syncStatus()))
|
||||
sync.start()
|
||||
api
|
||||
.getDids()
|
||||
.then((d) => (dids = d))
|
||||
.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.
|
||||
function allDids(): Did[] {
|
||||
const n = gvNumber()
|
||||
return n ? [...dids, { did: n, description: 'Google Voice', smsEnabled: true, provider: 'gvoice' }] : dids
|
||||
}
|
||||
|
||||
const providerOf = (did: string): Provider => (did === gvNumber() ? 'gvoice' : 'voipms')
|
||||
|
||||
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,
|
||||
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))
|
||||
@@ -86,46 +206,254 @@ async function servePhoto(req: Request): Promise<Response> {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- MMS attachments: mms-media://m/<messageId>/<index> ----
|
||||
async function serveMedia(req: Request): Promise<Response> {
|
||||
const [id, index] = new URL(req.url).pathname.slice(1).split('/').map(Number)
|
||||
const ref = await media.resolve(id, index)
|
||||
if (!ref?.file) return new Response(null, { status: 404 })
|
||||
const headers = { 'content-type': ref.mime ?? guessMime(ref.file) ?? 'application/octet-stream' }
|
||||
return new Response(fs.readFileSync(media.filePath(ref.file)), { headers })
|
||||
}
|
||||
|
||||
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))) }
|
||||
}
|
||||
|
||||
// ---- theme + zoom ----
|
||||
function applyTheme(): void {
|
||||
nativeTheme.themeSource = settings.theme
|
||||
win?.setBackgroundColor(windowBackground())
|
||||
}
|
||||
|
||||
function windowBackground(): string {
|
||||
return nativeTheme.shouldUseDarkColors ? '#121212' : '#ffffff'
|
||||
}
|
||||
|
||||
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> {
|
||||
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> {
|
||||
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
|
||||
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
|
||||
}
|
||||
sync?.burst()
|
||||
if (failed) throw failed
|
||||
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', async (): Promise<AppState> => {
|
||||
ipcMain.handle('getState', (): 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'],
|
||||
// Sandbox: show the main UI without an account (made-up data).
|
||||
configured: !!creds || !!gvNumber() || !!SANDBOX,
|
||||
username: creds?.username,
|
||||
settings,
|
||||
dataDir: getDataDir(),
|
||||
dids,
|
||||
keyringBackend: safeBackend()
|
||||
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) => {
|
||||
dids = await new VoipMs(creds).getDids()
|
||||
setDids(await new VoipMs(creds).getDids())
|
||||
return dids
|
||||
})
|
||||
ipcMain.handle('saveSetup', (_e, creds: Credentials, s: Settings) => {
|
||||
@@ -136,28 +464,72 @@ function registerIpc(): void {
|
||||
})
|
||||
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) startSync(creds)
|
||||
if (floorChanged) sync?.resetBackfill()
|
||||
if (creds && syncChanged) startSync(creds)
|
||||
if (syncChanged && gvSync) startGvSync()
|
||||
if (floorChanged) {
|
||||
sync?.resetBackfill()
|
||||
gvSync?.resetBackfill()
|
||||
}
|
||||
})
|
||||
// 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))
|
||||
db.markRead(did, contact)
|
||||
clearNotifications(did, contact)
|
||||
send('conversationsChanged')
|
||||
})
|
||||
ipcMain.handle('markUnread', (_e, did: string, contact: string) => {
|
||||
db.markUnread(did, contact)
|
||||
send('conversationsChanged')
|
||||
})
|
||||
ipcMain.handle('setArchived', (_e, did: string, contact: string, archived: boolean) => {
|
||||
db.setArchived(did, contact, archived)
|
||||
send('conversationsChanged')
|
||||
})
|
||||
ipcMain.handle('setName', (_e, did: string, contact: string, name: string | null) => {
|
||||
db.setName(did, contact, name)
|
||||
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) => sendText(did, contact, text))
|
||||
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')
|
||||
@@ -166,11 +538,18 @@ function registerIpc(): void {
|
||||
const m: Message | undefined = db.getMessage(id)
|
||||
if (!m || m.status !== 'failed') return
|
||||
db.deleteMessage(id)
|
||||
await sendText(m.did, m.contact, m.body)
|
||||
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('syncStatus', () => sync?.getStatus() ?? { phase: 'unconfigured', backfillDone: false, total: db.count() })
|
||||
ipcMain.handle('pollNow', () => sync?.pollNow())
|
||||
ipcMain.handle('syncStatus', () => syncStatus())
|
||||
ipcMain.handle('pollNow', () => Promise.all([sync?.pollNow(), gvSync?.pollNow()]))
|
||||
ipcMain.handle('openDataFolder', () => shell.openPath(getDataDir()))
|
||||
ipcMain.handle('snapshotNow', () => db.snapshot(snapshotDir()))
|
||||
ipcMain.handle('chooseDataDir', async () => {
|
||||
@@ -214,8 +593,8 @@ function createWindow(): void {
|
||||
height: 800,
|
||||
minWidth: 760,
|
||||
minHeight: 480,
|
||||
title: 'voip.ms Messages',
|
||||
backgroundColor: '#1b1b1d',
|
||||
title: SANDBOX ? 'bubble (sandbox)' : 'bubble',
|
||||
backgroundColor: windowBackground(),
|
||||
autoHideMenuBar: true,
|
||||
icon: path.join(__dirname, '../../resources/icon.png'),
|
||||
webPreferences: {
|
||||
@@ -235,12 +614,32 @@ function createWindow(): void {
|
||||
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.
|
||||
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) {
|
||||
if (win && !win.isDestroyed()) {
|
||||
if (win.isMinimized()) win.restore()
|
||||
win.focus()
|
||||
}
|
||||
@@ -249,15 +648,26 @@ app.on('second-instance', () => {
|
||||
app.whenReady().then(async () => {
|
||||
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) => {
|
||||
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()
|
||||
void contacts.load()
|
||||
// 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()
|
||||
|
||||
void dailySnapshot()
|
||||
setInterval(() => void dailySnapshot(), 60 * 60 * 1000)
|
||||
@@ -269,6 +679,7 @@ app.on('before-quit', (e) => {
|
||||
e.preventDefault()
|
||||
quitting = true
|
||||
sync?.stop()
|
||||
stopGv()
|
||||
contacts?.close()
|
||||
db.snapshot(snapshotDir())
|
||||
.catch((err) => console.error('[snapshot] on quit failed:', err))
|
||||
|
||||
Reference in New Issue
Block a user