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:
+38
-6
@@ -1,5 +1,6 @@
|
||||
// Reads contacts from GNOME's Evolution Data Server caches (read-only) and maps
|
||||
// phone numbers to names + photos.
|
||||
// phone numbers to names + photos. Adding a contact goes through EDS itself
|
||||
// (resources/eds-add-contact.py), which syncs it on to e.g. Nextcloud.
|
||||
import Database from 'better-sqlite3'
|
||||
import { execFile } from 'node:child_process'
|
||||
import { EventEmitter } from 'node:events'
|
||||
@@ -7,7 +8,7 @@ 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'
|
||||
import type { AddressBook, ContactInfo, NewContact } from '@shared/types'
|
||||
|
||||
export interface BookSource {
|
||||
uid: string
|
||||
@@ -130,10 +131,32 @@ export function parseVCard(vcard: string): VCardContact {
|
||||
|
||||
// ---------- 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')
|
||||
function helperPath(name = 'eds-sources.py'): string {
|
||||
// In a packaged app the helpers ship in resources/, in dev they're in the repo.
|
||||
const packaged = path.join(process.resourcesPath ?? '', name)
|
||||
return fs.existsSync(packaged) ? packaged : path.join(__dirname, '../../resources', name)
|
||||
}
|
||||
|
||||
function runAddHelper(args: string[], input?: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = execFile('python3', [helperPath('eds-add-contact.py'), ...args], { timeout: 60_000 }, (err, stdout, stderr) => {
|
||||
if (err) reject(new Error(stderr.trim().split('\n').pop() || err.message))
|
||||
else resolve(stdout)
|
||||
})
|
||||
if (input !== undefined) child.stdin?.end(input)
|
||||
})
|
||||
}
|
||||
|
||||
// Address books a contact can be added to, and the one GNOME Contacts uses.
|
||||
export async function listAddressBooks(): Promise<{ books: AddressBook[]; default?: string }> {
|
||||
const r = JSON.parse(await runAddHelper(['books'])) as { books: AddressBook[]; default: string | null }
|
||||
return { books: r.books, ...(r.default ? { default: r.default } : {}) }
|
||||
}
|
||||
|
||||
// Adds the contact; resolves with the name of the book it went into.
|
||||
export async function addToAddressBook(c: NewContact): Promise<string> {
|
||||
const r = JSON.parse(await runAddHelper(['add'], JSON.stringify(c))) as { book: string }
|
||||
return r.book
|
||||
}
|
||||
|
||||
export function listSources(): Promise<BookSource[]> {
|
||||
@@ -273,6 +296,15 @@ export class ContactDirectory extends EventEmitter {
|
||||
return this.all
|
||||
}
|
||||
|
||||
// Show a just-added contact right away; the next load() (when EDS writes
|
||||
// its cache) replaces it with the real entry.
|
||||
addLocal(info: ContactInfo): void {
|
||||
if (this.byNumber.has(info.number)) return
|
||||
this.byNumber.set(info.number, { info, rank: 0 })
|
||||
this.all = [...this.all, info].sort((a, b) => a.name.localeCompare(b.name))
|
||||
this.emit('changed')
|
||||
}
|
||||
|
||||
lookup(number: string): ContactInfo | undefined {
|
||||
return this.byNumber.get(normalizeNumber(number))?.info
|
||||
}
|
||||
|
||||
+342
-37
@@ -2,10 +2,28 @@
|
||||
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 type { Conversation, Direction, MediaRef, Message, MessageKind, MessageStatus, SearchHit } from '@shared/types'
|
||||
import { SNIPPET_END, SNIPPET_START } from '@shared/types'
|
||||
import { fixVoipDst } from './voipms'
|
||||
|
||||
const SCHEMA_VERSION = 1
|
||||
const SCHEMA_VERSION = 10
|
||||
|
||||
export interface ReadState {
|
||||
did: string
|
||||
contact: string
|
||||
lastRead: number // read up to this message time
|
||||
markedUnread: boolean
|
||||
unreadTs?: number | null // when read/unread last changed
|
||||
archivedAt?: number | null
|
||||
archivedTs?: number | null // when archived/unarchived last changed
|
||||
}
|
||||
|
||||
export interface NameChange {
|
||||
did: string
|
||||
contact: string
|
||||
name: string | null
|
||||
ts: number
|
||||
}
|
||||
|
||||
export interface NewMessage {
|
||||
id: number
|
||||
@@ -15,17 +33,27 @@ export interface NewMessage {
|
||||
body: string
|
||||
ts: number
|
||||
status?: MessageStatus
|
||||
kind?: MessageKind
|
||||
media?: MediaRef[]
|
||||
sender?: string
|
||||
}
|
||||
|
||||
interface MessageRow {
|
||||
id: number
|
||||
did: string
|
||||
contact: string
|
||||
direction: Direction
|
||||
body: string
|
||||
ts: number
|
||||
kind: 'sms' | 'mms'
|
||||
status: MessageStatus
|
||||
type MessageRow = Omit<Message, 'media' | 'error' | 'sender'> & { media_json: string | null; error: string | null; sender: string | null }
|
||||
|
||||
const MESSAGE_COLS = 'id, did, contact, direction, body, ts, kind, status, media_json, error, sender'
|
||||
|
||||
// How far a sent message's voip.ms time can be from the time we stamped it
|
||||
// locally and still count as the same message (sends can queue and retry).
|
||||
const MATCH_BEFORE = 2 * 60_000
|
||||
const MATCH_AFTER = 15 * 60_000
|
||||
|
||||
function fromRow({ media_json, error, sender, ...m }: MessageRow): Message {
|
||||
return {
|
||||
...m,
|
||||
...(media_json ? { media: JSON.parse(media_json) as MediaRef[] } : {}),
|
||||
...(error ? { error } : {}),
|
||||
...(sender ? { sender } : {})
|
||||
}
|
||||
}
|
||||
|
||||
export class MessageDb {
|
||||
@@ -43,7 +71,7 @@ export class MessageDb {
|
||||
private migrate(): void {
|
||||
const version = this.db.pragma('user_version', { simple: true }) as number
|
||||
if (version >= SCHEMA_VERSION) return
|
||||
this.db.exec(`
|
||||
if (version < 1) this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id INTEGER PRIMARY KEY, -- voip.ms id (negative = local pending)
|
||||
did TEXT NOT NULL,
|
||||
@@ -51,9 +79,9 @@ export class MessageDb {
|
||||
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)
|
||||
kind TEXT NOT NULL DEFAULT 'sms', -- 'sms' | 'mms'
|
||||
status TEXT NOT NULL DEFAULT 'delivered',
|
||||
media_json TEXT -- MMS attachments (future)
|
||||
media_json TEXT -- MMS attachments: MediaRef[]
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS messages_conv ON messages (did, contact, ts);
|
||||
CREATE INDEX IF NOT EXISTS messages_ts ON messages (ts);
|
||||
@@ -78,6 +106,52 @@ export class MessageDb {
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
`)
|
||||
// v2: sync switched from getSMS to getMMS (which also returns MMS). Redo the
|
||||
// history import once so past MMS show up; existing rows dedupe by id.
|
||||
if (version === 1) this.db.exec(`DELETE FROM kv WHERE key IN ('backfill_cursor', 'backfill_empty', 'backfill_done')`)
|
||||
// v3: per-conversation archive + manual "mark as unread".
|
||||
if (version < 3)
|
||||
this.db.exec(`
|
||||
ALTER TABLE read_state ADD COLUMN archived_at INTEGER; -- epoch ms; NULL = not archived
|
||||
ALTER TABLE read_state ADD COLUMN marked_unread INTEGER NOT NULL DEFAULT 0;
|
||||
`)
|
||||
// v4: times from voip.ms were an hour late during US daylight time, and
|
||||
// every getMMS row was labelled 'mms'. Times from voip.ms are whole seconds;
|
||||
// ones stamped locally on send carry milliseconds and were right.
|
||||
if (version >= 1 && version < 4) {
|
||||
const rows = this.db.prepare('SELECT id, ts FROM messages WHERE ts % 1000 = 0').all() as Array<{ id: number; ts: number }>
|
||||
const update = this.db.prepare('UPDATE messages SET ts = ? WHERE id = ?')
|
||||
this.db.transaction(() => {
|
||||
for (const r of rows) {
|
||||
const fixed = fixVoipDst(r.ts)
|
||||
if (fixed !== r.ts) update.run(fixed, r.id)
|
||||
}
|
||||
this.db.exec(`UPDATE messages SET kind = 'sms' WHERE kind = 'mms' AND media_json IS NULL`)
|
||||
})()
|
||||
}
|
||||
// v5: texts too long for one SMS came in as text-only MMS but were labelled
|
||||
// 'sms' (only rows with media counted as MMS).
|
||||
if (version >= 1 && version < 5) this.db.exec(`UPDATE messages SET kind = 'mms' WHERE kind = 'sms' AND length(body) > 160`)
|
||||
// v6: why a send failed, shown on the message.
|
||||
const cols = this.db.pragma('table_info(messages)') as Array<{ name: string }>
|
||||
if (!cols.some((c) => c.name === 'error')) this.db.exec(`ALTER TABLE messages ADD COLUMN error TEXT`)
|
||||
// v7: Google Voice. Who sent each incoming group message, and which GV
|
||||
// thread each conversation is (group threads have opaque ids).
|
||||
if (!cols.some((c) => c.name === 'sender')) this.db.exec(`ALTER TABLE messages ADD COLUMN sender TEXT`)
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS gv_threads (
|
||||
did TEXT NOT NULL, contact TEXT NOT NULL, thread_id TEXT NOT NULL,
|
||||
PRIMARY KEY (did, contact)
|
||||
);
|
||||
`)
|
||||
// v8: a name of your own for a conversation (group chats), kept locally.
|
||||
const rsCols = this.db.pragma('table_info(read_state)') as Array<{ name: string }>
|
||||
if (!rsCols.some((c) => c.name === 'name')) this.db.exec(`ALTER TABLE read_state ADD COLUMN name TEXT`)
|
||||
// v9: when a name was set, so renames on the desktop and the Rabbit merge (newest wins).
|
||||
if (!rsCols.some((c) => c.name === 'name_ts')) this.db.exec(`ALTER TABLE read_state ADD COLUMN name_ts INTEGER`)
|
||||
// v10: when read/unread and archived last changed, so they merge with the Rabbit too.
|
||||
if (!rsCols.some((c) => c.name === 'unread_ts')) this.db.exec(`ALTER TABLE read_state ADD COLUMN unread_ts INTEGER`)
|
||||
if (!rsCols.some((c) => c.name === 'archived_ts')) this.db.exec(`ALTER TABLE read_state ADD COLUMN archived_ts INTEGER`)
|
||||
this.db.pragma(`user_version = ${SCHEMA_VERSION}`)
|
||||
}
|
||||
|
||||
@@ -90,17 +164,48 @@ export class MessageDb {
|
||||
this.db.prepare('INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, value)
|
||||
}
|
||||
|
||||
// ---- unsent drafts, one per contact ----
|
||||
getDrafts(): Record<string, string> {
|
||||
const rows = this.db.prepare("SELECT key, value FROM kv WHERE key LIKE 'draft:%'").all() as { key: string; value: string }[]
|
||||
return Object.fromEntries(rows.map((r) => [r.key.slice('draft:'.length), r.value]))
|
||||
}
|
||||
setDraft(contact: string, text: string): void {
|
||||
if (text.trim()) this.set(`draft:${contact}`, text)
|
||||
else this.db.prepare('DELETE FROM kv WHERE key = ?').run(`draft:${contact}`)
|
||||
}
|
||||
|
||||
// ---- 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)`
|
||||
`INSERT OR IGNORE INTO messages (id, did, contact, direction, body, ts, status, kind, media_json, sender)
|
||||
VALUES (@id, @did, @contact, @direction, @body, @ts, @status, @kind, @media_json, @sender)`
|
||||
)
|
||||
// Any message newer than the archiving brings a conversation back (older
|
||||
// ones arriving via the history import don't).
|
||||
const unarchive = this.db.prepare(
|
||||
`UPDATE read_state SET archived_at = NULL
|
||||
WHERE did = ? AND contact = ? AND archived_at IS NOT NULL AND archived_at < ?`
|
||||
)
|
||||
const added: NewMessage[] = []
|
||||
this.db.transaction(() => {
|
||||
for (const m of msgs) {
|
||||
if (insert.run({ ...m, status: m.status ?? 'delivered' }).changes) added.push(m)
|
||||
const row = {
|
||||
id: m.id,
|
||||
did: m.did,
|
||||
contact: m.contact,
|
||||
direction: m.direction,
|
||||
body: m.body,
|
||||
ts: m.ts,
|
||||
status: m.status ?? 'delivered',
|
||||
kind: m.kind ?? 'sms',
|
||||
media_json: m.media?.length ? JSON.stringify(m.media) : null,
|
||||
sender: m.sender ?? null
|
||||
}
|
||||
if (insert.run(row).changes) {
|
||||
added.push(m)
|
||||
unarchive.run(m.did, m.contact, m.ts)
|
||||
}
|
||||
}
|
||||
})()
|
||||
return added
|
||||
@@ -116,8 +221,18 @@ export class MessageDb {
|
||||
// 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)
|
||||
const exists = this.getMessage(realId)
|
||||
if (exists) {
|
||||
// Poll beat us to it: keep our local copies of any attachments so they
|
||||
// don't need downloading again, and our kind (a text-only MMS of 160
|
||||
// characters or less looks like an SMS in the listing).
|
||||
const pending = this.getMessage(tempId)
|
||||
if (pending) this.db.prepare('UPDATE messages SET kind = ? WHERE id = ?').run(pending.kind, realId)
|
||||
const local = pending?.media
|
||||
if (local && exists.media) {
|
||||
const merged = exists.media.map((ref, i) => (local[i]?.file ? { ...ref, ...local[i] } : ref))
|
||||
this.db.prepare('UPDATE messages SET media_json = ? WHERE id = ?').run(JSON.stringify(merged), realId)
|
||||
}
|
||||
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)
|
||||
@@ -125,8 +240,32 @@ export class MessageDb {
|
||||
})()
|
||||
}
|
||||
|
||||
markFailed(tempId: number): void {
|
||||
this.db.prepare(`UPDATE messages SET status = 'failed' WHERE id = ?`).run(tempId)
|
||||
markFailed(tempId: number, error?: string): void {
|
||||
this.db.prepare(`UPDATE messages SET status = 'failed', error = ? WHERE id = ?`).run(error ?? null, tempId)
|
||||
}
|
||||
|
||||
// Sent messages that turned up in a poll take the place of our local
|
||||
// pending/failed copies (same text, sent around the same time). A send whose
|
||||
// reply never came back may still have gone out; this is how we find out.
|
||||
// Returns the local ids that were replaced.
|
||||
reconcileSent(added: NewMessage[]): number[] {
|
||||
const find = this.db.prepare(
|
||||
`SELECT id FROM messages
|
||||
WHERE id < 0 AND status IN ('pending', 'failed') AND direction = 'out'
|
||||
AND did = ? AND contact = ? AND body = ? AND ts BETWEEN ? AND ?
|
||||
ORDER BY ts, id DESC LIMIT 1`
|
||||
)
|
||||
const claimed: number[] = []
|
||||
this.db.transaction(() => {
|
||||
for (const m of [...added].sort((a, b) => a.ts - b.ts || a.id - b.id)) {
|
||||
if (m.direction !== 'out' || m.id < 0) continue
|
||||
const row = find.get(m.did, m.contact, m.body, m.ts - MATCH_AFTER, m.ts + MATCH_BEFORE) as { id: number } | undefined
|
||||
if (!row) continue
|
||||
this.confirmPending(row.id, m.id)
|
||||
claimed.push(row.id)
|
||||
}
|
||||
})()
|
||||
return claimed
|
||||
}
|
||||
|
||||
deleteMessage(id: number): void {
|
||||
@@ -134,18 +273,25 @@ export class MessageDb {
|
||||
}
|
||||
|
||||
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
|
||||
const row = this.db.prepare(`SELECT ${MESSAGE_COLS} FROM messages WHERE id = ?`).get(id) as MessageRow | undefined
|
||||
return row && fromRow(row)
|
||||
}
|
||||
|
||||
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`
|
||||
)
|
||||
const rows = this.db
|
||||
.prepare(`SELECT ${MESSAGE_COLS} FROM messages WHERE did = ? AND contact = ? ORDER BY ts, id`)
|
||||
.all(did, contact) as MessageRow[]
|
||||
return rows.map(fromRow)
|
||||
}
|
||||
|
||||
// Record that attachment `index` of message `id` is now cached locally.
|
||||
setMediaFile(id: number, index: number, patch: MediaRef): void {
|
||||
this.db.transaction(() => {
|
||||
const media = this.getMessage(id)?.media
|
||||
if (!media?.[index]) return
|
||||
media[index] = { ...media[index], ...patch }
|
||||
this.db.prepare('UPDATE messages SET media_json = ? WHERE id = ?').run(JSON.stringify(media), id)
|
||||
})()
|
||||
}
|
||||
|
||||
count(): number {
|
||||
@@ -156,31 +302,190 @@ export class MessageDb {
|
||||
listConversations(): Conversation[] {
|
||||
// Messages from before the initial history import never count as unread.
|
||||
const floor = Number(this.get('unread_floor') ?? 0)
|
||||
return this.db
|
||||
const rows = 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,
|
||||
last.body AS lastBody, last.direction AS lastDirection, last.kind AS lastKind, last.sender AS lastSender,
|
||||
json_extract(last.media_json, '$[0]') AS lastMedia,
|
||||
(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
|
||||
AND m.ts > MAX(COALESCE(r.last_read_ts, 0), @floor)) AS unread,
|
||||
r.archived_at IS NOT NULL AS archived,
|
||||
COALESCE(r.marked_unread, 0) AS markedUnread,
|
||||
r.name AS name
|
||||
FROM latest l
|
||||
JOIN messages last ON last.id =
|
||||
(SELECT id FROM messages m WHERE m.did = l.did AND m.contact = l.contact ORDER BY ts DESC, id DESC LIMIT 1)
|
||||
LEFT JOIN read_state r ON r.did = l.did AND r.contact = l.contact
|
||||
ORDER BY l.mts DESC`
|
||||
)
|
||||
.all({ floor }) as Conversation[]
|
||||
.all({ floor }) as Array<
|
||||
Omit<Conversation, 'lastMedia' | 'archived' | 'markedUnread' | 'lastSender' | 'name'> & {
|
||||
lastMedia: string | null
|
||||
archived: number
|
||||
markedUnread: number
|
||||
lastSender: string | null
|
||||
name: string | null
|
||||
}
|
||||
>
|
||||
return rows.map(({ lastMedia, archived, markedUnread, lastSender, name, ...c }) => ({
|
||||
...c,
|
||||
...(name ? { name } : {}),
|
||||
...(lastSender ? { lastSender } : {}),
|
||||
archived: !!archived,
|
||||
markedUnread: !!markedUnread,
|
||||
...(lastMedia ? { lastMedia: JSON.parse(lastMedia) as MediaRef } : {})
|
||||
}))
|
||||
}
|
||||
|
||||
// Whether anything has arrived since the conversation was last read.
|
||||
hasUnread(did: string, contact: string): boolean {
|
||||
const floor = Number(this.get('unread_floor') ?? 0)
|
||||
const r = this.db
|
||||
.prepare(
|
||||
`SELECT EXISTS (
|
||||
SELECT 1 FROM messages m LEFT JOIN read_state r ON r.did = m.did AND r.contact = m.contact
|
||||
WHERE m.did = @did AND m.contact = @contact AND m.direction = 'in'
|
||||
AND m.ts > MAX(COALESCE(r.last_read_ts, 0), @floor)
|
||||
) AS any`
|
||||
)
|
||||
.get({ did, contact, floor }) as { any: number }
|
||||
return !!r.any
|
||||
}
|
||||
|
||||
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`
|
||||
`INSERT INTO read_state (did, contact, last_read_ts, unread_ts)
|
||||
SELECT @did, @contact, COALESCE(MAX(ts), 0), @now FROM messages WHERE did = @did AND contact = @contact
|
||||
ON CONFLICT(did, contact) DO UPDATE SET last_read_ts = MAX(last_read_ts, excluded.last_read_ts), marked_unread = 0,
|
||||
unread_ts = excluded.unread_ts`
|
||||
)
|
||||
.run({ did, contact })
|
||||
.run({ did, contact, now: Date.now() })
|
||||
}
|
||||
|
||||
markUnread(did: string, contact: string): void {
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO read_state (did, contact, last_read_ts, marked_unread, unread_ts) VALUES (?, ?, 0, 1, ?)
|
||||
ON CONFLICT(did, contact) DO UPDATE SET marked_unread = 1, unread_ts = excluded.unread_ts`
|
||||
)
|
||||
.run(did, contact, Date.now())
|
||||
}
|
||||
|
||||
// Name a conversation (null/empty clears it, back to the members' names).
|
||||
setName(did: string, contact: string, name: string | null, ts = Date.now()): void {
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO read_state (did, contact, last_read_ts, name, name_ts) VALUES (?, ?, 0, ?, ?)
|
||||
ON CONFLICT(did, contact) DO UPDATE SET name = excluded.name, name_ts = excluded.name_ts`
|
||||
)
|
||||
.run(did, contact, name?.trim() || null, ts)
|
||||
}
|
||||
|
||||
// Every rename (including clearing one), for merging with the Rabbit.
|
||||
namesExport(): NameChange[] {
|
||||
return this.db.prepare('SELECT did, contact, name, name_ts AS ts FROM read_state WHERE name_ts IS NOT NULL').all() as NameChange[]
|
||||
}
|
||||
|
||||
// Apply renames made elsewhere, keeping whichever is newer. Returns how many changed.
|
||||
namesImport(changes: NameChange[]): number {
|
||||
let n = 0
|
||||
const mine = this.db.prepare('SELECT COALESCE(name_ts, 0) AS ts FROM read_state WHERE did = ? AND contact = ?')
|
||||
this.db.transaction(() => {
|
||||
for (const c of changes) {
|
||||
const cur = (mine.get(c.did, c.contact) as { ts: number } | undefined)?.ts ?? 0
|
||||
if (c.ts > cur) {
|
||||
this.setName(c.did, c.contact, c.name, c.ts)
|
||||
n++
|
||||
}
|
||||
}
|
||||
})()
|
||||
return n
|
||||
}
|
||||
|
||||
getName(did: string, contact: string): string | undefined {
|
||||
const r = this.db.prepare('SELECT name FROM read_state WHERE did = ? AND contact = ?').get(did, contact) as { name: string | null } | undefined
|
||||
return r?.name ?? undefined
|
||||
}
|
||||
|
||||
setArchived(did: string, contact: string, archived: boolean, now = Date.now()): void {
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO read_state (did, contact, last_read_ts, archived_at, archived_ts) VALUES (?, ?, 0, ?, ?)
|
||||
ON CONFLICT(did, contact) DO UPDATE SET archived_at = excluded.archived_at, archived_ts = excluded.archived_ts`
|
||||
)
|
||||
.run(did, contact, archived ? now : null, now)
|
||||
}
|
||||
|
||||
// Read/unread and archived state of every conversation, for merging with the Rabbit.
|
||||
readStateExport(): ReadState[] {
|
||||
return (
|
||||
this.db
|
||||
.prepare(
|
||||
`SELECT did, contact, last_read_ts AS lastRead, marked_unread AS markedUnread, unread_ts AS unreadTs,
|
||||
archived_at AS archivedAt, archived_ts AS archivedTs FROM read_state`
|
||||
)
|
||||
.all() as Array<Omit<ReadState, 'markedUnread'> & { markedUnread: number }>
|
||||
).map((r) => ({ ...r, markedUnread: !!r.markedUnread }))
|
||||
}
|
||||
|
||||
// Merge the other device's state: "read up to" takes the later of the two;
|
||||
// marked-unread and archived take whichever changed more recently.
|
||||
// Returns how many conversations changed here.
|
||||
readStateImport(rows: ReadState[]): number {
|
||||
let n = 0
|
||||
const mine = this.db.prepare(
|
||||
`SELECT last_read_ts AS lastRead, marked_unread AS markedUnread, COALESCE(unread_ts, 0) AS unreadTs,
|
||||
archived_at AS archivedAt, COALESCE(archived_ts, 0) AS archivedTs FROM read_state WHERE did = ? AND contact = ?`
|
||||
)
|
||||
const upsert = this.db.prepare(
|
||||
`INSERT INTO read_state (did, contact, last_read_ts, marked_unread, unread_ts, archived_at, archived_ts)
|
||||
VALUES (@did, @contact, @lastRead, @markedUnread, @unreadTs, @archivedAt, @archivedTs)
|
||||
ON CONFLICT(did, contact) DO UPDATE SET last_read_ts = excluded.last_read_ts, marked_unread = excluded.marked_unread,
|
||||
unread_ts = excluded.unread_ts, archived_at = excluded.archived_at, archived_ts = excluded.archived_ts`
|
||||
)
|
||||
this.db.transaction(() => {
|
||||
for (const t of rows) {
|
||||
const m = mine.get(t.did, t.contact) as
|
||||
| { lastRead: number; markedUnread: number; unreadTs: number; archivedAt: number | null; archivedTs: number }
|
||||
| undefined
|
||||
const cur = m ?? { lastRead: 0, markedUnread: 0, unreadTs: 0, archivedAt: null, archivedTs: 0 }
|
||||
const theirsUnread = (t.unreadTs ?? 0) > cur.unreadTs
|
||||
const theirsArchived = (t.archivedTs ?? 0) > cur.archivedTs
|
||||
const next = {
|
||||
did: t.did,
|
||||
contact: t.contact,
|
||||
lastRead: Math.max(cur.lastRead, t.lastRead ?? 0),
|
||||
markedUnread: theirsUnread ? (t.markedUnread ? 1 : 0) : cur.markedUnread,
|
||||
unreadTs: theirsUnread ? t.unreadTs : cur.unreadTs || null,
|
||||
archivedAt: theirsArchived ? (t.archivedAt ?? null) : cur.archivedAt,
|
||||
archivedTs: theirsArchived ? t.archivedTs : cur.archivedTs || null
|
||||
}
|
||||
if (next.lastRead !== cur.lastRead || theirsUnread || theirsArchived) {
|
||||
upsert.run(next)
|
||||
n++
|
||||
}
|
||||
}
|
||||
})()
|
||||
return n
|
||||
}
|
||||
|
||||
// ---- Google Voice threads ----
|
||||
setGvThread(did: string, contact: string, threadId: string): void {
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO gv_threads (did, contact, thread_id) VALUES (?, ?, ?)
|
||||
ON CONFLICT(did, contact) DO UPDATE SET thread_id = excluded.thread_id`
|
||||
)
|
||||
.run(did, contact, threadId)
|
||||
}
|
||||
|
||||
getGvThread(did: string, contact: string): string | undefined {
|
||||
const r = this.db.prepare('SELECT thread_id FROM gv_threads WHERE did = ? AND contact = ?').get(did, contact) as { thread_id: string } | undefined
|
||||
return r?.thread_id
|
||||
}
|
||||
|
||||
// ---- search ----
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
// "Export chat": a conversation, or the days of it between two dates, as plain
|
||||
// text or as a page (printed to PDF by index.ts), optionally with its photos.
|
||||
import { formatNumber, isGroup } from '@shared/phone'
|
||||
import type { ChatExport, MediaRef, Message } from '@shared/types'
|
||||
import { localDay } from './db'
|
||||
|
||||
// The messages in the export's dates (inclusive, local days); failed sends
|
||||
// never went anywhere, so they're left out.
|
||||
export function inRange(msgs: Message[], opts: Pick<ChatExport, 'from' | 'to'>): Message[] {
|
||||
return msgs.filter((m) => {
|
||||
if (m.status === 'failed') return false
|
||||
const day = localDay(new Date(m.ts))
|
||||
return (!opts.from || day >= opts.from) && (!opts.to || day <= opts.to)
|
||||
})
|
||||
}
|
||||
|
||||
const dayHeading = (ts: number): string =>
|
||||
new Date(ts).toLocaleDateString(undefined, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })
|
||||
const time = (ts: number): string => new Date(ts).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })
|
||||
const shortDate = (day: string): string =>
|
||||
new Date(`${day}T00:00`).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
|
||||
|
||||
export function rangeLabel(opts: Pick<ChatExport, 'from' | 'to'>): string {
|
||||
if (!opts.from && !opts.to) return 'All messages'
|
||||
if (opts.from && opts.to) return opts.from === opts.to ? shortDate(opts.from) : `${shortDate(opts.from)} – ${shortDate(opts.to)}`
|
||||
return opts.from ? `From ${shortDate(opts.from)}` : `Up to ${shortDate(opts.to!)}`
|
||||
}
|
||||
|
||||
// The chat's name, with the number after it for a one-to-one chat with someone in contacts.
|
||||
function heading(contact: string, opts: ChatExport): string {
|
||||
const number = formatNumber(contact)
|
||||
return isGroup(contact) || opts.title === number ? opts.title : `${opts.title} (${number})`
|
||||
}
|
||||
|
||||
function who(m: Message, contact: string, opts: ChatExport): string {
|
||||
if (m.direction === 'out') return 'Me'
|
||||
if (isGroup(contact) && m.sender) return opts.names[m.sender] ?? formatNumber(m.sender)
|
||||
return opts.title
|
||||
}
|
||||
|
||||
export function attachmentLabel(ref: MediaRef): string {
|
||||
const mime = ref.mime ?? ''
|
||||
return mime.startsWith('image/') ? '[Photo]' : mime.startsWith('audio/') ? '[Audio]' : mime.startsWith('video/') ? '[Video]' : '[Attachment]'
|
||||
}
|
||||
|
||||
export function exportText(contact: string, msgs: Message[], opts: ChatExport): string {
|
||||
const out = [`Chat with ${heading(contact, opts)}`, `${rangeLabel(opts)} · exported ${shortDate(localDay())}`]
|
||||
let day = ''
|
||||
for (const m of msgs) {
|
||||
const d = localDay(new Date(m.ts))
|
||||
if (d !== day) {
|
||||
day = d
|
||||
out.push('', `— ${dayHeading(m.ts)} —`, '')
|
||||
}
|
||||
const lead = `${time(m.ts)} ${who(m, contact, opts)}: `
|
||||
const lines = [...(m.body.trim() ? m.body.trim().split('\n') : []), ...(m.media ?? []).map(attachmentLabel)]
|
||||
const pad = ' '.repeat(lead.length)
|
||||
lines.forEach((l, i) => out.push((i === 0 ? lead : pad) + l))
|
||||
}
|
||||
return out.join('\n') + '\n'
|
||||
}
|
||||
|
||||
const esc = (s: string): string => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||
|
||||
// The page the PDF is printed from. `photo(m, i)` gives the src for an image
|
||||
// attachment to show, or undefined to show its label instead.
|
||||
export function exportHtml(contact: string, msgs: Message[], opts: ChatExport, photo: (m: Message, index: number) => string | undefined): string {
|
||||
const group = isGroup(contact)
|
||||
const body: string[] = []
|
||||
let day = ''
|
||||
let prev: Message | undefined
|
||||
for (const m of msgs) {
|
||||
const d = localDay(new Date(m.ts))
|
||||
if (d !== day) {
|
||||
day = d
|
||||
prev = undefined
|
||||
body.push(`<div class="day">${esc(dayHeading(m.ts))}</div>`)
|
||||
}
|
||||
const showSender = group && m.direction === 'in' && (prev?.direction !== 'in' || prev.sender !== m.sender)
|
||||
const parts: string[] = []
|
||||
if (showSender) parts.push(`<div class="sender">${esc(who(m, contact, opts))}</div>`)
|
||||
;(m.media ?? []).forEach((ref, i) => {
|
||||
const src = photo(m, i)
|
||||
parts.push(src ? `<img src="${esc(src)}">` : `<div class="att">${attachmentLabel(ref)}</div>`)
|
||||
})
|
||||
if (m.body.trim()) parts.push(`<div class="text">${esc(m.body.trim())}</div>`)
|
||||
parts.push(`<div class="time">${esc(time(m.ts))}</div>`)
|
||||
body.push(`<div class="msg ${m.direction}">${parts.join('')}</div>`)
|
||||
prev = m
|
||||
}
|
||||
return `<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8"><title>${esc(opts.title)}</title><style>
|
||||
@page { margin: 16mm 14mm; }
|
||||
body { font: 10.5pt system-ui, sans-serif; color: #1b1b1d; margin: 0; }
|
||||
h1 { font-size: 16pt; margin: 0 0 2pt; }
|
||||
.sub { color: #707070; font-size: 9pt; margin-bottom: 10pt; }
|
||||
.day { text-align: center; color: #707070; font-size: 8.5pt; margin: 14pt 0 6pt; break-after: avoid; }
|
||||
.msg { max-width: 72%; width: fit-content; margin: 3pt 0; padding: 5pt 9pt; border-radius: 11pt; break-inside: avoid; }
|
||||
.msg.in { background: #ececee; }
|
||||
.msg.out { background: #2c6bed; color: #fff; margin-left: auto; }
|
||||
.sender { font-size: 8.5pt; font-weight: 600; color: #555; margin-bottom: 2pt; }
|
||||
.text { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.time { font-size: 7.5pt; opacity: 0.65; text-align: right; margin-top: 2pt; }
|
||||
.att { font-style: italic; opacity: 0.8; }
|
||||
img { display: block; max-width: 100%; max-height: 240pt; border-radius: 7pt; margin: 2pt 0; }
|
||||
</style></head><body>
|
||||
<h1>${esc(heading(contact, opts))}</h1>
|
||||
<div class="sub">${esc(rangeLabel(opts))} · exported ${esc(shortDate(localDay()))}</div>
|
||||
${body.join('\n')}
|
||||
</body></html>
|
||||
`
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
// Google Voice's private web API (what voice.google.com itself calls), as
|
||||
// worked out by mautrix-gvoice. Unofficial: Google can change it at any time,
|
||||
// so everything here fails soft and only ever takes Google Voice down.
|
||||
//
|
||||
// Requests go through an Electron session that holds the Google sign-in
|
||||
// cookies (see ./session.ts); this class only needs a fetch that sends them
|
||||
// and a way to read the SAPISID cookie for the Authorization header.
|
||||
import crypto from 'node:crypto'
|
||||
import { decode, fromPblite, toPblite, type Decoded, type Schema } from './proto'
|
||||
import * as S from './schema'
|
||||
|
||||
export const ORIGIN = 'https://voice.google.com'
|
||||
const API_BASE = 'https://clients6.google.com/voice/v1/voiceclient'
|
||||
const WAA_BASE = 'https://waa-pa.clients6.google.com/$rpc/google.internal.waa.v1.Waa'
|
||||
|
||||
// Constants from the web client (pkg/libgv/constants.go).
|
||||
const API_KEY = 'AIzaSyDTYc1N4xiODyrQYK0Kl6g_y279LjYkrBg'
|
||||
const WAA_API_KEY = 'AIzaSyBGb5fGAyC-pRcRU6MUHb__b_vKha71HRE'
|
||||
export const WAA_REQUEST_KEY = '/JR8jsAkqotcKsEKhXic'
|
||||
const CLIENT_VERSION = '665865172'
|
||||
export const USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36'
|
||||
const CLIENT_DETAILS = new URLSearchParams({ appVersion: '5.0 (X11)', platform: 'Linux x86_64', userAgent: USER_AGENT }).toString()
|
||||
|
||||
const PBLITE = 'application/json+protobuf'
|
||||
const PROTOBUF = 'application/x-protobuf'
|
||||
|
||||
export interface Transport {
|
||||
fetch: (url: string, init: RequestInit) => Promise<Response>
|
||||
cookie: (name: string) => Promise<string | undefined>
|
||||
}
|
||||
|
||||
export class GVoiceError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly status?: number, // HTTP status, when Google answered
|
||||
readonly code?: string // Chromium network error, when it didn't
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
get signedOut(): boolean {
|
||||
return this.status === 401 || this.status === 403
|
||||
}
|
||||
}
|
||||
|
||||
export function sapisidHash(sapisid: string, now = Date.now(), origin = ORIGIN): string {
|
||||
const ts = Math.floor(now / 1000)
|
||||
const hash = crypto.createHash('sha1').update(`${ts} ${sapisid} ${origin}`).digest('hex')
|
||||
return `SAPISIDHASH ${ts}_${hash}`
|
||||
}
|
||||
|
||||
// A random id below 10^14, like the web client's.
|
||||
export function transactionId(): number {
|
||||
return Math.floor(Math.random() * 1e14)
|
||||
}
|
||||
|
||||
// GV wants E.164; we store bare 10-digit NANP numbers.
|
||||
export function toE164(n: string): string {
|
||||
const d = n.replace(/\D/g, '')
|
||||
if (d.length === 10) return `+1${d}`
|
||||
return `+${d}`
|
||||
}
|
||||
|
||||
// Text responses wrap the payload as "<length>\n<data>", the length counted in
|
||||
// UTF-16 code units (JS string units), and protobuf inside them is base64.
|
||||
export async function readBody(res: Response): Promise<{ mime: string; data: Uint8Array | string }> {
|
||||
const plain = (res.headers.get('content-type') ?? '').split(';')[0].trim()
|
||||
const safety = (res.headers.get('x-goog-safety-content-type') ?? '').split(';')[0].trim()
|
||||
const mime = safety || plain
|
||||
if (plain === 'text/plain') {
|
||||
const text = await res.text()
|
||||
const nl = text.indexOf('\n')
|
||||
const len = Number(text.slice(0, nl))
|
||||
const chunk = nl > 0 && Number.isFinite(len) ? text.slice(nl + 1, nl + 1 + len) : text
|
||||
return { mime, data: mime === PROTOBUF ? new Uint8Array(Buffer.from(chunk, 'base64')) : chunk }
|
||||
}
|
||||
if (mime === PROTOBUF) return { mime, data: new Uint8Array(await res.arrayBuffer()) }
|
||||
return { mime, data: await res.text() }
|
||||
}
|
||||
|
||||
export function decodeBody(schema: Schema, { mime, data }: { mime: string; data: Uint8Array | string }): Decoded {
|
||||
if (data instanceof Uint8Array) return decode(schema, data)
|
||||
if (mime === PBLITE || mime === 'application/json' || mime === 'text/plain') return fromPblite(schema, JSON.parse(data) as unknown[])
|
||||
throw new GVoiceError(`Google Voice sent an unexpected response (${mime || 'no content type'}).`)
|
||||
}
|
||||
|
||||
export interface SendSmsRequest {
|
||||
threadId: string // '' to start a new thread with `recipients`
|
||||
recipients: string[] // E.164
|
||||
text: string
|
||||
media?: { mime: string; data: Uint8Array }
|
||||
transactionId: number
|
||||
trackingData?: string
|
||||
}
|
||||
|
||||
export class GVoice {
|
||||
constructor(private t: Transport) {}
|
||||
|
||||
private async headers(url: URL, contentType?: string): Promise<Record<string, string>> {
|
||||
// Origin is added by the session (see session.ts): Chromium refuses it here.
|
||||
const h: Record<string, string> = {
|
||||
'X-Goog-AuthUser': '0',
|
||||
Referer: ORIGIN + '/',
|
||||
Accept: '*/*'
|
||||
}
|
||||
if (contentType) h['Content-Type'] = contentType
|
||||
if (url.host === 'clients6.google.com') {
|
||||
h['X-Client-Version'] = CLIENT_VERSION
|
||||
h['X-ClientDetails'] = CLIENT_DETAILS
|
||||
h['X-JavaScript-User-Agent'] = 'google-api-javascript-client/1.1.0'
|
||||
h['X-Requested-With'] = 'XMLHttpRequest'
|
||||
h['X-Goog-Encode-Response-If-Executable'] = 'base64'
|
||||
} else if (url.host.startsWith('waa-pa.')) {
|
||||
h['X-Goog-Api-Key'] = WAA_API_KEY
|
||||
h['X-User-Agent'] = 'grpc-web-javascript/0.1'
|
||||
}
|
||||
const sapisid = await this.t.cookie('SAPISID')
|
||||
if (!sapisid) throw new GVoiceError('Not signed in to Google Voice.', 401)
|
||||
h['Authorization'] = sapisidHash(sapisid)
|
||||
return h
|
||||
}
|
||||
|
||||
private async request(url: string, init: { method?: string; body?: string; contentType?: string } = {}): Promise<Response> {
|
||||
const u = new URL(url)
|
||||
if (u.host === 'clients6.google.com') {
|
||||
u.searchParams.set('key', API_KEY)
|
||||
u.searchParams.set('alt', 'proto')
|
||||
}
|
||||
let res: Response
|
||||
try {
|
||||
res = await this.t.fetch(u.toString(), {
|
||||
method: init.method ?? 'POST',
|
||||
headers: await this.headers(u, init.contentType),
|
||||
body: init.body,
|
||||
credentials: 'include'
|
||||
})
|
||||
} catch (e) {
|
||||
if (e instanceof GVoiceError) throw e
|
||||
const msg = (e as Error).message ?? String(e)
|
||||
throw new GVoiceError(msg, undefined, /net::(ERR_\w+)/.exec(msg)?.[1] ?? (e as Error).name)
|
||||
}
|
||||
if (!res.ok) {
|
||||
const detail = await res.text().catch(() => '')
|
||||
console.warn(`[gvoice] ${u.pathname} → ${res.status}`, detail.slice(0, 300))
|
||||
throw new GVoiceError(httpMessage(res.status), res.status)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
private async call(endpoint: string, reqSchema: Schema, req: Decoded, respSchema: Schema): Promise<Decoded> {
|
||||
const res = await this.request(endpoint, { body: JSON.stringify(toPblite(reqSchema, req)), contentType: PBLITE })
|
||||
return decodeBody(respSchema, await readBody(res))
|
||||
}
|
||||
|
||||
// Our Google Voice number, E.164.
|
||||
async getAccount(): Promise<string> {
|
||||
const r = await this.call(`${API_BASE}/account/get`, S.ReqGetAccount, { unknownInt2: 1 }, S.RespGetAccount)
|
||||
const acc = r.account as { primaryDestinationId: string; phones: Array<{ accountPhone?: { phoneNumber?: { e164: string } } }> }
|
||||
const number = acc.phones.map((p) => p.accountPhone?.phoneNumber?.e164).find(Boolean) ?? acc.primaryDestinationId
|
||||
if (!number) throw new GVoiceError("This Google account doesn't have a Google Voice number.")
|
||||
return number
|
||||
}
|
||||
|
||||
async listThreads(paginationToken = ''): Promise<{ threads: S.GvThread[]; paginationToken: string }> {
|
||||
const r = await this.call(
|
||||
`${API_BASE}/api2thread/list`,
|
||||
S.ReqListThreads,
|
||||
{ folder: S.ThreadFolder.TEXT_THREADS, unknownInt2: 20, unknownInt3: 15, paginationToken, unknownWrapper: { unknownInt2: 1, unknownInt3: 1 } },
|
||||
S.RespListThreads
|
||||
)
|
||||
return { threads: r.threads as S.GvThread[], paginationToken: r.paginationToken as string }
|
||||
}
|
||||
|
||||
async getThread(threadId: string, count = 100, paginationToken = ''): Promise<S.GvThread> {
|
||||
const r = await this.call(
|
||||
`${API_BASE}/api2thread/get`,
|
||||
S.ReqGetThread,
|
||||
{ threadId, maybeMessageCount: count, paginationToken, unknownWrapper: { unknownInt2: 1, unknownInt3: 1 } },
|
||||
S.RespGetThread
|
||||
)
|
||||
return r.thread as S.GvThread
|
||||
}
|
||||
|
||||
async sendSms(req: SendSmsRequest): Promise<{ threadId: string; threadItemId: string; timestampMs: number }> {
|
||||
const body: Decoded = {
|
||||
text: req.text,
|
||||
threadId: req.threadId,
|
||||
recipients: req.threadId ? [] : req.recipients,
|
||||
transactionId: { id: req.transactionId },
|
||||
trackingData: { data: req.trackingData || '!' }
|
||||
}
|
||||
if (req.media) {
|
||||
const type = S.SendMediaType[req.media.mime]
|
||||
if (!type) throw new GVoiceError(`Google Voice can't send ${req.media.mime} attachments, only photos.`, 400)
|
||||
body.media = { type, data: req.media.data }
|
||||
}
|
||||
const r = await this.call(`${API_BASE}/api2thread/sendsms`, S.ReqSendSMS, body, S.RespSendSMS)
|
||||
return r as { threadId: string; threadItemId: string; timestampMs: number }
|
||||
}
|
||||
|
||||
async markRead(threadId: string): Promise<void> {
|
||||
await this.call(
|
||||
`${API_BASE}/thread/updateattributes`,
|
||||
S.ReqUpdateAttributes,
|
||||
{ attributes: { threadId, read: true }, otherAttributes: { read: true }, unknownInt: 1 },
|
||||
S.RespEmpty
|
||||
)
|
||||
}
|
||||
|
||||
async downloadMedia(id: string): Promise<Response> {
|
||||
return this.request(`${ORIGIN}/u/0/a/i/${encodeURIComponent(id)}?s=${S.SizeSpec.ORIGINAL}`, { method: 'GET' })
|
||||
}
|
||||
|
||||
// ---- WAA (BotGuard) signing, see ./waa.ts ----
|
||||
async createWaa(): Promise<{ interpreterUrl: string; interpreterHash: string; program: string; globalName: string }> {
|
||||
const r = await this.call(`${WAA_BASE}/Create`, S.ReqCreateWaa, { requestKey: WAA_REQUEST_KEY }, S.RespCreateWaa)
|
||||
const w = r.waa as { interpreterUrl: { url: string }; interpreterHash: string; program: string; globalName: string }
|
||||
return { interpreterUrl: w.interpreterUrl.url, interpreterHash: w.interpreterHash, program: w.program, globalName: w.globalName }
|
||||
}
|
||||
|
||||
async pingWaa(payload: string): Promise<void> {
|
||||
await this.call(
|
||||
`${WAA_BASE}/Ping`,
|
||||
S.ReqPingWaa,
|
||||
{ requestKey: WAA_REQUEST_KEY, payload, i1: 72, i2: Math.floor(Math.random() * 2e9) },
|
||||
S.RespEmpty
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function httpMessage(status: number): string {
|
||||
if (status === 401 || status === 403) return 'Google Voice signed out. Reconnect it in Settings.'
|
||||
if (status === 429) return 'Google Voice is rate-limiting messages. Try again in a bit.'
|
||||
if (status === 404) return 'Google Voice could not find that conversation.'
|
||||
if (status >= 500) return `Google Voice had a server error (${status}).`
|
||||
return `Google Voice rejected the request (${status}).`
|
||||
}
|
||||
|
||||
// Network errors where the request certainly never reached Google.
|
||||
const NOT_SENT = new Set([
|
||||
'ERR_INTERNET_DISCONNECTED',
|
||||
'ERR_NAME_NOT_RESOLVED',
|
||||
'ERR_NAME_RESOLUTION_FAILED',
|
||||
'ERR_CONNECTION_REFUSED',
|
||||
'ERR_ADDRESS_UNREACHABLE',
|
||||
'ERR_PROXY_CONNECTION_FAILED'
|
||||
])
|
||||
|
||||
// For sendWithRetry: 'safe' = certainly not sent, retry; 'unknown' = may have
|
||||
// gone out, look before resending; 'fatal' = give up.
|
||||
export function classifyGvError(e: unknown): 'safe' | 'unknown' | 'fatal' {
|
||||
if (!(e instanceof GVoiceError)) return 'unknown'
|
||||
if (e.status === undefined) return e.code && NOT_SENT.has(e.code) ? 'safe' : 'unknown'
|
||||
if (e.status === 429) return 'safe'
|
||||
if (e.status >= 500) return 'unknown'
|
||||
return 'fatal'
|
||||
}
|
||||
|
||||
export function gvErrorMessage(e: unknown): string {
|
||||
const err = e as Error
|
||||
if (err instanceof GVoiceError) {
|
||||
if (err.status === undefined && err.code && NOT_SENT.has(err.code)) return "Couldn't reach Google Voice. Check your internet connection."
|
||||
return err.message
|
||||
}
|
||||
return err?.message || String(e)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
// Just enough protobuf for Google Voice's web API, without a dependency:
|
||||
// binary decoding (responses) plus "pblite" (requests, and the WAA endpoint),
|
||||
// Google's JSON form where a message is an array and field N sits at index N-1.
|
||||
//
|
||||
// Messages are described by small schemas mapping field names to numbers and
|
||||
// types; unknown fields are skipped.
|
||||
|
||||
export type Scalar = 'string' | 'bytes' | 'int' | 'bool' | 'float' | 'double'
|
||||
export type FieldType = Scalar | Schema
|
||||
export interface FieldDef {
|
||||
n: number
|
||||
t: FieldType
|
||||
rep?: boolean
|
||||
}
|
||||
export type Schema = { [name: string]: FieldDef }
|
||||
|
||||
// The decoded form: plain objects with every field present (proto3 defaults
|
||||
// for missing ones), so callers can read nested fields without checks.
|
||||
export type Decoded = { [name: string]: unknown }
|
||||
|
||||
function defaultFor(def: FieldDef): unknown {
|
||||
if (def.rep) return []
|
||||
switch (def.t) {
|
||||
case 'string':
|
||||
return ''
|
||||
case 'bytes':
|
||||
return new Uint8Array()
|
||||
case 'int':
|
||||
case 'float':
|
||||
case 'double':
|
||||
return 0
|
||||
case 'bool':
|
||||
return false
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function withDefaults(schema: Schema): Decoded {
|
||||
const out: Decoded = {}
|
||||
for (const [name, def] of Object.entries(schema)) out[name] = defaultFor(def)
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- binary ----
|
||||
|
||||
class Reader {
|
||||
pos = 0
|
||||
constructor(readonly buf: Uint8Array) {}
|
||||
|
||||
varint(): bigint {
|
||||
let result = 0n
|
||||
let shift = 0n
|
||||
for (;;) {
|
||||
if (this.pos >= this.buf.length) throw new Error('protobuf: truncated varint')
|
||||
const b = this.buf[this.pos++]
|
||||
result |= BigInt(b & 0x7f) << shift
|
||||
if (!(b & 0x80)) return result
|
||||
shift += 7n
|
||||
}
|
||||
}
|
||||
|
||||
bytes(len: number): Uint8Array {
|
||||
if (this.pos + len > this.buf.length) throw new Error('protobuf: truncated field')
|
||||
const out = this.buf.subarray(this.pos, this.pos + len)
|
||||
this.pos += len
|
||||
return out
|
||||
}
|
||||
}
|
||||
|
||||
const utf8 = new TextDecoder()
|
||||
|
||||
function scalarFromVarint(t: Scalar, v: bigint): unknown {
|
||||
if (t === 'bool') return v !== 0n
|
||||
return Number(BigInt.asIntN(64, v))
|
||||
}
|
||||
|
||||
function scalarFromFixed(t: Scalar, b: Uint8Array): unknown {
|
||||
const view = new DataView(b.buffer, b.byteOffset, b.byteLength)
|
||||
if (b.length === 4) return t === 'float' ? view.getFloat32(0, true) : view.getInt32(0, true)
|
||||
return t === 'double' ? view.getFloat64(0, true) : Number(view.getBigInt64(0, true))
|
||||
}
|
||||
|
||||
export function decode(schema: Schema, buf: Uint8Array): Decoded {
|
||||
const byNum = new Map<number, [string, FieldDef]>()
|
||||
for (const [name, def] of Object.entries(schema)) byNum.set(def.n, [name, def])
|
||||
const out = withDefaults(schema)
|
||||
const r = new Reader(buf)
|
||||
while (r.pos < buf.length) {
|
||||
const tag = Number(r.varint())
|
||||
const num = tag >>> 3
|
||||
const wire = tag & 7
|
||||
let raw: bigint | Uint8Array
|
||||
if (wire === 0) raw = r.varint()
|
||||
else if (wire === 1) raw = r.bytes(8)
|
||||
else if (wire === 2) raw = r.bytes(Number(r.varint()))
|
||||
else if (wire === 5) raw = r.bytes(4)
|
||||
else throw new Error(`protobuf: unsupported wire type ${wire}`)
|
||||
const field = byNum.get(num)
|
||||
if (!field) continue
|
||||
const [name, def] = field
|
||||
let values: unknown[]
|
||||
if (typeof raw === 'bigint') values = [scalarFromVarint(def.t as Scalar, raw)]
|
||||
else if (typeof def.t === 'object') values = [decode(def.t, raw)]
|
||||
else if (def.t === 'string') values = [utf8.decode(raw)]
|
||||
else if (def.t === 'bytes') values = [raw.slice()]
|
||||
else if (wire === 2) values = unpack(def.t, raw) // packed repeated numbers
|
||||
else values = [scalarFromFixed(def.t, raw)]
|
||||
if (def.rep) (out[name] as unknown[]).push(...values)
|
||||
else out[name] = values[values.length - 1]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function unpack(t: Scalar, buf: Uint8Array): unknown[] {
|
||||
const r = new Reader(buf)
|
||||
const out: unknown[] = []
|
||||
while (r.pos < buf.length) {
|
||||
if (t === 'float') out.push(scalarFromFixed(t, r.bytes(4)))
|
||||
else if (t === 'double') out.push(scalarFromFixed(t, r.bytes(8)))
|
||||
else out.push(scalarFromVarint(t, r.varint()))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- pblite ----
|
||||
|
||||
const isSet = (v: unknown): boolean =>
|
||||
v !== undefined && v !== null && v !== '' && v !== 0 && v !== false && !(Array.isArray(v) && !v.length) && !(v instanceof Uint8Array && !v.length)
|
||||
|
||||
function encodeValue(t: FieldType, v: unknown): unknown {
|
||||
if (typeof t === 'object') return toPblite(t, v as Decoded)
|
||||
if (t === 'bytes') return Buffer.from(v as Uint8Array).toString('base64')
|
||||
return v
|
||||
}
|
||||
|
||||
// Every array is as long as the schema's highest field number (unset fields
|
||||
// are null), matching what Google's own client sends.
|
||||
export function toPblite(schema: Schema, msg: Decoded): unknown[] {
|
||||
const max = Math.max(0, ...Object.values(schema).map((d) => d.n))
|
||||
const out: unknown[] = new Array(max).fill(null)
|
||||
for (const [name, def] of Object.entries(schema)) {
|
||||
const v = msg[name]
|
||||
if (!isSet(v)) continue
|
||||
out[def.n - 1] = def.rep ? (v as unknown[]).map((x) => encodeValue(def.t, x)) : encodeValue(def.t, v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function decodeValue(t: FieldType, v: unknown): unknown {
|
||||
if (typeof t === 'object') return Array.isArray(v) ? fromPblite(t, v) : withDefaults(t)
|
||||
switch (t) {
|
||||
case 'bytes':
|
||||
return typeof v === 'string' ? new Uint8Array(Buffer.from(v, 'base64')) : new Uint8Array()
|
||||
case 'string':
|
||||
return typeof v === 'string' ? v : String(v ?? '')
|
||||
case 'bool':
|
||||
return v === true || v === 1
|
||||
default:
|
||||
return Number(v ?? 0) // int64s may arrive as strings
|
||||
}
|
||||
}
|
||||
|
||||
export function fromPblite(schema: Schema, arr: unknown[]): Decoded {
|
||||
// Sparse high-numbered fields come as a trailing {"<n>": value} object.
|
||||
let extra: Record<string, unknown> = {}
|
||||
const last = arr[arr.length - 1]
|
||||
if (last && typeof last === 'object' && !Array.isArray(last)) {
|
||||
extra = last as Record<string, unknown>
|
||||
arr = arr.slice(0, -1)
|
||||
}
|
||||
const out = withDefaults(schema)
|
||||
for (const [name, def] of Object.entries(schema)) {
|
||||
const v = arr[def.n - 1] ?? extra[String(def.n)]
|
||||
if (v === null || v === undefined) continue
|
||||
out[name] = def.rep ? (Array.isArray(v) ? v.map((x) => decodeValue(def.t, x)) : []) : decodeValue(def.t, v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- binary encoding (test fixtures) ----
|
||||
|
||||
function writeVarint(out: number[], v: bigint): void {
|
||||
let x = BigInt.asUintN(64, v)
|
||||
do {
|
||||
let b = Number(x & 0x7fn)
|
||||
x >>= 7n
|
||||
if (x) b |= 0x80
|
||||
out.push(b)
|
||||
} while (x)
|
||||
}
|
||||
|
||||
const utf8enc = new TextEncoder()
|
||||
|
||||
// Binary protobuf encoding; the app only needs it to build test fixtures, but
|
||||
// it lives here so encode and decode stay in step.
|
||||
export function encode(schema: Schema, msg: Decoded): Uint8Array {
|
||||
const out: number[] = []
|
||||
for (const def of Object.values(schema).sort((a, b) => a.n - b.n)) {
|
||||
const name = Object.keys(schema).find((k) => schema[k] === def)!
|
||||
const v = msg[name]
|
||||
if (!isSet(v)) continue
|
||||
for (const x of def.rep ? (v as unknown[]) : [v]) {
|
||||
const t = def.t
|
||||
if (typeof t === 'object' || t === 'string' || t === 'bytes') {
|
||||
const body = typeof t === 'object' ? encode(t, x as Decoded) : t === 'string' ? utf8enc.encode(x as string) : (x as Uint8Array)
|
||||
writeVarint(out, BigInt((def.n << 3) | 2))
|
||||
writeVarint(out, BigInt(body.length))
|
||||
out.push(...body)
|
||||
} else if (t === 'float' || t === 'double') {
|
||||
const b = new DataView(new ArrayBuffer(t === 'float' ? 4 : 8))
|
||||
if (t === 'float') b.setFloat32(0, x as number, true)
|
||||
else b.setFloat64(0, x as number, true)
|
||||
writeVarint(out, BigInt((def.n << 3) | (t === 'float' ? 5 : 1)))
|
||||
out.push(...new Uint8Array(b.buffer))
|
||||
} else {
|
||||
writeVarint(out, BigInt(def.n << 3))
|
||||
writeVarint(out, BigInt(t === 'bool' ? (x ? 1 : 0) : (x as number)))
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Uint8Array(out)
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// Google Voice web API message shapes, from the reverse-engineered definitions
|
||||
// in mautrix-gvoice (pkg/libgv/gvproto). Only the fields we use are listed.
|
||||
import type { Schema } from './proto'
|
||||
|
||||
export const ThreadFolder = { ALL_THREADS: 1, TEXT_THREADS: 2 } as const
|
||||
|
||||
export const MessageType = {
|
||||
MISSED_CALL: 0,
|
||||
INCOMING_CALL: 1,
|
||||
VOICEMAIL: 2,
|
||||
OUTGOING_CALL: 7,
|
||||
SMS_IN: 10,
|
||||
SMS_OUT: 11,
|
||||
OUTGOING_CALL_CANCELLED: 14
|
||||
} as const
|
||||
|
||||
export const AttachmentStatus = { AVAILABLE: 1, NOT_SUPPORTED: 3 } as const
|
||||
export const SizeSpec = { ORIGINAL: 1 } as const
|
||||
|
||||
// Media types sendsms accepts, by MIME type.
|
||||
export const SendMediaType: Record<string, number> = {
|
||||
'image/jpeg': 1,
|
||||
'image/png': 2,
|
||||
'image/tiff': 3,
|
||||
'image/gif': 4,
|
||||
'image/bmp': 5,
|
||||
'image/webp': 6
|
||||
}
|
||||
|
||||
const Contact: Schema = {
|
||||
name: { n: 1, t: 'string' },
|
||||
phoneNumber: { n: 2, t: 'string' },
|
||||
blocked: { n: 7, t: 'bool' }
|
||||
}
|
||||
|
||||
const AttachmentMetadata: Schema = {
|
||||
size: { n: 1, t: 'int' },
|
||||
width: { n: 2, t: 'int' },
|
||||
height: { n: 3, t: 'int' }
|
||||
}
|
||||
|
||||
const Attachment: Schema = {
|
||||
mimeType: { n: 1, t: 'string' },
|
||||
id: { n: 2, t: 'string' },
|
||||
status: { n: 3, t: 'int' },
|
||||
metadata: { n: 4, t: AttachmentMetadata, rep: true },
|
||||
mediaType: { n: 5, t: 'int' }
|
||||
}
|
||||
|
||||
const MMSMessage: Schema = {
|
||||
text: { n: 1, t: 'string' },
|
||||
subject: { n: 2, t: 'string' },
|
||||
attachments: { n: 3, t: Attachment, rep: true },
|
||||
participants: { n: 4, t: Contact, rep: true },
|
||||
senderPhoneNumber: { n: 5, t: 'string' }
|
||||
}
|
||||
|
||||
export const Message: Schema = {
|
||||
id: { n: 1, t: 'string' },
|
||||
timestamp: { n: 2, t: 'int' }, // epoch ms
|
||||
contact: { n: 4, t: Contact },
|
||||
type: { n: 5, t: 'int' },
|
||||
status: { n: 6, t: 'int' },
|
||||
text: { n: 10, t: 'string' },
|
||||
mms: { n: 15, t: MMSMessage },
|
||||
transactionId: { n: 18, t: 'int' }
|
||||
}
|
||||
|
||||
export const Thread: Schema = {
|
||||
id: { n: 1, t: 'string' },
|
||||
read: { n: 2, t: 'bool' },
|
||||
messages: { n: 3, t: Message, rep: true }, // newest first
|
||||
paginationToken: { n: 4, t: 'string' },
|
||||
contacts: { n: 5, t: Contact, rep: true },
|
||||
isText: { n: 8, t: 'bool' },
|
||||
phoneNumbers: { n: 9, t: 'string', rep: true }
|
||||
}
|
||||
|
||||
export const ThreadAttributes: Schema = {
|
||||
threadId: { n: 1, t: 'string' },
|
||||
read: { n: 4, t: 'bool' }
|
||||
}
|
||||
|
||||
const UnknownWrapper: Schema = {
|
||||
unknownInt2: { n: 2, t: 'int' },
|
||||
unknownInt3: { n: 3, t: 'int' }
|
||||
}
|
||||
|
||||
// ---- requests (sent as pblite) ----
|
||||
|
||||
export const ReqGetAccount: Schema = { unknownInt2: { n: 2, t: 'int' } }
|
||||
|
||||
export const ReqListThreads: Schema = {
|
||||
folder: { n: 1, t: 'int' },
|
||||
unknownInt2: { n: 2, t: 'int' },
|
||||
unknownInt3: { n: 3, t: 'int' },
|
||||
paginationToken: { n: 4, t: 'string' },
|
||||
versionToken: { n: 5, t: 'string' },
|
||||
unknownWrapper: { n: 6, t: UnknownWrapper }
|
||||
}
|
||||
|
||||
export const ReqGetThread: Schema = {
|
||||
threadId: { n: 1, t: 'string' },
|
||||
maybeMessageCount: { n: 2, t: 'int' },
|
||||
paginationToken: { n: 3, t: 'string' },
|
||||
unknownWrapper: { n: 4, t: UnknownWrapper }
|
||||
}
|
||||
|
||||
export const ReqSendSMS: Schema = {
|
||||
text: { n: 5, t: 'string' },
|
||||
threadId: { n: 6, t: 'string' },
|
||||
recipients: { n: 7, t: 'string', rep: true },
|
||||
transactionId: { n: 9, t: { id: { n: 1, t: 'int' } } },
|
||||
media: { n: 10, t: { type: { n: 1, t: 'int' }, data: { n: 2, t: 'bytes' } } },
|
||||
trackingData: { n: 11, t: { data: { n: 1, t: 'string' } } }
|
||||
}
|
||||
|
||||
export const ReqUpdateAttributes: Schema = {
|
||||
attributes: { n: 1, t: ThreadAttributes },
|
||||
otherAttributes: { n: 2, t: ThreadAttributes },
|
||||
unknownInt: { n: 3, t: 'int' }
|
||||
}
|
||||
|
||||
export const ReqCreateWaa: Schema = { requestKey: { n: 1, t: 'string' } }
|
||||
|
||||
export const ReqPingWaa: Schema = {
|
||||
requestKey: { n: 1, t: 'string' },
|
||||
payload: { n: 2, t: 'string' },
|
||||
i1: { n: 3, t: 'int' },
|
||||
i2: { n: 4, t: 'int' }
|
||||
}
|
||||
|
||||
// ---- responses (binary protobuf, except WAA's pblite) ----
|
||||
|
||||
const PhoneNumber: Schema = { e164: { n: 1, t: 'string' } }
|
||||
|
||||
export const RespGetAccount: Schema = {
|
||||
account: {
|
||||
n: 1,
|
||||
t: {
|
||||
primaryDestinationId: { n: 1, t: 'string' },
|
||||
phones: { n: 3, t: { accountPhone: { n: 1, t: { phoneNumber: { n: 1, t: PhoneNumber } } } }, rep: true }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const RespListThreads: Schema = {
|
||||
threads: { n: 1, t: Thread, rep: true },
|
||||
paginationToken: { n: 2, t: 'string' },
|
||||
versionToken: { n: 3, t: 'string' }
|
||||
}
|
||||
|
||||
export const RespGetThread: Schema = { thread: { n: 1, t: Thread } }
|
||||
|
||||
export const RespSendSMS: Schema = {
|
||||
threadId: { n: 2, t: 'string' },
|
||||
threadItemId: { n: 3, t: 'string' },
|
||||
timestampMs: { n: 4, t: 'int' }
|
||||
}
|
||||
|
||||
export const RespEmpty: Schema = {}
|
||||
|
||||
export const RespCreateWaa: Schema = {
|
||||
waa: {
|
||||
n: 1,
|
||||
t: {
|
||||
respId: { n: 1, t: 'string' },
|
||||
interpreterUrl: { n: 3, t: { url: { n: 4, t: 'string' } } },
|
||||
interpreterHash: { n: 4, t: 'string' },
|
||||
program: { n: 5, t: 'string' },
|
||||
globalName: { n: 6, t: 'string' }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- typed views of decoded messages ----
|
||||
|
||||
export interface GvContact {
|
||||
name: string
|
||||
phoneNumber: string
|
||||
blocked: boolean
|
||||
}
|
||||
export interface GvAttachment {
|
||||
mimeType: string
|
||||
id: string
|
||||
status: number
|
||||
metadata: Array<{ size: number; width: number; height: number }>
|
||||
}
|
||||
export interface GvMessage {
|
||||
id: string
|
||||
timestamp: number
|
||||
contact?: GvContact
|
||||
type: number
|
||||
text: string
|
||||
mms?: { text: string; subject: string; attachments: GvAttachment[]; senderPhoneNumber: string; participants: GvContact[] }
|
||||
transactionId: number
|
||||
}
|
||||
export interface GvThread {
|
||||
id: string
|
||||
read: boolean
|
||||
messages: GvMessage[]
|
||||
paginationToken: string
|
||||
contacts: GvContact[]
|
||||
isText: boolean
|
||||
phoneNumbers: string[]
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// The Google sign-in that Google Voice requests ride on: a persistent Electron
|
||||
// session (cookies live in userData, outside the backed-up data folder, like
|
||||
// the voip.ms password). Chromium keeps the cookie jar, including the rotation
|
||||
// Google does through Set-Cookie, so we never handle most cookies ourselves.
|
||||
import { BrowserWindow, session, type Session } from 'electron'
|
||||
import { ORIGIN, USER_AGENT, type Transport } from './client'
|
||||
|
||||
const PARTITION = 'persist:gvoice'
|
||||
const SIGN_IN_URL = 'https://voice.google.com/u/0/messages'
|
||||
|
||||
let ses: Session | undefined
|
||||
|
||||
export function gvSession(): Session {
|
||||
if (!ses) {
|
||||
ses = session.fromPartition(PARTITION)
|
||||
// Google turns away sign-ins from browsers that say they're Electron.
|
||||
ses.setUserAgent(USER_AGENT)
|
||||
// The API only answers requests from voice.google.com. fetch() won't let
|
||||
// us set Origin ourselves, so add it on the way out.
|
||||
ses.webRequest.onBeforeSendHeaders(
|
||||
{ urls: ['https://clients6.google.com/*', 'https://*.clients6.google.com/*', 'https://voice.google.com/u/*'] },
|
||||
(d, cb) => cb({ requestHeaders: d.requestHeaders['Origin'] ? d.requestHeaders : { ...d.requestHeaders, Origin: ORIGIN } })
|
||||
)
|
||||
}
|
||||
return ses
|
||||
}
|
||||
|
||||
export function gvTransport(): Transport {
|
||||
return {
|
||||
fetch: (url, init) => gvSession().fetch(url, init),
|
||||
cookie: async (name) => {
|
||||
const jar = await gvSession().cookies.get({ domain: 'google.com' })
|
||||
const find = (n: string): string | undefined => jar.find((c) => c.name === n)?.value
|
||||
// SAPISID and __Secure-3PAPISID carry the same value; Google sometimes
|
||||
// only sets the latter.
|
||||
return find(name) ?? (name === 'SAPISID' ? find('__Secure-3PAPISID') : undefined)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function hasGvSession(): Promise<boolean> {
|
||||
return !!(await gvTransport().cookie('SAPISID'))
|
||||
}
|
||||
|
||||
// Sign in with Google in a window of our own. Resolves once the sign-in
|
||||
// cookies exist and Google Voice has loaded; rejects if the window is closed.
|
||||
export function signInWindow(parent?: BrowserWindow): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const win = new BrowserWindow({
|
||||
parent,
|
||||
width: 520,
|
||||
height: 720,
|
||||
title: 'Sign in to Google Voice',
|
||||
autoHideMenuBar: true,
|
||||
webPreferences: { partition: PARTITION, sandbox: true, contextIsolation: true, nodeIntegration: false }
|
||||
})
|
||||
let done = false
|
||||
const check = async (): Promise<void> => {
|
||||
if (done || win.isDestroyed()) return
|
||||
const url = win.webContents.getURL()
|
||||
if (url.startsWith('https://voice.google.com/') && (await hasGvSession())) {
|
||||
done = true
|
||||
clearInterval(timer)
|
||||
resolve()
|
||||
win.close()
|
||||
}
|
||||
}
|
||||
// Navigation events don't reliably fire as Google's pages hand off, so
|
||||
// also just look every second.
|
||||
const timer = setInterval(() => void check(), 1000)
|
||||
win.webContents.on('did-navigate', () => void check())
|
||||
win.webContents.on('did-navigate-in-page', () => void check())
|
||||
// Closing the window by hand once signed in counts as done too.
|
||||
win.on('closed', () => {
|
||||
clearInterval(timer)
|
||||
if (done) return
|
||||
void hasGvSession().then((ok) => (ok ? resolve() : reject(new Error('Sign-in was cancelled before it finished.'))))
|
||||
})
|
||||
void win.loadURL(SIGN_IN_URL, { userAgent: USER_AGENT })
|
||||
})
|
||||
}
|
||||
|
||||
// Fallback for when Google refuses to sign in inside the app: cookies copied
|
||||
// from a browser where you're signed in, as a "Copy as cURL" command, a raw
|
||||
// Cookie header, or a JSON object of name → value.
|
||||
export function parseCookies(input: string): Record<string, string> {
|
||||
const text = input.trim()
|
||||
if (text.startsWith('{')) {
|
||||
const obj = JSON.parse(text) as Record<string, unknown>
|
||||
return Object.fromEntries(Object.entries(obj).filter(([, v]) => typeof v === 'string')) as Record<string, string>
|
||||
}
|
||||
let header = text
|
||||
const curl = /(?:-H|--header)\s+(['"])cookie:\s*(.*?)\1/is.exec(text) ?? /(?:-b|--cookie)\s+(['"])(.*?)\1/s.exec(text)
|
||||
if (curl) header = curl[2]
|
||||
else header = header.replace(/^cookie:\s*/i, '')
|
||||
const out: Record<string, string> = {}
|
||||
for (const part of header.split(';')) {
|
||||
const eq = part.indexOf('=')
|
||||
if (eq <= 0) continue
|
||||
out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export async function importCookies(cookies: Record<string, string>): Promise<void> {
|
||||
if (!cookies['SAPISID']) throw new Error("Those cookies don't include SAPISID. Copy a request to voice.google.com while signed in.")
|
||||
const jar = gvSession().cookies
|
||||
const expirationDate = Date.now() / 1000 + 365 * 86400
|
||||
for (const [name, value] of Object.entries(cookies)) {
|
||||
// OSID belongs to voice.google.com itself; __Host- cookies can't carry a domain.
|
||||
const hostOnly = name === 'OSID' || name.startsWith('__Host-')
|
||||
await jar.set({
|
||||
url: hostOnly ? 'https://voice.google.com' : 'https://google.com',
|
||||
...(hostOnly ? {} : { domain: '.google.com' }),
|
||||
path: '/',
|
||||
name,
|
||||
value,
|
||||
secure: true,
|
||||
sameSite: 'no_restriction',
|
||||
expirationDate
|
||||
})
|
||||
}
|
||||
await jar.flushStore()
|
||||
}
|
||||
|
||||
// The sign-in cookies, for copying to the Rabbit's app. Domain-wide
|
||||
// (.google.com) cookies win over same-named host ones.
|
||||
export async function exportCookies(): Promise<Record<string, string>> {
|
||||
const jar = await gvSession().cookies.get({ domain: 'google.com' })
|
||||
const out: Record<string, string> = {}
|
||||
for (const c of [...jar].sort((a, b) => Number((a.domain ?? '').startsWith('.')) - Number((b.domain ?? '').startsWith('.'))))
|
||||
out[c.name] = c.value
|
||||
return out
|
||||
}
|
||||
|
||||
export async function clearGvSession(): Promise<void> {
|
||||
await gvSession().clearStorageData()
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
// Google Voice history import + polling, alongside the voip.ms SyncEngine.
|
||||
// Same events ('messages', 'status'), its own status, its own failures.
|
||||
import crypto from 'node:crypto'
|
||||
import { EventEmitter } from 'node:events'
|
||||
import type { MessageDb, NewMessage } from '../db'
|
||||
import { groupKey, normalizeNumber } from '@shared/phone'
|
||||
import type { GvStatus, MediaRef } from '@shared/types'
|
||||
import { GVoiceError, type GVoice } from './client'
|
||||
import { AttachmentStatus, MessageType, SizeSpec, type GvMessage, type GvThread } from './schema'
|
||||
|
||||
// GV message ids are opaque strings; ours are integers. Map them into a range
|
||||
// of their own, far above voip.ms's ids and the negative local pending ones.
|
||||
const GV_ID_BASE = 2 ** 52
|
||||
export function gvMessageId(id: string): number {
|
||||
const h = crypto.createHash('sha256').update(id).digest()
|
||||
return GV_ID_BASE + h.readUIntBE(0, 6)
|
||||
}
|
||||
|
||||
export function isGvMessageId(id: number): boolean {
|
||||
return id >= GV_ID_BASE
|
||||
}
|
||||
|
||||
// The conversation a thread belongs to: the other person's number, or for a
|
||||
// group, every member's number (see groupKey).
|
||||
export function threadContact(thread: Pick<GvThread, 'phoneNumbers'>, self: string): string {
|
||||
const others = thread.phoneNumbers.map(normalizeNumber).filter((n) => n && n !== self)
|
||||
return others.length > 1 ? groupKey(others) : (others[0] ?? '')
|
||||
}
|
||||
|
||||
export function toNewMessage(m: GvMessage, did: string, contact: string, group: boolean): NewMessage | undefined {
|
||||
if (m.type !== MessageType.SMS_IN && m.type !== MessageType.SMS_OUT) return undefined // calls, voicemail
|
||||
const direction = m.type === MessageType.SMS_OUT ? 'out' : 'in'
|
||||
const mms = m.mms
|
||||
const text = mms?.text || m.text
|
||||
const body = mms?.subject ? `${mms.subject}\n${text}` : text
|
||||
const media: MediaRef[] = (mms?.attachments ?? [])
|
||||
.filter((a) => a.id && a.status !== AttachmentStatus.NOT_SUPPORTED)
|
||||
.map((a) => {
|
||||
const meta = a.metadata.find((x) => x.size === SizeSpec.ORIGINAL) ?? a.metadata.reduce((best, x) => (x.width > (best?.width ?? 0) ? x : best), a.metadata[0])
|
||||
return {
|
||||
url: `gv:${a.id}`,
|
||||
...(a.mimeType ? { mime: a.mimeType } : {}),
|
||||
...(meta?.width ? { width: meta.width, height: meta.height } : {})
|
||||
}
|
||||
})
|
||||
const out: NewMessage = { id: gvMessageId(m.id), did, contact, direction, body, ts: m.timestamp }
|
||||
if (media.length) {
|
||||
out.kind = 'mms'
|
||||
out.media = media
|
||||
}
|
||||
if (group && direction === 'in') {
|
||||
const sender = normalizeNumber(mms?.senderPhoneNumber || m.contact?.phoneNumber || '')
|
||||
if (sender) out.sender = sender
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export interface GvSyncOptions {
|
||||
did: string // our GV number, normalized
|
||||
pollSeconds: number
|
||||
backfillFloor: string // YYYY-MM-DD
|
||||
}
|
||||
|
||||
const MIN_POLL_SECONDS = 20
|
||||
const PAGE = 100
|
||||
|
||||
export class GvSyncEngine extends EventEmitter {
|
||||
private pollTimer?: NodeJS.Timeout
|
||||
private burstUntil = 0
|
||||
private running = false
|
||||
private backfilling = false
|
||||
private polling?: Promise<void>
|
||||
private status: GvStatus
|
||||
|
||||
constructor(
|
||||
private db: MessageDb,
|
||||
private gv: GVoice,
|
||||
private opts: GvSyncOptions
|
||||
) {
|
||||
super()
|
||||
this.status = { phase: 'idle', backfillDone: db.get('gv_backfill_done') === '1' }
|
||||
}
|
||||
|
||||
getStatus(): GvStatus {
|
||||
return this.status
|
||||
}
|
||||
|
||||
private setStatus(patch: Partial<GvStatus>): void {
|
||||
this.status = { ...this.status, ...patch }
|
||||
this.emit('status', this.status)
|
||||
}
|
||||
|
||||
private fail(e: unknown): void {
|
||||
const signedOut = e instanceof GVoiceError && e.signedOut
|
||||
this.setStatus({ phase: signedOut ? 'signedOut' : 'error', error: (e as Error).message })
|
||||
}
|
||||
|
||||
// Store a thread's messages; returns how many were new.
|
||||
private storeThread(thread: GvThread, messages = thread.messages): number {
|
||||
const contact = threadContact(thread, this.opts.did)
|
||||
if (!contact) return 0
|
||||
this.db.setGvThread(this.opts.did, contact, thread.id)
|
||||
const group = contact.includes(',')
|
||||
const msgs = messages.map((m) => toNewMessage(m, this.opts.did, contact, group)).filter((m): m is NewMessage => !!m)
|
||||
const added = this.db.upsertMessages(msgs)
|
||||
this.db.reconcileSent(added)
|
||||
// Already read on the phone or the web: don't show it as unread here.
|
||||
if (added.length && thread.read) this.db.markRead(this.opts.did, contact)
|
||||
if (added.length) this.emit('messages', added)
|
||||
return added.length
|
||||
}
|
||||
|
||||
// Imports from before read state was carried over left everything unread;
|
||||
// once, go through the thread list and mark read what GV says is read.
|
||||
private async syncReadStateOnce(): Promise<void> {
|
||||
if (this.db.get('gv_read_synced') === '1' || !this.status.backfillDone) return
|
||||
let token = ''
|
||||
let changed = false
|
||||
do {
|
||||
const page = await this.gv.listThreads(token)
|
||||
for (const t of page.threads) {
|
||||
const contact = threadContact(t, this.opts.did)
|
||||
if (t.read && contact) {
|
||||
this.db.markRead(this.opts.did, contact)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
token = page.paginationToken
|
||||
} while (token && this.running)
|
||||
if (!this.running) return
|
||||
this.db.set('gv_read_synced', '1')
|
||||
if (changed) this.emit('readChanged')
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.running) return
|
||||
this.running = true
|
||||
void this.poll().finally(() => this.scheduleNextPoll())
|
||||
if (!this.status.backfillDone) void this.backfill()
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.running = false
|
||||
clearTimeout(this.pollTimer)
|
||||
}
|
||||
|
||||
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 : Math.max(MIN_POLL_SECONDS, this.opts.pollSeconds) * 1000)
|
||||
this.pollTimer = setTimeout(() => {
|
||||
void this.poll().finally(() => this.scheduleNextPoll())
|
||||
}, d)
|
||||
}
|
||||
|
||||
async pollNow(): Promise<void> {
|
||||
await this.poll()
|
||||
}
|
||||
|
||||
private poll(): Promise<void> {
|
||||
this.polling ??= this.fetchRecent().finally(() => (this.polling = undefined))
|
||||
return this.polling
|
||||
}
|
||||
|
||||
// The thread list carries each thread's latest few messages. If none of
|
||||
// them were known yet and the thread already has history here, more may
|
||||
// have arrived than the list shows, so fetch the thread itself.
|
||||
private async fetchRecent(): Promise<void> {
|
||||
try {
|
||||
const { threads } = await this.gv.listThreads()
|
||||
for (const t of threads) {
|
||||
if (!t.messages.length) continue
|
||||
const known = t.messages.some((m) => this.db.getMessage(gvMessageId(m.id)))
|
||||
const contact = threadContact(t, this.opts.did)
|
||||
const hasHistory = !!contact && this.db.getGvThread(this.opts.did, contact) === t.id
|
||||
this.storeThread(t)
|
||||
if (!known && hasHistory && t.paginationToken) this.storeThread(t, (await this.gv.getThread(t.id, PAGE)).messages)
|
||||
}
|
||||
this.setStatus({ lastPoll: Date.now(), error: undefined, phase: this.backfilling ? 'backfill' : 'polling' })
|
||||
await this.syncReadStateOnce()
|
||||
} catch (e) {
|
||||
this.fail(e)
|
||||
}
|
||||
}
|
||||
|
||||
// Walk every text thread (resumable page by page), and each thread's
|
||||
// messages back to the floor date.
|
||||
private async backfill(): Promise<void> {
|
||||
if (this.backfilling) return
|
||||
this.backfilling = true
|
||||
this.setStatus({ phase: 'backfill' })
|
||||
const floor = Date.parse(this.opts.backfillFloor + 'T00:00:00Z')
|
||||
let token = this.db.get('gv_backfill_token') ?? ''
|
||||
try {
|
||||
while (this.running) {
|
||||
const page = await this.gv.listThreads(token)
|
||||
for (const t of page.threads) {
|
||||
let thread = t
|
||||
let pageToken = ''
|
||||
// The listing's copy is partial; page the thread from the newest.
|
||||
for (;;) {
|
||||
thread = await this.gv.getThread(t.id, PAGE, pageToken)
|
||||
this.storeThread(thread)
|
||||
const oldest = thread.messages[thread.messages.length - 1]
|
||||
if (!thread.paginationToken || !oldest || oldest.timestamp < floor || !this.running) break
|
||||
pageToken = thread.paginationToken
|
||||
await new Promise((r) => setTimeout(r, 250))
|
||||
}
|
||||
}
|
||||
token = page.paginationToken
|
||||
this.db.set('gv_backfill_token', token)
|
||||
if (!token || !page.threads.length) break
|
||||
}
|
||||
if (this.running) {
|
||||
this.db.set('gv_backfill_done', '1')
|
||||
this.db.set('gv_read_synced', '1')
|
||||
this.setStatus({ phase: 'polling', backfillDone: true })
|
||||
}
|
||||
} catch (e) {
|
||||
this.fail(e)
|
||||
if (!(e instanceof GVoiceError && e.signedOut)) setTimeout(() => this.running && void this.backfill(), 60_000)
|
||||
} finally {
|
||||
this.backfilling = false
|
||||
}
|
||||
}
|
||||
|
||||
resetBackfill(): void {
|
||||
for (const k of ['gv_backfill_token', 'gv_backfill_done']) this.db.db.prepare('DELETE FROM kv WHERE key = ?').run(k)
|
||||
this.status.backfillDone = false
|
||||
if (this.running) void this.backfill()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Message signing ("WAA" / BotGuard). Google Voice's web client attaches a
|
||||
// signature, computed by an obfuscated script Google serves, to every text it
|
||||
// sends; sends without one work but get rate-limited sooner. Like
|
||||
// mautrix-gvoice's electron.mjs, we run Google's script in a hidden window,
|
||||
// locked down so it can't load anything else, and ask it for signatures.
|
||||
//
|
||||
// Everything here is best-effort: on any failure the send goes out unsigned.
|
||||
import { BrowserWindow, session } from 'electron'
|
||||
import crypto from 'node:crypto'
|
||||
import { USER_AGENT, type GVoice } from './client'
|
||||
|
||||
const EXPIRY = 60 * 60_000
|
||||
const TIMEOUT = 10_000
|
||||
const ABOUT_URLS = new Set(['https://voice.google.com/', 'https://voice.google.com/about', 'https://voice.google.com/u/0/about'])
|
||||
|
||||
// Runs inside the hidden page.
|
||||
const LOAD_SCRIPT = (src: string): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const s = document.createElement('script')
|
||||
s.src = src
|
||||
s.onload = () => resolve()
|
||||
s.onerror = () => reject(new Error('script failed to load'))
|
||||
document.head.appendChild(s)
|
||||
})
|
||||
|
||||
type Payload = { message_ids: string; destinations: string; thread_id: string } | undefined
|
||||
const RUN_PROGRAM = (globalName: string, program: string, payload: Payload): Promise<string> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const vm = (window as unknown as Record<string, { a: (...args: unknown[]) => void }>)[globalName]
|
||||
if (!vm) return reject(new Error('signer not loaded'))
|
||||
vm.a(
|
||||
program,
|
||||
(fn1: (cb: (r: string) => void, args: unknown[]) => void) => fn1((r) => resolve(r), [payload, undefined, undefined, undefined]),
|
||||
true,
|
||||
undefined,
|
||||
() => undefined
|
||||
)
|
||||
})
|
||||
|
||||
const b64sha256 = (s: string): string => crypto.createHash('sha256').update(s).digest('base64')
|
||||
|
||||
const withTimeout = <T>(p: Promise<T>, ms: number): Promise<T> =>
|
||||
Promise.race([p, new Promise<T>((_, reject) => setTimeout(() => reject(new Error('timed out')), ms))])
|
||||
|
||||
export class WaaSigner {
|
||||
private win?: BrowserWindow
|
||||
private ready?: Promise<void>
|
||||
private initedAt = 0
|
||||
private program = ''
|
||||
private globalName = ''
|
||||
private scriptUrl = ''
|
||||
|
||||
constructor(private gv: GVoice) {}
|
||||
|
||||
private async open(): Promise<BrowserWindow> {
|
||||
if (this.win && !this.win.isDestroyed()) return this.win
|
||||
const ses = session.fromPartition('gvoice-waa') // in-memory, no Google cookies
|
||||
ses.webRequest.onBeforeRequest((d, cb) => cb({ cancel: !(ABOUT_URLS.has(d.url) || d.url === this.scriptUrl) }))
|
||||
ses.webRequest.onHeadersReceived((d, cb) => {
|
||||
const headers = { ...d.responseHeaders }
|
||||
for (const k of Object.keys(headers)) if (k.toLowerCase() === 'content-security-policy') delete headers[k]
|
||||
cb({ responseHeaders: headers })
|
||||
})
|
||||
const win = new BrowserWindow({
|
||||
show: false,
|
||||
webPreferences: { session: ses, sandbox: true, contextIsolation: true, nodeIntegration: false }
|
||||
})
|
||||
await win.loadURL('https://voice.google.com/about', { userAgent: USER_AGENT })
|
||||
this.win = win
|
||||
return win
|
||||
}
|
||||
|
||||
private init(): Promise<void> {
|
||||
this.ready = (async () => {
|
||||
const waa = await this.gv.createWaa()
|
||||
const win = await this.open()
|
||||
this.program = waa.program
|
||||
this.globalName = waa.globalName
|
||||
const url = waa.interpreterUrl.startsWith('//') ? 'https:' + waa.interpreterUrl : waa.interpreterUrl
|
||||
if (url !== this.scriptUrl) {
|
||||
this.scriptUrl = url
|
||||
await win.webContents.executeJavaScript(`(${LOAD_SCRIPT.toString()})(${JSON.stringify(url)})`)
|
||||
}
|
||||
this.initedAt = Date.now()
|
||||
// The web client checks in once with an empty payload.
|
||||
void this.run(undefined)
|
||||
.then((sig) => this.gv.pingWaa(sig))
|
||||
.catch(() => undefined)
|
||||
})()
|
||||
this.ready.catch(() => (this.ready = undefined))
|
||||
return this.ready
|
||||
}
|
||||
|
||||
private async run(payload: Payload): Promise<string> {
|
||||
const js = `(${RUN_PROGRAM.toString()})(${JSON.stringify(this.globalName)}, ${JSON.stringify(this.program)}, ${JSON.stringify(payload)})`
|
||||
return withTimeout(this.win!.webContents.executeJavaScript(js) as Promise<string>, TIMEOUT)
|
||||
}
|
||||
|
||||
// Signature for a send, or undefined if one couldn't be had.
|
||||
async sign(threadId: string, recipients: string[], transactionId: number): Promise<string | undefined> {
|
||||
try {
|
||||
if (!this.ready || Date.now() - this.initedAt > EXPIRY) await this.init()
|
||||
else await this.ready
|
||||
const sig = await this.run({
|
||||
message_ids: b64sha256(String(transactionId)),
|
||||
destinations: b64sha256(recipients.join('|')),
|
||||
thread_id: b64sha256(threadId)
|
||||
})
|
||||
return sig || undefined
|
||||
} catch (e) {
|
||||
console.warn('[gvoice] signing failed, sending unsigned:', (e as Error).message)
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.win && !this.win.isDestroyed()) this.win.destroy()
|
||||
this.win = undefined
|
||||
this.ready = undefined
|
||||
}
|
||||
}
|
||||
+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))
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
// MMS attachments cached on disk in <dataDir>/media, next to the database, so
|
||||
// backups include them and they outlive voip.ms's copies. Files are named by
|
||||
// content hash; messages reference them via MediaRef.file.
|
||||
import { nativeImage, net } from 'electron'
|
||||
import crypto from 'node:crypto'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { extFor, guessMime } from '@shared/mime'
|
||||
import type { MediaRef } from '@shared/types'
|
||||
import type { MessageDb, NewMessage } from './db'
|
||||
|
||||
export class MediaStore {
|
||||
private inflight = new Map<string, Promise<MediaRef | undefined>>()
|
||||
|
||||
constructor(
|
||||
readonly dir: string,
|
||||
private db: MessageDb,
|
||||
// How to fetch a MediaRef.url; Google Voice's gv:<id> refs need its session.
|
||||
private fetchUrl: (url: string) => Promise<Response> = (url) => net.fetch(url)
|
||||
) {}
|
||||
|
||||
filePath(file: string): string {
|
||||
return path.join(this.dir, path.basename(file))
|
||||
}
|
||||
|
||||
save(data: Uint8Array, mime: string): string {
|
||||
const file = `${crypto.createHash('sha1').update(data).digest('hex')}.${extFor(mime)}`
|
||||
fs.mkdirSync(this.dir, { recursive: true })
|
||||
const dest = this.filePath(file)
|
||||
if (!fs.existsSync(dest)) fs.writeFileSync(dest, data)
|
||||
return file
|
||||
}
|
||||
|
||||
// The local copy of attachment `index` of message `id`, downloading it first
|
||||
// if we only have the provider's URL. Undefined when it can't be had.
|
||||
async resolve(id: number, index: number): Promise<MediaRef | undefined> {
|
||||
const ref = this.db.getMessage(id)?.media?.[index]
|
||||
if (!ref) return undefined
|
||||
if (ref.file && fs.existsSync(this.filePath(ref.file))) return ref
|
||||
if (!ref.url) return undefined
|
||||
const key = `${id}/${index}`
|
||||
let p = this.inflight.get(key)
|
||||
if (!p) {
|
||||
p = this.download(id, index, ref.url).finally(() => this.inflight.delete(key))
|
||||
this.inflight.set(key, p)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
private async download(id: number, index: number, url: string): Promise<MediaRef | undefined> {
|
||||
try {
|
||||
const res = await this.fetchUrl(url)
|
||||
const header = res.headers.get('content-type')?.split(';')[0].trim()
|
||||
// voip.ms answers expired/unknown media with a 200 HTML page.
|
||||
if (!res.ok || header === 'text/html') return undefined
|
||||
const mime = header && header !== 'application/octet-stream' ? header : (guessMime(url) ?? 'application/octet-stream')
|
||||
const data = new Uint8Array(await res.arrayBuffer())
|
||||
const file = this.save(data, mime)
|
||||
// Remember the size so the chat can reserve space before the image loads.
|
||||
const patch: MediaRef = { file, mime }
|
||||
if (mime.startsWith('image/')) {
|
||||
const size = nativeImage.createFromBuffer(Buffer.from(data)).getSize()
|
||||
if (size.width) Object.assign(patch, size)
|
||||
}
|
||||
this.db.setMediaFile(id, index, patch)
|
||||
return { url, ...patch }
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
// Cache attachments of freshly synced messages right away, one at a time.
|
||||
prefetch(msgs: NewMessage[]): void {
|
||||
const todo = msgs.flatMap((m) => (m.media ?? []).map((_, i) => [m.id, i] as const))
|
||||
void (async () => {
|
||||
for (const [id, i] of todo) await this.resolve(id, i)
|
||||
})()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// New-message notifications. Sent at low urgency, which GNOME files straight
|
||||
// into the notification list (click the clock) without a pop-up banner.
|
||||
import { Notification } from 'electron'
|
||||
import { formatNumber, groupMembers, isGroup } from '@shared/phone'
|
||||
import type { ContactDirectory } from './contacts'
|
||||
import type { MessageDb, NewMessage } from './db'
|
||||
import { reactionPreview } from '@shared/reactions'
|
||||
|
||||
// Only messages this recent notify: history imports bring in old ones.
|
||||
const RECENT = 10 * 60_000
|
||||
|
||||
export interface NotifyDeps {
|
||||
db: MessageDb
|
||||
contacts: ContactDirectory
|
||||
onClick: (key: { did: string; contact: string }) => void
|
||||
}
|
||||
|
||||
// Shown notifications by conversation, kept referenced so their click
|
||||
// handlers survive garbage collection until GNOME dismisses them, and so
|
||||
// reading the conversation in the app can take them back out of the list.
|
||||
const live = new Map<string, Set<Notification>>()
|
||||
|
||||
const convKey = (did: string, contact: string): string => `${did}\n${contact}`
|
||||
|
||||
// The conversation's been read: its notifications are stale.
|
||||
export function clearNotifications(did: string, contact: string): void {
|
||||
const shown = live.get(convKey(did, contact))
|
||||
if (!shown) return
|
||||
live.delete(convKey(did, contact))
|
||||
for (const n of shown) n.close()
|
||||
}
|
||||
|
||||
const nameOf = (contacts: ContactDirectory, n: string): string => contacts.lookup(n)?.name ?? formatNumber(n)
|
||||
|
||||
export function conversationTitle(db: MessageDb, contacts: ContactDirectory, did: string, contact: string): string {
|
||||
const own = db.getName(did, contact)
|
||||
if (own) return own
|
||||
if (!isGroup(contact)) return nameOf(contacts, contact)
|
||||
return groupMembers(contact)
|
||||
.map((n) => contacts.lookup(n)?.name.split(/\s+/)[0] ?? formatNumber(n))
|
||||
.join(', ')
|
||||
}
|
||||
|
||||
function preview(m: NewMessage): string {
|
||||
const reaction = reactionPreview(m.body)
|
||||
if (reaction) return reaction
|
||||
const body = m.body.replace(/\s+/g, ' ').trim()
|
||||
if (body) return body
|
||||
return m.media?.length ? '📷 Photo' : ''
|
||||
}
|
||||
|
||||
// One notification per conversation with new incoming messages.
|
||||
export function notifyNew(msgs: NewMessage[], { db, contacts, onClick }: NotifyDeps, now = Date.now()): void {
|
||||
if (!Notification.isSupported()) return
|
||||
const byConv = new Map<string, NewMessage[]>()
|
||||
for (const m of msgs) {
|
||||
if (m.direction !== 'in' || m.ts < now - RECENT) continue
|
||||
const key = convKey(m.did, m.contact)
|
||||
byConv.set(key, [...(byConv.get(key) ?? []), m])
|
||||
}
|
||||
for (const list of byConv.values()) {
|
||||
const last = list.reduce((a, b) => (b.ts > a.ts ? b : a))
|
||||
const { did, contact } = last
|
||||
const sender = isGroup(contact) && last.sender ? `${nameOf(contacts, last.sender).split(/\s+/)[0]}: ` : ''
|
||||
const more = list.length > 1 ? ` (+${list.length - 1} more)` : ''
|
||||
const n = new Notification({
|
||||
title: conversationTitle(db, contacts, did, contact),
|
||||
body: sender + preview(last) + more,
|
||||
urgency: 'low'
|
||||
})
|
||||
const key = convKey(did, contact)
|
||||
const shown = live.get(key) ?? new Set()
|
||||
live.set(key, shown.add(n))
|
||||
n.on('click', () => onClick({ did, contact }))
|
||||
n.on('close', () => {
|
||||
shown.delete(n)
|
||||
if (!shown.size && live.get(key) === shown) live.delete(key)
|
||||
})
|
||||
n.show()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
// Installing the Android app on a Rabbit R1 (or any Android device) over adb,
|
||||
// with the accounts, history and chat names copied into its private storage,
|
||||
// so it opens signed in and with everything already there.
|
||||
//
|
||||
// Files go in through `adb shell -T "run-as <pkg> ..."`: run-as needs the APK
|
||||
// to be debuggable (android/build.py builds it that way), and shell -T (no
|
||||
// pty) passes stdin through byte for byte, waits for the command to finish and
|
||||
// returns its exit code. (exec-in does none of the last two: it ends the
|
||||
// remote command as soon as stdin runs out.) Nothing secret touches the desktop's disk on
|
||||
// the way: the accounts JSON is piped straight in.
|
||||
import Database from 'better-sqlite3'
|
||||
import { app } from 'electron'
|
||||
import { spawn } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import type { MessageDb, NameChange, ReadState } from './db'
|
||||
|
||||
export interface RabbitConfig {
|
||||
sandbox?: boolean
|
||||
voipms: { username: string; password: string } | null
|
||||
gvoice: { number: string; cookies: Record<string, string> } | null
|
||||
dids: Array<{ did: string; description: string }>
|
||||
defaultDid?: string
|
||||
}
|
||||
|
||||
export interface RabbitTarget {
|
||||
pkg: string
|
||||
apk: string
|
||||
}
|
||||
|
||||
export interface DeviceInfo {
|
||||
serial: string
|
||||
model: string
|
||||
installedVersion?: string
|
||||
}
|
||||
|
||||
const ADB_DIRS = ['/usr/local/sbin', '/usr/local/bin', '/usr/bin', path.join(os.homedir(), 'Android/Sdk/platform-tools')]
|
||||
|
||||
export function findAdb(): string | undefined {
|
||||
const dirs = [...(process.env['PATH'] ?? '').split(':'), ...ADB_DIRS]
|
||||
return dirs.map((d) => path.join(d, 'adb')).find((f) => f && fs.existsSync(f))
|
||||
}
|
||||
|
||||
// The APK shipped with the desktop app (android/build.py --ship).
|
||||
export function bundledApk(): { apk: string; version?: string } | undefined {
|
||||
const packaged = path.join(process.resourcesPath ?? '', 'android', 'VoipMessages.apk')
|
||||
const dev = path.join(app.getAppPath(), 'resources', 'android', 'VoipMessages.apk')
|
||||
const apk = [packaged, dev].find((f) => fs.existsSync(f))
|
||||
if (!apk) return undefined
|
||||
try {
|
||||
const meta = JSON.parse(fs.readFileSync(apk.replace(/\.apk$/, '.json'), 'utf8')) as { version_name: string }
|
||||
return { apk, version: meta.version_name }
|
||||
} catch {
|
||||
return { apk }
|
||||
}
|
||||
}
|
||||
|
||||
class Adb {
|
||||
constructor(
|
||||
readonly adb: string,
|
||||
readonly serial: string
|
||||
) {}
|
||||
|
||||
// Runs adb; resolves stdout. `input` is piped to stdin (a Buffer or a stream).
|
||||
run(args: string[], input?: Buffer | NodeJS.ReadableStream, timeoutMs = 120_000): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const p = spawn(this.adb, this.serial ? ['-s', this.serial, ...args] : args)
|
||||
const out: Buffer[] = []
|
||||
const err: Buffer[] = []
|
||||
const timer = setTimeout(() => p.kill(), timeoutMs)
|
||||
p.stdout.on('data', (d: Buffer) => out.push(d))
|
||||
p.stderr.on('data', (d: Buffer) => err.push(d))
|
||||
p.on('error', reject)
|
||||
p.on('close', (code) => {
|
||||
clearTimeout(timer)
|
||||
const stderr = Buffer.concat(err).toString().trim()
|
||||
if (code === 0) resolve(Buffer.concat(out))
|
||||
else reject(new Error(stderr.split('\n').pop() || `adb ${args[0]} failed (${code})`))
|
||||
})
|
||||
if (input instanceof Buffer) p.stdin.end(input)
|
||||
else if (input) (input as NodeJS.ReadableStream).pipe(p.stdin)
|
||||
else p.stdin.end()
|
||||
})
|
||||
}
|
||||
|
||||
async shell(cmd: string, timeoutMs?: number): Promise<string> {
|
||||
return (await this.run(['shell', cmd], undefined, timeoutMs)).toString()
|
||||
}
|
||||
|
||||
// A command run as the app (in its private data dir), fed `input`.
|
||||
asApp(pkg: string, cmd: string, input?: Buffer | NodeJS.ReadableStream, timeoutMs?: number): Promise<Buffer> {
|
||||
return this.run(['shell', '-T', `run-as ${pkg} sh -c ${shq(cmd)}`], input, timeoutMs)
|
||||
}
|
||||
|
||||
readAsApp(pkg: string, file: string): Promise<Buffer> {
|
||||
return this.run(['exec-out', `run-as ${pkg} sh -c ${shq(`cat ${file} 2>/dev/null || true`)}`])
|
||||
}
|
||||
}
|
||||
|
||||
const shq = (s: string): string => `'${s.replace(/'/g, `'\\''`)}'`
|
||||
|
||||
async function listDevices(adb: string): Promise<Array<{ serial: string; state: string; model: string }>> {
|
||||
const out = await new Adb(adb, '').run(['devices', '-l']).catch(() => Buffer.from(''))
|
||||
return out
|
||||
.toString()
|
||||
.split('\n')
|
||||
.slice(1)
|
||||
.map((l) => l.trim())
|
||||
.filter(Boolean)
|
||||
.map((l) => {
|
||||
const [serial, state] = l.split(/\s+/)
|
||||
const model = /model:(\S+)/.exec(l)?.[1]?.replace(/_/g, ' ') ?? serial
|
||||
return { serial, state, model }
|
||||
})
|
||||
}
|
||||
|
||||
export async function connect(): Promise<Adb> {
|
||||
const adb = findAdb()
|
||||
if (!adb) throw new Error("adb isn't installed on this computer.")
|
||||
const devices = await listDevices(adb)
|
||||
const ready = devices.find((d) => d.state === 'device')
|
||||
if (ready) return new Adb(adb, ready.serial)
|
||||
if (devices.some((d) => d.state === 'unauthorized')) throw new Error('Unlock the Rabbit and allow USB debugging for this computer.')
|
||||
throw new Error('No Rabbit connected. Plug it in over USB (with USB debugging on).')
|
||||
}
|
||||
|
||||
export async function status(pkg: string): Promise<DeviceInfo | undefined> {
|
||||
const adb = findAdb()
|
||||
if (!adb) return undefined
|
||||
const ready = (await listDevices(adb)).find((d) => d.state === 'device')
|
||||
if (!ready) return undefined
|
||||
const a = new Adb(adb, ready.serial)
|
||||
const info = await a.shell(`dumpsys package ${pkg} | grep -m1 versionName`).catch(() => '')
|
||||
const version = /versionName=(\S+)/.exec(info)?.[1]
|
||||
return { serial: ready.serial, model: ready.model, ...(version ? { installedVersion: version } : {}) }
|
||||
}
|
||||
|
||||
// A copy of the history the Android app can open: its SQLite has no FTS5,
|
||||
// so the search index (and the triggers that feed it) come out.
|
||||
async function historyCopy(db: MessageDb): Promise<string> {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'voip-rabbit-'))
|
||||
const file = path.join(dir, 'messages.db')
|
||||
await db.db.backup(file)
|
||||
const copy = new Database(file)
|
||||
copy.exec(`
|
||||
DROP TRIGGER IF EXISTS messages_ai; DROP TRIGGER IF EXISTS messages_ad; DROP TRIGGER IF EXISTS messages_au;
|
||||
DROP TABLE IF EXISTS messages_fts;
|
||||
`)
|
||||
copy.pragma('journal_mode = DELETE')
|
||||
copy.exec('VACUUM')
|
||||
copy.close()
|
||||
return file
|
||||
}
|
||||
|
||||
// Merge chat names and read/unread/archived state both ways: the Rabbit's
|
||||
// (files/state.json, which the app keeps current) into the desktop, then the
|
||||
// combined result back (files/state-in.json, applied by the app on its next
|
||||
// start or check). Newest change wins on each side. Returns how many
|
||||
// conversations changed here.
|
||||
interface SyncState {
|
||||
names: NameChange[]
|
||||
read: ReadState[]
|
||||
}
|
||||
|
||||
async function syncState(a: Adb, pkg: string, db: MessageDb): Promise<number> {
|
||||
const raw = (await a.readAsApp(pkg, 'files/state.json')).toString().trim()
|
||||
let theirs: SyncState = { names: [], read: [] }
|
||||
try {
|
||||
if (raw) theirs = { names: [], read: [], ...(JSON.parse(raw) as Partial<SyncState>) }
|
||||
} catch {
|
||||
/* a half-written file: skip this round */
|
||||
}
|
||||
const changed = db.namesImport(theirs.names) + db.readStateImport(theirs.read)
|
||||
const ours: SyncState = { names: db.namesExport(), read: db.readStateExport() }
|
||||
await a.asApp(pkg, 'umask 077 && cat > files/state-in.json.tmp && mv files/state-in.json.tmp files/state-in.json', Buffer.from(JSON.stringify(ours)))
|
||||
return changed
|
||||
}
|
||||
|
||||
export type Progress = (step: string) => void
|
||||
|
||||
export interface InstallDeps {
|
||||
db: MessageDb
|
||||
mediaDir: string
|
||||
target: RabbitTarget
|
||||
config: () => Promise<RabbitConfig>
|
||||
progress: Progress
|
||||
}
|
||||
|
||||
async function pushConfig(a: Adb, pkg: string, cfg: RabbitConfig): Promise<void> {
|
||||
// Straight from memory into the app's private files: no temp file.
|
||||
await a.asApp(pkg, 'mkdir -p files && umask 077 && cat > files/config.json.tmp && mv files/config.json.tmp files/config.json', Buffer.from(JSON.stringify(cfg)))
|
||||
}
|
||||
|
||||
async function lockDown(a: Adb, pkg: string): Promise<void> {
|
||||
await a.asApp(pkg, 'chmod -R go-rwx files')
|
||||
}
|
||||
|
||||
// Fresh install (or reinstall): app, permissions, accounts, history, photos, names.
|
||||
// Photos the Rabbit doesn't have yet (files are named by content hash, so a
|
||||
// name it already has is the same file). Returns how many were sent.
|
||||
async function copyMedia(a: Adb, pkg: string, mediaDir: string, progress: Progress): Promise<number> {
|
||||
if (!fs.existsSync(mediaDir)) return 0
|
||||
const have = new Set((await a.asApp(pkg, 'mkdir -p files/media && ls files/media')).toString().split('\n').map((l) => l.trim()))
|
||||
const missing = fs.readdirSync(mediaDir).filter((f) => !have.has(f) && fs.statSync(path.join(mediaDir, f)).isFile())
|
||||
if (!missing.length) return 0
|
||||
progress(`Copying ${missing.length.toLocaleString()} photo${missing.length === 1 ? '' : 's'} and attachments…`)
|
||||
const tar = spawn('tar', ['-C', mediaDir, '-cf', '-', '-T', '-'])
|
||||
tar.stdin.end(missing.join('\n') + '\n')
|
||||
await a.asApp(pkg, 'cd files/media && tar xf -', tar.stdout, 1_800_000)
|
||||
return missing.length
|
||||
}
|
||||
|
||||
// 'full': the app plus history and photos (first install, or starting over;
|
||||
// only photos the Rabbit lacks are sent). 'update': just the new app version
|
||||
// -- Android keeps the app's data across an update -- plus accounts and the
|
||||
// names / read-status merge.
|
||||
export async function install({ db, mediaDir, target, config, progress, mode = 'full' }: InstallDeps & { mode?: 'full' | 'update' }): Promise<number> {
|
||||
const { pkg, apk } = target
|
||||
progress('Connecting to the Rabbit…')
|
||||
const a = await connect()
|
||||
progress('Installing the app…')
|
||||
await a.run(['install', '-r', '-g', apk], undefined, 300_000)
|
||||
// Background checks: exempt from Doze and background limits.
|
||||
await a.shell(`dumpsys deviceidle whitelist +${pkg}`).catch(() => undefined)
|
||||
await a.shell(`cmd appops set ${pkg} RUN_ANY_IN_BACKGROUND allow`).catch(() => undefined)
|
||||
await a.shell(`am force-stop ${pkg}`)
|
||||
|
||||
progress('Copying your accounts…')
|
||||
await pushConfig(a, pkg, await config())
|
||||
|
||||
if (mode === 'full') {
|
||||
progress('Copying your message history…')
|
||||
const history = await historyCopy(db)
|
||||
try {
|
||||
await a.asApp(pkg, 'rm -f files/messages.db files/messages.db-wal files/messages.db-shm files/messages.db-journal')
|
||||
await a.asApp(pkg, 'umask 077 && cat > files/messages.db', fs.createReadStream(history), 600_000)
|
||||
} finally {
|
||||
fs.rmSync(path.dirname(history), { recursive: true, force: true })
|
||||
}
|
||||
await copyMedia(a, pkg, mediaDir, progress)
|
||||
}
|
||||
|
||||
progress('Syncing chat names and read status…')
|
||||
const names = await syncState(a, pkg, db)
|
||||
await lockDown(a, pkg)
|
||||
progress('Opening it on the Rabbit…')
|
||||
await a.shell(`am start -n ${pkg}/me.teafry.voipmessages.MainActivity`)
|
||||
return names
|
||||
}
|
||||
|
||||
// Accounts and chat names again (e.g. after reconnecting Google Voice), without
|
||||
// touching the app or its history. Returns how many names changed here.
|
||||
export async function sync({ db, target, config, progress }: Omit<InstallDeps, 'mediaDir'>): Promise<number> {
|
||||
const { pkg } = target
|
||||
progress('Connecting to the Rabbit…')
|
||||
const a = await connect()
|
||||
const installed = await a.shell(`pm path ${pkg}`).catch(() => '')
|
||||
if (!installed.trim()) throw new Error("The app isn't on the Rabbit yet. Use Install to Rabbit first.")
|
||||
progress('Copying your accounts…')
|
||||
await pushConfig(a, pkg, await config())
|
||||
progress('Syncing chat names and read status…')
|
||||
const names = await syncState(a, pkg, db)
|
||||
await lockDown(a, pkg)
|
||||
return names
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// Sandbox mode, for trying the app (and UI work) without going anywhere near
|
||||
// the real account: VOIPMS_SANDBOX=<dir> (or VOIPMS_DEMO=1, which uses a temp
|
||||
// dir) keeps *everything* under <dir> -- the Electron profile (so no saved
|
||||
// voip.ms password and no Google sign-in), settings, and the message database
|
||||
// -- skips the system address book, and fills an empty database with made-up
|
||||
// conversations. Imported first by index.ts so it applies before anything
|
||||
// reads a path.
|
||||
import { app } from 'electron'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import type { MessageDb, NewMessage } from './db'
|
||||
import { gvMessageId } from './gvoice/sync'
|
||||
|
||||
export const SANDBOX: string | undefined =
|
||||
process.env['VOIPMS_SANDBOX'] || (process.env['VOIPMS_DEMO'] ? path.join(os.tmpdir(), 'voipms-sandbox') : undefined)
|
||||
|
||||
if (SANDBOX) {
|
||||
app.setPath('userData', path.join(SANDBOX, 'profile'))
|
||||
process.env['VOIPMS_DATA_DIR'] = path.join(SANDBOX, 'data')
|
||||
console.log(`[sandbox] everything lives in ${SANDBOX}`)
|
||||
} else {
|
||||
// The app was "voip.ms Messages" before it was bubble, and Electron names
|
||||
// the profile folder after the app: keep using the old one so the saved
|
||||
// login, Google sign-in and data-location pointer carry over.
|
||||
app.setPath('userData', path.join(app.getPath('appData'), 'voip.ms Messages'))
|
||||
}
|
||||
|
||||
// Fictional numbers (555-01xx is reserved for fiction).
|
||||
export const DEMO_VOIP = '5415550100'
|
||||
export const DEMO_GV = '5415550177'
|
||||
|
||||
export function seedDemo(db: MessageDb): void {
|
||||
if (db.count() > 0) return
|
||||
const now = Date.now()
|
||||
const min = 60_000
|
||||
const group = '5415550101,5415550102,5415550103'
|
||||
let id = 1000
|
||||
const v = (contact: string, direction: 'in' | 'out', body: string, ago: number): NewMessage => ({
|
||||
id: id++,
|
||||
did: DEMO_VOIP,
|
||||
contact,
|
||||
direction,
|
||||
body,
|
||||
ts: now - ago * min
|
||||
})
|
||||
const g = (contact: string, direction: 'in' | 'out', body: string, ago: number, sender?: string): NewMessage => ({
|
||||
id: gvMessageId(`demo-${id++}`),
|
||||
did: DEMO_GV,
|
||||
contact,
|
||||
direction,
|
||||
body,
|
||||
ts: now - ago * min,
|
||||
...(sender ? { sender } : {})
|
||||
})
|
||||
db.upsertMessages([
|
||||
v('5415550110', 'in', 'Are we still on for Saturday?', 300),
|
||||
v('5415550110', 'out', 'Yep! 10am at the market', 290),
|
||||
v('5415550111', 'in', 'Your table is ready', 2000),
|
||||
g('5415550120', 'in', 'Package left at the front door', 90),
|
||||
g('5415550120', 'out', 'Thanks!', 85),
|
||||
g(group, 'in', 'Who is bringing snacks to the hike?', 40, '5415550101'),
|
||||
g(group, 'in', 'I can do chips', 38, '5415550102'),
|
||||
g(group, 'in', 'and salsa', 37, '5415550102'),
|
||||
g(group, 'out', 'I’ll bring cookies 🍪', 30),
|
||||
g(group, 'in', 'Loved “I’ll bring cookies 🍪”', 29, '5415550101'),
|
||||
g(group, 'in', 'Laughed at “I’ll bring cookies 🍪”', 28, '5415550103'),
|
||||
g(group, 'in', 'Perfect, see everyone at 9', 5, '5415550103'),
|
||||
g(group, 'in', 'Emphasized “Perfect, see everyone at 9”', 4, '5415550102')
|
||||
])
|
||||
db.setGvThread(DEMO_GV, group, 'g.demo')
|
||||
db.set('unread_floor', '0')
|
||||
db.set('gv_number', DEMO_GV)
|
||||
db.set('dids', JSON.stringify([{ did: DEMO_VOIP, description: 'Demo', smsEnabled: true }]))
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Sending one message, retrying when it's safe to.
|
||||
import type { MessageDb } from './db'
|
||||
import { classifySendError, sendErrorMessage, type SendFailure } from './voipms'
|
||||
|
||||
const MAX_ATTEMPTS = 3
|
||||
// Pause before sending again after an attempt that certainly didn't go out.
|
||||
const RETRY_DELAYS = [3000, 10_000]
|
||||
// After an attempt that may have gone out (no reply), look for it in the
|
||||
// listing at these points before sending again.
|
||||
const CHECK_DELAYS = [5000, 15_000]
|
||||
|
||||
export interface SendDeps {
|
||||
db: Pick<MessageDb, 'getMessage' | 'confirmPending' | 'markFailed'>
|
||||
// One attempt; resolves with the id voip.ms assigned.
|
||||
attempt: () => Promise<number>
|
||||
// Fetch recent messages, which replaces the local copy of anything that
|
||||
// turns out to have been sent (MessageDb.reconcileSent).
|
||||
checkSent: () => Promise<void>
|
||||
sleep?: (ms: number) => Promise<void>
|
||||
// How to read the provider's errors (default: voip.ms's).
|
||||
classify?: (e: unknown) => SendFailure
|
||||
describe?: (e: unknown) => string
|
||||
}
|
||||
|
||||
const wait = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
|
||||
|
||||
// Delivers pending message `tempId`; never throws. On giving up the message
|
||||
// is marked failed with the reason.
|
||||
export async function sendWithRetry(
|
||||
tempId: number,
|
||||
{ db, attempt, checkSent, sleep = wait, classify = classifySendError, describe = sendErrorMessage }: SendDeps
|
||||
): Promise<void> {
|
||||
// A poll found the message already sent and replaced our local copy.
|
||||
const sent = (): boolean => !db.getMessage(tempId)
|
||||
for (let n = 1; ; n++) {
|
||||
try {
|
||||
db.confirmPending(tempId, await attempt())
|
||||
return
|
||||
} catch (e) {
|
||||
if (sent()) return
|
||||
const kind = classify(e)
|
||||
if (kind === 'unknown') {
|
||||
for (const ms of CHECK_DELAYS) {
|
||||
await sleep(ms)
|
||||
await checkSent().catch(() => undefined)
|
||||
if (sent()) return
|
||||
}
|
||||
}
|
||||
if (kind === 'fatal' || n >= MAX_ATTEMPTS) {
|
||||
db.markFailed(tempId, describe(e))
|
||||
return
|
||||
}
|
||||
if (kind === 'safe') await sleep(RETRY_DELAYS[n - 1] ?? RETRY_DELAYS.at(-1)!)
|
||||
if (sent()) return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,9 @@ import type { Settings } from '@shared/types'
|
||||
const DEFAULTS: Settings = {
|
||||
pollSeconds: 30,
|
||||
dids: [],
|
||||
backfillFloor: '2010-01-01'
|
||||
backfillFloor: '2010-01-01',
|
||||
theme: 'system',
|
||||
notifications: true
|
||||
}
|
||||
|
||||
const pointerFile = (): string => path.join(app.getPath('userData'), 'data-location.json')
|
||||
|
||||
+26
-11
@@ -2,7 +2,7 @@
|
||||
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 { charCount, normalizeNumber, SMS_TEXT_LIMIT } from '@shared/phone'
|
||||
import type { SyncStatus } from '@shared/types'
|
||||
|
||||
const WINDOW_DAYS = 90
|
||||
@@ -19,7 +19,7 @@ function parseYmd(s: string): number {
|
||||
}
|
||||
|
||||
export function toNewMessage(r: RawSms): NewMessage {
|
||||
return {
|
||||
const m: NewMessage = {
|
||||
id: Number(r.id),
|
||||
did: normalizeNumber(r.did),
|
||||
contact: normalizeNumber(r.contact),
|
||||
@@ -27,12 +27,23 @@ export function toNewMessage(r: RawSms): NewMessage {
|
||||
body: r.message ?? '',
|
||||
ts: parseVoipDate(r.date)
|
||||
}
|
||||
// With all_messages=1 every row carries the media columns, SMS included, so
|
||||
// only rows that actually have media count as MMS -- or text too long for
|
||||
// one SMS, which voip.ms carries as a text-only MMS.
|
||||
const urls = (r.media?.length ? r.media : [r.col_media1, r.col_media2, r.col_media3]).filter((u): u is string => !!u)
|
||||
if (urls.length) {
|
||||
m.kind = 'mms'
|
||||
m.media = urls.map((url) => ({ url }))
|
||||
} else if (charCount(m.body) > SMS_TEXT_LIMIT) {
|
||||
m.kind = 'mms'
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// 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 })
|
||||
export async function fetchRange(api: Pick<VoipMs, 'getMessages'>, from: number, to: number, limit = PAGE_LIMIT): Promise<RawSms[]> {
|
||||
const rows = await api.getMessages({ 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)
|
||||
@@ -51,7 +62,7 @@ export class SyncEngine extends EventEmitter {
|
||||
private burstUntil = 0
|
||||
private running = false
|
||||
private backfilling = false
|
||||
private polling = false
|
||||
private polling?: Promise<void>
|
||||
private status: SyncStatus
|
||||
|
||||
constructor(
|
||||
@@ -81,6 +92,7 @@ export class SyncEngine extends EventEmitter {
|
||||
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)
|
||||
this.db.reconcileSent(added)
|
||||
if (added.length) this.emit('messages', added)
|
||||
}
|
||||
|
||||
@@ -112,22 +124,25 @@ export class SyncEngine extends EventEmitter {
|
||||
}, d)
|
||||
}
|
||||
|
||||
// Manual refresh. Joins a check that's already under way rather than
|
||||
// returning early, so the caller knows when fresh results are in.
|
||||
async pollNow(): Promise<void> {
|
||||
await this.poll()
|
||||
}
|
||||
|
||||
private async poll(): Promise<void> {
|
||||
if (this.polling) return
|
||||
this.polling = true
|
||||
private poll(): Promise<void> {
|
||||
this.polling ??= this.fetchRecent().finally(() => (this.polling = undefined))
|
||||
return this.polling
|
||||
}
|
||||
|
||||
private async fetchRecent(): Promise<void> {
|
||||
try {
|
||||
const now = Date.now()
|
||||
const rows = await this.api.getSms({ from: ymd(now - DAY), to: ymd(now + DAY), limit: PAGE_LIMIT })
|
||||
const rows = await this.api.getMessages({ 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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// Per-machine window state (not a synced preference, so kept out of settings.json).
|
||||
import { app } from 'electron'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
interface UiState {
|
||||
zoom?: number
|
||||
}
|
||||
|
||||
const file = (): string => path.join(app.getPath('userData'), 'ui-state.json')
|
||||
|
||||
function load(): UiState {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(file(), 'utf8')) as UiState
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
export function loadZoom(): number {
|
||||
return load().zoom ?? 0
|
||||
}
|
||||
|
||||
export function saveZoom(zoom: number): void {
|
||||
fs.mkdirSync(path.dirname(file()), { recursive: true })
|
||||
fs.writeFileSync(file(), JSON.stringify({ ...load(), zoom }, null, 2))
|
||||
}
|
||||
+91
-14
@@ -10,6 +10,11 @@ export interface RawSms {
|
||||
did: string
|
||||
contact: string
|
||||
message: string
|
||||
// getMMS only: up to three media URLs ("" when unused).
|
||||
media?: string[]
|
||||
col_media1?: string
|
||||
col_media2?: string
|
||||
col_media3?: string
|
||||
}
|
||||
|
||||
const FRIENDLY_ERRORS: Record<string, string> = {
|
||||
@@ -20,7 +25,12 @@ const FRIENDLY_ERRORS: Record<string, string> = {
|
||||
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.'
|
||||
sms_failed: 'voip.ms failed to send the message.',
|
||||
mms_failed: 'voip.ms failed to send the MMS.',
|
||||
mms_toolong: 'Message is too long for an MMS (2048 characters max).',
|
||||
invalid_media: 'voip.ms rejected the attachment (unsupported type or too large).',
|
||||
media_toolarge: 'The attachment is too large for voip.ms MMS.',
|
||||
not_signed_in: 'Not signed in.'
|
||||
}
|
||||
|
||||
export class VoipMsError extends Error {
|
||||
@@ -29,18 +39,29 @@ export class VoipMsError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
function toFormData(params: URLSearchParams): FormData {
|
||||
const fd = new FormData()
|
||||
for (const [k, v] of params) fd.set(k, v)
|
||||
return fd
|
||||
}
|
||||
|
||||
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)
|
||||
// POST sends params as a multipart form body: needed for base64 media, which
|
||||
// is far too big for a query string. (voip.ms routes urlencoded POSTs to its
|
||||
// SOAP endpoint, which answers with a 500 fault — multipart is required.)
|
||||
private async call<T>(method: string, params: Record<string, string | number | undefined> = {}, post = false): Promise<T> {
|
||||
const form = new URLSearchParams()
|
||||
form.set('api_username', this.creds.username)
|
||||
form.set('api_password', this.creds.password)
|
||||
form.set('method', method)
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v !== undefined && v !== '') url.searchParams.set(k, String(v))
|
||||
if (v !== undefined && v !== '') form.set(k, String(v))
|
||||
}
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(60_000) })
|
||||
const res = post
|
||||
? await fetch(ENDPOINT, { method: 'POST', body: toFormData(form), signal: AbortSignal.timeout(120_000) })
|
||||
: await fetch(`${ENDPOINT}?${form}`, { signal: AbortSignal.timeout(method.startsWith('send') ? 120_000 : 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)
|
||||
@@ -56,30 +77,86 @@ export class VoipMs {
|
||||
}))
|
||||
}
|
||||
|
||||
// getMMS with all_messages=1 returns SMS *and* MMS in one listing, with
|
||||
// absolute media URLs (getSMS only gives relative ones). SMS and MMS ids come
|
||||
// from separate sequences but live in disjoint ranges (~1e8 vs ~1e7).
|
||||
// Returns [] when voip.ms reports no messages for the range.
|
||||
async getSms(opts: { from: string; to: string; did?: string; limit?: number }): Promise<RawSms[]> {
|
||||
async getMessages(opts: { from: string; to: string; did?: string; limit?: number }): Promise<RawSms[]> {
|
||||
try {
|
||||
const r = await this.call<{ sms: RawSms[] }>('getSMS', {
|
||||
const r = await this.call<{ sms: RawSms[] }>('getMMS', {
|
||||
from: opts.from,
|
||||
to: opts.to,
|
||||
did: opts.did,
|
||||
limit: opts.limit ?? 10000,
|
||||
timezone: 0
|
||||
timezone: 0,
|
||||
all_messages: 1
|
||||
})
|
||||
return r.sms ?? []
|
||||
} catch (e) {
|
||||
if (e instanceof VoipMsError && e.status === 'no_sms') return []
|
||||
if (e instanceof VoipMsError && (e.status === 'no_sms' || e.status === 'no_mms')) return []
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
// media: data URLs ("data:image/jpeg;base64,...") or public URLs, max 3.
|
||||
async sendMms(did: string, dst: string, message: string, media: string[]): Promise<number> {
|
||||
const params: Record<string, string> = { did, dst, message }
|
||||
media.slice(0, 3).forEach((m, i) => (params[`media${i + 1}`] = m))
|
||||
const r = await this.call<{ mms: number | string }>('sendMMS', params, true)
|
||||
return Number(r.mms)
|
||||
}
|
||||
|
||||
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
|
||||
// How a failed send should be handled:
|
||||
// fatal - voip.ms rejected it; sending again won't help.
|
||||
// safe - it definitely didn't go out; send again.
|
||||
// unknown - it may have gone out (e.g. we gave up waiting for the reply);
|
||||
// check the listing before sending again, or it arrives twice.
|
||||
export type SendFailure = 'fatal' | 'safe' | 'unknown'
|
||||
|
||||
// Network errors raised before the request reached voip.ms.
|
||||
const NOT_SENT_CODES = new Set(['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH'])
|
||||
|
||||
export function classifySendError(e: unknown): SendFailure {
|
||||
if (e instanceof VoipMsError) return e.status === 'sms_failed' || e.status === 'mms_failed' ? 'safe' : 'fatal'
|
||||
const code = ((e as { cause?: { code?: string } })?.cause?.code) ?? (e as { code?: string })?.code
|
||||
if (code && NOT_SENT_CODES.has(code)) return 'safe'
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
// A short explanation to show on a message that couldn't be sent.
|
||||
export function sendErrorMessage(e: unknown): string {
|
||||
const err = e as Error
|
||||
if (err?.name === 'TimeoutError' || err?.name === 'AbortError') return "voip.ms didn't respond in time."
|
||||
if (err instanceof VoipMsError) return err.message
|
||||
const code = (err as { cause?: { code?: string } })?.cause?.code
|
||||
if (code && NOT_SENT_CODES.has(code)) return "Couldn't reach voip.ms. Check your internet connection."
|
||||
if (err?.message === 'fetch failed') return 'The connection to voip.ms was interrupted.'
|
||||
return err?.message || String(e)
|
||||
}
|
||||
|
||||
// voip.ms's `timezone` parameter adds its own daylight-saving hour: asking for
|
||||
// timezone=0 returns UTC+1 for any message dated inside *US* daylight time
|
||||
// (verified against messages with known send times; winter dates are exact).
|
||||
// Undo that hour so stored times are true UTC.
|
||||
const HOUR = 3_600_000
|
||||
const easternOffset = new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', timeZoneName: 'shortOffset' })
|
||||
|
||||
function isUsDst(ms: number): boolean {
|
||||
return easternOffset.formatToParts(ms).find((p) => p.type === 'timeZoneName')?.value === 'GMT-4'
|
||||
}
|
||||
|
||||
// A time voip.ms reported for timezone=0 (as epoch ms) -> the real instant.
|
||||
export function fixVoipDst(ms: number): number {
|
||||
return isUsDst(ms - HOUR) ? ms - HOUR : ms
|
||||
}
|
||||
|
||||
// "2024-01-02 03:04:05" (fetched with timezone=0) -> epoch ms UTC
|
||||
export function parseVoipDate(s: string): number {
|
||||
return Date.parse(s.replace(' ', 'T') + 'Z')
|
||||
return fixVoipDst(Date.parse(s.replace(' ', 'T') + 'Z'))
|
||||
}
|
||||
|
||||
+23
-2
@@ -12,16 +12,35 @@ const api: Api = {
|
||||
testCredentials: (creds) => ipcRenderer.invoke('testCredentials', creds),
|
||||
saveSetup: (creds, settings) => ipcRenderer.invoke('saveSetup', creds, settings),
|
||||
updateSettings: (settings) => ipcRenderer.invoke('updateSettings', settings),
|
||||
setTheme: (theme) => ipcRenderer.invoke('setTheme', theme),
|
||||
signOut: () => ipcRenderer.invoke('signOut'),
|
||||
connectGoogleVoice: () => ipcRenderer.invoke('connectGoogleVoice'),
|
||||
connectGoogleVoiceCookies: (text) => ipcRenderer.invoke('connectGoogleVoiceCookies', text),
|
||||
disconnectGoogleVoice: () => ipcRenderer.invoke('disconnectGoogleVoice'),
|
||||
rabbitStatus: () => ipcRenderer.invoke('rabbitStatus'),
|
||||
rabbitInstall: (mode) => ipcRenderer.invoke('rabbitInstall', mode),
|
||||
rabbitSync: () => ipcRenderer.invoke('rabbitSync'),
|
||||
onRabbitProgress: (cb) => on('rabbitProgress', cb),
|
||||
|
||||
listContacts: () => ipcRenderer.invoke('listContacts'),
|
||||
listAddressBooks: () => ipcRenderer.invoke('listAddressBooks'),
|
||||
addContact: (c) => ipcRenderer.invoke('addContact', c),
|
||||
listConversations: () => ipcRenderer.invoke('listConversations'),
|
||||
getMessages: (did, contact) => ipcRenderer.invoke('getMessages', did, contact),
|
||||
markRead: (did, contact) => ipcRenderer.invoke('markRead', did, contact),
|
||||
markUnread: (did, contact) => ipcRenderer.invoke('markUnread', did, contact),
|
||||
setArchived: (did, contact, archived) => ipcRenderer.invoke('setArchived', did, contact, archived),
|
||||
setName: (did, contact, name) => ipcRenderer.invoke('setName', did, contact, name),
|
||||
getDrafts: () => ipcRenderer.invoke('getDrafts'),
|
||||
setDraft: (contact, text) => ipcRenderer.invoke('setDraft', contact, text),
|
||||
search: (query, scope) => ipcRenderer.invoke('search', query, scope),
|
||||
send: (did, contact, text) => ipcRenderer.invoke('send', did, contact, text),
|
||||
send: (did, contact, text, attachments) => ipcRenderer.invoke('send', did, contact, text, attachments),
|
||||
deleteFailed: (id) => ipcRenderer.invoke('deleteFailed', id),
|
||||
retryFailed: (id) => ipcRenderer.invoke('retryFailed', id),
|
||||
saveMedia: (id, index) => ipcRenderer.invoke('saveMedia', id, index),
|
||||
exportChat: (did, contact, opts) => ipcRenderer.invoke('exportChat', did, contact, opts),
|
||||
readMedia: (id, index) => ipcRenderer.invoke('readMedia', id, index),
|
||||
copyImage: (png) => ipcRenderer.invoke('copyImage', png),
|
||||
|
||||
syncStatus: () => ipcRenderer.invoke('syncStatus'),
|
||||
pollNow: () => ipcRenderer.invoke('pollNow'),
|
||||
@@ -32,7 +51,9 @@ const api: Api = {
|
||||
onMessages: (cb) => on('messages', cb),
|
||||
onConversationsChanged: (cb) => on('conversationsChanged', cb),
|
||||
onSyncStatus: (cb) => on('syncStatus', cb),
|
||||
onContactsChanged: (cb) => on('contactsChanged', cb)
|
||||
onContactsChanged: (cb) => on('contactsChanged', cb),
|
||||
onStateChanged: (cb) => on('stateChanged', cb),
|
||||
onOpenConversation: (cb) => on('openConversation', cb)
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld('api', api)
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>voip.ms Messages</title>
|
||||
<title>bubble</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:*"
|
||||
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: contact-photo: mms-media:; media-src 'self' blob: mms-media:; connect-src 'self' ws://localhost:*"
|
||||
/>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -5,6 +5,9 @@ import { Sidebar, type SidebarMode } from './components/Sidebar'
|
||||
import { ChatView } from './components/ChatView'
|
||||
import { Setup } from './components/Setup'
|
||||
import { SettingsDialog } from './components/SettingsDialog'
|
||||
import { ConversationInfo } from './components/ConversationInfo'
|
||||
import { AddContact, AddContactContext } from './components/AddContact'
|
||||
import { ExportChat } from './components/ExportChat'
|
||||
|
||||
export interface ConvKey {
|
||||
did: string
|
||||
@@ -30,6 +33,10 @@ export function App() {
|
||||
const [sync, setSync] = useState<SyncStatus>()
|
||||
const [settingsOpen, setSettingsOpen] = useState(false)
|
||||
const [msgVersion, setMsgVersion] = useState(0)
|
||||
const [archiveView, setArchiveView] = useState(false)
|
||||
const [info, setInfo] = useState<ConvKey | null>(null)
|
||||
const [exporting, setExporting] = useState<ConvKey | null>(null)
|
||||
const [adding, setAdding] = useState<string | null>(null)
|
||||
|
||||
const refreshState = useCallback(() => void window.api.getState().then(setState), [])
|
||||
const refreshConversations = useCallback(() => {
|
||||
@@ -46,17 +53,26 @@ export function App() {
|
||||
const offs = [
|
||||
window.api.onConversationsChanged(refreshConversations),
|
||||
window.api.onContactsChanged(refreshContacts),
|
||||
window.api.onSyncStatus(setSync)
|
||||
window.api.onStateChanged(refreshState),
|
||||
window.api.onSyncStatus(setSync),
|
||||
// Clicked in the notification list.
|
||||
window.api.onOpenConversation((key) => {
|
||||
setMode('chats')
|
||||
setSelected(key)
|
||||
setJump(undefined)
|
||||
})
|
||||
]
|
||||
return () => offs.forEach((off) => off())
|
||||
}, [refreshState, refreshConversations, refreshContacts])
|
||||
|
||||
const contactMap = useMemo(() => new Map(contacts.map((c) => [c.number, c])), [contacts])
|
||||
const named = (key: ConvKey | null): string | undefined => conversations.find((c) => sameConv(c, key))?.name
|
||||
|
||||
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
|
||||
// The sync list is voip.ms's; Google Voice is on whenever it's connected.
|
||||
return chosen.length ? all.filter((d) => d.provider === 'gvoice' || chosen.includes(d.did)) : all
|
||||
}, [state])
|
||||
|
||||
const open = useCallback((key: ConvKey, jumpTo?: number) => {
|
||||
@@ -64,6 +80,12 @@ export function App() {
|
||||
setJump(jumpTo !== undefined ? { id: jumpTo, nonce: Date.now() } : undefined)
|
||||
}, [])
|
||||
|
||||
// An open chat would immediately mark itself read again, so close it.
|
||||
const onMarkUnread = useCallback((key: ConvKey) => setSelected((cur) => (sameConv(cur, key) ? null : cur)), [])
|
||||
|
||||
// The list currently shown in the sidebar (for Alt+↑/↓).
|
||||
const listed = useMemo(() => conversations.filter((c) => c.archived === archiveView), [conversations, archiveView])
|
||||
|
||||
// Keyboard shortcuts (Signal-like).
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent): void => {
|
||||
@@ -75,21 +97,22 @@ export function App() {
|
||||
} else if (mod && e.key.toLowerCase() === 'n') {
|
||||
e.preventDefault()
|
||||
setMode('compose')
|
||||
} else if (e.altKey && (e.key === 'ArrowDown' || e.key === 'ArrowUp') && conversations.length) {
|
||||
} else if (e.altKey && (e.key === 'ArrowDown' || e.key === 'ArrowUp') && listed.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])
|
||||
const i = listed.findIndex((c) => sameConv(c, selected))
|
||||
const next = e.key === 'ArrowDown' ? Math.min(listed.length - 1, i + 1) : Math.max(0, i - 1)
|
||||
open(listed[i < 0 ? 0 : next])
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [conversations, selected, open])
|
||||
}, [listed, selected, open])
|
||||
|
||||
if (!state) return <div className="app loading" />
|
||||
if (!state.configured) return <Setup initial={state} onDone={refreshState} />
|
||||
|
||||
return (
|
||||
<AddContactContext.Provider value={setAdding}>
|
||||
<div className="app">
|
||||
<Sidebar
|
||||
mode={mode}
|
||||
@@ -103,14 +126,28 @@ export function App() {
|
||||
onOpen={open}
|
||||
sync={sync}
|
||||
multiDid={smsDids.length > 1}
|
||||
smsDids={smsDids}
|
||||
gvNumber={state.gvoiceNumber}
|
||||
defaultDid={state.settings.defaultDid ?? smsDids[0]?.did}
|
||||
onSettings={() => setSettingsOpen(true)}
|
||||
archiveView={archiveView}
|
||||
setArchiveView={setArchiveView}
|
||||
onMarkUnread={onMarkUnread}
|
||||
onInfo={setInfo}
|
||||
onExport={setExporting}
|
||||
/>
|
||||
{selected ? (
|
||||
<ChatView
|
||||
key={`${selected.did}:${selected.contact}`}
|
||||
conv={selected}
|
||||
contact={contactMap.get(selected.contact)}
|
||||
contactMap={contactMap}
|
||||
conversations={conversations}
|
||||
onOpen={open}
|
||||
name={named(selected)}
|
||||
onInfo={() => setInfo(selected)}
|
||||
onExport={() => setExporting(selected)}
|
||||
gvNumber={state.gvoiceNumber}
|
||||
jump={jump}
|
||||
highlight={mode === 'search' ? query : ''}
|
||||
version={msgVersion}
|
||||
@@ -120,11 +157,14 @@ export function App() {
|
||||
) : (
|
||||
<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 className="empty-title">bubble</div>
|
||||
</div>
|
||||
</main>
|
||||
)}
|
||||
{info && (
|
||||
<ConversationInfo conv={info} name={named(info)} contactMap={contactMap} gvNumber={state.gvoiceNumber} onClose={() => setInfo(null)} />
|
||||
)}
|
||||
{exporting && <ExportChat conv={exporting} name={named(exporting)} contactMap={contactMap} onClose={() => setExporting(null)} />}
|
||||
{settingsOpen && (
|
||||
<SettingsDialog
|
||||
state={state}
|
||||
@@ -133,6 +173,8 @@ export function App() {
|
||||
onChanged={refreshState}
|
||||
/>
|
||||
)}
|
||||
{adding && <AddContact number={adding} defaultBook={state.settings.contactBook} onClose={() => setAdding(null)} />}
|
||||
</div>
|
||||
</AddContactContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { createContext, useContext, useEffect, useState } from 'react'
|
||||
import { formatNumber } from '@shared/phone'
|
||||
import type { AddressBook } from '@shared/types'
|
||||
import { CloseIcon } from './Icons'
|
||||
|
||||
// Anywhere a number shows, "Add to contacts…" calls this (provided by App).
|
||||
export const AddContactContext = createContext<(number: string) => void>(() => undefined)
|
||||
export const useAddContact = (): ((number: string) => void) => useContext(AddContactContext)
|
||||
|
||||
const cleanError = (e: Error): string => e.message.replace(/^Error invoking remote method '\w+': (Error: )?/, '')
|
||||
|
||||
const e164 = (n: string): string => (n.length === 10 ? `+1${n}` : `+${n}`)
|
||||
|
||||
interface Props {
|
||||
number: string
|
||||
defaultBook?: string // from Settings; else GNOME Contacts' default
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export function AddContact({ number, defaultBook, onClose }: Props) {
|
||||
const [first, setFirst] = useState('')
|
||||
const [last, setLast] = useState('')
|
||||
const [org, setOrg] = useState('')
|
||||
const [books, setBooks] = useState<AddressBook[]>()
|
||||
const [book, setBook] = useState<string>()
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
|
||||
useEffect(() => {
|
||||
window.api
|
||||
.listAddressBooks()
|
||||
.then((r) => {
|
||||
setBooks(r.books)
|
||||
setBook(r.books.some((b) => b.uid === defaultBook) ? defaultBook : (r.default ?? r.books[0]?.uid))
|
||||
})
|
||||
.catch((e: Error) => setError(cleanError(e)))
|
||||
}, [defaultBook])
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent): void => {
|
||||
if (e.key === 'Escape') onClose()
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [onClose])
|
||||
|
||||
const canSave = !!(first.trim() || last.trim() || org.trim()) && !!book && !busy
|
||||
const save = (): void => {
|
||||
if (!canSave) return
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
window.api
|
||||
.addContact({ first: first.trim(), last: last.trim(), org: org.trim(), number: e164(number), book })
|
||||
.then(onClose)
|
||||
.catch((e: Error) => {
|
||||
setError(cleanError(e))
|
||||
setBusy(false)
|
||||
})
|
||||
}
|
||||
const onEnter = (e: React.KeyboardEvent): void => {
|
||||
if (e.key === 'Enter') save()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
|
||||
<div className="modal add-contact" role="dialog" aria-label="Add to contacts">
|
||||
<header>
|
||||
<h2>Add to contacts</h2>
|
||||
<button className="icon-btn" onClick={onClose} title="Close">
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</header>
|
||||
<section>
|
||||
<div className="kv">
|
||||
<span>Mobile</span>
|
||||
<span>{formatNumber(number)}</span>
|
||||
</div>
|
||||
<input className="text-input" placeholder="First name" value={first} autoFocus onChange={(e) => setFirst(e.target.value)} onKeyDown={onEnter} />
|
||||
<input className="text-input" placeholder="Last name" value={last} onChange={(e) => setLast(e.target.value)} onKeyDown={onEnter} />
|
||||
<input className="text-input" placeholder="Organization" value={org} onChange={(e) => setOrg(e.target.value)} onKeyDown={onEnter} />
|
||||
{books && books.length > 1 && (
|
||||
<label className="field">
|
||||
Address book
|
||||
<select value={book} onChange={(e) => setBook(e.target.value)}>
|
||||
{books.map((b) => (
|
||||
<option key={b.uid} value={b.uid}>
|
||||
{b.name}
|
||||
{b.account ? ` (${b.account})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{error && <p className="form-error">{error}</p>}
|
||||
</section>
|
||||
<footer>
|
||||
<button onClick={onClose}>Cancel</button>
|
||||
<button className="primary" disabled={!canSave} onClick={save}>
|
||||
{busy ? 'Adding…' : 'Add'}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
import { useState } from 'react'
|
||||
import { isGroup } from '@shared/phone'
|
||||
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 }
|
||||
// Scales with --s, which the sidebar lowers when it's resized narrow.
|
||||
const px = (n: number): string => `calc(${n}px * var(--s, 1))`
|
||||
const style = { width: px(size), height: px(size), fontSize: px(size * 0.4), background: bg, color: fg }
|
||||
if (contact?.photo && broken !== contact.photo) {
|
||||
return (
|
||||
<div className="avatar" style={style}>
|
||||
@@ -14,10 +17,19 @@ export function Avatar({ number, contact, size = 40 }: { number: string; contact
|
||||
)
|
||||
}
|
||||
const text = contact ? initials(contact.name) : ''
|
||||
if (isGroup(number)) {
|
||||
return (
|
||||
<div className="avatar" style={style}>
|
||||
<svg viewBox="0 0 24 24" style={{ width: px(size * 0.6), height: px(size * 0.6) }} fill="currentColor" aria-hidden>
|
||||
<path d="M9 11a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7Zm7.5 0a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM9 12.5c-3.3 0-6.5 1.7-6.5 4.2V19h13v-2.3c0-2.5-3.2-4.2-6.5-4.2Zm7.5.3c-.6 0-1.2.1-1.8.2 1.3.9 2.3 2.2 2.3 3.7V19h4.5v-2c0-2.3-2.4-4.2-5-4.2Z" />
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
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>
|
||||
<svg viewBox="0 0 24 24" style={{ width: px(size * 0.55), height: px(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>
|
||||
)}
|
||||
|
||||
@@ -1,18 +1,27 @@
|
||||
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 { formatNumber, groupMembers, isGroup } from '@shared/phone'
|
||||
import type { ContactInfo, Conversation, Did, Message, SearchHit } from '@shared/types'
|
||||
import type { ConvKey, Jump } from '../App'
|
||||
import { dayLabel, displayName, sameDay } from '../format'
|
||||
import { chatsWith, convName, dayLabel, sameDay, senderName, senderShortName } from '../format'
|
||||
import { Avatar } from './Avatar'
|
||||
import { Composer } from './Composer'
|
||||
import { Composer, type ComposerHandle } from './Composer'
|
||||
import { CloseIcon, DownIcon, SearchIcon, UpIcon } from './Icons'
|
||||
import { Lightbox } from './Lightbox'
|
||||
import { MessageBubble } from './MessageBubble'
|
||||
import { foldReactions, type Reaction } from '@shared/reactions'
|
||||
import { Via } from './Via'
|
||||
import { useAddContact } from './AddContact'
|
||||
import { ContextMenu, type MenuItem } from './ContextMenu'
|
||||
import { imageMenuItems } from './Lightbox'
|
||||
|
||||
type Row = { kind: 'day'; key: string; ts: number } | { kind: 'msg'; key: string; m: Message; groupStart: boolean; groupEnd: boolean }
|
||||
|
||||
const GROUP_GAP = 5 * 60_000
|
||||
|
||||
// Breathing room between the newest message and the composer.
|
||||
const ListFooter = () => <div className="list-footer" />
|
||||
|
||||
function buildRows(msgs: Message[]): Row[] {
|
||||
const rows: Row[] = []
|
||||
msgs.forEach((m, i) => {
|
||||
@@ -20,8 +29,9 @@ function buildRows(msgs: Message[]): Row[] {
|
||||
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
|
||||
const groupStart = newDay || prev.direction !== m.direction || prev.sender !== m.sender || m.ts - prev.ts > GROUP_GAP
|
||||
const groupEnd =
|
||||
!next || !sameDay(m.ts, next.ts) || next.direction !== m.direction || next.sender !== m.sender || next.ts - m.ts > GROUP_GAP
|
||||
rows.push({ kind: 'msg', key: String(m.id), m, groupStart, groupEnd })
|
||||
})
|
||||
return rows
|
||||
@@ -30,6 +40,13 @@ function buildRows(msgs: Message[]): Row[] {
|
||||
interface Props {
|
||||
conv: ConvKey
|
||||
contact?: ContactInfo
|
||||
contactMap: Map<string, ContactInfo>
|
||||
conversations: Conversation[]
|
||||
onOpen: (key: ConvKey) => void
|
||||
name?: string // a name you gave the conversation
|
||||
onInfo: () => void
|
||||
onExport: () => void
|
||||
gvNumber?: string
|
||||
jump?: Jump
|
||||
highlight: string
|
||||
version: number
|
||||
@@ -37,15 +54,48 @@ interface Props {
|
||||
onChangeDid: (did: string) => void
|
||||
}
|
||||
|
||||
export function ChatView({ conv, contact, jump, highlight, version, smsDids, onChangeDid }: Props) {
|
||||
export function ChatView({ conv, contact, contactMap, conversations, onOpen, name: ownName, onInfo, onExport, gvNumber, jump, highlight, version, smsDids, onChangeDid }: Props) {
|
||||
const name = convName(conv.contact, contactMap, ownName)
|
||||
const addContact = useAddContact()
|
||||
const [menu, setMenu] = useState<{ number: string; x: number; y: number }>()
|
||||
const [headerMenu, setHeaderMenu] = useState<{ x: number; y: number }>()
|
||||
// "Other chats with …": the groups (and other-number 1:1s) someone's in.
|
||||
const [others, setOthers] = useState<{ number: string; x: number; y: number }>()
|
||||
const othersItem = (number: string, x: number, y: number, label: string): MenuItem => ({
|
||||
label,
|
||||
onSelect: () => setOthers({ number, x, y })
|
||||
})
|
||||
const otherChatItems = (number: string): MenuItem[] => {
|
||||
const chats = chatsWith(number, conversations, conv)
|
||||
if (!chats.length) return [{ label: `No other chats with ${senderShortName(number, contactMap)}`, onSelect: () => undefined, disabled: true }]
|
||||
return chats.map((c) => ({
|
||||
label:
|
||||
(isGroup(c.contact) ? convName(c.contact, contactMap, c.name) : `${senderName(c.contact, contactMap)} (just you two, from ${formatNumber(c.did)})`) +
|
||||
(c.archived ? ' — archived' : ''),
|
||||
onSelect: () => onOpen({ did: c.did, contact: c.contact })
|
||||
}))
|
||||
}
|
||||
// Right-click a group member's name: other chats with them, and "Add to
|
||||
// contacts…" if they aren't in your contacts.
|
||||
const numberMenu = (number?: string) => (e: React.MouseEvent) => {
|
||||
if (!number) return
|
||||
e.preventDefault()
|
||||
setMenu({ number, x: e.clientX, y: e.clientY })
|
||||
}
|
||||
const group = isGroup(conv.contact)
|
||||
const members = group ? groupMembers(conv.contact).map((n) => senderName(n, contactMap)) : []
|
||||
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 [lightbox, setLightbox] = useState<{ id: number; index: number }>()
|
||||
const [dragging, setDragging] = useState(false)
|
||||
const virtuoso = useRef<VirtuosoHandle>(null)
|
||||
const searchInput = useRef<HTMLInputElement>(null)
|
||||
const composer = useRef<ComposerHandle>(null)
|
||||
const atBottom = useRef(true)
|
||||
|
||||
// Load (and reload on any change) the whole conversation.
|
||||
useEffect(() => {
|
||||
@@ -66,7 +116,11 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
|
||||
return () => window.removeEventListener('focus', onFocus)
|
||||
}, [conv.did, conv.contact])
|
||||
|
||||
const rows = useMemo(() => buildRows(messages ?? []), [messages])
|
||||
// iPhone tapbacks ("Loved “…”") become reactions on the message they quote.
|
||||
const folded = useMemo(() => foldReactions(messages ?? []), [messages])
|
||||
const rows = useMemo(() => buildRows(folded.shown), [folded])
|
||||
const [reactionList, setReactionList] = useState<{ reactions: Reaction[]; x: number; y: number }>()
|
||||
const showReactions = useCallback((reactions: Reaction[], x: number, y: number) => setReactionList({ reactions, x, y }), [])
|
||||
const indexOf = useCallback((id: number) => rows.findIndex((r) => r.kind === 'msg' && r.m.id === id), [rows])
|
||||
|
||||
const flash = useCallback((id: number) => {
|
||||
@@ -142,21 +196,58 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [])
|
||||
|
||||
const openMedia = useCallback((id: number, index: number) => setLightbox({ id, index }), [])
|
||||
const [mediaMenu, setMediaMenu] = useState<{ id: number; index: number; x: number; y: number }>()
|
||||
const showMediaMenu = useCallback((id: number, index: number, e: React.MouseEvent) => {
|
||||
e.preventDefault()
|
||||
setMediaMenu({ id, index, x: e.clientX, y: e.clientY })
|
||||
}, [])
|
||||
// Images that arrive after layout grow the list; stay pinned to the newest.
|
||||
const onMediaLoad = useCallback(() => {
|
||||
if (atBottom.current) virtuoso.current?.scrollToIndex({ index: 'LAST', align: 'end' })
|
||||
}, [])
|
||||
|
||||
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">
|
||||
<main
|
||||
className={`chat${dragging ? ' dragging' : ''}`}
|
||||
onDragOver={(e) => {
|
||||
if (!e.dataTransfer.types.includes('Files')) return
|
||||
e.preventDefault()
|
||||
setDragging(true)
|
||||
}}
|
||||
onDragLeave={(e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node)) setDragging(false)
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault()
|
||||
setDragging(false)
|
||||
composer.current?.addFiles([...e.dataTransfer.files])
|
||||
}}
|
||||
>
|
||||
<header
|
||||
className="chat-header"
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault()
|
||||
setHeaderMenu({ x: e.clientX, y: e.clientY })
|
||||
}}
|
||||
>
|
||||
<Avatar number={conv.contact} contact={contact} size={36} />
|
||||
<div className="chat-title">
|
||||
<div className="chat-name">{displayName(conv.contact, contact)}</div>
|
||||
<div
|
||||
className={`chat-title${group ? ' clickable' : ''}`}
|
||||
onClick={group ? onInfo : undefined}
|
||||
title={group ? 'Get info' : undefined}
|
||||
>
|
||||
<div className="chat-name">{name}</div>
|
||||
<div className="chat-sub">
|
||||
{contact ? formatNumber(conv.contact) : ''}
|
||||
{group ? `${members.length} people` : contact ? formatNumber(conv.contact) : ''}
|
||||
{smsDids.length > 1 && (
|
||||
<span className="chat-via">
|
||||
{contact ? ' · ' : ''}via {formatNumber(conv.did)}
|
||||
{contact || group ? ' · ' : ''}
|
||||
<Via did={conv.did} gvNumber={gvNumber} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
@@ -172,7 +263,7 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
|
||||
<input
|
||||
ref={searchInput}
|
||||
value={q}
|
||||
placeholder={`Search in ${displayName(conv.contact, contact)}`}
|
||||
placeholder={`Search in ${name}`}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') stepHit(e.shiftKey ? -1 : 1)
|
||||
@@ -206,8 +297,8 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
|
||||
{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 className="new-conv-name">{name}</div>
|
||||
{group ? <div className="new-conv-sub">{members.join(', ')}</div> : contact && <div className="new-conv-sub">{formatNumber(conv.contact)}</div>}
|
||||
</div>
|
||||
) : (
|
||||
<Virtuoso
|
||||
@@ -216,9 +307,12 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
|
||||
className="message-scroller"
|
||||
computeItemKey={(_, r) => r.key}
|
||||
initialTopMostItemIndex={{ index: initialIndex, align: jump ? 'center' : 'end' }}
|
||||
followOutput={(atBottom) => (atBottom ? 'smooth' : false)}
|
||||
followOutput={(bottom) => (bottom ? 'smooth' : false)}
|
||||
atBottomStateChange={(bottom) => (atBottom.current = bottom)}
|
||||
atBottomThreshold={80}
|
||||
alignToBottom
|
||||
increaseViewportBy={{ top: 800, bottom: 800 }}
|
||||
components={{ Footer: ListFooter }}
|
||||
itemContent={(_, r) =>
|
||||
r.kind === 'day' ? (
|
||||
<div className="day-sep">
|
||||
@@ -227,10 +321,17 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
|
||||
) : (
|
||||
<MessageBubble
|
||||
m={r.m}
|
||||
sender={group && r.m.sender && r.groupStart ? senderName(r.m.sender, contactMap) : undefined}
|
||||
onSenderMenu={numberMenu(r.m.sender)}
|
||||
groupStart={r.groupStart}
|
||||
groupEnd={r.groupEnd}
|
||||
flash={flashId === r.m.id}
|
||||
highlight={mark}
|
||||
onOpenMedia={openMedia}
|
||||
onMediaMenu={showMediaMenu}
|
||||
onMediaLoad={onMediaLoad}
|
||||
reactions={folded.reactions.get(r.m.id)}
|
||||
onShowReactions={showReactions}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -238,7 +339,56 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Composer conv={conv} isNew={isNew} smsDids={smsDids} onChangeDid={onChangeDid} />
|
||||
<Composer ref={composer} conv={conv} isNew={isNew} smsDids={smsDids} gvNumber={gvNumber} onChangeDid={onChangeDid} />
|
||||
{dragging && <div className="drop-hint">Drop to attach</div>}
|
||||
{lightbox && <Lightbox {...lightbox} onClose={() => setLightbox(undefined)} />}
|
||||
{reactionList && (
|
||||
<ContextMenu
|
||||
x={reactionList.x}
|
||||
y={reactionList.y}
|
||||
items={reactionList.reactions.map((r) => ({
|
||||
label: `${r.emoji} ${r.from === 'me' ? 'You' : senderName(r.from, contactMap)}`,
|
||||
onSelect: () => undefined
|
||||
}))}
|
||||
onClose={() => setReactionList(undefined)}
|
||||
/>
|
||||
)}
|
||||
{mediaMenu && (
|
||||
<ContextMenu
|
||||
x={mediaMenu.x}
|
||||
y={mediaMenu.y}
|
||||
items={imageMenuItems(mediaMenu.id, mediaMenu.index)}
|
||||
onClose={() => setMediaMenu(undefined)}
|
||||
/>
|
||||
)}
|
||||
{headerMenu && (
|
||||
<ContextMenu
|
||||
x={headerMenu.x}
|
||||
y={headerMenu.y}
|
||||
items={[
|
||||
...(group
|
||||
? groupMembers(conv.contact).map((n) =>
|
||||
othersItem(n, headerMenu.x, headerMenu.y, `Other chats with ${senderShortName(n, contactMap)}`)
|
||||
)
|
||||
: [othersItem(conv.contact, headerMenu.x, headerMenu.y, 'Other chats with this person')]),
|
||||
...(!group && !contact ? [{ label: 'Add to contacts…', onSelect: () => addContact(conv.contact), separator: true }] : []),
|
||||
{ label: 'Export chat…', onSelect: onExport, separator: group || !!contact }
|
||||
]}
|
||||
onClose={() => setHeaderMenu(undefined)}
|
||||
/>
|
||||
)}
|
||||
{menu && (
|
||||
<ContextMenu
|
||||
x={menu.x}
|
||||
y={menu.y}
|
||||
items={[
|
||||
othersItem(menu.number, menu.x, menu.y, `Other chats with ${senderShortName(menu.number, contactMap)}`),
|
||||
...(contactMap.get(menu.number) ? [] : [{ label: 'Add to contacts…', onSelect: () => addContact(menu.number) }])
|
||||
]}
|
||||
onClose={() => setMenu(undefined)}
|
||||
/>
|
||||
)}
|
||||
{others && <ContextMenu x={others.x} y={others.y} items={otherChatItems(others.number)} onClose={() => setOthers(undefined)} />}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,48 +1,178 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { formatNumber, splitMessage } from '@shared/phone'
|
||||
import { useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type ChangeEvent, type Ref } from 'react'
|
||||
import { charCount, formatNumber, isGroup, SMS_TEXT_LIMIT } from '@shared/phone'
|
||||
import type { Did } from '@shared/types'
|
||||
import type { ConvKey } from '../App'
|
||||
import { SendIcon } from './Icons'
|
||||
import { emojiQuery, exactEmoji, searchEmoji } from '../emoji'
|
||||
import { formatBytes, MAX_ATTACHMENTS, MMS_TEXT_LIMIT, prepareAttachment, type Attachment } from '../media'
|
||||
import { EmojiSuggest } from './EmojiSuggest'
|
||||
import { AttachIcon, CloseIcon, SendIcon } from './Icons'
|
||||
|
||||
// Drafts survive switching conversations (not app restarts).
|
||||
// Unsent text survives switching conversations and app restarts (it's kept in
|
||||
// the database until sent or cleared); attachments only the former.
|
||||
const drafts = new Map<string, string>()
|
||||
const draftsLoaded = window.api.getDrafts().then((saved) => {
|
||||
for (const [contact, text] of Object.entries(saved)) if (!drafts.get(contact)) drafts.set(contact, text)
|
||||
})
|
||||
const attachmentDrafts = new Map<string, Attachment[]>()
|
||||
|
||||
export interface ComposerHandle {
|
||||
addFiles: (files: File[]) => void
|
||||
}
|
||||
|
||||
interface Props {
|
||||
conv: ConvKey
|
||||
isNew: boolean
|
||||
smsDids: Did[]
|
||||
gvNumber?: string
|
||||
onChangeDid: (did: string) => void
|
||||
ref?: Ref<ComposerHandle>
|
||||
}
|
||||
|
||||
export function Composer({ conv, isNew, smsDids, onChangeDid }: Props) {
|
||||
const cleanError = (e: Error): string => e.message.replace(/^Error invoking remote method '\w+': (Error: )?/, '')
|
||||
|
||||
// A complete `:shortname:` just typed at the caret, e.g. "hi :joy:".
|
||||
const CLOSED_SHORTNAME = /(?:^|[\s([]):([a-z0-9_+-]+):$/i
|
||||
|
||||
export function Composer({ conv, isNew, smsDids, gvNumber, onChangeDid, ref }: Props) {
|
||||
const key = conv.contact
|
||||
// Google Voice: no SMS/MMS split to count toward, and photos only.
|
||||
const gv = conv.did === gvNumber
|
||||
// A group thread lives on Google Voice; it can't switch numbers.
|
||||
const fromDids = isGroup(conv.contact) ? smsDids.filter((d) => d.did === gvNumber) : smsDids
|
||||
const [text, setText] = useState(() => drafts.get(key) ?? '')
|
||||
const [attachments, setAttachments] = useState<Attachment[]>(() => attachmentDrafts.get(key) ?? [])
|
||||
const [preparing, setPreparing] = useState(0)
|
||||
const [error, setError] = useState<string>()
|
||||
const ref = useRef<HTMLTextAreaElement>(null)
|
||||
const textarea = useRef<HTMLTextAreaElement>(null)
|
||||
const fileInput = useRef<HTMLInputElement>(null)
|
||||
const [caret, setCaret] = useState(text.length)
|
||||
const [focused, setFocused] = useState(false)
|
||||
const [activeEmoji, setActiveEmoji] = useState(0)
|
||||
// Where the `:` sat when Escape closed the emoji list, so it stays closed
|
||||
// while that shortname is being typed.
|
||||
const [dismissedAt, setDismissedAt] = useState<number>()
|
||||
const pendingCaret = useRef<number>(undefined)
|
||||
|
||||
useEffect(() => {
|
||||
ref.current?.focus()
|
||||
textarea.current?.focus()
|
||||
}, [])
|
||||
|
||||
// A chat opened before the saved drafts arrived picks its draft up now.
|
||||
useEffect(() => {
|
||||
drafts.set(key, text)
|
||||
const el = ref.current
|
||||
let live = true
|
||||
void draftsLoaded.then(() => {
|
||||
const saved = drafts.get(key)
|
||||
if (live && saved) {
|
||||
setText((cur) => cur || saved)
|
||||
setCaret(saved.length)
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
live = false
|
||||
}
|
||||
}, [key])
|
||||
|
||||
useEffect(() => {
|
||||
if ((drafts.get(key) ?? '') !== text) {
|
||||
drafts.set(key, text)
|
||||
void window.api.setDraft(key, text)
|
||||
}
|
||||
const el = textarea.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('')
|
||||
// Put the caret after an emoji we swapped in (setting the value moves it to the end).
|
||||
useLayoutEffect(() => {
|
||||
if (pendingCaret.current === undefined) return
|
||||
textarea.current?.setSelectionRange(pendingCaret.current, pendingCaret.current)
|
||||
pendingCaret.current = undefined
|
||||
}, [text])
|
||||
|
||||
useEffect(() => {
|
||||
attachmentDrafts.set(key, attachments)
|
||||
}, [attachments, key])
|
||||
|
||||
const addFiles = (files: File[]): void => {
|
||||
if (!files.length) return
|
||||
setError(undefined)
|
||||
window.api.send(conv.did, conv.contact, body).catch((e: Error) => setError(e.message.replace(/^Error invoking remote method '\w+': (Error: )?/, '')))
|
||||
const room = MAX_ATTACHMENTS - attachments.length - preparing
|
||||
if (room <= 0) {
|
||||
setError(`An MMS can carry at most ${MAX_ATTACHMENTS} attachments.`)
|
||||
return
|
||||
}
|
||||
if (files.length > room) setError(`Only the first ${room} added — an MMS can carry at most ${MAX_ATTACHMENTS} attachments.`)
|
||||
if (gv && files.some((f) => !f.type.startsWith('image/'))) {
|
||||
setError('Google Voice can only send photos.')
|
||||
files = files.filter((f) => f.type.startsWith('image/'))
|
||||
}
|
||||
for (const file of files.slice(0, room)) {
|
||||
setPreparing((n) => n + 1)
|
||||
prepareAttachment(file)
|
||||
.then((a) => setAttachments((cur) => [...cur, a]))
|
||||
.catch((e: Error) => setError(e.message))
|
||||
.finally(() => setPreparing((n) => n - 1))
|
||||
}
|
||||
textarea.current?.focus()
|
||||
}
|
||||
|
||||
const len = [...text.trim()].length
|
||||
const parts = len ? splitMessage(text).length : 0
|
||||
useImperativeHandle(ref, () => ({ addFiles }))
|
||||
|
||||
const remove = (a: Attachment): void => {
|
||||
URL.revokeObjectURL(a.previewUrl)
|
||||
setAttachments((cur) => cur.filter((x) => x !== a))
|
||||
}
|
||||
|
||||
// Text too long for one SMS goes out as a single text-only MMS.
|
||||
const len = charCount(text.trim())
|
||||
const isMms = attachments.length > 0 || len > SMS_TEXT_LIMIT
|
||||
const tooLong = !gv && len > MMS_TEXT_LIMIT
|
||||
const canSend = (len > 0 || attachments.length > 0) && !preparing && !tooLong
|
||||
|
||||
const submit = (): void => {
|
||||
if (!canSend) return
|
||||
const body = text.trim()
|
||||
const outgoing = attachments.map(({ name, mime, data, width, height }) => ({ name, mime, data, width, height }))
|
||||
attachments.forEach((a) => URL.revokeObjectURL(a.previewUrl))
|
||||
setText('')
|
||||
setCaret(0)
|
||||
setAttachments([])
|
||||
setError(undefined)
|
||||
window.api.send(conv.did, conv.contact, body, outgoing.length ? outgoing : undefined).catch((e: Error) => setError(cleanError(e)))
|
||||
}
|
||||
|
||||
const emojiMatch = focused ? emojiQuery(text, caret) : null
|
||||
const suggestions = emojiMatch && emojiMatch.start !== dismissedAt ? searchEmoji(emojiMatch.query) : []
|
||||
const active = Math.min(activeEmoji, suggestions.length - 1)
|
||||
|
||||
const replaceAt = (from: number, to: number, emoji: string): void => {
|
||||
pendingCaret.current = from + emoji.length
|
||||
setText(text.slice(0, from) + emoji + text.slice(to))
|
||||
setCaret(pendingCaret.current)
|
||||
}
|
||||
|
||||
const pickEmoji = (i: number): void => {
|
||||
if (emojiMatch && suggestions[i]) replaceAt(emojiMatch.start, caret, suggestions[i].char)
|
||||
}
|
||||
|
||||
const onChange = (e: ChangeEvent<HTMLTextAreaElement>): void => {
|
||||
const { value, selectionStart: pos } = e.target
|
||||
setActiveEmoji(0)
|
||||
const closed = CLOSED_SHORTNAME.exec(value.slice(0, pos))
|
||||
const emoji = closed && exactEmoji(closed[1])
|
||||
if (emoji) {
|
||||
const from = pos - closed![1].length - 2
|
||||
pendingCaret.current = from + emoji.length
|
||||
setText(value.slice(0, from) + emoji + value.slice(pos))
|
||||
setCaret(pendingCaret.current)
|
||||
return
|
||||
}
|
||||
if (!emojiQuery(value, pos)) setDismissedAt(undefined)
|
||||
setText(value)
|
||||
setCaret(pos)
|
||||
}
|
||||
|
||||
return (
|
||||
<footer className="composer">
|
||||
@@ -51,39 +181,116 @@ export function Composer({ conv, isNew, smsDids, onChangeDid }: Props) {
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
{isNew && smsDids.length > 1 && (
|
||||
{isNew && fromDids.length > 1 && (
|
||||
<label className="from-picker">
|
||||
From
|
||||
<select value={conv.did} onChange={(e) => onChangeDid(e.target.value)}>
|
||||
{smsDids.map((d) => (
|
||||
{fromDids.map((d) => (
|
||||
<option key={d.did} value={d.did}>
|
||||
{formatNumber(d.did)}
|
||||
{d.description ? ` — ${d.description}` : ''}
|
||||
{d.provider === 'gvoice' ? ' — Google Voice' : d.description ? ` — ${d.description}` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{(attachments.length > 0 || preparing > 0) && (
|
||||
<div className="attach-tray">
|
||||
{attachments.map((a) => (
|
||||
<div key={a.previewUrl} className="attach-item" title={a.note ?? a.name}>
|
||||
{a.mime.startsWith('image/') ? (
|
||||
<img src={a.previewUrl} alt="" draggable={false} />
|
||||
) : (
|
||||
<div className="attach-file">{a.mime.split('/')[0]}</div>
|
||||
)}
|
||||
<span className={`attach-size${a.note ? ' shrunk' : ''}`}>{formatBytes(a.data.byteLength)}</span>
|
||||
<button className="attach-remove" title="Remove" onClick={() => remove(a)}>
|
||||
<CloseIcon size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{Array.from({ length: preparing }, (_, i) => (
|
||||
<div key={`p${i}`} className="attach-item preparing" title="Compressing…">
|
||||
<span className="spinner" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="composer-row">
|
||||
{suggestions.length > 0 && <EmojiSuggest items={suggestions} active={active} onPick={pickEmoji} onHover={setActiveEmoji} />}
|
||||
<button
|
||||
className="icon-btn attach-btn"
|
||||
title={gv ? 'Attach photos' : 'Attach photo, video or audio'}
|
||||
disabled={attachments.length + preparing >= MAX_ATTACHMENTS}
|
||||
onClick={() => fileInput.current?.click()}
|
||||
>
|
||||
<AttachIcon />
|
||||
</button>
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
accept={gv ? 'image/*' : 'image/*,video/*,audio/*'}
|
||||
multiple
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
addFiles([...(e.target.files ?? [])])
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
<textarea
|
||||
ref={ref}
|
||||
ref={textarea}
|
||||
rows={1}
|
||||
value={text}
|
||||
placeholder="Message"
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onChange={onChange}
|
||||
onSelect={(e) => setCaret(e.currentTarget.selectionStart)}
|
||||
onFocus={() => setFocused(true)}
|
||||
onBlur={() => setFocused(false)}
|
||||
onPaste={(e) => {
|
||||
const files = [...e.clipboardData.files]
|
||||
if (files.length) {
|
||||
e.preventDefault()
|
||||
addFiles(files)
|
||||
}
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (suggestions.length && !e.nativeEvent.isComposing) {
|
||||
const n = suggestions.length
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
setActiveEmoji((active + (e.key === 'ArrowDown' ? 1 : n - 1)) % n)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Tab' || (e.key === 'Enter' && !e.shiftKey)) {
|
||||
e.preventDefault()
|
||||
pickEmoji(active)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setDismissedAt(emojiMatch!.start)
|
||||
return
|
||||
}
|
||||
}
|
||||
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}>
|
||||
{len > 0 &&
|
||||
!gv &&
|
||||
(isMms ? (
|
||||
<span className={`counter multi${tooLong ? ' over' : ''}`} title="Sends as one MMS (up to 2048 characters)">
|
||||
MMS · {len}/{MMS_TEXT_LIMIT}
|
||||
</span>
|
||||
) : (
|
||||
<span className="counter" title="An SMS carries up to 160 characters; longer texts send as one MMS">
|
||||
{len}/{SMS_TEXT_LIMIT}
|
||||
</span>
|
||||
))}
|
||||
<button className="send-btn" title="Send (Enter)" disabled={!canSend} onClick={submit}>
|
||||
<SendIcon />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
|
||||
export interface MenuItem {
|
||||
label: string
|
||||
onSelect: () => void
|
||||
disabled?: boolean
|
||||
separator?: boolean // draw a line above this item
|
||||
}
|
||||
|
||||
// A small right-click menu at (x, y), kept inside the window. Closes on any
|
||||
// outside click, Escape, scroll, resize or the window losing focus.
|
||||
export function ContextMenu({ x, y, items, onClose }: { x: number; y: number; items: MenuItem[]; onClose: () => void }) {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const [pos, setPos] = useState({ left: x, top: y })
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const r = ref.current!.getBoundingClientRect()
|
||||
setPos({ left: Math.min(x, window.innerWidth - r.width - 4), top: Math.min(y, window.innerHeight - r.height - 4) })
|
||||
}, [x, y])
|
||||
|
||||
useEffect(() => {
|
||||
const onDown = (e: MouseEvent): void => {
|
||||
if (!ref.current?.contains(e.target as Node)) onClose()
|
||||
}
|
||||
const onKey = (e: KeyboardEvent): void => {
|
||||
if (e.key === 'Escape') onClose()
|
||||
}
|
||||
window.addEventListener('mousedown', onDown, true)
|
||||
window.addEventListener('keydown', onKey)
|
||||
window.addEventListener('wheel', onClose, { passive: true })
|
||||
window.addEventListener('resize', onClose)
|
||||
window.addEventListener('blur', onClose)
|
||||
return () => {
|
||||
window.removeEventListener('mousedown', onDown, true)
|
||||
window.removeEventListener('keydown', onKey)
|
||||
window.removeEventListener('wheel', onClose)
|
||||
window.removeEventListener('resize', onClose)
|
||||
window.removeEventListener('blur', onClose)
|
||||
}
|
||||
}, [onClose])
|
||||
|
||||
return (
|
||||
<div ref={ref} className="context-menu" role="menu" style={pos} onContextMenu={(e) => e.preventDefault()}>
|
||||
{items.map((it, i) => [
|
||||
it.separator && <div key={`sep${i}`} className="menu-sep" />,
|
||||
<button
|
||||
key={i}
|
||||
role="menuitem"
|
||||
disabled={it.disabled}
|
||||
onClick={() => {
|
||||
onClose()
|
||||
it.onSelect()
|
||||
}}
|
||||
>
|
||||
{it.label}
|
||||
</button>
|
||||
])}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { formatNumber, groupMembers } from '@shared/phone'
|
||||
import type { ContactInfo } from '@shared/types'
|
||||
import type { ConvKey } from '../App'
|
||||
import { convName, displayName } from '../format'
|
||||
import { Avatar } from './Avatar'
|
||||
import { CloseIcon } from './Icons'
|
||||
import { Via } from './Via'
|
||||
import { useAddContact } from './AddContact'
|
||||
|
||||
interface Props {
|
||||
conv: ConvKey
|
||||
name?: string // the name you gave it, if any
|
||||
contactMap: Map<string, ContactInfo>
|
||||
gvNumber?: string
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
// "Get info" for a group chat: who's in it, and a name of your own for it
|
||||
// (kept on this computer only).
|
||||
export function ConversationInfo({ conv, name, contactMap, gvNumber, onClose }: Props) {
|
||||
const [draft, setDraft] = useState(name ?? '')
|
||||
const members = groupMembers(conv.contact)
|
||||
const membersName = convName(conv.contact, contactMap)
|
||||
const dirty = draft.trim() !== (name ?? '')
|
||||
const addContact = useAddContact()
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent): void => {
|
||||
if (e.key === 'Escape') onClose()
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [onClose])
|
||||
|
||||
const save = (): void => {
|
||||
void window.api.setName(conv.did, conv.contact, draft.trim() || null).then(onClose)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
|
||||
<div className="modal conv-info" role="dialog" aria-label="Chat info">
|
||||
<header>
|
||||
<h2>Chat info</h2>
|
||||
<button className="icon-btn" onClick={onClose} title="Close">
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<section className="conv-info-top">
|
||||
<Avatar number={conv.contact} size={72} />
|
||||
<div className="conv-info-title">{convName(conv.contact, contactMap, name)}</div>
|
||||
<div className="muted small">
|
||||
{members.length} people · <Via did={conv.did} gvNumber={gvNumber} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>Name</h3>
|
||||
<input
|
||||
className="conv-name-input"
|
||||
value={draft}
|
||||
placeholder={membersName}
|
||||
autoFocus
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && dirty && save()}
|
||||
/>
|
||||
<p className="muted small">Only you see this name; it stays on this computer. Leave it empty to show the members' names.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>Members</h3>
|
||||
{members.map((n) => {
|
||||
const c = contactMap.get(n)
|
||||
return (
|
||||
<div key={n} className="member">
|
||||
<Avatar number={n} contact={c} size={36} />
|
||||
<div className="member-main">
|
||||
<div>{displayName(n, c)}</div>
|
||||
{c && (
|
||||
<div className="muted small">
|
||||
{formatNumber(n)}
|
||||
{c.label ? ` · ${c.label}` : ''}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!c && (
|
||||
<button className="member-add" onClick={() => addContact(n)}>
|
||||
Add to contacts…
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
<button onClick={onClose}>{dirty ? 'Cancel' : 'Close'}</button>
|
||||
<button className="primary" disabled={!dirty} onClick={save}>
|
||||
Save
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,20 +1,32 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { memo, useCallback, useContext, useEffect, useState } from 'react'
|
||||
import { Virtuoso } from 'react-virtuoso'
|
||||
import { formatNumber } from '@shared/phone'
|
||||
import { isGroup } from '@shared/phone'
|
||||
import type { ContactInfo, Conversation } from '@shared/types'
|
||||
import { sameConv, type ConvKey } from '../App'
|
||||
import { displayName, shortTime } from '../format'
|
||||
import { convName, previewText, senderShortName, shortTime } from '../format'
|
||||
import { Avatar } from './Avatar'
|
||||
import { AddContactContext } from './AddContact'
|
||||
import { ContextMenu } from './ContextMenu'
|
||||
import { Via } from './Via'
|
||||
|
||||
interface Props {
|
||||
conversations: Conversation[]
|
||||
contactMap: Map<string, ContactInfo>
|
||||
selected: ConvKey | null
|
||||
multiDid: boolean
|
||||
gvNumber?: string
|
||||
emptyText: string
|
||||
onOpen: (key: ConvKey) => void
|
||||
onMarkUnread: (key: ConvKey) => void
|
||||
onInfo: (key: ConvKey) => void
|
||||
onExport: (key: ConvKey) => void
|
||||
}
|
||||
|
||||
export function ConversationList({ conversations, contactMap, selected, multiDid, onOpen }: Props) {
|
||||
export function ConversationList({ conversations, contactMap, selected, multiDid, gvNumber, emptyText, onOpen, onMarkUnread, onInfo, onExport }: Props) {
|
||||
const [menu, setMenu] = useState<{ conv: Conversation; x: number; y: number }>()
|
||||
const addContact = useContext(AddContactContext)
|
||||
const closeMenu = useCallback(() => setMenu(undefined), [])
|
||||
const openMenu = useCallback((conv: Conversation, x: number, y: number) => setMenu({ conv, x, y }), [])
|
||||
// Re-render every minute so relative times ("5m") stay fresh.
|
||||
const [, tick] = useState(0)
|
||||
useEffect(() => {
|
||||
@@ -22,53 +34,101 @@ export function ConversationList({ conversations, contactMap, selected, multiDid
|
||||
return () => clearInterval(t)
|
||||
}, [])
|
||||
|
||||
if (!conversations.length) return <div className="list-empty">No conversations yet.</div>
|
||||
if (!conversations.length) return <div className="list-empty">{emptyText}</div>
|
||||
|
||||
const menuItems = (c: Conversation) => [
|
||||
...(isGroup(c.contact) ? [{ label: 'Get info…', onSelect: () => onInfo(c) }] : []),
|
||||
...(!isGroup(c.contact) && !contactMap.get(c.contact) ? [{ label: 'Add to contacts…', onSelect: () => addContact(c.contact) }] : []),
|
||||
c.archived
|
||||
? { label: 'Unarchive', onSelect: () => void window.api.setArchived(c.did, c.contact, false) }
|
||||
: { label: 'Archive', onSelect: () => void window.api.setArchived(c.did, c.contact, true) },
|
||||
c.unread > 0 || c.markedUnread
|
||||
? { label: 'Mark as read', onSelect: () => void window.api.markRead(c.did, c.contact) }
|
||||
: {
|
||||
label: 'Mark as unread',
|
||||
onSelect: () => {
|
||||
onMarkUnread(c)
|
||||
void window.api.markUnread(c.did, c.contact)
|
||||
}
|
||||
},
|
||||
{ label: 'Export chat…', onSelect: () => onExport(c) }
|
||||
]
|
||||
|
||||
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}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<>
|
||||
<Virtuoso
|
||||
className="conv-list"
|
||||
data={conversations}
|
||||
computeItemKey={(_, c) => `${c.did}:${c.contact}`}
|
||||
itemContent={(_, c) => (
|
||||
<ConversationRow
|
||||
conv={c}
|
||||
contact={contactMap.get(c.contact)}
|
||||
name={convName(c.contact, contactMap, c.name)}
|
||||
sender={c.lastSender && c.lastDirection === 'in' ? senderShortName(c.lastSender, contactMap) : undefined}
|
||||
active={sameConv(c, selected)}
|
||||
multiDid={multiDid}
|
||||
gvNumber={gvNumber}
|
||||
onOpen={onOpen}
|
||||
onMenu={openMenu}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{menu && <ContextMenu x={menu.x} y={menu.y} items={menuItems(menu.conv)} onClose={closeMenu} />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const ConversationRow = memo(function ConversationRow({
|
||||
conv,
|
||||
contact,
|
||||
name,
|
||||
sender,
|
||||
active,
|
||||
multiDid,
|
||||
onOpen
|
||||
gvNumber,
|
||||
onOpen,
|
||||
onMenu
|
||||
}: {
|
||||
conv: Conversation
|
||||
contact?: ContactInfo
|
||||
name: string
|
||||
sender?: string // group chats: who sent the last message
|
||||
active: boolean
|
||||
multiDid: boolean
|
||||
gvNumber?: string
|
||||
onOpen: (key: ConvKey) => void
|
||||
onMenu: (conv: Conversation, x: number, y: number) => void
|
||||
}) {
|
||||
const preview = (conv.lastDirection === 'out' ? 'You: ' : '') + conv.lastBody.replace(/\s+/g, ' ')
|
||||
const preview = (conv.lastDirection === 'out' ? 'You: ' : sender ? `${sender}: ` : '') + previewText(conv)
|
||||
return (
|
||||
<button className={`row${active ? ' active' : ''}${conv.unread ? ' unread' : ''}`} onClick={() => onOpen(conv)}>
|
||||
<button
|
||||
className={`row${active ? ' active' : ''}${conv.unread || conv.markedUnread ? ' unread' : ''}`}
|
||||
onClick={() => onOpen(conv)}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault()
|
||||
onMenu(conv, e.clientX, e.clientY)
|
||||
}}
|
||||
>
|
||||
<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-name">{name}</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>}
|
||||
{conv.unread > 0 ? (
|
||||
<span className="badge">{conv.unread > 99 ? '99+' : conv.unread}</span>
|
||||
) : (
|
||||
conv.markedUnread && <span className="badge dot" title="Marked as unread" />
|
||||
)}
|
||||
</div>
|
||||
{multiDid && <div className="row-via">via {formatNumber(conv.did)}</div>}
|
||||
{multiDid && (
|
||||
<div className="row-via">
|
||||
<Via did={conv.did} gvNumber={gvNumber} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import type { EmojiMatch } from '../emoji'
|
||||
|
||||
interface Props {
|
||||
items: EmojiMatch[]
|
||||
active: number
|
||||
onPick: (i: number) => void
|
||||
onHover: (i: number) => void
|
||||
}
|
||||
|
||||
// The `:shortname` completion list above the composer. It never takes focus:
|
||||
// the textarea keeps handling keys, and clicks are caught on mousedown.
|
||||
export function EmojiSuggest({ items, active, onPick, onHover }: Props) {
|
||||
const list = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
list.current?.children[active]?.scrollIntoView({ block: 'nearest' })
|
||||
}, [active])
|
||||
|
||||
return (
|
||||
<div ref={list} className="emoji-suggest" role="listbox" onMouseDown={(e) => e.preventDefault()}>
|
||||
{items.map((it, i) => (
|
||||
<div
|
||||
key={it.char}
|
||||
role="option"
|
||||
aria-selected={i === active}
|
||||
className={i === active ? 'active' : undefined}
|
||||
onMouseEnter={() => onHover(i)}
|
||||
onClick={() => onPick(i)}
|
||||
>
|
||||
<span className="emoji-glyph">{it.char}</span>
|
||||
<span className="emoji-name">:{it.name}:</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { groupMembers, isGroup } from '@shared/phone'
|
||||
import type { ContactInfo } from '@shared/types'
|
||||
import type { ConvKey } from '../App'
|
||||
import { convName, senderName } from '../format'
|
||||
import { CloseIcon } from './Icons'
|
||||
|
||||
interface Props {
|
||||
conv: ConvKey
|
||||
name?: string // the name you gave it, if any
|
||||
contactMap: Map<string, ContactInfo>
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const cleanError = (e: Error): string => e.message.replace(/^Error invoking remote method '\w+': (Error: )?/, '')
|
||||
const day = (d: Date): string => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
||||
|
||||
// "Export chat…": all of it or the days between two dates, as a PDF (with or
|
||||
// without its photos) or a .txt; then the usual save dialog picks where.
|
||||
export function ExportChat({ conv, name, contactMap, onClose }: Props) {
|
||||
const today = day(new Date())
|
||||
const [allTime, setAllTime] = useState(true)
|
||||
const [from, setFrom] = useState(day(new Date(Date.now() - 30 * 86_400_000)))
|
||||
const [to, setTo] = useState(today)
|
||||
const [format, setFormat] = useState<'pdf' | 'txt'>('pdf')
|
||||
const [attachments, setAttachments] = useState(true)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent): void => {
|
||||
if (e.key === 'Escape' && !busy) onClose()
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [onClose, busy])
|
||||
|
||||
const badDates = !allTime && (!from || !to || from > to)
|
||||
const go = (): void => {
|
||||
if (badDates || busy) return
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
const names = Object.fromEntries((isGroup(conv.contact) ? groupMembers(conv.contact) : []).map((n) => [n, senderName(n, contactMap)]))
|
||||
window.api
|
||||
.exportChat(conv.did, conv.contact, {
|
||||
...(allTime ? {} : { from, to }),
|
||||
format,
|
||||
attachments: format === 'pdf' && attachments,
|
||||
title: convName(conv.contact, contactMap, name),
|
||||
names
|
||||
})
|
||||
.then((saved) => (saved ? onClose() : setBusy(false)))
|
||||
.catch((e: Error) => {
|
||||
setError(cleanError(e))
|
||||
setBusy(false)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && !busy && onClose()}>
|
||||
<div className="modal export-chat" role="dialog" aria-label="Export chat">
|
||||
<header>
|
||||
<h2>Export chat</h2>
|
||||
<button className="icon-btn" onClick={onClose} disabled={busy} title="Close">
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h3>Messages</h3>
|
||||
<label className="field">
|
||||
All time
|
||||
<input type="checkbox" checked={allTime} onChange={(e) => setAllTime(e.target.checked)} />
|
||||
</label>
|
||||
<div className={`export-dates${allTime ? ' disabled' : ''}`}>
|
||||
<label className="field">
|
||||
From
|
||||
<input type="date" value={from} max={today} disabled={allTime} onChange={(e) => setFrom(e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
To
|
||||
<input type="date" value={to} max={today} disabled={allTime} onChange={(e) => setTo(e.target.value)} />
|
||||
</label>
|
||||
</div>
|
||||
{badDates && <p className="form-error">The start date needs to be on or before the end date.</p>}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>Format</h3>
|
||||
<div className="field">
|
||||
Save as
|
||||
<div className="segmented" role="radiogroup" aria-label="Format">
|
||||
{(['pdf', 'txt'] as const).map((f) => (
|
||||
<button key={f} role="radio" aria-checked={format === f} className={format === f ? 'on' : ''} onClick={() => setFormat(f)}>
|
||||
{f === 'pdf' ? 'PDF' : 'Text (.txt)'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<label className={`field${format === 'txt' ? ' disabled' : ''}`}>
|
||||
Include attachments
|
||||
<input type="checkbox" checked={format === 'pdf' && attachments} disabled={format === 'txt'} onChange={(e) => setAttachments(e.target.checked)} />
|
||||
</label>
|
||||
{format === 'txt' && <p className="muted small">A text file lists attachments as [Photo], [Audio] and so on.</p>}
|
||||
{error && <p className="form-error">{error}</p>}
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
<button onClick={onClose} disabled={busy}>
|
||||
Cancel
|
||||
</button>
|
||||
<button className="primary" disabled={badDates || busy} onClick={go}>
|
||||
{busy ? 'Exporting…' : 'Export…'}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -56,3 +56,35 @@ export const AlertIcon = () => (
|
||||
<path d="M12 8v5M12 16h.01" />
|
||||
</svg>
|
||||
)
|
||||
export const AttachIcon = () => (
|
||||
<svg {...base}>
|
||||
<path d="m21 11.5-8.6 8.6a5.5 5.5 0 0 1-7.8-7.8l8.6-8.6a3.7 3.7 0 0 1 5.2 5.2l-8.6 8.6a1.8 1.8 0 0 1-2.6-2.6l8-8" />
|
||||
</svg>
|
||||
)
|
||||
export const DownloadIcon = () => (
|
||||
<svg {...base}>
|
||||
<path d="M12 3v12m-5-5 5 5 5-5M4 20h16" />
|
||||
</svg>
|
||||
)
|
||||
export const RefreshIcon = () => (
|
||||
<svg {...base}>
|
||||
<path d="M20 11a8 8 0 0 0-14.3-4.9L4 8" />
|
||||
<path d="M4 3v5h5" />
|
||||
<path d="M4 13a8 8 0 0 0 14.3 4.9L20 16" />
|
||||
<path d="M20 21v-5h-5" />
|
||||
</svg>
|
||||
)
|
||||
export const ArchiveIcon = () => (
|
||||
<svg {...base}>
|
||||
<rect x="3" y="4" width="18" height="5" rx="1" />
|
||||
<path d="M5 9v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9M10 13h4" />
|
||||
</svg>
|
||||
)
|
||||
export const GroupIcon = () => (
|
||||
<svg {...base}>
|
||||
<circle cx="9" cy="8" r="3.5" />
|
||||
<path d="M2.5 20a6.5 6.5 0 0 1 13 0" />
|
||||
<path d="M16 4.6a3.5 3.5 0 0 1 0 6.8" />
|
||||
<path d="M18.5 14.2a6.5 6.5 0 0 1 3 5.8" />
|
||||
</svg>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { ContextMenu, type MenuItem } from './ContextMenu'
|
||||
import { CloseIcon, DownloadIcon } from './Icons'
|
||||
import { mediaSrc } from './MessageBubble'
|
||||
|
||||
// Copy an attachment to the clipboard as a PNG (so GIF/WebP/HEIC work too).
|
||||
async function copyImage(id: number, index: number): Promise<void> {
|
||||
const { mime, data } = await window.api.readMedia(id, index)
|
||||
const bitmap = await createImageBitmap(new Blob([data], { type: mime }))
|
||||
try {
|
||||
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height)
|
||||
canvas.getContext('2d')!.drawImage(bitmap, 0, 0)
|
||||
const png = await canvas.convertToBlob({ type: 'image/png' })
|
||||
await window.api.copyImage(new Uint8Array(await png.arrayBuffer()))
|
||||
} finally {
|
||||
bitmap.close()
|
||||
}
|
||||
}
|
||||
|
||||
// Right-click on an image, in the chat or the lightbox.
|
||||
export const imageMenuItems = (id: number, index: number): MenuItem[] => [
|
||||
{ label: 'Copy image', onSelect: () => void copyImage(id, index).catch(() => undefined) },
|
||||
{ label: 'Save image…', onSelect: () => void window.api.saveMedia(id, index).catch(() => undefined) }
|
||||
]
|
||||
|
||||
export function Lightbox({ id, index, onClose }: { id: number; index: number; onClose: () => void }) {
|
||||
const [menu, setMenu] = useState<{ x: number; y: number }>()
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent): void => {
|
||||
if (e.key === 'Escape' && !menu) onClose()
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [onClose, menu])
|
||||
|
||||
return (
|
||||
<div className="lightbox" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
|
||||
<div className="lightbox-bar">
|
||||
<button className="icon-btn" title="Save…" onClick={() => void window.api.saveMedia(id, index)}>
|
||||
<DownloadIcon />
|
||||
</button>
|
||||
<button className="icon-btn" title="Close (Esc)" onClick={onClose}>
|
||||
<CloseIcon size={20} />
|
||||
</button>
|
||||
</div>
|
||||
<img
|
||||
src={mediaSrc(id, index)}
|
||||
alt=""
|
||||
draggable={false}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault()
|
||||
setMenu({ x: e.clientX, y: e.clientY })
|
||||
}}
|
||||
/>
|
||||
{menu && <ContextMenu x={menu.x} y={menu.y} items={imageMenuItems(id, index)} onClose={() => setMenu(undefined)} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { memo, type ReactNode } from 'react'
|
||||
import type { Message } from '@shared/types'
|
||||
import { memo, useState, type ReactNode } from 'react'
|
||||
import { mediaKind } from '@shared/mime'
|
||||
import type { MediaRef, Message } from '@shared/types'
|
||||
import type { Reaction } from '@shared/reactions'
|
||||
import { highlightChunks, timeOfDay } from '../format'
|
||||
import { AlertIcon, ClockIcon } from './Icons'
|
||||
|
||||
@@ -26,15 +28,61 @@ function renderText(text: string, highlight: string): ReactNode[] {
|
||||
return out
|
||||
}
|
||||
|
||||
export const mediaSrc = (id: number, index: number): string => `mms-media://m/${id}/${index}`
|
||||
|
||||
// Display box for an image: fit within 300×360, keeping the aspect ratio when
|
||||
// we know it (so the list doesn't jump when the image arrives).
|
||||
function imageBox(ref: MediaRef): { width: number; height: number } | undefined {
|
||||
if (!ref.width || !ref.height) return undefined
|
||||
const scale = Math.min(1, 300 / ref.width, 360 / ref.height)
|
||||
return { width: Math.round(ref.width * scale), height: Math.round(ref.height * scale) }
|
||||
}
|
||||
|
||||
function Attachment({ id, index, media, onOpen, onMenu, onLoad }: { id: number; index: number; media: MediaRef; onOpen: () => void; onMenu: (e: React.MouseEvent) => void; onLoad: () => void }) {
|
||||
const [broken, setBroken] = useState(false)
|
||||
const src = mediaSrc(id, index)
|
||||
const kind = mediaKind(media)
|
||||
if (broken) return <div className="media-missing">Media unavailable</div>
|
||||
if (kind === 'image')
|
||||
return (
|
||||
<img
|
||||
className="media-img"
|
||||
src={src}
|
||||
alt=""
|
||||
draggable={false}
|
||||
style={imageBox(media) ?? { minHeight: 120, minWidth: 120 }}
|
||||
onClick={onOpen}
|
||||
onContextMenu={onMenu}
|
||||
onLoad={onLoad}
|
||||
onError={() => setBroken(true)}
|
||||
/>
|
||||
)
|
||||
if (kind === 'video') return <video className="media-video" src={src} controls preload="metadata" onLoadedMetadata={onLoad} onError={() => setBroken(true)} />
|
||||
if (kind === 'audio') return <audio className="media-audio" src={src} controls preload="metadata" onError={() => setBroken(true)} />
|
||||
return (
|
||||
<button className="media-file" onClick={() => void window.api.saveMedia(id, index).catch(() => setBroken(true))}>
|
||||
Attachment · Save…
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
interface Props {
|
||||
m: Message
|
||||
sender?: string // group chats: name shown above the first bubble of a run
|
||||
onSenderMenu?: (e: React.MouseEvent) => void
|
||||
reactions?: Reaction[]
|
||||
onShowReactions?: (reactions: Reaction[], x: number, y: number) => void
|
||||
groupStart: boolean
|
||||
groupEnd: boolean
|
||||
flash: boolean
|
||||
highlight: string
|
||||
onOpenMedia: (id: number, index: number) => void
|
||||
onMediaMenu: (id: number, index: number, e: React.MouseEvent) => void
|
||||
onMediaLoad: () => void
|
||||
}
|
||||
|
||||
export const MessageBubble = memo(function MessageBubble({ m, groupStart, groupEnd, flash, highlight }: Props) {
|
||||
export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMenu, reactions, onShowReactions, groupStart, groupEnd, flash, highlight, onOpenMedia, onMediaMenu, onMediaLoad }: Props) {
|
||||
const media = m.media ?? []
|
||||
const cls = [
|
||||
'msg',
|
||||
m.direction,
|
||||
@@ -47,9 +95,29 @@ export const MessageBubble = memo(function MessageBubble({ m, groupStart, groupE
|
||||
.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>
|
||||
{sender && (
|
||||
<div className="msg-sender" onContextMenu={onSenderMenu}>
|
||||
{sender}
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className={`bubble${media.length ? ' has-media' : ''}${media.length && !m.body ? ' media-only' : ''}`}
|
||||
title={new Date(m.ts).toLocaleString()}
|
||||
>
|
||||
{media.length > 0 && (
|
||||
<div className="media">
|
||||
{media.map((ref, i) => (
|
||||
<Attachment key={i} id={m.id} index={i} media={ref} onOpen={() => onOpenMedia(m.id, i)} onMenu={(e) => onMediaMenu(m.id, i, e)} onLoad={onMediaLoad} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{m.body && <span className="text">{renderText(m.body, highlight)}</span>}
|
||||
<span className="meta">
|
||||
{m.kind === 'mms' && !media.length && (
|
||||
<span className="kind-tag" title="Sent as one MMS, so it arrives as a single message">
|
||||
MMS
|
||||
</span>
|
||||
)}
|
||||
{timeOfDay(m.ts)}
|
||||
{m.status === 'pending' && (
|
||||
<span className="status" title="Sending…">
|
||||
@@ -58,9 +126,19 @@ export const MessageBubble = memo(function MessageBubble({ m, groupStart, groupE
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
{reactions && reactions.length > 0 && (
|
||||
<button
|
||||
className="reactions"
|
||||
title="See who reacted"
|
||||
onClick={(e) => onShowReactions?.(reactions, e.clientX, e.clientY)}
|
||||
>
|
||||
{[...new Set(reactions.map((r) => r.emoji))].join('')}
|
||||
{reactions.length > 1 && <span className="reaction-count">{reactions.length}</span>}
|
||||
</button>
|
||||
)}
|
||||
{m.status === 'failed' && (
|
||||
<div className="failed-row">
|
||||
<AlertIcon /> Not sent ·
|
||||
<AlertIcon /> Not sent{m.error ? `: ${m.error}` : ''} ·
|
||||
<button onClick={() => void window.api.retryFailed(m.id).catch(() => undefined)}>Retry</button>·
|
||||
<button onClick={() => void window.api.deleteFailed(m.id)}>Delete</button>
|
||||
</div>
|
||||
|
||||
@@ -1,24 +1,32 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { formatNumber, normalizeNumber } from '@shared/phone'
|
||||
import type { ContactInfo, Conversation } from '@shared/types'
|
||||
import { formatNumber, groupKey, normalizeNumber } from '@shared/phone'
|
||||
import type { ContactInfo, Conversation, Did } from '@shared/types'
|
||||
import type { ConvKey } from '../App'
|
||||
import { Avatar } from './Avatar'
|
||||
import { BackIcon } from './Icons'
|
||||
import { BackIcon, CloseIcon, GroupIcon } from './Icons'
|
||||
import { matchesContact } from './SearchResults'
|
||||
|
||||
interface Props {
|
||||
contacts: ContactInfo[]
|
||||
conversations: Conversation[]
|
||||
smsDids: Did[]
|
||||
gvNumber?: string
|
||||
defaultDid?: string
|
||||
onPick: (key: ConvKey) => void
|
||||
onCancel: () => void
|
||||
}
|
||||
|
||||
export function NewChat({ contacts, conversations, defaultDid, onPick, onCancel }: Props) {
|
||||
export function NewChat({ contacts, conversations, smsDids, gvNumber, defaultDid, onPick, onCancel }: Props) {
|
||||
const [q, setQ] = useState('')
|
||||
const [cursor, setCursor] = useState(0)
|
||||
const [from, setFrom] = useState(defaultDid)
|
||||
const [fromChosen, setFromChosen] = useState(false)
|
||||
// Building a group (Google Voice only): picking people adds them to it.
|
||||
const [grouping, setGrouping] = useState(false)
|
||||
const [members, setMembers] = useState<string[]>([])
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const canGroup = !!from && from === gvNumber
|
||||
|
||||
useEffect(() => inputRef.current?.focus(), [])
|
||||
|
||||
@@ -31,45 +39,116 @@ export function NewChat({ contacts, conversations, defaultDid, onPick, onCancel
|
||||
|
||||
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])
|
||||
return [...list]
|
||||
.filter((c) => !members.includes(c.number))
|
||||
.sort((a, b) => (recency.get(b.number) ?? 0) - (recency.get(a.number) ?? 0) || a.name.localeCompare(b.name))
|
||||
.slice(0, 100)
|
||||
}, [q, contacts, recency, members])
|
||||
|
||||
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 }] : []),
|
||||
...(typedIsNumber && !matches.some((m) => m.number === typed) && !members.includes(typed) ? [{ number: typed }] : []),
|
||||
...matches.map((c) => ({ number: c.number, contact: c }))
|
||||
]
|
||||
const nameOf = (n: string): string => contacts.find((c) => c.number === n)?.name ?? formatNumber(n)
|
||||
|
||||
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 })
|
||||
const open = (contact: string): void => {
|
||||
if (!from) return
|
||||
// Reuse an existing conversation with this person (or group) if there is
|
||||
// one -- from the chosen number, or any number if none was chosen.
|
||||
const existing = conversations.find((c) => c.contact === contact && (c.did === from || !fromChosen))
|
||||
onPick({ did: existing?.did ?? from, contact })
|
||||
}
|
||||
|
||||
// Groups only exist on Google Voice, so starting one sends from there.
|
||||
const startGroup = (): void => {
|
||||
if (!gvNumber) return
|
||||
setFrom(gvNumber)
|
||||
setFromChosen(true)
|
||||
setGrouping(true)
|
||||
setQ('')
|
||||
inputRef.current?.focus()
|
||||
}
|
||||
|
||||
const addMember = (number: string): void => {
|
||||
if (!grouping) startGroup()
|
||||
setMembers((m) => [...m, number])
|
||||
setQ('')
|
||||
inputRef.current?.focus()
|
||||
}
|
||||
|
||||
// Opens the chat with exactly these people -- the existing one if there is.
|
||||
const done = (): void => {
|
||||
if (members.length) open(members.length > 1 ? groupKey(members) : members[0])
|
||||
}
|
||||
|
||||
const pick = (number: string): void => (grouping ? addMember(number) : open(number))
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="sidebar-header compose">
|
||||
<button className="icon-btn" title="Back" onClick={onCancel}>
|
||||
<BackIcon />
|
||||
</button>
|
||||
<span className="compose-title">New chat</span>
|
||||
<span className="compose-title">{grouping ? 'New group' : 'New chat'}</span>
|
||||
{grouping && (
|
||||
<button className="primary small start-group" disabled={!members.length} onClick={done}>
|
||||
Done
|
||||
</button>
|
||||
)}
|
||||
</header>
|
||||
{smsDids.length > 1 && (
|
||||
<label className="from-picker compose-from">
|
||||
From
|
||||
<select
|
||||
value={from}
|
||||
onChange={(e) => {
|
||||
setFrom(e.target.value)
|
||||
setFromChosen(true)
|
||||
if (e.target.value !== gvNumber) {
|
||||
setMembers([])
|
||||
setGrouping(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{smsDids.map((d) => (
|
||||
<option key={d.did} value={d.did}>
|
||||
{formatNumber(d.did)}
|
||||
{d.provider === 'gvoice' ? ' — Google Voice' : d.description ? ` — ${d.description}` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{members.length > 0 && (
|
||||
<div className="chips">
|
||||
{members.map((n) => (
|
||||
<span key={n} className="chip">
|
||||
{nameOf(n)}
|
||||
<button title="Remove" onClick={() => setMembers((m) => m.filter((x) => x !== n))}>
|
||||
<CloseIcon size={12} />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="to-field">
|
||||
<span>To:</span>
|
||||
<span>{grouping ? 'Add:' : 'To:'}</span>
|
||||
<input
|
||||
ref={inputRef}
|
||||
value={q}
|
||||
placeholder="Name or number"
|
||||
placeholder={grouping && !members.length ? 'Add people to the group' : 'Name or number'}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') onCancel()
|
||||
else if (e.key === 'Enter' && grouping && !q.trim() && members.length) done()
|
||||
else if (e.key === 'Backspace' && !q && members.length) setMembers((m) => m.slice(0, -1))
|
||||
else if (e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
setCursor((c) => Math.min(options.length - 1, c + 1))
|
||||
@@ -80,28 +159,49 @@ export function NewChat({ contacts, conversations, defaultDid, onPick, onCancel
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{!defaultDid && <div className="list-empty">No SMS-enabled number to send from. Check Settings.</div>}
|
||||
{!from && <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) => (
|
||||
{!grouping && !q.trim() && (
|
||||
<button
|
||||
key={o.number + (o.contact ? '' : ':typed')}
|
||||
data-i={i}
|
||||
className={`row${i === cursor ? ' active' : ''}`}
|
||||
onMouseEnter={() => setCursor(i)}
|
||||
onClick={() => pick(o.number)}
|
||||
className="row group-row"
|
||||
disabled={!gvNumber}
|
||||
title={gvNumber ? undefined : 'Group chats need Google Voice — connect it in Settings.'}
|
||||
onClick={startGroup}
|
||||
>
|
||||
<Avatar number={o.number} contact={o.contact} size={40} />
|
||||
<span className="group-row-icon">
|
||||
<GroupIcon />
|
||||
</span>
|
||||
<div className="row-main">
|
||||
<div className="row-top">
|
||||
<span className="row-name">{o.contact?.name ?? formatNumber(o.number)}</span>
|
||||
<span className="row-name">Group chat</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>
|
||||
<span className="row-preview">{gvNumber ? 'Pick several people, then Done' : 'Needs Google Voice (Settings)'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
{options.map((o, i) => (
|
||||
<div key={o.number + (o.contact ? '' : ':typed')} className="row-wrap">
|
||||
<button 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>
|
||||
{canGroup && !grouping && (
|
||||
<button className="add-member" title="Start a group with this person" onClick={() => addMember(o.number)}>
|
||||
+ Group
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{q && !options.length && <div className="list-empty">No matching contacts. Type a 10-digit number.</div>}
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { formatNumber } from '@shared/phone'
|
||||
import { formatNumber, groupMembers, isGroup } 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 { convName, senderName, shortTime } from '../format'
|
||||
import { Avatar } from './Avatar'
|
||||
|
||||
interface Props {
|
||||
@@ -38,10 +38,19 @@ export function SearchResults({ query, conversations, contacts, contactMap, defa
|
||||
}
|
||||
}, [query])
|
||||
|
||||
const chats = useMemo(
|
||||
() => conversations.filter((c) => matchesContact(query, contactMap.get(c.contact)?.name ?? '', c.contact)).slice(0, 8),
|
||||
[query, conversations, contactMap]
|
||||
)
|
||||
const chats = useMemo(() => {
|
||||
// Chats whose own title matches come first, so a group you named isn't
|
||||
// crowded out by every other chat that merely includes a matching member.
|
||||
const byName: Conversation[] = []
|
||||
const byMember: Conversation[] = []
|
||||
for (const c of conversations) {
|
||||
if (matchesContact(query, convName(c.contact, contactMap, c.name), c.contact)) byName.push(c)
|
||||
// A group turns up under any of its members, whatever it's called.
|
||||
else if (isGroup(c.contact) && groupMembers(c.contact).some((n) => matchesContact(query, senderName(n, contactMap), n)))
|
||||
byMember.push(c)
|
||||
}
|
||||
return [...byName, ...byMember].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)
|
||||
@@ -61,10 +70,10 @@ export function SearchResults({ query, conversations, contacts, contactMap, defa
|
||||
<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>
|
||||
<span className="row-name">{convName(c.contact, contactMap, c.name)}</span>
|
||||
</div>
|
||||
<div className="row-bottom">
|
||||
<span className="row-preview">{formatNumber(c.contact)}</span>
|
||||
<span className="row-preview">{isGroup(c.contact) ? 'Group' : formatNumber(c.contact)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
@@ -113,7 +122,7 @@ export function SearchResults({ query, conversations, contacts, contactMap, defa
|
||||
<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-name">{convName(h.contact, contactMap, conversations.find((c) => c.did === h.did && c.contact === h.contact)?.name)}</span>
|
||||
<span className="row-time">{shortTime(h.ts)}</span>
|
||||
</div>
|
||||
<div className="row-snippet">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { AppState } from '@shared/api'
|
||||
import type { AppState, RabbitStatus } from '@shared/api'
|
||||
import { formatNumber } from '@shared/phone'
|
||||
import type { Settings, SyncStatus } from '@shared/types'
|
||||
import type { AddressBook, GvStatus, Settings, SyncStatus, Theme } from '@shared/types'
|
||||
import { CloseIcon } from './Icons'
|
||||
|
||||
interface Props {
|
||||
@@ -14,8 +14,10 @@ interface Props {
|
||||
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)
|
||||
// voip.ms numbers; Google Voice has its own section.
|
||||
const smsDids = state.dids.filter((d) => d.smsEnabled && d.provider !== 'gvoice')
|
||||
// Theme is saved on click, so it never makes the dialog dirty.
|
||||
const dirty = JSON.stringify({ ...s, theme: undefined }) !== JSON.stringify({ ...state.settings, theme: undefined })
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent): void => {
|
||||
@@ -32,6 +34,7 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
|
||||
}
|
||||
|
||||
const synced = s.dids.length ? s.dids : smsDids.map((d) => d.did)
|
||||
const sendFrom = state.gvoiceNumber ? [...synced, state.gvoiceNumber] : synced
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
|
||||
@@ -43,6 +46,36 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h3>Appearance</h3>
|
||||
<div className="field">
|
||||
Theme
|
||||
<div className="segmented" role="radiogroup" aria-label="Theme">
|
||||
{(['system', 'light', 'dark'] as Theme[]).map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
role="radio"
|
||||
aria-checked={s.theme === t}
|
||||
className={s.theme === t ? 'on' : ''}
|
||||
onClick={() => {
|
||||
setS({ ...s, theme: t })
|
||||
void window.api.setTheme(t).then(onChanged)
|
||||
}}
|
||||
>
|
||||
{t[0].toUpperCase() + t.slice(1)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<label className="field">
|
||||
Show new messages in the notification list
|
||||
<input type="checkbox" checked={s.notifications} onChange={(e) => setS({ ...s, notifications: e.target.checked })} />
|
||||
</label>
|
||||
<p className="muted small">
|
||||
Zoom with <kbd>Ctrl</kbd> <kbd>+</kbd> / <kbd>Ctrl</kbd> <kbd>−</kbd>, and <kbd>Ctrl</kbd> <kbd>0</kbd> to reset.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>Account</h3>
|
||||
<div className="kv">
|
||||
@@ -71,6 +104,12 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<GoogleVoiceSection number={state.gvoiceNumber} status={sync?.gvoice} onChanged={onChanged} />
|
||||
|
||||
<ContactsSection value={s.contactBook} onChange={(contactBook) => setS({ ...s, contactBook })} />
|
||||
|
||||
<RabbitSection onChanged={onChanged} />
|
||||
|
||||
{smsDids.length > 0 && (
|
||||
<section>
|
||||
<h3>Numbers</h3>
|
||||
@@ -88,13 +127,14 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
|
||||
<span className="muted">{d.description}</span>
|
||||
</label>
|
||||
))}
|
||||
{smsDids.length > 1 && (
|
||||
{sendFrom.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) => (
|
||||
<select value={s.defaultDid ?? sendFrom[0]} onChange={(e) => setS({ ...s, defaultDid: e.target.value })}>
|
||||
{sendFrom.map((d) => (
|
||||
<option key={d} value={d}>
|
||||
{formatNumber(d)}
|
||||
{d === state.gvoiceNumber ? ' — Google Voice' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -137,7 +177,7 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
<button onClick={onClose}>Cancel</button>
|
||||
<button onClick={onClose}>{dirty ? 'Cancel' : 'Close'}</button>
|
||||
<button className="primary" disabled={!dirty} onClick={() => void save()}>
|
||||
Save
|
||||
</button>
|
||||
@@ -146,3 +186,211 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const cleanError = (e: Error): string => e.message.replace(/^Error invoking remote method '\w+': (Error: )?/, '')
|
||||
|
||||
function gvStatusText(st?: GvStatus): string {
|
||||
if (!st) return 'Starting…'
|
||||
if (st.phase === 'signedOut') return 'Signed out'
|
||||
if (st.phase === 'error') return `Error: ${st.error ?? 'unknown'}`
|
||||
if (!st.backfillDone) return 'Importing history…'
|
||||
return st.lastPoll ? `Up to date (checked ${new Date(st.lastPoll).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })})` : 'Connected'
|
||||
}
|
||||
|
||||
function GoogleVoiceSection({ number, status, onChanged }: { number?: string; status?: GvStatus; onChanged: () => void }) {
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const [cookies, setCookies] = useState('')
|
||||
const signedOut = status?.phase === 'signedOut'
|
||||
|
||||
const run = (p: Promise<void>): void => {
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
p.then(onChanged)
|
||||
.catch((e: Error) => setError(cleanError(e)))
|
||||
.finally(() => setBusy(false))
|
||||
}
|
||||
|
||||
const fallback = (
|
||||
<details className="gv-fallback">
|
||||
<summary>Sign-in window not working?</summary>
|
||||
<p className="muted small">
|
||||
Google sometimes refuses sign-ins inside apps. Instead, sign in at voice.google.com in Firefox, open the developer tools
|
||||
(F12) → Network, reload, right-click any request to <code>clients6.google.com</code> → Copy → Copy as cURL, and paste it here.
|
||||
It holds your Google sign-in, so only paste it here.
|
||||
</p>
|
||||
<textarea value={cookies} onChange={(e) => setCookies(e.target.value)} placeholder="curl 'https://clients6.google.com/…' -H 'Cookie: …'" rows={4} />
|
||||
<button disabled={busy || !cookies.trim()} onClick={() => run(window.api.connectGoogleVoiceCookies(cookies).then(() => setCookies('')))}>
|
||||
Connect with these cookies
|
||||
</button>
|
||||
</details>
|
||||
)
|
||||
|
||||
return (
|
||||
<section>
|
||||
<h3>Google Voice</h3>
|
||||
{number ? (
|
||||
<>
|
||||
<div className="kv">
|
||||
<span>Number</span>
|
||||
<span>{formatNumber(number)}</span>
|
||||
</div>
|
||||
<div className="kv">
|
||||
<span>Status</span>
|
||||
<span>{gvStatusText(status)}</span>
|
||||
</div>
|
||||
<div className="btn-row">
|
||||
{signedOut && (
|
||||
<button className="primary" disabled={busy} onClick={() => run(window.api.connectGoogleVoice())}>
|
||||
Reconnect…
|
||||
</button>
|
||||
)}
|
||||
<button className="danger" disabled={busy} onClick={() => run(window.api.disconnectGoogleVoice())}>
|
||||
Disconnect
|
||||
</button>
|
||||
</div>
|
||||
{signedOut && fallback}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="muted small">
|
||||
Text from your Google Voice number here too. This uses the private API behind voice.google.com (Google has no public one),
|
||||
so a change on Google's side can break it until the app is updated. voip.ms keeps working either way.
|
||||
</p>
|
||||
<button className="primary" disabled={busy} onClick={() => run(window.api.connectGoogleVoice())}>
|
||||
{busy ? 'Waiting for sign-in…' : 'Connect Google Voice…'}
|
||||
</button>
|
||||
{fallback}
|
||||
</>
|
||||
)}
|
||||
{error && <p className="form-error">{error}</p>}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// Where "Add to contacts" puts new contacts.
|
||||
function ContactsSection({ value, onChange }: { value?: string; onChange: (uid?: string) => void }) {
|
||||
const [books, setBooks] = useState<AddressBook[]>()
|
||||
const [fallback, setFallback] = useState<string>()
|
||||
const [error, setError] = useState<string>()
|
||||
useEffect(() => {
|
||||
window.api
|
||||
.listAddressBooks()
|
||||
.then((r) => {
|
||||
setBooks(r.books)
|
||||
setFallback(r.books.find((b) => b.uid === r.default)?.name)
|
||||
})
|
||||
.catch((e: Error) => setError(cleanError(e)))
|
||||
}, [])
|
||||
return (
|
||||
<section>
|
||||
<h3>Contacts</h3>
|
||||
<label className="field">
|
||||
Add new contacts to
|
||||
<select value={value ?? ''} disabled={!books} onChange={(e) => onChange(e.target.value || undefined)}>
|
||||
<option value="">Same as GNOME Contacts{fallback ? ` (${fallback})` : ''}</option>
|
||||
{books?.map((b) => (
|
||||
<option key={b.uid} value={b.uid}>
|
||||
{b.name}
|
||||
{b.account ? ` (${b.account})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className="muted small">Right-click a number that isn't in your contacts to add it.</p>
|
||||
{error && <p className="form-error">{error}</p>}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// The Android app on a Rabbit R1, installed and kept in step over USB.
|
||||
function RabbitSection({ onChanged }: { onChanged: () => void }) {
|
||||
const [st, setSt] = useState<RabbitStatus>()
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [step, setStep] = useState<string>()
|
||||
const [error, setError] = useState<string>()
|
||||
const [done, setDone] = useState<string>()
|
||||
|
||||
const refresh = (): void => void window.api.rabbitStatus().then(setSt)
|
||||
useEffect(() => {
|
||||
refresh()
|
||||
const t = setInterval(refresh, 4000) // notice it being plugged in
|
||||
const off = window.api.onRabbitProgress(setStep)
|
||||
return () => {
|
||||
clearInterval(t)
|
||||
off()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const run = (what: 'install' | 'update' | 'sync'): void => {
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
setDone(undefined)
|
||||
;(what === 'sync' ? window.api.rabbitSync() : window.api.rabbitInstall(what === 'update' ? 'update' : 'full'))
|
||||
.then(() => {
|
||||
setDone(
|
||||
what === 'install'
|
||||
? 'Installed. It\'s open on the Rabbit now.'
|
||||
: what === 'update'
|
||||
? 'Updated. It\'s open on the Rabbit now.'
|
||||
: 'Synced accounts, chat names and read status.'
|
||||
)
|
||||
onChanged()
|
||||
})
|
||||
.catch((e: Error) => setError(cleanError(e)))
|
||||
.finally(() => {
|
||||
setBusy(false)
|
||||
setStep(undefined)
|
||||
refresh()
|
||||
})
|
||||
}
|
||||
|
||||
const device = st?.device
|
||||
const installed = device?.installedVersion
|
||||
return (
|
||||
<section>
|
||||
<h3>Rabbit</h3>
|
||||
<div className="kv">
|
||||
<span>Device</span>
|
||||
<span>{!st ? '…' : !st.adb ? 'adb not installed' : device ? device.model : 'Not connected'}</span>
|
||||
</div>
|
||||
{device && (
|
||||
<div className="kv">
|
||||
<span>bubble on it</span>
|
||||
<span>
|
||||
{installed ? `Version ${installed}` : 'Not installed'}
|
||||
{installed && st?.bundledVersion && installed !== st.bundledVersion ? ` (update to ${st.bundledVersion} available)` : ''}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<p className="muted small">
|
||||
Install puts the app on the Rabbit along with your voip.ms and Google Voice sign-ins, your message history and photos, and
|
||||
your chat names. Update installs a new version of the app and keeps everything already on the Rabbit. Sync sends the
|
||||
sign-ins again (say, after reconnecting Google Voice here) and merges chat names and read/unread/archived both ways, newest
|
||||
change winning. Recopy replaces the Rabbit's history with this computer's, sending only photos it doesn't have.
|
||||
</p>
|
||||
<div className="btn-row">
|
||||
{installed ? (
|
||||
<button className="primary" disabled={busy} onClick={() => run('update')}>
|
||||
Update app
|
||||
</button>
|
||||
) : (
|
||||
<button className="primary" disabled={busy || !device} onClick={() => run('install')}>
|
||||
Install to Rabbit
|
||||
</button>
|
||||
)}
|
||||
<button disabled={busy || !installed} onClick={() => run('sync')}>
|
||||
Sync to Rabbit
|
||||
</button>
|
||||
{installed && (
|
||||
<button disabled={busy} onClick={() => run('install')}>
|
||||
Recopy history & photos
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{busy && step && <p className="muted small">{step}</p>}
|
||||
{done && <p className="muted small">{done}</p>}
|
||||
{error && <p className="form-error">{error}</p>}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ export function Setup({ initial, onDone }: { initial: AppState; onDone: () => vo
|
||||
return (
|
||||
<div className="setup">
|
||||
<div className="setup-card">
|
||||
<h1>voip.ms Messages</h1>
|
||||
<h1>bubble</h1>
|
||||
{!dids ? (
|
||||
<>
|
||||
<p className="muted">
|
||||
|
||||
@@ -1,13 +1,89 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import type { ContactInfo, Conversation, SyncStatus } from '@shared/types'
|
||||
import { useEffect, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react'
|
||||
import type { ContactInfo, Conversation, Did, 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'
|
||||
import { ArchiveIcon, BackIcon, CloseIcon, ComposeIcon, GearIcon, RefreshIcon, SearchIcon } from './Icons'
|
||||
|
||||
export type SidebarMode = 'chats' | 'search' | 'compose'
|
||||
|
||||
// Dragging below the default width shrinks the sidebar's contents
|
||||
// proportionally (via --s) rather than dropping parts of each row.
|
||||
const DEFAULT_WIDTH = 340
|
||||
const MIN_WIDTH = 170
|
||||
const MAX_WIDTH = 640
|
||||
const MIN_CHAT_WIDTH = 320
|
||||
const WIDTH_KEY = 'sidebarWidth'
|
||||
|
||||
function clampWidth(w: number): number {
|
||||
return Math.round(Math.max(MIN_WIDTH, Math.min(w, MAX_WIDTH, window.innerWidth - MIN_CHAT_WIDTH)))
|
||||
}
|
||||
|
||||
function loadWidth(): number {
|
||||
try {
|
||||
const w = Number(localStorage.getItem(WIDTH_KEY))
|
||||
if (w) return clampWidth(w)
|
||||
} catch {
|
||||
// storage unavailable: fall back to the default
|
||||
}
|
||||
return DEFAULT_WIDTH
|
||||
}
|
||||
|
||||
function useSidebarWidth() {
|
||||
const [width, setWidth] = useState(loadWidth)
|
||||
const [dragging, setDragging] = useState(false)
|
||||
|
||||
// Re-clamp when the window shrinks so the chat pane keeps some room.
|
||||
useEffect(() => {
|
||||
const onResize = (): void => setWidth((w) => Math.max(MIN_WIDTH, Math.min(w, window.innerWidth - MIN_CHAT_WIDTH)))
|
||||
window.addEventListener('resize', onResize)
|
||||
return () => window.removeEventListener('resize', onResize)
|
||||
}, [])
|
||||
|
||||
const save = (w: number): void => {
|
||||
try {
|
||||
localStorage.setItem(WIDTH_KEY, String(w))
|
||||
} catch {
|
||||
// not fatal; the width just won't persist
|
||||
}
|
||||
}
|
||||
|
||||
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>): void => {
|
||||
if (e.button !== 0) return
|
||||
e.preventDefault()
|
||||
const handle = e.currentTarget
|
||||
handle.setPointerCapture(e.pointerId)
|
||||
const startX = e.clientX
|
||||
const startW = width
|
||||
let latest = startW
|
||||
setDragging(true)
|
||||
const onMove = (ev: PointerEvent): void => {
|
||||
latest = clampWidth(startW + ev.clientX - startX)
|
||||
setWidth(latest)
|
||||
}
|
||||
const onUp = (): void => {
|
||||
handle.removeEventListener('pointermove', onMove)
|
||||
handle.removeEventListener('pointerup', onUp)
|
||||
handle.removeEventListener('pointercancel', onUp)
|
||||
setDragging(false)
|
||||
save(latest)
|
||||
}
|
||||
handle.addEventListener('pointermove', onMove)
|
||||
handle.addEventListener('pointerup', onUp)
|
||||
handle.addEventListener('pointercancel', onUp)
|
||||
}
|
||||
|
||||
const reset = (): void => {
|
||||
const w = clampWidth(DEFAULT_WIDTH)
|
||||
setWidth(w)
|
||||
save(w)
|
||||
}
|
||||
|
||||
const scale = Math.min(1, width / DEFAULT_WIDTH)
|
||||
return { width, scale, dragging, onPointerDown, reset }
|
||||
}
|
||||
|
||||
interface Props {
|
||||
mode: SidebarMode
|
||||
setMode: (m: SidebarMode) => void
|
||||
@@ -20,12 +96,20 @@ interface Props {
|
||||
onOpen: (key: ConvKey, jumpTo?: number) => void
|
||||
sync?: SyncStatus
|
||||
multiDid: boolean
|
||||
smsDids: Did[]
|
||||
gvNumber?: string
|
||||
defaultDid?: string
|
||||
onSettings: () => void
|
||||
archiveView: boolean
|
||||
setArchiveView: (on: boolean) => void
|
||||
onMarkUnread: (key: ConvKey) => void
|
||||
onInfo: (key: ConvKey) => void
|
||||
onExport: (key: ConvKey) => void
|
||||
}
|
||||
|
||||
export function Sidebar(p: Props) {
|
||||
const searchRef = useRef<HTMLInputElement>(null)
|
||||
const size = useSidebarWidth()
|
||||
|
||||
useEffect(() => {
|
||||
if (p.mode === 'search') searchRef.current?.focus()
|
||||
@@ -37,11 +121,13 @@ export function Sidebar(p: Props) {
|
||||
}
|
||||
|
||||
return (
|
||||
<aside className="sidebar">
|
||||
<aside className="sidebar" style={{ width: size.width, '--s': size.scale } as CSSProperties}>
|
||||
{p.mode === 'compose' ? (
|
||||
<NewChat
|
||||
contacts={p.contacts}
|
||||
conversations={p.conversations}
|
||||
smsDids={p.smsDids}
|
||||
gvNumber={p.gvNumber}
|
||||
defaultDid={p.defaultDid}
|
||||
onCancel={() => p.setMode('chats')}
|
||||
onPick={(key) => {
|
||||
@@ -88,6 +174,18 @@ export function Sidebar(p: Props) {
|
||||
<button className="icon-btn" title="New chat (Ctrl+N)" onClick={() => p.setMode('compose')}>
|
||||
<ComposeIcon />
|
||||
</button>
|
||||
<RefreshButton />
|
||||
<button
|
||||
className={`icon-btn${p.archiveView ? ' on' : ''}`}
|
||||
title={p.archiveView ? 'Back to chats' : 'Archived chats'}
|
||||
aria-pressed={p.archiveView}
|
||||
onClick={() => {
|
||||
p.setArchiveView(!p.archiveView)
|
||||
if (p.mode === 'search') clearSearch()
|
||||
}}
|
||||
>
|
||||
<ArchiveIcon />
|
||||
</button>
|
||||
<button className="icon-btn" title="Settings" onClick={p.onSettings}>
|
||||
<GearIcon />
|
||||
</button>
|
||||
@@ -103,18 +201,39 @@ export function Sidebar(p: Props) {
|
||||
onOpen={p.onOpen}
|
||||
/>
|
||||
) : (
|
||||
<ConversationList
|
||||
conversations={p.conversations}
|
||||
contactMap={p.contactMap}
|
||||
selected={p.selected}
|
||||
multiDid={p.multiDid}
|
||||
onOpen={p.onOpen}
|
||||
/>
|
||||
<>
|
||||
{p.archiveView && (
|
||||
<div className="archive-header">
|
||||
<button className="icon-btn inline" title="Back to chats" onClick={() => p.setArchiveView(false)}>
|
||||
<BackIcon />
|
||||
</button>
|
||||
Archived chats
|
||||
</div>
|
||||
)}
|
||||
<ConversationList
|
||||
conversations={p.conversations.filter((c) => c.archived === p.archiveView)}
|
||||
contactMap={p.contactMap}
|
||||
selected={p.selected}
|
||||
multiDid={p.multiDid}
|
||||
gvNumber={p.gvNumber}
|
||||
emptyText={p.archiveView ? 'No archived chats. Right-click a chat to archive it.' : 'No conversations yet.'}
|
||||
onOpen={p.onOpen}
|
||||
onMarkUnread={p.onMarkUnread}
|
||||
onInfo={p.onInfo}
|
||||
onExport={p.onExport}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<SyncFooter sync={p.sync} />
|
||||
<div
|
||||
className={`sidebar-resizer${size.dragging ? ' dragging' : ''}`}
|
||||
title="Drag to resize · double-click to reset"
|
||||
onPointerDown={size.onPointerDown}
|
||||
onDoubleClick={size.reset}
|
||||
/>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -123,14 +242,23 @@ function SyncFooter({ sync }: { sync?: SyncStatus }) {
|
||||
if (!sync) return null
|
||||
let text = ''
|
||||
let cls = 'sync-footer'
|
||||
const gv = sync.gvoice
|
||||
if (sync.phase === 'error') {
|
||||
text = `⚠ ${sync.error ?? 'Sync error'}`
|
||||
cls += ' error'
|
||||
} else if (gv?.phase === 'signedOut') {
|
||||
text = '⚠ Google Voice signed out. Reconnect it in Settings.'
|
||||
cls += ' error'
|
||||
} else if (gv?.phase === 'error') {
|
||||
text = `⚠ Google Voice: ${gv.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 if (gv && !gv.backfillDone && gv.phase === 'backfill') {
|
||||
text = `Importing Google Voice history… · ${sync.total.toLocaleString()} messages`
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
@@ -140,3 +268,19 @@ function SyncFooter({ sync }: { sync?: SyncStatus }) {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RefreshButton() {
|
||||
const [busy, setBusy] = useState(false)
|
||||
const refresh = (): void => {
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
// Keep the spin visible briefly even when voip.ms answers instantly.
|
||||
const minSpin = new Promise((r) => setTimeout(r, 600))
|
||||
void Promise.allSettled([window.api.pollNow(), minSpin]).then(() => setBusy(false))
|
||||
}
|
||||
return (
|
||||
<button className={`icon-btn${busy ? ' spinning' : ''}`} title="Check for new messages" onClick={refresh}>
|
||||
<RefreshIcon />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { formatNumber } from '@shared/phone'
|
||||
|
||||
// "via <number>", with a GV tag when it's the Google Voice number.
|
||||
export function Via({ did, gvNumber }: { did: string; gvNumber?: string }) {
|
||||
return (
|
||||
<>
|
||||
via {did === gvNumber && <span className="gv-tag">GV</span>}
|
||||
{formatNumber(did)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,45 @@
|
||||
import data from './emoji-data.json'
|
||||
|
||||
// [emoji, shortnames] in picker order; generated by scripts/gen-emoji.mjs.
|
||||
const EMOJI = data as [string, string[]][]
|
||||
const BY_NAME = new Map(EMOJI.flatMap(([char, names]) => names.map((n) => [n, char] as const)))
|
||||
|
||||
export interface EmojiMatch {
|
||||
char: string
|
||||
name: string
|
||||
}
|
||||
|
||||
const NAME_CHAR = /[a-z0-9_+-]/i
|
||||
const MIN_QUERY = 2
|
||||
|
||||
// The `:shortname` being typed at the caret, if any. The colon has to start a
|
||||
// word so times ("10:30") and URLs ("http://") don't open the picker.
|
||||
export function emojiQuery(text: string, caret: number): { start: number; query: string } | null {
|
||||
let i = caret
|
||||
while (i > 0 && NAME_CHAR.test(text[i - 1])) i--
|
||||
const start = i - 1
|
||||
if (start < 0 || text[start] !== ':') return null
|
||||
if (start > 0 && !/[\s([]/.test(text[start - 1])) return null
|
||||
const query = text.slice(i, caret)
|
||||
return query.length >= MIN_QUERY ? { start, query } : null
|
||||
}
|
||||
|
||||
// An exact name first, then prefix matches, then matches at a word start
|
||||
// ("_heart"), then any substring; ties keep picker order. One entry per emoji.
|
||||
export function searchEmoji(query: string, limit = 8): EmojiMatch[] {
|
||||
const q = query.toLowerCase()
|
||||
const tiers: EmojiMatch[][] = [[], [], [], []]
|
||||
for (const [char, names] of EMOJI) {
|
||||
let best: { tier: number; name: string } | undefined
|
||||
for (const name of names) {
|
||||
const at = name.indexOf(q)
|
||||
if (at < 0) continue
|
||||
const tier = name === q ? 0 : at === 0 ? 1 : name[at - 1] === '_' ? 2 : 3
|
||||
if (!best || tier < best.tier) best = { tier, name }
|
||||
}
|
||||
if (best) tiers[best.tier].push({ char, name: best.name })
|
||||
}
|
||||
return tiers.flat().slice(0, limit)
|
||||
}
|
||||
|
||||
export const exactEmoji = (name: string): string | undefined => BY_NAME.get(name.toLowerCase())
|
||||
@@ -1,5 +1,7 @@
|
||||
import { formatNumber } from '@shared/phone'
|
||||
import type { ContactInfo } from '@shared/types'
|
||||
import { mediaKind } from '@shared/mime'
|
||||
import { formatNumber, groupMembers, isGroup } from '@shared/phone'
|
||||
import { reactionPreview } from '@shared/reactions'
|
||||
import type { ContactInfo, Conversation } from '@shared/types'
|
||||
|
||||
const DAY = 86_400_000
|
||||
|
||||
@@ -44,10 +46,51 @@ export function sameDay(a: number, b: number): boolean {
|
||||
return startOfDay(a) === startOfDay(b)
|
||||
}
|
||||
|
||||
const MEDIA_LABELS = { image: '📷 Photo', video: '🎥 Video', audio: '🎤 Audio', file: '📎 Attachment' }
|
||||
|
||||
// Sidebar preview line for a conversation's last message.
|
||||
export function previewText(c: Pick<Conversation, 'lastBody' | 'lastMedia'>): string {
|
||||
const reaction = reactionPreview(c.lastBody)
|
||||
if (reaction) return reaction
|
||||
const body = c.lastBody.replace(/\s+/g, ' ').trim()
|
||||
if (!c.lastMedia) return body
|
||||
const label = MEDIA_LABELS[mediaKind(c.lastMedia)]
|
||||
return body ? `${label.split(' ')[0]} ${body}` : label
|
||||
}
|
||||
|
||||
export function displayName(number: string, contact?: ContactInfo): string {
|
||||
return contact?.name ?? formatNumber(number)
|
||||
}
|
||||
|
||||
const firstName = (number: string, contactMap: Map<string, ContactInfo>): string =>
|
||||
contactMap.get(number)?.name.split(/\s+/)[0] ?? formatNumber(number)
|
||||
|
||||
// A conversation's title: the name you gave it, the person, or a group's
|
||||
// members ("Sam, Alex +2").
|
||||
export function convName(contact: string, contactMap: Map<string, ContactInfo>, name?: string): string {
|
||||
if (name) return name
|
||||
if (!isGroup(contact)) return displayName(contact, contactMap.get(contact))
|
||||
const names = groupMembers(contact).map((n) => firstName(n, contactMap))
|
||||
return names.length > 3 ? `${names.slice(0, 3).join(', ')} +${names.length - 3}` : names.join(', ')
|
||||
}
|
||||
|
||||
// Every other chat this number is in -- groups, and 1:1s from your other
|
||||
// numbers -- newest first.
|
||||
export function chatsWith(number: string, conversations: Conversation[], except: { did: string; contact: string }): Conversation[] {
|
||||
return conversations
|
||||
.filter((c) => groupMembers(c.contact).includes(number) && !(c.did === except.did && c.contact === except.contact))
|
||||
.sort((a, b) => b.lastTs - a.lastTs)
|
||||
}
|
||||
|
||||
// Who sent a group message, as shown above their bubbles and in previews.
|
||||
export function senderName(number: string, contactMap: Map<string, ContactInfo>): string {
|
||||
return displayName(number, contactMap.get(number))
|
||||
}
|
||||
|
||||
export function senderShortName(number: string, contactMap: Map<string, ContactInfo>): string {
|
||||
return firstName(number, contactMap)
|
||||
}
|
||||
|
||||
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']
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// Preparing attachments for MMS: voip.ms accepts ~1.2 MB per file and carriers
|
||||
// are often stricter, so anything bigger gets downscaled / re-encoded as JPEG.
|
||||
import type { OutgoingAttachment } from '@shared/types'
|
||||
|
||||
export const MMS_BUDGET = 900 * 1024
|
||||
export const MAX_ATTACHMENTS = 3
|
||||
export const MMS_TEXT_LIMIT = 2048
|
||||
|
||||
// Formats every phone can show; anything else is re-encoded as JPEG.
|
||||
const PASSTHROUGH_IMAGES = new Set(['image/jpeg', 'image/png', 'image/gif'])
|
||||
const EDGES = [2048, 1600, 1280, 1024, 800, 640]
|
||||
const QUALITIES = [0.85, 0.72, 0.6]
|
||||
|
||||
export interface Attachment extends OutgoingAttachment {
|
||||
previewUrl: string // blob: URL for the composer tray
|
||||
originalBytes: number
|
||||
note?: string // e.g. "Resized from 6.2 MB"
|
||||
}
|
||||
|
||||
// Scale/quality attempts in order, from gentlest to harshest. The first one
|
||||
// is always full size so small-but-exotic images (WebP, HEIC…) just convert.
|
||||
export function compressionSteps(width: number, height: number): Array<{ scale: number; quality: number }> {
|
||||
const long = Math.max(width, height)
|
||||
const scales = [...new Set([1, ...EDGES.map((e) => Math.min(1, e / long))])].sort((a, b) => b - a)
|
||||
return scales.flatMap((scale) => QUALITIES.map((quality) => ({ scale, quality })))
|
||||
}
|
||||
|
||||
export function formatBytes(n: number): string {
|
||||
if (n < 1024) return `${n} B`
|
||||
if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`
|
||||
return `${(n / 1024 / 1024).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
async function withPreview(blob: Blob, name: string, extra: Partial<Attachment> & { originalBytes: number }): Promise<Attachment> {
|
||||
return {
|
||||
name,
|
||||
mime: blob.type,
|
||||
data: new Uint8Array(await blob.arrayBuffer()),
|
||||
previewUrl: URL.createObjectURL(blob),
|
||||
...extra
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareAttachment(file: File): Promise<Attachment> {
|
||||
const kind = file.type.split('/')[0]
|
||||
if (kind === 'video' || kind === 'audio') {
|
||||
if (file.size > MMS_BUDGET)
|
||||
throw new Error(
|
||||
`${kind === 'video' ? 'Video' : 'Audio'} is ${formatBytes(file.size)} — MMS attachments must be under ${formatBytes(MMS_BUDGET)}.`
|
||||
)
|
||||
return withPreview(file, file.name, { originalBytes: file.size })
|
||||
}
|
||||
if (kind !== 'image') throw new Error(`Can't send ${file.name || 'that file'}: only photos, video and audio can go by MMS.`)
|
||||
|
||||
let bitmap: ImageBitmap
|
||||
try {
|
||||
bitmap = await createImageBitmap(file)
|
||||
} catch {
|
||||
throw new Error(`Can't read ${file.name || 'that image'} (unsupported format). Try saving it as JPEG or PNG.`)
|
||||
}
|
||||
const { width, height } = bitmap
|
||||
try {
|
||||
if (file.size <= MMS_BUDGET && PASSTHROUGH_IMAGES.has(file.type)) {
|
||||
return withPreview(file, file.name, { originalBytes: file.size, width, height })
|
||||
}
|
||||
for (const { scale, quality } of compressionSteps(width, height)) {
|
||||
const w = Math.max(1, Math.round(width * scale))
|
||||
const h = Math.max(1, Math.round(height * scale))
|
||||
const canvas = new OffscreenCanvas(w, h)
|
||||
const ctx = canvas.getContext('2d')!
|
||||
ctx.fillStyle = '#fff' // JPEG has no alpha: flatten transparency onto white
|
||||
ctx.fillRect(0, 0, w, h)
|
||||
ctx.imageSmoothingQuality = 'high'
|
||||
ctx.drawImage(bitmap, 0, 0, w, h)
|
||||
const blob = await canvas.convertToBlob({ type: 'image/jpeg', quality })
|
||||
if (blob.size <= MMS_BUDGET) {
|
||||
const name = file.name.replace(/\.[^.]*$/, '') + '.jpg'
|
||||
const shrunk = file.size > MMS_BUDGET
|
||||
const note =
|
||||
file.type === 'image/gif' ? 'Too big to animate — sending a still' : shrunk ? `Shrunk from ${formatBytes(file.size)}` : undefined
|
||||
return withPreview(blob, name, { originalBytes: file.size, width: w, height: h, note })
|
||||
}
|
||||
}
|
||||
throw new Error(`Couldn't shrink ${file.name || 'that image'} below ${formatBytes(MMS_BUDGET)}.`)
|
||||
} finally {
|
||||
bitmap.close()
|
||||
}
|
||||
}
|
||||
+604
-51
@@ -1,10 +1,11 @@
|
||||
/* Signal Desktop–inspired theme. Light + dark follow the system setting. */
|
||||
/* Signal Desktop–inspired theme. Light + dark follow prefers-color-scheme, which the main process points at the system or the Settings choice (nativeTheme.themeSource). */
|
||||
:root {
|
||||
--accent: #2c6bed;
|
||||
--accent-hover: #1f5ad6;
|
||||
--bg: #ffffff;
|
||||
--sidebar: #ffffff;
|
||||
--panel: #f6f6f6;
|
||||
--menu-bg: #ffffff;
|
||||
--border: #e9e9e9;
|
||||
--text: #1b1b1b;
|
||||
--muted: #6b6b6b;
|
||||
@@ -28,6 +29,7 @@
|
||||
--bg: #121212;
|
||||
--sidebar: #1b1b1d;
|
||||
--panel: #242426;
|
||||
--menu-bg: #2a2a2d;
|
||||
--border: #2e2e30;
|
||||
--text: #e9e9e9;
|
||||
--muted: #a3a3a3;
|
||||
@@ -55,7 +57,7 @@ body,
|
||||
margin: 0;
|
||||
}
|
||||
body {
|
||||
font-family: Inter, 'Cantarell', system-ui, -apple-system, 'Segoe UI', sans-serif;
|
||||
font-family: Inter, 'Cantarell', system-ui, -apple-system, 'Segoe UI', 'Apple Color Emoji', 'Noto Color Emoji', sans-serif;
|
||||
font-size: 14px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
@@ -100,41 +102,65 @@ mark {
|
||||
}
|
||||
|
||||
/* ---------- sidebar ---------- */
|
||||
/* Width is set inline (user-resizable). Below the default width --s drops
|
||||
under 1 and everything sized with var(--s) shrinks with it. */
|
||||
.sidebar {
|
||||
width: 340px;
|
||||
min-width: 280px;
|
||||
position: relative;
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-size: calc(14px * var(--s, 1));
|
||||
background: var(--sidebar);
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
.sidebar svg[width='20'] {
|
||||
width: calc(20px * var(--s, 1));
|
||||
height: calc(20px * var(--s, 1));
|
||||
}
|
||||
.sidebar svg[width='16'] {
|
||||
width: calc(16px * var(--s, 1));
|
||||
height: calc(16px * var(--s, 1));
|
||||
}
|
||||
.sidebar-resizer {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: -4px;
|
||||
bottom: 0;
|
||||
width: 8px;
|
||||
z-index: 5;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.sidebar-resizer:hover,
|
||||
.sidebar-resizer.dragging {
|
||||
background: linear-gradient(to right, transparent 3px, var(--accent) 3px, var(--accent) 5px, transparent 5px);
|
||||
}
|
||||
.sidebar-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 12px 10px 8px 12px;
|
||||
gap: calc(4px * var(--s, 1));
|
||||
padding: calc(12px * var(--s, 1)) calc(10px * var(--s, 1)) calc(8px * var(--s, 1)) calc(12px * var(--s, 1));
|
||||
}
|
||||
.sidebar-header.compose {
|
||||
gap: 8px;
|
||||
gap: calc(8px * var(--s, 1));
|
||||
}
|
||||
.compose-title {
|
||||
font-weight: 600;
|
||||
font-size: 15px;
|
||||
font-size: calc(15px * var(--s, 1));
|
||||
}
|
||||
.search-box {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: var(--input-bg);
|
||||
border-radius: 8px;
|
||||
height: 32px;
|
||||
padding: 0 4px 0 8px;
|
||||
border-radius: calc(8px * var(--s, 1));
|
||||
height: calc(32px * var(--s, 1));
|
||||
padding: 0 calc(4px * var(--s, 1)) 0 calc(8px * var(--s, 1));
|
||||
min-width: 0;
|
||||
}
|
||||
.search-glyph {
|
||||
color: var(--faint);
|
||||
display: flex;
|
||||
padding-right: 6px;
|
||||
padding-right: calc(6px * var(--s, 1));
|
||||
}
|
||||
.search-box input {
|
||||
flex: 1;
|
||||
@@ -147,8 +173,8 @@ mark {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
width: calc(32px * var(--s, 1));
|
||||
height: calc(32px * var(--s, 1));
|
||||
border: 0;
|
||||
background: transparent;
|
||||
border-radius: 50%;
|
||||
@@ -164,14 +190,14 @@ mark {
|
||||
cursor: default;
|
||||
}
|
||||
.icon-btn.inline {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
width: calc(24px * var(--s, 1));
|
||||
height: calc(24px * var(--s, 1));
|
||||
margin-left: -4px;
|
||||
margin-right: 2px;
|
||||
margin-right: calc(2px * var(--s, 1));
|
||||
}
|
||||
.icon-btn.small {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
width: calc(28px * var(--s, 1));
|
||||
height: calc(28px * var(--s, 1));
|
||||
}
|
||||
.sidebar-body {
|
||||
flex: 1;
|
||||
@@ -182,31 +208,31 @@ mark {
|
||||
height: 100%;
|
||||
}
|
||||
.list-empty {
|
||||
padding: 24px 16px;
|
||||
padding: calc(24px * var(--s, 1)) calc(16px * var(--s, 1));
|
||||
color: var(--muted);
|
||||
text-align: center;
|
||||
}
|
||||
.section-label {
|
||||
padding: 14px 16px 6px;
|
||||
padding: calc(14px * var(--s, 1)) calc(16px * var(--s, 1)) calc(6px * var(--s, 1));
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
font-size: calc(13px * var(--s, 1));
|
||||
color: var(--text);
|
||||
}
|
||||
.section-label .count {
|
||||
color: var(--faint);
|
||||
font-weight: 400;
|
||||
margin-left: 4px;
|
||||
margin-left: calc(4px * var(--s, 1));
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
width: calc(100% - 16px);
|
||||
margin: 0 8px;
|
||||
padding: 10px 8px;
|
||||
gap: calc(12px * var(--s, 1));
|
||||
width: calc(100% - calc(16px * var(--s, 1)));
|
||||
margin: 0 calc(8px * var(--s, 1));
|
||||
padding: calc(10px * var(--s, 1)) calc(8px * var(--s, 1));
|
||||
border: 0;
|
||||
border-radius: 10px;
|
||||
border-radius: calc(10px * var(--s, 1));
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
}
|
||||
@@ -227,29 +253,29 @@ mark {
|
||||
.row-bottom {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
gap: calc(8px * var(--s, 1));
|
||||
}
|
||||
.row-name {
|
||||
flex: 1;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
font-size: calc(14px * var(--s, 1));
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.row-time {
|
||||
font-size: 12px;
|
||||
font-size: calc(12px * var(--s, 1));
|
||||
color: var(--faint);
|
||||
flex: none;
|
||||
}
|
||||
.row-preview {
|
||||
flex: 1;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
font-size: calc(13px * var(--s, 1));
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
margin-top: 2px;
|
||||
margin-top: calc(2px * var(--s, 1));
|
||||
}
|
||||
.row.unread .row-preview {
|
||||
color: var(--text);
|
||||
@@ -259,14 +285,14 @@ mark {
|
||||
font-weight: 600;
|
||||
}
|
||||
.row-via {
|
||||
font-size: 11px;
|
||||
font-size: calc(11px * var(--s, 1));
|
||||
color: var(--faint);
|
||||
margin-top: 2px;
|
||||
margin-top: calc(2px * var(--s, 1));
|
||||
}
|
||||
.row-snippet {
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
margin-top: 2px;
|
||||
font-size: calc(13px * var(--s, 1));
|
||||
margin-top: calc(2px * var(--s, 1));
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
@@ -279,28 +305,28 @@ mark {
|
||||
.badge {
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
border-radius: 10px;
|
||||
font-size: 11px;
|
||||
border-radius: calc(10px * var(--s, 1));
|
||||
font-size: calc(11px * var(--s, 1));
|
||||
font-weight: 600;
|
||||
min-width: 20px;
|
||||
height: 20px;
|
||||
line-height: 20px;
|
||||
padding: 0 6px;
|
||||
min-width: calc(20px * var(--s, 1));
|
||||
height: calc(20px * var(--s, 1));
|
||||
line-height: calc(20px * var(--s, 1));
|
||||
padding: 0 calc(6px * var(--s, 1));
|
||||
text-align: center;
|
||||
flex: none;
|
||||
}
|
||||
.search-results {
|
||||
padding-bottom: 12px;
|
||||
padding-bottom: calc(12px * var(--s, 1));
|
||||
}
|
||||
.to-field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0 12px 8px;
|
||||
padding: 0 10px;
|
||||
height: 36px;
|
||||
gap: calc(8px * var(--s, 1));
|
||||
margin: 0 calc(12px * var(--s, 1)) calc(8px * var(--s, 1));
|
||||
padding: 0 calc(10px * var(--s, 1));
|
||||
height: calc(36px * var(--s, 1));
|
||||
background: var(--input-bg);
|
||||
border-radius: 8px;
|
||||
border-radius: calc(8px * var(--s, 1));
|
||||
}
|
||||
.to-field span {
|
||||
color: var(--muted);
|
||||
@@ -312,9 +338,9 @@ mark {
|
||||
background: transparent;
|
||||
}
|
||||
.sync-footer {
|
||||
font-size: 12px;
|
||||
font-size: calc(12px * var(--s, 1));
|
||||
color: var(--muted);
|
||||
padding: 8px 14px;
|
||||
padding: calc(8px * var(--s, 1)) calc(14px * var(--s, 1));
|
||||
border-top: 1px solid var(--border);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
@@ -380,6 +406,7 @@ mark {
|
||||
.chat-name {
|
||||
font-weight: 600;
|
||||
font-size: 15px;
|
||||
user-select: text;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -519,6 +546,7 @@ mark {
|
||||
.failed-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
color: var(--danger);
|
||||
@@ -539,6 +567,7 @@ mark {
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.composer-row {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 8px;
|
||||
@@ -555,6 +584,41 @@ mark {
|
||||
max-height: 200px;
|
||||
user-select: text;
|
||||
}
|
||||
.emoji-suggest {
|
||||
position: absolute;
|
||||
bottom: calc(100% + 6px);
|
||||
left: 44px;
|
||||
z-index: 20;
|
||||
min-width: 240px;
|
||||
max-height: 290px;
|
||||
overflow-y: auto;
|
||||
padding: 4px;
|
||||
background: var(--menu-bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.emoji-suggest [role='option'] {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 5px 10px;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.emoji-suggest .active {
|
||||
background: var(--row-hover);
|
||||
}
|
||||
.emoji-glyph {
|
||||
font-size: 22px;
|
||||
line-height: 1;
|
||||
width: 26px;
|
||||
text-align: center;
|
||||
}
|
||||
.emoji-name {
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
.counter {
|
||||
font-size: 11px;
|
||||
color: var(--faint);
|
||||
@@ -564,6 +628,15 @@ mark {
|
||||
.counter.multi {
|
||||
color: var(--accent);
|
||||
}
|
||||
.kind-tag {
|
||||
font-size: 9px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
padding: 0 4px;
|
||||
border: 1px solid currentColor;
|
||||
border-radius: 4px;
|
||||
line-height: 13px;
|
||||
}
|
||||
.send-btn {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
@@ -691,6 +764,10 @@ label.did {
|
||||
label.did.disabled {
|
||||
opacity: 0.5;
|
||||
}
|
||||
.export-chat .field.disabled,
|
||||
.export-dates.disabled {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
@@ -775,3 +852,479 @@ label.did.disabled {
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
/* ---------- MMS ---------- */
|
||||
.bubble.has-media {
|
||||
padding: 4px 4px 6px;
|
||||
}
|
||||
.bubble.has-media .text {
|
||||
display: block;
|
||||
padding: 4px 8px 0;
|
||||
}
|
||||
.bubble.has-media .meta {
|
||||
margin-right: 8px;
|
||||
}
|
||||
.bubble.media-only {
|
||||
padding: 0;
|
||||
background: transparent !important;
|
||||
position: relative;
|
||||
}
|
||||
.bubble.media-only .meta {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
bottom: 8px;
|
||||
margin: 0;
|
||||
padding: 1px 7px;
|
||||
border-radius: 10px;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
color: #fff;
|
||||
opacity: 1;
|
||||
}
|
||||
.media {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.media-img {
|
||||
display: block;
|
||||
max-width: min(300px, 100%);
|
||||
max-height: 360px;
|
||||
object-fit: cover;
|
||||
border-radius: 14px;
|
||||
background: var(--input-bg);
|
||||
cursor: zoom-in;
|
||||
}
|
||||
.media-video {
|
||||
display: block;
|
||||
max-width: min(300px, 100%);
|
||||
max-height: 360px;
|
||||
border-radius: 14px;
|
||||
background: #000;
|
||||
}
|
||||
.media-audio {
|
||||
display: block;
|
||||
width: 260px;
|
||||
max-width: 100%;
|
||||
}
|
||||
.media-missing,
|
||||
.media-file {
|
||||
padding: 18px 20px;
|
||||
border-radius: 14px;
|
||||
background: color-mix(in srgb, currentColor 12%, transparent);
|
||||
font-size: 13px;
|
||||
opacity: 0.8;
|
||||
border: 0;
|
||||
}
|
||||
.bubble.media-only .media-missing,
|
||||
.bubble.media-only .media-file {
|
||||
color: var(--muted);
|
||||
background: var(--input-bg);
|
||||
padding-right: 84px; /* room for the time pill */
|
||||
}
|
||||
|
||||
.attach-tray {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 0 0 8px 40px;
|
||||
}
|
||||
.attach-item {
|
||||
position: relative;
|
||||
width: 76px;
|
||||
height: 76px;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
background: var(--input-bg);
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.attach-item img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.attach-file {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
text-transform: capitalize;
|
||||
}
|
||||
.attach-size {
|
||||
position: absolute;
|
||||
left: 4px;
|
||||
bottom: 4px;
|
||||
font-size: 10px;
|
||||
padding: 0 5px;
|
||||
border-radius: 6px;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
color: #fff;
|
||||
}
|
||||
.attach-size.shrunk::before {
|
||||
content: '↓ ';
|
||||
}
|
||||
.attach-remove {
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
right: 3px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
color: #fff;
|
||||
}
|
||||
.spinner {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid var(--faint);
|
||||
border-top-color: transparent;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
.attach-btn {
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
.counter.over {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.chat {
|
||||
position: relative;
|
||||
}
|
||||
.drop-hint {
|
||||
position: absolute;
|
||||
inset: 8px;
|
||||
border: 2px dashed var(--accent);
|
||||
border-radius: 14px;
|
||||
background: color-mix(in srgb, var(--bg) 85%, transparent);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--accent);
|
||||
pointer-events: none;
|
||||
z-index: 5;
|
||||
}
|
||||
|
||||
.lightbox {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 20;
|
||||
background: rgba(0, 0, 0, 0.88);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 56px 32px 32px;
|
||||
}
|
||||
.lightbox img {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.lightbox-bar {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 12px;
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
}
|
||||
.lightbox .icon-btn {
|
||||
color: #ddd;
|
||||
}
|
||||
.lightbox .icon-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* ---------- settings: appearance ---------- */
|
||||
.segmented {
|
||||
display: inline-flex;
|
||||
background: var(--input-bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 2px;
|
||||
}
|
||||
.modal .segmented button:not(.icon-btn):not(.primary) {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
border-radius: 6px;
|
||||
padding: 4px 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.modal .segmented button.on:not(.icon-btn):not(.primary) {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
kbd {
|
||||
font-family: inherit;
|
||||
font-size: 11px;
|
||||
padding: 1px 5px;
|
||||
border: 1px solid var(--border);
|
||||
border-bottom-width: 2px;
|
||||
border-radius: 4px;
|
||||
background: var(--input-bg);
|
||||
}
|
||||
.icon-btn.spinning svg {
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
.list-footer {
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
/* ---------- archive + unread ---------- */
|
||||
.icon-btn.on {
|
||||
background: var(--row-active);
|
||||
color: var(--text);
|
||||
}
|
||||
.archive-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: calc(6px * var(--s, 1));
|
||||
padding: calc(4px * var(--s, 1)) calc(16px * var(--s, 1)) calc(8px * var(--s, 1));
|
||||
font-weight: 600;
|
||||
font-size: calc(13px * var(--s, 1));
|
||||
}
|
||||
.badge.dot {
|
||||
min-width: calc(12px * var(--s, 1));
|
||||
width: calc(12px * var(--s, 1));
|
||||
height: calc(12px * var(--s, 1));
|
||||
padding: 0;
|
||||
align-self: center;
|
||||
}
|
||||
.context-menu {
|
||||
position: fixed;
|
||||
z-index: 30;
|
||||
min-width: 170px;
|
||||
padding: 4px;
|
||||
background: var(--menu-bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
box-shadow: var(--shadow);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.context-menu button {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
padding: 7px 12px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
.context-menu button:hover,
|
||||
.context-menu button:focus-visible {
|
||||
background: var(--row-hover);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
/* ---------- Google Voice + group chats ---------- */
|
||||
.gv-tag {
|
||||
font-size: 9px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
padding: 0 3px;
|
||||
margin-right: 4px;
|
||||
border: 1px solid currentColor;
|
||||
border-radius: 4px;
|
||||
line-height: 12px;
|
||||
display: inline-block;
|
||||
}
|
||||
.msg-sender {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
margin: 0 0 2px 10px;
|
||||
}
|
||||
.compose-from {
|
||||
margin: 0 calc(12px * var(--s, 1)) calc(8px * var(--s, 1));
|
||||
}
|
||||
.start-group {
|
||||
margin-left: auto;
|
||||
padding: 4px 12px;
|
||||
}
|
||||
.chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin: 0 calc(12px * var(--s, 1)) calc(8px * var(--s, 1));
|
||||
}
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 2px 4px 2px 10px;
|
||||
border-radius: 999px;
|
||||
background: var(--input-bg);
|
||||
font-size: 13px;
|
||||
}
|
||||
.chip button {
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--muted);
|
||||
display: flex;
|
||||
padding: 2px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
.chip button:hover {
|
||||
background: var(--row-active);
|
||||
}
|
||||
.row-wrap {
|
||||
position: relative;
|
||||
}
|
||||
.add-member {
|
||||
position: absolute;
|
||||
right: 12px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
font-size: 12px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--sidebar);
|
||||
color: var(--muted);
|
||||
border-radius: 999px;
|
||||
padding: 2px 8px;
|
||||
opacity: 0;
|
||||
}
|
||||
.row-wrap:hover .add-member,
|
||||
.add-member:focus-visible {
|
||||
opacity: 1;
|
||||
}
|
||||
.add-member:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
.gv-fallback {
|
||||
margin-top: 10px;
|
||||
}
|
||||
.gv-fallback summary {
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.gv-fallback textarea {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
font: 12px ui-monospace, monospace;
|
||||
margin: 6px 0;
|
||||
padding: 6px 8px;
|
||||
background: var(--input-bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
/* ---------- chat info ---------- */
|
||||
.chat-title.clickable {
|
||||
cursor: pointer;
|
||||
}
|
||||
.chat-title.clickable:hover .chat-name {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.conv-info-top {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
text-align: center;
|
||||
}
|
||||
.conv-info-title {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.conv-name-input {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 8px 10px;
|
||||
background: var(--input-bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
color: var(--text);
|
||||
font-size: 15px;
|
||||
}
|
||||
.member {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 6px 0;
|
||||
}
|
||||
.member-main {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* ---------- add contact ---------- */
|
||||
.text-input {
|
||||
display: block;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
margin-top: 10px;
|
||||
padding: 8px 10px;
|
||||
background: var(--input-bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
color: var(--text);
|
||||
font-size: 15px;
|
||||
}
|
||||
.add-contact .field {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.member-add {
|
||||
margin-left: auto;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* ---------- reactions (iPhone tapbacks) ---------- */
|
||||
.reactions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-top: -6px;
|
||||
margin-bottom: 2px;
|
||||
padding: 1px 7px;
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
border-radius: 999px;
|
||||
border: 2px solid var(--bg);
|
||||
background: var(--bubble-in);
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
.msg.in .reactions {
|
||||
margin-left: 10px;
|
||||
}
|
||||
.msg.out .reactions {
|
||||
margin-right: 10px;
|
||||
}
|
||||
.reaction-count {
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.group-row-icon {
|
||||
flex: none;
|
||||
width: calc(40px * var(--s, 1));
|
||||
height: calc(40px * var(--s, 1));
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--input-bg);
|
||||
color: var(--muted);
|
||||
}
|
||||
.context-menu button:disabled {
|
||||
color: var(--muted);
|
||||
background: transparent;
|
||||
}
|
||||
.context-menu .menu-sep {
|
||||
height: 1px;
|
||||
margin: 4px 6px;
|
||||
background: var(--border);
|
||||
}
|
||||
|
||||
+32
-2
@@ -1,5 +1,5 @@
|
||||
// The typed bridge exposed to the renderer as window.api.
|
||||
import type { ContactInfo, Conversation, Credentials, Did, Message, SearchHit, Settings, SyncStatus } from './types'
|
||||
import type { AddressBook, ChatExport, ContactInfo, NewContact, Conversation, Credentials, Did, Message, OutgoingAttachment, SearchHit, Settings, SyncStatus, Theme } from './types'
|
||||
|
||||
export interface AppState {
|
||||
configured: boolean
|
||||
@@ -8,6 +8,13 @@ export interface AppState {
|
||||
dataDir: string
|
||||
dids: Did[]
|
||||
keyringBackend: string
|
||||
gvoiceNumber?: string // set when Google Voice is connected
|
||||
}
|
||||
|
||||
export interface RabbitStatus {
|
||||
adb: boolean // adb is installed
|
||||
bundledVersion?: string // the Android app this build carries
|
||||
device?: { serial: string; model: string; installedVersion?: string }
|
||||
}
|
||||
|
||||
export interface Api {
|
||||
@@ -15,16 +22,37 @@ export interface Api {
|
||||
testCredentials(creds: Credentials): Promise<Did[]>
|
||||
saveSetup(creds: Credentials, settings: Settings): Promise<void>
|
||||
updateSettings(settings: Settings): Promise<void>
|
||||
setTheme(theme: Theme): Promise<void>
|
||||
signOut(): Promise<void>
|
||||
connectGoogleVoice(): Promise<void>
|
||||
connectGoogleVoiceCookies(text: string): Promise<void>
|
||||
disconnectGoogleVoice(): Promise<void>
|
||||
|
||||
rabbitStatus(): Promise<RabbitStatus>
|
||||
rabbitInstall(mode?: 'full' | 'update'): Promise<void> // update: app only, keeps its data
|
||||
rabbitSync(): Promise<void>
|
||||
onRabbitProgress(cb: (step: string) => void): () => void
|
||||
|
||||
listContacts(): Promise<ContactInfo[]>
|
||||
listAddressBooks(): Promise<{ books: AddressBook[]; default?: string }>
|
||||
addContact(c: NewContact): Promise<string> // resolves with the book's name
|
||||
listConversations(): Promise<Conversation[]>
|
||||
getMessages(did: string, contact: string): Promise<Message[]>
|
||||
markRead(did: string, contact: string): Promise<void>
|
||||
markUnread(did: string, contact: string): Promise<void>
|
||||
setArchived(did: string, contact: string, archived: boolean): Promise<void>
|
||||
setName(did: string, contact: string, name: string | null): Promise<void>
|
||||
// Unsent composer text, by contact; kept until sent or cleared.
|
||||
getDrafts(): Promise<Record<string, string>>
|
||||
setDraft(contact: string, text: string): Promise<void>
|
||||
search(query: string, scope?: { did: string; contact: string }): Promise<SearchHit[]>
|
||||
send(did: string, contact: string, text: string): Promise<void>
|
||||
send(did: string, contact: string, text: string, attachments?: OutgoingAttachment[]): Promise<void>
|
||||
deleteFailed(id: number): Promise<void>
|
||||
retryFailed(id: number): Promise<void>
|
||||
saveMedia(id: number, index: number): Promise<void>
|
||||
exportChat(did: string, contact: string, opts: ChatExport): Promise<boolean> // false: no file chosen
|
||||
readMedia(id: number, index: number): Promise<{ mime: string; data: Uint8Array<ArrayBuffer> }>
|
||||
copyImage(png: Uint8Array): Promise<void> // onto the system clipboard
|
||||
|
||||
syncStatus(): Promise<SyncStatus>
|
||||
pollNow(): Promise<void>
|
||||
@@ -36,4 +64,6 @@ export interface Api {
|
||||
onConversationsChanged(cb: () => void): () => void
|
||||
onSyncStatus(cb: (s: SyncStatus) => void): () => void
|
||||
onContactsChanged(cb: () => void): () => void
|
||||
onStateChanged(cb: () => void): () => void
|
||||
onOpenConversation(cb: (key: { did: string; contact: string }) => void): () => void
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Attachment type helpers shared by main (file names) and renderer (display).
|
||||
import type { MediaRef } from './types'
|
||||
|
||||
const EXT_BY_MIME: Record<string, string> = {
|
||||
'image/jpeg': 'jpg',
|
||||
'image/png': 'png',
|
||||
'image/gif': 'gif',
|
||||
'image/webp': 'webp',
|
||||
'image/bmp': 'bmp',
|
||||
'video/mp4': 'mp4',
|
||||
'video/3gpp': '3gp',
|
||||
'video/quicktime': 'mov',
|
||||
'audio/mpeg': 'mp3',
|
||||
'audio/mp4': 'm4a',
|
||||
'audio/amr': 'amr',
|
||||
'audio/ogg': 'ogg',
|
||||
'text/vcard': 'vcf',
|
||||
'text/x-vcard': 'vcf',
|
||||
'text/plain': 'txt'
|
||||
}
|
||||
const MIME_BY_EXT: Record<string, string> = {
|
||||
...Object.fromEntries(Object.entries(EXT_BY_MIME).map(([m, e]) => [e, m])),
|
||||
jpeg: 'image/jpeg'
|
||||
}
|
||||
|
||||
export function guessMime(nameOrUrl: string): string | undefined {
|
||||
const ext = /\.([a-z0-9]+)(?:[?#].*)?$/i.exec(nameOrUrl)?.[1]?.toLowerCase()
|
||||
return ext ? MIME_BY_EXT[ext] : undefined
|
||||
}
|
||||
|
||||
export function extFor(mime: string | undefined): string {
|
||||
return (mime && EXT_BY_MIME[mime.split(';')[0].trim()]) || 'bin'
|
||||
}
|
||||
|
||||
export type MediaKind = 'image' | 'video' | 'audio' | 'file'
|
||||
|
||||
export function mediaKind(ref: MediaRef): MediaKind {
|
||||
const mime = ref.mime ?? guessMime(ref.file ?? ref.url ?? '') ?? ''
|
||||
const top = mime.split('/')[0]
|
||||
return top === 'image' || top === 'video' || top === 'audio' ? top : 'file'
|
||||
}
|
||||
+21
-19
@@ -14,23 +14,25 @@ export function formatNumber(n: string): string {
|
||||
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
|
||||
// Group chats (Google Voice only) are keyed by their members' numbers, sorted
|
||||
// and comma-joined, in the place a 1:1 chat keeps its one number.
|
||||
export function groupKey(numbers: string[]): string {
|
||||
return [...new Set(numbers.map(normalizeNumber).filter(Boolean))].sort().join(',')
|
||||
}
|
||||
|
||||
export function isGroup(contact: string): boolean {
|
||||
return contact.includes(',')
|
||||
}
|
||||
|
||||
export function groupMembers(contact: string): string[] {
|
||||
return contact.split(',')
|
||||
}
|
||||
|
||||
// voip.ms's sendSMS takes at most 160 characters. Longer texts go out as one
|
||||
// text-only MMS, which the recipient sees as a single message (split SMS arrive
|
||||
// as separate fragments, often out of order).
|
||||
export const SMS_TEXT_LIMIT = 160
|
||||
|
||||
export function charCount(text: string): number {
|
||||
return [...text].length
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
// iMessage "tapbacks" sent to non-iPhones arrive as plain texts:
|
||||
// Loved “see you at 9” Laughed at “lol” Reacted 🎉 to “we won”
|
||||
// Removed a heart from “see you at 9” Liked an image
|
||||
// We fold them into emoji reactions on the message they quote (found by
|
||||
// searching back through the conversation), the way Signal shows reactions.
|
||||
// A reaction whose message can't be found stays an ordinary message.
|
||||
|
||||
const VERBS: Record<string, string> = {
|
||||
loved: '❤️',
|
||||
liked: '👍',
|
||||
disliked: '👎',
|
||||
'laughed at': '😂',
|
||||
emphasized: '‼️',
|
||||
questioned: '❓'
|
||||
}
|
||||
|
||||
const REMOVED: Record<string, string> = {
|
||||
'a heart': '❤️',
|
||||
'a like': '👍',
|
||||
'a dislike': '👎',
|
||||
'a laugh': '😂',
|
||||
'an exclamation': '‼️',
|
||||
'an exclamation mark': '‼️',
|
||||
'a question mark': '❓'
|
||||
}
|
||||
|
||||
// Quotes come curly from iPhones, sometimes straight.
|
||||
const Q_OPEN = '[“"”]'
|
||||
const Q_CLOSE = '[”"“]'
|
||||
const MEDIA = /^(?:an? )?(?:image|photo|picture|movie|video|attachment|audio message|gif|sticker)$/i
|
||||
|
||||
export interface ParsedReaction {
|
||||
emoji: string
|
||||
removed: boolean
|
||||
// The quoted text, or `media` for "Loved an image" and the like.
|
||||
target: { text: string } | { media: true }
|
||||
}
|
||||
|
||||
const REACTED = new RegExp(`^Reacted (.+?) to (?:${Q_OPEN}([\\s\\S]*)${Q_CLOSE}|(.+))$`)
|
||||
const VERB = new RegExp(`^(Loved|Liked|Disliked|Laughed at|Emphasized|Questioned) (?:${Q_OPEN}([\\s\\S]*)${Q_CLOSE}|(.+))$`)
|
||||
const REMOVE = new RegExp(`^Removed (an? .+?) from (?:${Q_OPEN}([\\s\\S]*)${Q_CLOSE}|(.+))$`)
|
||||
|
||||
function target(quoted: string | undefined, bare: string | undefined): ParsedReaction['target'] | null {
|
||||
if (quoted !== undefined) return { text: quoted }
|
||||
if (bare && MEDIA.test(bare.trim())) return { media: true }
|
||||
return null
|
||||
}
|
||||
|
||||
export function parseReaction(body: string): ParsedReaction | null {
|
||||
const s = body.trim()
|
||||
let m = VERB.exec(s)
|
||||
if (m) {
|
||||
const t = target(m[2], m[3])
|
||||
return t && { emoji: VERBS[m[1].toLowerCase()], removed: false, target: t }
|
||||
}
|
||||
m = REACTED.exec(s)
|
||||
if (m && [...m[1]].length <= 4) {
|
||||
const t = target(m[2], m[3])
|
||||
return t && { emoji: m[1], removed: false, target: t }
|
||||
}
|
||||
m = REMOVE.exec(s)
|
||||
if (m) {
|
||||
const kind = m[1].toLowerCase()
|
||||
// "Removed a 😂 from …" (newer iOS) names the emoji itself.
|
||||
const emoji = REMOVED[kind] ?? (/^an? (.{1,4})$/u.exec(m[1])?.[1] ?? '')
|
||||
const t = target(m[2], m[3])
|
||||
return emoji && t ? { emoji, removed: true, target: t } : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export interface Reaction {
|
||||
emoji: string
|
||||
from: string // the reactor's number, or 'me'
|
||||
ts: number
|
||||
}
|
||||
|
||||
interface Foldable {
|
||||
id: number
|
||||
body: string
|
||||
ts: number
|
||||
direction: 'in' | 'out'
|
||||
contact: string
|
||||
sender?: string
|
||||
media?: unknown[]
|
||||
}
|
||||
|
||||
// Phones swap straight and curly apostrophes, so compare without the difference.
|
||||
const norm = (s: string): string => s.replace(/[‘’]/g, "'").replace(/\s+/g, ' ').trim()
|
||||
|
||||
function matches(body: string, quoted: string): boolean {
|
||||
const b = norm(body)
|
||||
const q = norm(quoted)
|
||||
if (!q) return false
|
||||
if (b === q) return true
|
||||
// Long messages get quoted cut short with an ellipsis.
|
||||
const cut = q.replace(/(…|\.\.\.)$/, '').trimEnd()
|
||||
return cut !== q && cut.length >= 8 && b.startsWith(cut)
|
||||
}
|
||||
|
||||
// The conversation's messages (oldest first) without the reaction texts we
|
||||
// could place, plus each placed reaction keyed by the message it's on. Each
|
||||
// person keeps one reaction per message, like iMessage: a newer one replaces
|
||||
// theirs, a "Removed …" takes it away.
|
||||
export function foldReactions<T extends Foldable>(msgs: T[]): { shown: T[]; reactions: Map<number, Reaction[]> } {
|
||||
const hidden = new Set<number>()
|
||||
const byTarget = new Map<number, Map<string, Reaction>>()
|
||||
msgs.forEach((m, i) => {
|
||||
const r = parseReaction(m.body)
|
||||
if (!r) return
|
||||
let found: T | undefined
|
||||
for (let j = i - 1; j >= 0 && !found; j--) {
|
||||
const c = msgs[j]
|
||||
if (hidden.has(c.id) || parseReaction(c.body)) continue
|
||||
if ('media' in r.target ? !!c.media?.length : matches(c.body, r.target.text)) found = c
|
||||
}
|
||||
if (!found) return
|
||||
hidden.add(m.id)
|
||||
const from = m.direction === 'out' ? 'me' : (m.sender ?? m.contact)
|
||||
const mine = byTarget.get(found.id) ?? new Map<string, Reaction>()
|
||||
if (r.removed) {
|
||||
if (mine.get(from)?.emoji === r.emoji) mine.delete(from)
|
||||
} else {
|
||||
mine.set(from, { emoji: r.emoji, from, ts: m.ts })
|
||||
}
|
||||
byTarget.set(found.id, mine)
|
||||
})
|
||||
const reactions = new Map<number, Reaction[]>()
|
||||
for (const [id, mine] of byTarget) if (mine.size) reactions.set(id, [...mine.values()].sort((a, b) => a.ts - b.ts))
|
||||
return { shown: hidden.size ? msgs.filter((m) => !hidden.has(m.id)) : msgs, reactions }
|
||||
}
|
||||
|
||||
// A reaction text as a short preview line: "❤️ to “see you at 9”".
|
||||
export function reactionPreview(body: string): string | null {
|
||||
const r = parseReaction(body)
|
||||
if (!r) return null
|
||||
const what = 'media' in r.target ? 'a photo' : `“${norm(r.target.text)}”`
|
||||
return r.removed ? `Removed ${r.emoji} from ${what}` : `${r.emoji} to ${what}`
|
||||
}
|
||||
+70
-1
@@ -2,6 +2,37 @@
|
||||
|
||||
export type Direction = 'in' | 'out'
|
||||
export type MessageStatus = 'delivered' | 'pending' | 'failed'
|
||||
export type MessageKind = 'sms' | 'mms'
|
||||
export type Theme = 'system' | 'light' | 'dark'
|
||||
|
||||
// One MMS attachment. `url` is where voip.ms serves it; `file` is our cached
|
||||
// copy (a name inside <dataDir>/media), filled in once downloaded or sent.
|
||||
export interface MediaRef {
|
||||
url?: string
|
||||
file?: string
|
||||
mime?: string
|
||||
width?: number
|
||||
height?: number
|
||||
}
|
||||
|
||||
// "Export chat": which days, which format, and the names shown in the chat.
|
||||
export interface ChatExport {
|
||||
from?: string // YYYY-MM-DD, inclusive; neither = all time
|
||||
to?: string
|
||||
format: 'pdf' | 'txt'
|
||||
attachments: boolean // PDF only: show photos (otherwise "[Photo]")
|
||||
title: string // the chat's name as shown
|
||||
names: Record<string, string> // group senders' names, by number
|
||||
}
|
||||
|
||||
// An attachment on its way out (already compressed by the renderer).
|
||||
export interface OutgoingAttachment {
|
||||
name: string
|
||||
mime: string
|
||||
data: Uint8Array
|
||||
width?: number
|
||||
height?: number
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id: number
|
||||
@@ -10,8 +41,11 @@ export interface Message {
|
||||
direction: Direction
|
||||
body: string
|
||||
ts: number // epoch ms, UTC
|
||||
kind: 'sms' | 'mms'
|
||||
kind: MessageKind
|
||||
status: MessageStatus
|
||||
media?: MediaRef[]
|
||||
error?: string // why a send failed
|
||||
sender?: string // who sent an incoming group message (normalized number)
|
||||
}
|
||||
|
||||
export interface Conversation {
|
||||
@@ -20,7 +54,13 @@ export interface Conversation {
|
||||
lastBody: string
|
||||
lastTs: number
|
||||
lastDirection: Direction
|
||||
lastKind: MessageKind
|
||||
lastMedia?: MediaRef // first attachment of the last message, if any
|
||||
lastSender?: string // sender of the last message, in group chats
|
||||
name?: string // a name you gave the conversation (local only)
|
||||
unread: number
|
||||
markedUnread: boolean // manually marked unread (shown as a dot)
|
||||
archived: boolean
|
||||
}
|
||||
|
||||
export interface ContactInfo {
|
||||
@@ -31,6 +71,20 @@ export interface ContactInfo {
|
||||
book: string
|
||||
}
|
||||
|
||||
export interface AddressBook {
|
||||
uid: string
|
||||
name: string
|
||||
account: string // e.g. the Nextcloud account it belongs to
|
||||
}
|
||||
|
||||
export interface NewContact {
|
||||
first: string
|
||||
last: string
|
||||
org: string
|
||||
number: string // E.164
|
||||
book?: string // address book uid; default: GNOME Contacts' own default
|
||||
}
|
||||
|
||||
export interface SearchHit {
|
||||
id: number
|
||||
did: string
|
||||
@@ -40,10 +94,13 @@ export interface SearchHit {
|
||||
snippet: string // contains / markers around matched text
|
||||
}
|
||||
|
||||
export type Provider = 'voipms' | 'gvoice'
|
||||
|
||||
export interface Did {
|
||||
did: string
|
||||
description: string
|
||||
smsEnabled: boolean
|
||||
provider?: Provider // absent = voip.ms
|
||||
}
|
||||
|
||||
export interface SyncStatus {
|
||||
@@ -53,6 +110,15 @@ export interface SyncStatus {
|
||||
lastPoll?: number
|
||||
error?: string
|
||||
total: number
|
||||
gvoice?: GvStatus
|
||||
}
|
||||
|
||||
// Google Voice syncs on its own, so it reports separately.
|
||||
export interface GvStatus {
|
||||
phase: 'idle' | 'backfill' | 'polling' | 'error' | 'signedOut'
|
||||
backfillDone: boolean
|
||||
lastPoll?: number
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
@@ -60,6 +126,9 @@ export interface Settings {
|
||||
dids: string[] // DIDs to sync; empty = all SMS-enabled
|
||||
defaultDid?: string
|
||||
backfillFloor: string // YYYY-MM-DD, stop backfill here
|
||||
theme: Theme
|
||||
notifications: boolean // new messages go to the notification list
|
||||
contactBook?: string // where "Add to contacts" puts them; default: GNOME Contacts' default
|
||||
}
|
||||
|
||||
export interface Credentials {
|
||||
|
||||
Reference in New Issue
Block a user