Compare commits

..
20 Commits
Author SHA1 Message Date
trav 2356d8e61e v0.8.4: a one-line chat header with the search field always there
The name, a group's size and the [GV]/[MS]/[SIM] tag (at the right) share one line, so the header, its picture included, is smaller. Search in chat is a field at the end of the name panel: click in and type; Esc clears it, Enter/Shift+Enter step, Ctrl+Shift+F still jumps there. The panel still opens Get info, except over the field.
2026-11-12 17:19:18 -08:00
trav 52d4b827fb v0.8.3: chat list rows are two lines, with bigger text
The [GV]/[MS]/[SIM] tag sits at the end of the preview line, under the time, instead of a third line of its own; the name, preview and time are a size up in the room it left.
2026-11-12 16:19:02 -08:00
trav 19d477c388 v0.8.2: the chat list and header say just [GV], [MS] or [SIM]
Not "via [GV] (541) …": the tag alone, with the full number as its tooltip. Get info still says it in full (now [MS] for voip.ms too).
2026-11-12 15:35:23 -08:00
trav 9004e8620f v0.8.1: Get info shows the newest photos first
The thumbnails run newest first, like Signal; the full-size view still steps ← older, → newer, as in the chat.
2026-11-12 15:18:59 -08:00
trav cacbe1829b v0.8.0: bubble for Android 0.7.3 — Get info for everyone, with the chat's photos; no more "MMS Received"
Desktop:
- Click a chat's picture or name (or right-click it in the list → Get info…)
  for any chat, not only groups. One person: their picture, name, number
  (and its label), which of your numbers you're texting from, Add to
  contacts… if they aren't one. The number no longer sits in the header.
- Get info lists every photo and video in the chat as thumbnails, oldest
  first like the chat, scrolled to the newest. Each opens full size.
- The full-size view steps through the chat's photos with ← and → (or the
  side buttons) and says "n of N · date", from Get info or from the chat.
  Its glyphs were light gray on the white buttons; now the usual glyph color.

Both: voip.ms puts "MMS Received" as the text of a received picture that
came without words. Nobody wrote it, so it's dropped as messages come in,
and once from the ones already stored (only on messages with pictures, so
someone typing "MMS received" still shows).

Tried in a sandbox with made-up chats and generated pictures, driven over
DevTools: the header, Get info for a person and a group, thumbnails,
←/→ through 14 pictures, Esc closing the picture then the dialog, and the
v11 migration clearing a stored "MMS Received".
2026-11-12 15:01:56 -08:00
trav 7feca6f270 v0.7.2: bubble for Android 0.7.2 — reactions quote the message exactly, so the other phone can find it 2026-11-11 04:50:28 -08:00
trav 6448fe47a1 v0.7.1: bubble for Android 0.7.1 — your own reaction shows as a white disc in the long-press row
Tried on the Rabbit with the dev app and made-up chats: long-press row, +
grid, sending, replacing and taking back a reaction, the Spanish tapback and
the edit with its history, and Settings → Reactions. The only fix: the dark
gray highlight on your reaction was hard to see, so it's the picked-tile
white of rabbit.html#looks, inset to a circle.
2026-11-10 18:07:02 -08:00
trav a55c9ca288 v0.7.0: bubble for Android 0.7.0 — react to messages, reactions in other languages, and edits
Android, ported from the desktop's reactions.ts / edits.ts (same readings:
checked side by side on the same 32 cases):
- Long-press a message: the quick reaction row (yours lit, tap again to take
  it back), + for every emoji (EmojiPicker, the desktop's emoji list as
  res/raw/emoji_list.txt, minus any the font can't draw), and Copy text.
- Settings → Reactions → Quick reactions: pick a spot, then its emoji; Reset.
- Tapbacks in other languages fold like the desktop's; "Edited to “…”" edits
  its message, which says "Edited · time"; tap it for the earlier texts.
- Chat list and notifications preview an edit as "✏️ new text".
- push_sandbox.py has a Spanish tapback and an edit to try it on.

Desktop: version 0.7.0; gen-emoji also writes the Android list.
2026-11-10 17:38:09 -08:00
trav fe34c50101 Desktop: react to messages, reactions in other languages, and edits
- Right-click a message (or photo): a quick reaction row above Copy, + for
  every emoji, and "Customize quick reactions…" there to change the row
  (saved in settings as quickReactions; default ❤️ 👍 👎 😂 ‼️ ❓). Yours
  shows sunk; clicking it again takes it back. A reaction goes out as an
  ordinary text worded like an iPhone's ("Loved “…”", "Reacted 🎉 to “…”",
  "Removed a heart from “…”"), long messages quoted cut short.
- Tapbacks in other languages ("Le encanta “…”", "Hat „…“ geliebt",
  "A aimé « … »"...): read from the words around the quote, and only folded
  when the quote matches an earlier message. A failed reaction stays in view.
- "Edited to “…”": applied to the sender's message from the last 20 minutes
  that reads most like it (or their only one); the bubble says "Edited", and
  clicking it shows the earlier texts. Reactions to the old text still land.
- Popovers re-fit the window when they grow.
2026-11-10 17:33:48 -08:00
travandClaude Opus 5.5 23abc9fa6d Title bar: window buttons on the left are clickable again
The centred title spans the whole bar and inherits its drag region; it came
after the left button group, so its drag covered their no-drag and a click
started a window move instead. The title now goes first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:37:24 -08:00
trav 7671bf6aeb Preferences: one Accounts page (voip.ms, Google Voice, Numbers with checking), and jai gets its own page 2026-11-08 20:42:18 -08:00
trav 37007cc797 v0.6.0: bubble for Android 0.6.0 — the house look on the Rabbit, and a stretchy pull-to-refresh that pops
Desktop: Signal vibes or travewave, chosen in Preferences → Appearance.
Rabbit: white on pure black, 22/28/32 sp text, outlined buttons and dim-edged
text boxes, and drawn icons instead of emoji (rabbit.html). Pulling the chat
list further once the search box shows stretches a bubble that pops at the
mark and starts the check, then a spinner until it's done.
2026-11-08 19:39:58 -08:00
trav 1cbb7b3bc8 Desktop: the travewave house look (shared-resources design.html), switchable with Signal vibes
Preferences → Appearance → Style picks Signal vibes (the look so far) or
travewave: house grays, embossed buttons and tiles, a debossed chat-name
panel, 8 px framed lists, button-like scrollbars, Century Gothic for names
and messages. Either way the window is now one rounded frameless tile with
its own title bar (GNOME's button layout) and a menu bar shown by tapping
Alt (Edit → Preferences…, Ctrl+,), tooltips drawn by the page with a
"Show tooltips" preference, and Preferences laid out like VLC's
(categories left, changes apply at once, Close).
2026-11-08 19:36:53 -08:00
travandClaude Opus 5.5 8bfe013e15 Marked-unread dot is magenta instead of blue
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 16:39:08 -08:00
trav 37f138702b v0.5.1: bubble for Android 0.5.1 — no double sends when a text with an emoji is cut off mid-send
voip.ms's listing drops emoji, so a send whose reply was lost (here the
laptop slept 8 s after Send) never matched its own copy in the listing and
went out a second time. Match with the emoji taken out (exact match first),
and after an uncertain send only send again once a listing check actually
got through; if none can, mark it failed with a note instead.
2026-11-07 14:05:23 -08:00
trav 950b8ce067 v0.5.0: bubble for Android 0.5.0 — text from the Rabbit's SIM on the desktop, and chat names and read status sync, through jai
A relay on jai (server/bubble_relay.py, stdlib + SQLite, tailscale address
only, bearer token) carries sealed blobs between the desktop and the Rabbit:
AES-256-GCM with a key the desktop makes and hands over USB (Sync to Rabbit),
so jai can neither read nor forge anything. It deletes what's been picked up,
and anything after 14 days.

- Desktop (src/main/relay.ts): "Rabbit SIM" is a number to text from, groups
  included; the SIM's history and new texts arrive; older photos are fetched
  when shown; names and read/unread/archived go both ways. Settings → Rabbit
  relay connects it.
- Rabbit (Relay.java, RelayJob): no timer of its own for the battery; it rides
  along with the background checks, plus one network job after a text, a send
  or a swipe. Each send from the desktop goes out at most once and not after a
  day. Plain http only to jai and localhost (network_security_config).
- scripts/deploy-jai.sh; tests: server unit tests, an end-to-end relay test,
  and DEVICE=1 relay.device.test.ts against the dev app.
2026-11-06 17:35:00 -08:00
trav ec9e472265 v0.4.0: bubble for Android 0.4.0 — an inverted (lighter) icon, chosen in Settings on both
The original icon is a little dark: resources/icon-inverted.png and
ic_launcher_inverted.png are its negative (alpha kept).

- Desktop: Settings → Appearance → Icon (Dark / Inverted), saved on click;
  sets the window icon and rewrites the launcher's installed copy
- Android: Settings → Icon; two launcher activity-aliases, one enabled
2026-11-06 17:20:56 -08:00
trav 5e5ef18e01 v0.3.0: bubble for Android 0.3.0 — texts over the Rabbit's own SIM card
A third source next to voip.ms and Google Voice, while bubble is Android's
default SMS app (Settings → SIM card asks for the role). SMS and MMS in and
out, group chats as MMS, the phone's existing texts imported, and Android's
message store kept as the record so another app still agrees.

- Sim: role check, sending (SmsManager, waits for the radio), receiving,
  chunked import from content://sms and content://mms
- Pdu: MMS wire format (notification-ind, retrieve-conf, send-req, ack)
- SmsReceiver, MmsReceiver, MmsDownloaded, MmsFiles, RespondService,
  SendToActivity: what Android requires of a default SMS app
- The import no longer shares a lock with Config.get, which froze the screens
  on the first copy of a long history
2026-11-06 17:18:58 -08:00
trav cde8cc6c55 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.
2026-11-06 02:19:56 -08:00
travandClaude Opus 5 241a44f0ee voip.ms Messages: Signal-style desktop SMS client
Electron + React app that imports the full voip.ms SMS history into a
local SQLite/FTS5 database, polls for new messages, sends SMS, resolves
names/photos from GNOME EDS address books, and supports global and
per-chat search with jump-to-message.

Data lives in ~/Documents/voipms-desktop-data (covered by Deja Dup) with
daily consistent snapshots.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 21:25:12 -07:00
55 changed files with 409 additions and 957 deletions
-6
View File
@@ -6,9 +6,3 @@ dist/
# Android build output # Android build output
android/build/ android/build/
# Local only
CLAUDE.md
android/*.keystore
__pycache__/
scripts/relay.env
+39
View File
@@ -0,0 +1,39 @@
# bubble (voip.ms Messages)
Desktop SMS client (Electron, `src/`) plus its Rabbit R1 companion app
(plain Java, `android/`, see `android/README.md`).
## trav's data is off limits
Never read trav's messages, contacts, accounts or anything the apps keep
about him, and never screenshot the real app showing them. Standard:
`~/Documents/shared-resources/privacy.html`. If reading it seems necessary,
ask trav first, every time (what and why); one yes covers one look. No
exceptions granted so far.
Where his data lives:
- Desktop: `~/.config/voip.ms Messages/` (Electron userData: the message
database, settings, secrets, photo cache, ui-state.json).
- Rabbit R1: the private storage of `me.teafry.voipmessages`
(`files/messages.db`, `files/config.json`, `files/media/`,
`files/state*.json`). Don't `run-as` into it, and don't screenshot that app.
- Rabbit R1 SIM texts: Android's shared message store (`content://sms`,
`content://mms`, the telephony provider), which bubble reads and writes as
the default SMS app. Don't query it over adb, and don't make an app the
default SMS app yourself (it hands that app his texts).
- jai: `~/Documents/bubble-server/data/` (the relay's mailbox and token).
Everything in relay.db is sealed, but it's still his messages: don't read
it, and never print the token (`scripts/deploy-jai.sh --token` is for trav).
The desktop keeps the relay's address, token and key in
`~/.config/voip.ms Messages/relay.bin`.
Test with fake data only:
- Desktop: `VOIPMS_SANDBOX=/tmp/x npm run dev`.
- Relay: `server/test_bubble_relay.py` and `test/relay.test.ts` run a throwaway
local server; `DEVICE=1 npm test -- test/relay.device.test.ts` drives the dev
app on a plugged-in Rabbit through `adb reverse`. Never test against jai's.
- Android: the dev app `me.teafry.voipmessages.dev`
(`python3 android/build.py --dev --install`, then
`python3 android/tools/push_sandbox.py` for made-up conversations).
+101 -11
View File
@@ -1,20 +1,110 @@
# bubble # bubble
![bubble](docs/screenshot.png) A Signal Desktop–style SMS client for [voip.ms](https://voip.ms). It keeps your full message history on your own machine, lets you search it, and shows your GNOME contacts' names and photos.
A Signal-style desktop SMS/MMS client for [voip.ms](https://voip.ms) and Google Voice (Electron, Linux), plus a companion texting app for the Rabbit R1 (`android/`). ## Features
- Keeps your whole message history locally (SQLite), with full-text search - A conversation list on the left, with contact photos, previews, times, and unread badges. The chat opens on the right.
- Group chats, MMS, reactions, emoji shortcodes, GNOME contacts - A **full local copy of your history.** On first run the app imports everything from voip.ms, working backwards in 90-day windows, and picks up where it left off if interrupted. After that it checks for new messages every 30 seconds (you can change this).
- Optional relay server to sync with the Rabbit R1: it only ever holds sealed messages (`server/`, deployed with `scripts/deploy-relay.sh`) - **Search** everything from the sidebar (Ctrl+F). Results show a highlighted preview, and clicking one jumps to that exact message. You can also search inside a single chat (Ctrl+Shift+F), using Enter and Shift+Enter to step through the matches.
- **New chat** (Ctrl+N), with autocomplete from your contacts by name or number.
- Contacts are read-only, straight from GNOME's Evolution Data Server caches: your Nextcloud CardDAV books and anything else GNOME Contacts shows. They reload automatically when the books sync.
- Messages longer than 160 characters are split automatically. If a send fails, it's marked with Retry and Delete options.
- **MMS**: photos, video and audio appear inline in the chat. Click a photo to view it full size or save it. You can attach up to 3 files with the paperclip, by drag-and-drop, or by pasting. Photos too big for voip.ms (the budget is 900 KB each) are shrunk automatically before sending.
- **Emoji shortcodes**: type `:` and at least two letters, for example `:jo`, to get matching emoji. Pick one with ↑/↓ and Tab/Enter or by clicking it; Esc closes the list. A finished `:joy:` converts on its own. The shortcodes are Signal's and Slack's, from [emoji-datasource](https://github.com/iamcal/emoji-data); `npm run gen:emoji` regenerates them.
- Alt+↑/↓ moves between conversations.
- Ctrl +/− zooms and Ctrl 0 resets. Choose Light, Dark, or System under Settings → Appearance, and the dark or inverted (lighter) icon.
- **The Rabbit's SIM, from here** (Settings → Rabbit relay): with bubble as the Rabbit R1's texting app, its SIM is a third number to text from ("Rabbit SIM"), its texts show up here, and chat names and read/unread/archived stay in step with the Rabbit, no cable needed. It goes through a small relay on jai (`server/bubble_relay.py`, deployed with `scripts/deploy-jai.sh`), which only ever holds AES-256-GCM-sealed messages: the key lives on this computer and the Rabbit, never on jai. A text sent from here goes out at the Rabbit's next background check, so it can take a while; older photos come over when you open them.
## Run ## Where your data lives
| What | Where | Backed up? |
|---|---|---|
| Message database | `~/Documents/voipms-desktop-data/messages.db` | ✅ Déjà Dup covers `~/Documents` |
| Daily snapshots, last 7 kept | `~/Documents/voipms-desktop-data/snapshots/` | ✅ |
| Settings | `~/Documents/voipms-desktop-data/settings.json` | ✅ |
| MMS photos and attachments (cached on arrival) | `~/Documents/voipms-desktop-data/media/` | ✅ |
| API password | GNOME Keyring (via Electron `safeStorage`) → `~/.config/voipms-desktop/credentials.bin` | ❌ on purpose; you re-enter it after a restore |
| Contact photo cache | `~/.config/voipms-desktop/photo-cache/` | ❌ not needed |
| Rabbit relay address, token and key | GNOME Keyring → `~/.config/voip.ms Messages/relay.bin` | ❌ on purpose; reconnect and Sync to Rabbit after a restore |
The snapshots are consistent SQLite copies, made daily and whenever you quit. So even if a backup catches the live database halfway through a write, the backup still holds a clean, restorable copy. To move the data folder, go to Settings → Storage → Move…. If you point it at a folder that already holds a `messages.db`, for example one restored from backup, the app uses that history.
## Setup
In the voip.ms portal, go to **Main Menu → SOAP & REST/JSON API** and:
1. Enable the API.
2. Set an **API password**. This is separate from your login password.
3. Add your IP address under **Enable IP Addresses**.
Then launch the app and enter your account email and API password.
### The Rabbit relay (optional)
1. `scripts/deploy-jai.sh` puts the relay on jai (its own folder, port 8080 on the tailscale address only); `scripts/deploy-jai.sh --token` prints its token.
2. Settings → Rabbit relay: paste the token, Connect.
3. Plug in the Rabbit and press Sync to Rabbit once: that hands it the address, token and the sealing key.
### Apple-style emoji (optional)
To look like Signal, the app uses an `Apple Color Emoji` font when one is installed, and falls back to Noto Color Emoji otherwise. To install it for your user only (about 116 MB):
```sh ```sh
npm run deps:install # via sfw (npm i -g sfw) curl -L -o ~/.local/share/fonts/AppleColorEmoji.ttf \
VOIPMS_SANDBOX=/tmp/bubble-demo npm run dev # try it with made-up data https://github.com/samuelngs/apple-emoji-linux/releases/latest/download/AppleColorEmoji-Linux.ttf
npm run dev # real account: enter your voip.ms API login fc-cache -f
npm run install-desktop # build the AppImage + GNOME launcher
``` ```
voip.ms setup: Main Menu → SOAP & REST/JSON API → enable the API, set an API password, allow your IP. Alternatively, install the `fonts-apple-color-emoji.rpm` from the same release to make it available system-wide. Restart the app afterward.
## Development
Dependencies are installed through [Socket Firewall](https://docs.socket.dev/docs/socket-firewall-free)
(`sfw`), which checks every package, transitive ones included, against socket.dev
before npm downloads it. Install it once with `npm i -g sfw`, then use the
`deps:*` scripts instead of bare `npm install` (a Claude Code hook in
`.claude/` enforces this for Claude):
```bash
npm run deps:install # after cloning or pulling changes to package-lock.json
npm run deps:add -- pkg # add a package
npm run deps:update # update within package.json's ranges
```
```bash
npm run dev # run with hot reload
npm test # unit tests (run under Electron's Node for better-sqlite3)
npm run test:live # also reads your real EDS address books (read-only)
npm run typecheck
npm run install-desktop # build the AppImage and add a GNOME launcher
```
To try the app or work on the UI without going near your real account, run it
in a sandbox. Everything it uses (Electron profile, so no saved voip.ms password
or Google sign-in, plus settings and the message database) lives under the given
folder; it skips your address book and fills itself with made-up conversations,
1:1 and group, on a demo voip.ms number and a demo Google Voice number:
```bash
VOIPMS_SANDBOX=/tmp/voipms-sandbox npm run dev # or VOIPMS_DEMO=1, same folder
rm -rf /tmp/voipms-sandbox # start over
```
### Layout
```
src/main/ Electron main process
voipms.ts REST client (getDIDsInfo, getSMS, sendSMS)
sync.ts history backfill + polling
db.ts SQLite schema, FTS5 search, snapshots
contacts.ts EDS cache reader + vCard parser
secrets.ts keyring-encrypted credentials
settings.ts data folder + preferences
src/preload/ typed IPC bridge (window.api)
src/renderer/ React UI
src/shared/ types + phone-number helpers shared by both sides
resources/ icon, eds-sources.py (lists live EDS address books)
```
The message table already reserves `kind` and `media_json` columns for MMS support.
+3 -3
View File
@@ -87,7 +87,7 @@ Install/Sync buttons then target the dev app with the sandbox's made-up data.
side, through `MmsFiles`. Long texts go as multipart SMS; photos, voice notes side, through `MmsFiles`. Long texts go as multipart SMS; photos, voice notes
and group chats as MMS (needs mobile data on). The dev app's sandbox never and group chats as MMS (needs mobile data on). The dev app's sandbox never
uses the SIM. uses the SIM.
- Relay (`Relay`, `RelayJob`): the desktop's link through the relay server (its - Relay (`Relay`, `RelayJob`): the desktop's link through jai (its
`src/main/relay.ts`, server `server/bubble_relay.py`). config.json's `relay` `src/main/relay.ts`, server `server/bubble_relay.py`). config.json's `relay`
(address, token, AES-256-GCM key) comes from Sync to Rabbit. The SIM's (address, token, AES-256-GCM key) comes from Sync to Rabbit. The SIM's
messages go to the desktop, sends typed there go out here (each one at most messages go to the desktop, sends typed there go out here (each one at most
@@ -96,7 +96,7 @@ Install/Sync buttons then target the dev app with the sandbox's made-up data.
of its own: it rides along with `PollJob`'s checks, plus one network job a few of its own: it rides along with `PollJob`'s checks, plus one network job a few
seconds after something happens here (a text in, a send done, a swipe or seconds after something happens here (a text in, a send done, a swipe or
rename), and a catch-up when the app is opened (at most once a minute). Plain rename), and a catch-up when the app is opened (at most once a minute). Plain
http is allowed only to a tailscale (100.64/10) address and localhost http is allowed only to jai's tailscale address and localhost
(`Config`; `res/xml/network_security_config.xml` lets cleartext through). (`res/xml/network_security_config.xml`).
- The scroll wheel is left alone: it stays the volume control (and volume - The scroll wheel is left alone: it stays the volume control (and volume
down + the side button still takes a screenshot). down + the side button still takes a screenshot).
@@ -13,24 +13,23 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
/** /**
* Tap the paperclip and the composer swells upward into a bubble while * Hold the paperclip and the composer swells upward into a bubble while
* camera, photo and microphone (no microphone on a Google Voice chat, which * camera, photo and microphone (no microphone on a Google Voice chat, which
* can't send voice notes) float out from under the clip, jostle each * can't send voice notes) float out from under the clip, jostle each
* other apart and settle above and to the right of it. The next touch picks: * other apart and settle above and to the right of it. The thumb stays down:
* a soft spotlight follows the thumb inside the bubble, leans toward whichever * a soft spotlight follows it inside the bubble, leans toward whichever icon
* icon it's near (so it needn't be exact), and that icon gets a glowing blue * it's near (so it needn't be exact), and that icon gets a glowing blue ring.
* ring. Let go on one to attach that; let go on none and they all slip back * Let go on one to attach that; let go on none and they all slip back under
* under the clip as the bubble sinks. * the clip as the bubble sinks.
*
* <p>Not hold-and-drag from the clip: on the R1 the clip is in the bottom
* 48 dp, where a swipe up is the system's home gesture.
* *
* <p>The way out is a little physics: each icon is sprung to a home spot and * <p>The way out is a little physics: each icon is sprung to a home spot and
* the icons push each other away, launched a beat apart in nearly the same * the icons push each other away, launched a beat apart in nearly the same
* direction so they bump and fan out. The bubble's height just chases the * direction so they bump and fan out. The bubble's height just chases the
* icons. The way back is a plain ease-in, since they're only going away. * icons. The way back is a plain ease-in, since they're only going away.
* *
* <p>Lives on the window's decor while open and takes its touches itself. * <p>Lives on the window's decor while open; the paperclip's own touch
* listener feeds it ({@link #move}, {@link #release}) since the touch began there.
* After a quick tap ({@link #stay}) it takes the next touch itself instead.
*/ */
final class AttachBubble extends View { final class AttachBubble extends View {
interface OnPick { interface OnPick {
@@ -70,6 +69,7 @@ final class AttachBubble extends View {
private float width; // the bubble's right edge private float width; // the bubble's right edge
private float tx, ty; // the thumb private float tx, ty; // the thumb
private boolean touched; // the thumb has moved since the bubble opened private boolean touched; // the thumb has moved since the bubble opened
private boolean sticky; // opened by a tap: the next touch picks or closes
// Icon state, in dp from the clip's centre with y up. // Icon state, in dp from the clip's centre with y up.
private final float[] px = new float[3], py = new float[3], vx = new float[3], vy = new float[3]; private final float[] px = new float[3], py = new float[3], vx = new float[3], vy = new float[3];
@@ -134,7 +134,7 @@ final class AttachBubble extends View {
width = cx + (float) Math.cos(Math.toRadians(HOME_DEG[n - 1])) * HOME_DIST * dp + iconR + margin; width = cx + (float) Math.cos(Math.toRadians(HOME_DEG[n - 1])) * HOME_DIST * dp + iconR + margin;
tx = cx; tx = cx;
ty = cy; ty = cy;
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
invalidate(); invalidate();
} }
@@ -230,8 +230,18 @@ final class AttachBubble extends View {
if (pick >= 0) performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK); if (pick >= 0) performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK);
} }
boolean dragged() {
return touched;
}
/** Opened by a quick tap: stay out until the next touch. */
void stay() {
sticky = true;
}
@Override @Override
public boolean onTouchEvent(MotionEvent e) { public boolean onTouchEvent(MotionEvent e) {
if (!sticky) return true;
switch (e.getActionMasked()) { switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_MOVE:
@@ -39,6 +39,8 @@ public final class ChatActivity extends BaseActivity {
private static final int PICK = 1; private static final int PICK = 1;
private static final int VOICE = 2; private static final int VOICE = 2;
private static final int CAMERA = 3; private static final int CAMERA = 3;
/** A press on the paperclip shorter than this (ms), without dragging, is a tap: the bubble stays open. */
private static final int TAP_MS = 250;
private static final int MAX_PHOTOS = 3; private static final int MAX_PHOTOS = 3;
private String did, contact; private String did, contact;
@@ -46,7 +48,6 @@ public final class ChatActivity extends BaseActivity {
private ListView list; private ListView list;
private TextView titleView, subView, counter, attach, send; private TextView titleView, subView, counter, attach, send;
private EditText input; private EditText input;
private TextView unsentBanner;
private LinearLayout header, composerBox, tray, fromRow; private LinearLayout header, composerBox, tray, fromRow;
// The keyboard is up: the composer shrinks so what's being typed and the // The keyboard is up: the composer shrinks so what's being typed and the
// last few messages both fit above it (see setCompact). // last few messages both fit above it (see setCompact).
@@ -63,6 +64,8 @@ public final class ChatActivity extends BaseActivity {
// Audio playing in the list: one at a time, keyed "id/index". // Audio playing in the list: one at a time, keyed "id/index".
private android.media.MediaPlayer player; private android.media.MediaPlayer player;
private String playing; private String playing;
// The bubble while a press on the paperclip is feeding it.
private AttachBubble bubble;
// Where the camera is writing the photo it's taking. // Where the camera is writing the photo it's taking.
private Uri shot; private Uri shot;
@@ -107,21 +110,6 @@ public final class ChatActivity extends BaseActivity {
list.setAdapter(adapter); list.setAdapter(adapter);
root.addView(list, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1)); root.addView(list, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1));
// Texts here that didn't go out: never just a quiet line on a bubble.
unsentBanner = Ui.bold(Ui.text(this, "", Ui.T_SMALL, 0xFFFFFFFF));
unsentBanner.setBackgroundColor(Ui.DANGER);
unsentBanner.setPadding(Ui.dp(this, 32), Ui.dp(this, 16), Ui.dp(this, 32), Ui.dp(this, 16));
unsentBanner.setVisibility(View.GONE);
unsentBanner.setOnClickListener(v -> {
for (int i = 0; i < rows.size(); i++)
if (rows.get(i) instanceof Store.Msg && "failed".equals(((Store.Msg) rows.get(i)).status)) {
list.setSelection(i);
failedMenu((Store.Msg) rows.get(i));
return;
}
});
root.addView(unsentBanner);
root.addView(composer()); root.addView(composer());
setContentView(root); setContentView(root);
root.getViewTreeObserver().addOnGlobalLayoutListener(() -> { root.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
@@ -135,16 +123,23 @@ public final class ChatActivity extends BaseActivity {
/** /**
* The R1 has 640 px of height and the keyboard takes about half: with a * The R1 has 640 px of height and the keyboard takes about half: with a
* photo attached, the composer would push the text box under it. So * photo attached, the full-size composer would push the text box under
* while it's up, the photos shrink, the text box gives up a line and the * it. So while it's up, the photos, text and padding all shrink and the
* subtitle goes, leaving the text box and a few messages in view. (The * subtitle goes, leaving the text box and a few messages in view.
* composer itself is always the small size: see composer().)
*/ */
private void setCompact(boolean on) { private void setCompact(boolean on) {
compact = on; compact = on;
header.setPadding(Ui.dp(this, 24), Ui.dp(this, on ? 4 : 10), Ui.dp(this, 24), Ui.dp(this, on ? 4 : 10)); header.setPadding(Ui.dp(this, 24), Ui.dp(this, on ? 4 : 10), Ui.dp(this, 24), Ui.dp(this, on ? 4 : 10));
subView.setVisibility(on || subView.getText().length() == 0 ? View.GONE : View.VISIBLE); subView.setVisibility(on || subView.getText().length() == 0 ? View.GONE : View.VISIBLE);
composerBox.setPadding(Ui.dp(this, 12), Ui.dp(this, on ? 4 : 10), Ui.dp(this, 12), Ui.dp(this, on ? 4 : 10));
input.setTextSize(TypedValue.COMPLEX_UNIT_SP, on ? Ui.T_SMALL : Ui.T_BODY);
input.setPadding(Ui.dp(this, on ? 18 : 24), Ui.dp(this, on ? 8 : 14), Ui.dp(this, on ? 18 : 24), Ui.dp(this, on ? 8 : 14));
input.setMaxLines(on ? 3 : 4); input.setMaxLines(on ? 3 : 4);
for (TextView b : new TextView[] {attach, send}) {
b.setMinWidth(Ui.dp(this, on ? 60 : 80));
b.setMinHeight(Ui.dp(this, on ? 56 : 80));
b.setTextSize(TypedValue.COMPLEX_UNIT_SP, on ? 28 : 34);
}
for (int i = 0; i < tray.getChildCount(); i++) tray.getChildAt(i).setLayoutParams(thumbParams()); for (int i = 0; i < tray.getChildCount(); i++) tray.getChildAt(i).setLayoutParams(thumbParams());
if (on) list.post(this::showLatest); if (on) list.post(this::showLatest);
} }
@@ -170,9 +165,7 @@ public final class ChatActivity extends BaseActivity {
LinearLayout box = composerBox = new LinearLayout(this); LinearLayout box = composerBox = new LinearLayout(this);
box.setOrientation(LinearLayout.VERTICAL); box.setOrientation(LinearLayout.VERTICAL);
box.setBackgroundColor(Ui.PANEL); box.setBackgroundColor(Ui.PANEL);
// Always the compact size (it used to shrink only with the keyboard box.setPadding(Ui.dp(this, 12), Ui.dp(this, 10), Ui.dp(this, 12), Ui.dp(this, 10));
// up): the big one's padding was wasted on a 640 px screen.
box.setPadding(Ui.dp(this, 12), Ui.dp(this, 4), Ui.dp(this, 12), Ui.dp(this, 4));
// From-number picker, only for a conversation with nothing in it yet. // From-number picker, only for a conversation with nothing in it yet.
fromRow = new LinearLayout(this); fromRow = new LinearLayout(this);
@@ -190,23 +183,17 @@ public final class ChatActivity extends BaseActivity {
LinearLayout row = new LinearLayout(this); LinearLayout row = new LinearLayout(this);
row.setGravity(Gravity.BOTTOM); row.setGravity(Gravity.BOTTOM);
// Not lined up by text baseline: the attach/send glyphs have no text,
// and matching their empty baseline lifted the text box out the top
// of the composer, cut off.
row.setBaselineAligned(false);
attach = Ui.headerButton(this, Glyph.Kind.ATTACH); attach = Ui.headerButton(this, Glyph.Kind.ATTACH);
attach.setOnClickListener(v -> openAttach()); attach.setOnTouchListener((v, e) -> attachTouch(e));
compactButton(attach);
input = new EditText(this); input = new EditText(this);
input.setHint("Message"); input.setHint("Message");
input.setHintTextColor(Ui.MUTED); input.setHintTextColor(Ui.MUTED);
input.setTextColor(Ui.TEXT); input.setTextColor(Ui.TEXT);
input.setTextSize(TypedValue.COMPLEX_UNIT_SP, Ui.T_SMALL); input.setTextSize(TypedValue.COMPLEX_UNIT_SP, Ui.T_BODY);
input.setMaxLines(4); input.setMaxLines(4);
input.setBackground(Ui.input(this, 36)); input.setBackground(Ui.input(this, 36));
input.setPadding(Ui.dp(this, 18), Ui.dp(this, 8), Ui.dp(this, 18), Ui.dp(this, 8)); input.setPadding(Ui.dp(this, 24), Ui.dp(this, 14), Ui.dp(this, 24), Ui.dp(this, 14));
send = Ui.headerButton(this, Glyph.Kind.SEND, Ui.ACCENT); send = Ui.headerButton(this, Glyph.Kind.SEND, Ui.ACCENT);
compactButton(send);
send.setOnClickListener(v -> submit()); send.setOnClickListener(v -> submit());
row.addView(attach); row.addView(attach);
row.addView(input, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); row.addView(input, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
@@ -235,12 +222,6 @@ public final class ChatActivity extends BaseActivity {
return box; return box;
} }
private void compactButton(TextView b) {
b.setMinWidth(Ui.dp(this, 60));
b.setMinHeight(Ui.dp(this, 56));
b.setTextSize(TypedValue.COMPLEX_UNIT_SP, 28);
}
private android.content.SharedPreferences drafts() { private android.content.SharedPreferences drafts() {
return getSharedPreferences("drafts", MODE_PRIVATE); return getSharedPreferences("drafts", MODE_PRIVATE);
} }
@@ -262,7 +243,6 @@ public final class ChatActivity extends BaseActivity {
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
Notifier.clear(this, did, contact); Notifier.clear(this, did, contact);
Notifier.clearUnsent(this, did, contact);
} }
@Override @Override
@@ -327,11 +307,6 @@ public final class ChatActivity extends BaseActivity {
View firstView = list.getChildAt(0); View firstView = list.getChildAt(0);
Object anchor = !atBottom && firstPos < rows.size() ? rows.get(firstPos) : null; Object anchor = !atBottom && firstPos < rows.size() ? rows.get(firstPos) : null;
int anchorTop = firstView == null ? 0 : firstView.getTop(); int anchorTop = firstView == null ? 0 : firstView.getTop();
int unsent = 0;
for (Store.Msg m : msgs) if ("failed".equals(m.status)) unsent++;
unsentBanner.setVisibility(unsent > 0 ? View.VISIBLE : View.GONE);
unsentBanner.setText("⚠ " + (unsent > 1 ? unsent + " of your texts weren't sent." : "Your text wasn't sent.")
+ " Tap to retry, edit or delete.");
rows.clear(); rows.clear();
for (int i = 0; i < msgs.size(); i++) { for (int i = 0; i < msgs.size(); i++) {
Store.Msg m = msgs.get(i); Store.Msg m = msgs.get(i);
@@ -400,13 +375,33 @@ public final class ChatActivity extends BaseActivity {
} }
/** /**
* Tap the paperclip and the bubble opens; tap a choice, or anywhere else * Press the paperclip and the bubble is out at once: drag to a choice and
* to close it. Not hold-and-drag: the clip sits in the R1's bottom 48 dp, * let go. A quick tap leaves it open to tap a choice (or anywhere else to close).
* where a swipe up is the system's home gesture, and no app can opt out of that.
*/ */
private void openAttach() { private boolean attachTouch(android.view.MotionEvent e) {
switch (e.getActionMasked()) {
case android.view.MotionEvent.ACTION_DOWN:
attach.getParent().requestDisallowInterceptTouchEvent(true);
// Google Voice only lets apps send photos: no voice-note choice there. // Google Voice only lets apps send photos: no voice-note choice there.
new AttachBubble(this, attach, composerBox, !Config.get(this).isGv(did), this::attachKind).show(this); bubble = new AttachBubble(this, attach, composerBox, !Config.get(this).isGv(did), this::attachKind);
bubble.show(this);
return true;
case android.view.MotionEvent.ACTION_MOVE:
if (bubble != null) bubble.move(e.getRawX(), e.getRawY());
return true;
case android.view.MotionEvent.ACTION_UP:
if (bubble == null) return true;
if (e.getEventTime() - e.getDownTime() < TAP_MS && !bubble.dragged()) bubble.stay();
else bubble.release();
bubble = null;
return true;
case android.view.MotionEvent.ACTION_CANCEL:
if (bubble != null) bubble.dismiss();
bubble = null;
return true;
default:
return true;
}
} }
private void attachKind(int which) { private void attachKind(int which) {
@@ -666,8 +661,7 @@ public final class ChatActivity extends BaseActivity {
bubble.addView(media); bubble.addView(media);
bubble.addView(body); bubble.addView(body);
bubble.addView(meta); bubble.addView(meta);
failed = Ui.bold(Ui.text(c, "", Ui.T_SMALL, Ui.DANGER)); failed = Ui.text(c, "", Ui.T_TINY, Ui.DANGER);
failed.setPadding(Ui.dp(c, 14), Ui.dp(c, 6), Ui.dp(c, 14), Ui.dp(c, 6));
reacts = Ui.text(c, "", Ui.T_SMALL, Ui.TEXT); reacts = Ui.text(c, "", Ui.T_SMALL, Ui.TEXT);
reacts.setBackground(Ui.round(Ui.BUBBLE_IN, Ui.dp(c, 30))); reacts.setBackground(Ui.round(Ui.BUBBLE_IN, Ui.dp(c, 30)));
reacts.setPadding(Ui.dp(c, 14), Ui.dp(c, 4), Ui.dp(c, 14), Ui.dp(c, 4)); reacts.setPadding(Ui.dp(c, 14), Ui.dp(c, 4), Ui.dp(c, 14), Ui.dp(c, 4));
@@ -703,11 +697,7 @@ public final class ChatActivity extends BaseActivity {
setGravity(out ? Gravity.END : Gravity.START); setGravity(out ? Gravity.END : Gravity.START);
((LayoutParams) bubble.getLayoutParams()).gravity = out ? Gravity.END : Gravity.START; ((LayoutParams) bubble.getLayoutParams()).gravity = out ? Gravity.END : Gravity.START;
bubble.setBackground(Ui.round(out ? Ui.ACCENT : Ui.BUBBLE_IN, Ui.dp(c, 30))); bubble.setBackground(Ui.round(out ? Ui.ACCENT : Ui.BUBBLE_IN, Ui.dp(c, 30)));
if ("failed".equals(msg.status)) { bubble.setAlpha("failed".equals(msg.status) ? 0.6f : 1f);
android.graphics.drawable.GradientDrawable g = Ui.round(Ui.ACCENT, Ui.dp(c, 30));
g.setStroke(Ui.dp(c, 4), Ui.DANGER);
bubble.setBackground(g);
}
bubble.setMinimumWidth(0); bubble.setMinimumWidth(0);
// Keep bubbles to ~80% of the width. // Keep bubbles to ~80% of the width.
body.setMaxWidth(Math.round(getResources().getDisplayMetrics().widthPixels * 0.72f)); body.setMaxWidth(Math.round(getResources().getDisplayMetrics().widthPixels * 0.72f));
@@ -720,8 +710,7 @@ public final class ChatActivity extends BaseActivity {
meta.setTextColor(out ? 0xB3FFFFFF : Ui.MUTED); meta.setTextColor(out ? 0xB3FFFFFF : Ui.MUTED);
Ui.glyph(meta, "pending".equals(msg.status) ? Glyph.Kind.CLOCK : null, true); Ui.glyph(meta, "pending".equals(msg.status) ? Glyph.Kind.CLOCK : null, true);
failed.setVisibility("failed".equals(msg.status) ? VISIBLE : GONE); failed.setVisibility("failed".equals(msg.status) ? VISIBLE : GONE);
failed.setText("⚠ Not sent. " + (msg.error != null ? msg.error + " " : "") + "Tap to retry, edit or delete."); failed.setText("⚠ Not sent" + (msg.error != null ? ": " + msg.error : "") + " · tap to retry");
failed.setGravity(out ? Gravity.END : Gravity.START);
List<Reactions.Reaction> rs = reactions.get(msg.id); List<Reactions.Reaction> rs = reactions.get(msg.id);
reacts.setVisibility(rs == null ? GONE : VISIBLE); reacts.setVisibility(rs == null ? GONE : VISIBLE);
if (rs != null) { if (rs != null) {
@@ -758,14 +747,6 @@ public final class ChatActivity extends BaseActivity {
ImageView iv = new ImageView(c); ImageView iv = new ImageView(c);
iv.setScaleType(ImageView.ScaleType.CENTER_CROP); iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setBackgroundColor(0x22FFFFFF); iv.setBackgroundColor(0x22FFFFFF);
// The picture's corners match the bubble's (30 dp).
float corner = Ui.dp(c, 30);
iv.setOutlineProvider(new android.view.ViewOutlineProvider() {
@Override public void getOutline(View v, android.graphics.Outline o) {
o.setRoundRect(0, 0, v.getWidth(), v.getHeight(), corner);
}
});
iv.setClipToOutline(true);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(bw, bh); FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(bw, bh);
iv.setLayoutParams(new LinearLayout.LayoutParams(bw, bh)); iv.setLayoutParams(new LinearLayout.LayoutParams(bw, bh));
String tag = id + "/" + index; String tag = id + "/" + index;
@@ -889,33 +870,7 @@ public final class ChatActivity extends BaseActivity {
Store.get(this).deleteMessage(m.id); Store.get(this).deleteMessage(m.id);
changed(); changed();
}) })
.setNeutralButton("Edit", (d, w) -> editFailed(m)) .setNeutralButton("Cancel", null)
.show(); .show();
} }
/**
* Back into the box to change before sending again: its words (and
* photos) go into the composer and the failed copy goes. A voice note
* can't be edited, so it just goes back to Retry.
*/
private void editFailed(Store.Msg m) {
List<Sender.Photo> back = new ArrayList<>();
for (JSONObject ref : m.media()) {
String mime = ref.optString("mime");
if (!mime.startsWith("image/")) {
Toast.makeText(this, "A voice note can't be edited: retry or delete it.", Toast.LENGTH_LONG).show();
return;
}
back.add(new Sender.Photo(ref.optString("file"), mime, ref.optInt("width"), ref.optInt("height")));
}
String cur = input.getText().toString();
input.setText(cur.trim().isEmpty() ? m.body : m.body + "\n" + cur);
input.setSelection(input.getText().length());
for (Sender.Photo p : back) addToTray(p);
input.requestFocus();
MainActivity.bg.execute(() -> {
Store.get(this).deleteMessage(m.id);
changed();
});
}
} }
@@ -53,7 +53,7 @@ final class Config {
final List<Did> dids = new CopyOnWriteArrayList<>(); final List<Did> dids = new CopyOnWriteArrayList<>();
private boolean hasSim; private boolean hasSim;
String defaultDid; String defaultDid;
/** The relay server (Relay.java): address, bearer token, and the 32-byte key that seals everything. */ /** The relay through jai (Relay.java): address, bearer token, and the 32-byte key that seals everything. */
String relayUrl, relayToken; String relayUrl, relayToken;
byte[] relayKey; byte[] relayKey;
/** Made-up data for testing (android/tools/push_sandbox.py): never goes online. */ /** Made-up data for testing (android/tools/push_sandbox.py): never goes online. */
@@ -127,8 +127,8 @@ final class Config {
if (r != null) { if (r != null) {
String url = r.optString("url", ""), token = r.optString("token", ""); String url = r.optString("url", ""), token = r.optString("token", "");
byte[] key = android.util.Base64.decode(r.optString("key", ""), android.util.Base64.DEFAULT); byte[] key = android.util.Base64.decode(r.optString("key", ""), android.util.Base64.DEFAULT);
// Plain http only to a tailscale (100.64/10) address or localhost, as the desktop allows, and a real key. // Only the addresses network_security_config lets through, and a real key.
if (url.matches("http://(100\\.(6[4-9]|[7-9]\\d|1[01]\\d|12[0-7])\\.\\d+\\.\\d+|127\\.0\\.0\\.1)(:\\d+)?|https://[^/]+") && !token.isEmpty() && key.length == 32) { if (url.matches("http://(100\\.\\d+\\.\\d+\\.\\d+|127\\.0\\.0\\.1)(:\\d+)?|https://[^/]+") && !token.isEmpty() && key.length == 32) {
cfg.relayUrl = url; cfg.relayUrl = url;
cfg.relayToken = token; cfg.relayToken = token;
cfg.relayKey = key; cfg.relayKey = key;
@@ -430,21 +430,11 @@ public final class MainActivity extends BaseActivity {
String body = reaction != null ? reaction : c.lastBody == null ? "" : c.lastBody.replaceAll("\\s+", " ").trim(); String body = reaction != null ? reaction : c.lastBody == null ? "" : c.lastBody.replaceAll("\\s+", " ").trim();
if (body.isEmpty() && c.lastMediaJson != null) body = "Photo"; if (body.isEmpty() && c.lastMediaJson != null) body = "Photo";
String who = "out".equals(c.lastDirection) ? "You: " : group && c.lastSender != null ? Contacts.firstName(ctx, c.lastSender) + ": " : ""; String who = "out".equals(c.lastDirection) ? "You: " : group && c.lastSender != null ? Contacts.firstName(ctx, c.lastSender) + ": " : "";
boolean unread = c.unread > 0 || c.markedUnread;
if (c.failed > 0) {
// A text here didn't go out: red, ahead of everything else.
preview.setText("Not sent · " + who + body);
preview.setTextColor(Ui.DANGER);
badge.setVisibility(VISIBLE);
badge.setText("!");
badge.setBackground(Ui.round(Ui.DANGER, Ui.dp(ctx, 20)));
} else {
preview.setText(who + body); preview.setText(who + body);
boolean unread = c.unread > 0 || c.markedUnread;
preview.setTextColor(unread ? Ui.TEXT : Ui.MUTED); preview.setTextColor(unread ? Ui.TEXT : Ui.MUTED);
badge.setVisibility(unread ? VISIBLE : GONE); badge.setVisibility(unread ? VISIBLE : GONE);
badge.setText(c.unread > 99 ? "99+" : c.unread > 0 ? String.valueOf(c.unread) : "•"); badge.setText(c.unread > 99 ? "99+" : c.unread > 0 ? String.valueOf(c.unread) : "•");
badge.setBackground(Ui.round(Ui.ACCENT, Ui.dp(ctx, 20)));
}
via.setText(Config.get(ctx).dids.size() > 1 ? Ui.via(ctx, c.did) : ""); via.setText(Config.get(ctx).dids.size() > 1 ? Ui.via(ctx, c.did) : "");
via.setVisibility(Config.get(ctx).dids.size() > 1 ? VISIBLE : GONE); via.setVisibility(Config.get(ctx).dids.size() > 1 ? VISIBLE : GONE);
} }
@@ -19,7 +19,6 @@ final class Notifier {
private Notifier() {} private Notifier() {}
private static final String CHANNEL = "messages"; private static final String CHANNEL = "messages";
private static final String UNSENT = "unsent";
// Only messages this recent notify (not a big catch-up after being offline). // Only messages this recent notify (not a big catch-up after being offline).
private static final long RECENT = 6 * 60 * 60_000L; private static final long RECENT = 6 * 60 * 60_000L;
@@ -66,44 +65,6 @@ final class Notifier {
c.getSystemService(NotificationManager.class).cancel((did + contact).hashCode()); c.getSystemService(NotificationManager.class).cancel((did + contact).hashCode());
} }
/**
* Your text didn't go out. Its own channel, whatever the notification
* setting and even with a screen in front: a send that fails quietly is
* the worst thing a phone can do. Do Not Disturb still applies.
*/
static void notifyUnsent(Context c, List<Store.Msg> msgs) {
NotificationManager nm = c.getSystemService(NotificationManager.class);
nm.createNotificationChannel(new NotificationChannel(UNSENT, "Texts that didn't send", NotificationManager.IMPORTANCE_HIGH));
Map<String, List<Store.Msg>> byConv = new LinkedHashMap<>();
for (Store.Msg m : msgs) byConv.computeIfAbsent(m.did + "\n" + m.contact, k -> new ArrayList<>()).add(m);
Store store = Store.get(c);
for (List<Store.Msg> list : byConv.values()) {
Store.Msg first = list.get(0);
String who = Contacts.title(c, first.contact, store.getName(first.did, first.contact));
String title = list.size() > 1 ? list.size() + " texts to " + who + " weren't sent" : "Text to " + who + " wasn't sent";
String preview = first.body.trim().isEmpty() ? "Your message" : "“" + first.body.trim() + "”";
String body = list.size() > 1 ? "Open the chat to retry, edit or delete them."
: preview + " · " + (first.error != null ? first.error : "Open the chat to retry it.");
int id = ("unsent" + first.did + first.contact).hashCode();
PendingIntent pi = PendingIntent.getActivity(c, id, ChatActivity.intent(c, first.did, first.contact),
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
nm.notify(id, new Notification.Builder(c, UNSENT)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setStyle(new Notification.BigTextStyle().bigText(body))
.setShowWhen(true)
.setAutoCancel(true)
.setContentIntent(pi)
.build());
}
}
/** The chat's open, and its banner says the same. */
static void clearUnsent(Context c, String did, String contact) {
c.getSystemService(NotificationManager.class).cancel(("unsent" + did + contact).hashCode());
}
private static Bundle conversation(String did, String contact) { private static Bundle conversation(String did, String contact) {
Bundle b = new Bundle(); Bundle b = new Bundle();
b.putString("did", did); b.putString("did", did);
@@ -28,13 +28,13 @@ import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
/** /**
* The relay server (the desktop's src/main/relay.ts; server in * The relay through jai (the desktop's src/main/relay.ts; server in
* server/bubble_relay.py): the SIM's texts go to the desktop, texts typed * server/bubble_relay.py): the SIM's texts go to the desktop, texts typed
* there go out over the SIM here, and chat names and read/unread/archived * there go out over the SIM here, and chat names and read/unread/archived
* stay in step without a cable. * stay in step without a cable.
* *
* Everything is AES-256-GCM sealed with the key the desktop handed over USB * Everything is AES-256-GCM sealed with the key the desktop handed over USB
* (config.json "relay"); the relay server only passes blobs on. It runs with the checks * (config.json "relay"); jai only passes blobs on. It runs with the checks
* the Rabbit already makes (PollJob) plus one network job after something * the Rabbit already makes (PollJob) plus one network job after something
* happens here (a text, a send, a swipe), never on a timer of its own: the * happens here (a text, a send, a swipe), never on a timer of its own: the
* battery pays for nothing new while nothing's going on. * battery pays for nothing new while nothing's going on.
@@ -141,7 +141,7 @@ final class Relay {
// ---- one sync ---- // ---- one sync ----
/** One round with the relay server (more while there's more). Off the main thread; quiet when it's unreachable. */ /** One round with jai (more while there's more). Off the main thread; quiet when jai's unreachable. */
static void sync(Context c) { static void sync(Context c) {
Config cfg = Config.get(c); Config cfg = Config.get(c);
if (!configured(cfg)) return; if (!configured(cfg)) return;
@@ -241,11 +241,11 @@ final class Relay {
h.put("Authorization", "Bearer " + cfg.relayToken); h.put("Authorization", "Bearer " + cfg.relayToken);
h.put("Content-Type", "application/json"); h.put("Content-Type", "application/json");
Http.Response r = Http.request("POST", cfg.relayUrl + "/sync", h, body, 120_000); Http.Response r = Http.request("POST", cfg.relayUrl + "/sync", h, body, 120_000);
if (r.status == 401) throw new Exception("The relay server turned down the token (Sync to Rabbit from the desktop again)"); if (r.status == 401) throw new Exception("jai turned down the token (Sync to Rabbit from the desktop again)");
if (r.status != 200) throw new Exception("The relay server answered " + r.status); if (r.status != 200) throw new Exception("jai answered " + r.status);
JSONObject res = new JSONObject(new String(r.body, StandardCharsets.UTF_8)); JSONObject res = new JSONObject(new String(r.body, StandardCharsets.UTF_8));
// The relay server has them now. // jai has them now.
if (resultsPushed > 0) takeList(c, "results", resultsPushed); if (resultsPushed > 0) takeList(c, "results", resultsPushed);
if (wantsDone > 0) takeList(c, "wants", wantsDone); if (wantsDone > 0) takeList(c, "wants", wantsDone);
SharedPreferences.Editor ed = p.edit().putLong("smsLast", newSms[0]).putLong("mmsLast", newMms[0]); SharedPreferences.Editor ed = p.edit().putLong("smsLast", newSms[0]).putLong("mmsLast", newMms[0]);
@@ -346,7 +346,6 @@ final class Relay {
} }
private static void result(Context c, String id, long msgId, String error) { private static void result(Context c, String id, long msgId, String error) {
inflight(c, id, 0);
try { try {
JSONObject o = new JSONObject().put("t", "sent").put("id", id); JSONObject o = new JSONObject().put("t", "sent").put("id", id);
o.put("msgId", msgId != 0 ? msgId : JSONObject.NULL); o.put("msgId", msgId != 0 ? msgId : JSONObject.NULL);
@@ -395,44 +394,6 @@ final class Relay {
result(c, id, 0, "It was empty."); result(c, id, 0, "It was empty.");
return; return;
} }
long temp = Sender.send(c, Sim.DID, contact, text, photos, (msgId, error) -> result(c, id, msgId, error)); Sender.send(c, Sim.DID, contact, text, photos, (msgId, error) -> result(c, id, msgId, error));
// Until its result is posted: if this process dies first, the next one
// still answers the desktop (orphaned), so it never waits forever.
if (temp < 0) inflight(c, id, temp);
}
/** Remember (tempId < 0) or forget (0) the local message a desktop send became. */
private static synchronized void inflight(Context c, String id, long tempId) {
SharedPreferences p = prefs(c);
Set<String> s = new HashSet<>(p.getStringSet("inflight", new HashSet<>()));
s.removeIf(e -> e.startsWith(id + "\t"));
if (tempId < 0) s.add(id + "\t" + tempId);
p.edit().putStringSet("inflight", s).commit();
}
/**
* Sends an earlier process left unfinished: those the desktop asked for are
* reported back to it as failed (it alerts there). Returns the others.
*/
static List<Store.Msg> orphaned(Context c, List<Store.Msg> orphans) {
Map<Long, String> byTemp = new HashMap<>();
synchronized (Relay.class) {
for (String e : prefs(c).getStringSet("inflight", new HashSet<>())) {
int tab = e.indexOf('\t');
try {
byTemp.put(Long.parseLong(e.substring(tab + 1)), e.substring(0, tab));
} catch (Exception ignored) {
}
}
// Whatever isn't an orphan finished (or will be answered by this process).
prefs(c).edit().remove("inflight").commit();
}
List<Store.Msg> mine = new ArrayList<>();
for (Store.Msg m : orphans) {
String id = byTemp.get(m.id);
if (id == null) mine.add(m);
else result(c, id, 0, m.error);
}
return mine;
} }
} }
@@ -69,12 +69,7 @@ final class Sender {
send(ctx, did, contact, text, photos, null); send(ctx, did, contact, text, photos, null);
} }
/** static void send(Context ctx, String did, String contact, String text, List<Photo> photos, Done done) {
* Returns the local id of the (first) pending message. With `done` (the
* desktop's sends over the relay) the outcome goes back to whoever asked,
* who alerts on failure; without, a failure notifies here.
*/
static long send(Context ctx, String did, String contact, String text, List<Photo> photos, Done done) {
Context c = ctx.getApplicationContext(); Context c = ctx.getApplicationContext();
Config cfg = Config.get(c); Config cfg = Config.get(c);
if (cfg.sandbox) { if (cfg.sandbox) {
@@ -86,13 +81,12 @@ final class Sender {
store.confirmPending(id, real); store.confirmPending(id, real);
Sync.changed(); Sync.changed();
if (done != null) done.done(real, null); if (done != null) done.done(real, null);
return real; return;
} }
if (cfg.isGv(did)) { if (cfg.isGv(did)) {
if (photos.isEmpty()) { if (photos.isEmpty()) {
return enqueue(c, pending(did, contact, text, null), () -> gvSend(c, did, contact, text, null), true, done); enqueue(c, pending(did, contact, text, null), () -> gvSend(c, did, contact, text, null), true, done);
} else { } else {
long first = 0;
// Google Voice carries one photo per message: the text rides with the first. // Google Voice carries one photo per message: the text rides with the first.
for (int i = 0; i < photos.size(); i++) { for (int i = 0; i < photos.size(); i++) {
String body = i == 0 ? text : ""; String body = i == 0 ? text : "";
@@ -101,27 +95,26 @@ final class Sender {
one.add(p); one.add(p);
Store.Msg m = pending(did, contact, body, one); Store.Msg m = pending(did, contact, body, one);
m.ts += i; m.ts += i;
long id = enqueue(c, m, () -> gvSend(c, did, contact, body, p), true, i == 0 ? done : null); enqueue(c, m, () -> gvSend(c, did, contact, body, p), true, i == 0 ? done : null);
if (i == 0) first = id;
} }
return first;
} }
return;
} }
if (Sim.isSim(did)) { if (Sim.isSim(did)) {
// A long text goes as several SMS parts; photos, voice notes and groups as one MMS. // A long text goes as several SMS parts; photos, voice notes and groups as one MMS.
boolean mms = !photos.isEmpty() || Phone.isGroup(contact); boolean mms = !photos.isEmpty() || Phone.isGroup(contact);
Store.Msg m = pending(did, contact, text, photos); Store.Msg m = pending(did, contact, text, photos);
if (mms) m.kind = "mms"; if (mms) m.kind = "mms";
Done told = (id, err) -> { enqueue(c, m, () -> mms ? Sim.sendMms(c, contact, text, photos) : Sim.sendSms(c, contact, text), false, (id, err) -> {
if (done != null) done.done(id, err); if (done != null) done.done(id, err);
Relay.soon(c); // the desktop hears about it on the next round Relay.soon(c); // the desktop hears about it on the next round
}; });
return enqueue(c, m, () -> mms ? Sim.sendMms(c, contact, text, photos) : Sim.sendSms(c, contact, text), false, told, done == null); return;
} }
boolean mms = !photos.isEmpty() || Phone.charCount(text) > Phone.SMS_TEXT_LIMIT; boolean mms = !photos.isEmpty() || Phone.charCount(text) > Phone.SMS_TEXT_LIMIT;
Store.Msg m = pending(did, contact, text, photos); Store.Msg m = pending(did, contact, text, photos);
if (mms) m.kind = "mms"; if (mms) m.kind = "mms";
return enqueue(c, m, () -> { enqueue(c, m, () -> {
VoipMs api = new VoipMs(cfg.voipUser, cfg.voipPass); VoipMs api = new VoipMs(cfg.voipUser, cfg.voipPass);
if (!mms) return api.sendSms(did, contact, text); if (!mms) return api.sendSms(did, contact, text);
List<String> media = new ArrayList<>(); List<String> media = new ArrayList<>();
@@ -147,11 +140,7 @@ final class Sender {
return m; return m;
} }
private static long enqueue(Context c, Store.Msg m, Attempt attempt, boolean gv, Done done) { private static void enqueue(Context c, Store.Msg m, Attempt attempt, boolean gv, Done done) {
return enqueue(c, m, attempt, gv, done, done == null);
}
private static long enqueue(Context c, Store.Msg m, Attempt attempt, boolean gv, Done done, boolean alert) {
Store store = Store.get(c); Store store = Store.get(c);
long tempId = store.insertPending(m); long tempId = store.insertPending(m);
Sync.changed(); Sync.changed();
@@ -160,28 +149,7 @@ final class Sender {
String error = deliver(c, store, tempId, attempt, gv, id); String error = deliver(c, store, tempId, attempt, gv, id);
Sync.changed(); Sync.changed();
if (done != null) done.done(id[0], error); if (done != null) done.done(id[0], error);
Store.Msg after = store.getMessage(tempId);
if (alert && after != null && "failed".equals(after.status)) {
List<Store.Msg> one = new ArrayList<>();
one.add(after);
Notifier.notifyUnsent(c, one);
}
}); });
return tempId;
}
/**
* At startup, the sends an earlier process left unfinished (already marked
* failed): the desktop's go back to it as failed, the rest notify here.
*/
static void recover(Context c, List<Store.Msg> orphans) {
if (orphans.isEmpty()) return;
// Now, before this process's own sends add to the relay's in-flight list.
List<Store.Msg> mine = Relay.orphaned(c, orphans);
new Thread(() -> {
if (!mine.isEmpty()) Notifier.notifyUnsent(c, mine);
Sync.changed();
}, "recover-sends").start();
} }
/** Null when it went out (its id in id[0]), else why not. */ /** Null when it went out (its id in id[0]), else why not. */
@@ -144,7 +144,7 @@ public final class SettingsActivity extends BaseActivity {
} }
if (Relay.configured(cfg)) { if (Relay.configured(cfg)) {
section("Relay server"); section("Relay (jai)");
kv("Desktop link", Relay.status(c)); kv("Desktop link", Relay.status(c));
note("Texts typed on the desktop for \"via SIM\" go out at this Rabbit's background check, and chat names and read status" note("Texts typed on the desktop for \"via SIM\" go out at this Rabbit's background check, and chat names and read status"
+ " go both ways. Sealed with a key only the desktop and this Rabbit have."); + " go both ways. Sealed with a key only the desktop and this Rabbit have.");
@@ -29,11 +29,7 @@ final class Store {
private static final long MATCH_AFTER = 15 * 60_000L; private static final long MATCH_AFTER = 15 * 60_000L;
static synchronized Store get(Context c) { static synchronized Store get(Context c) {
if (instance == null) { if (instance == null) instance = new Store(c.getApplicationContext());
instance = new Store(c.getApplicationContext());
// A new process: any send still 'pending' belonged to one that died.
Sender.recover(c.getApplicationContext(), instance.failOrphanedSends());
}
return instance; return instance;
} }
@@ -100,11 +96,6 @@ final class Store {
db.execSQL("UPDATE messages SET body = '' WHERE media_json IS NOT NULL AND lower(trim(body)) = 'mms received'"); db.execSQL("UPDATE messages SET body = '' WHERE media_json IS NOT NULL AND lower(trim(body)) = 'mms received'");
set("mms_received_stripped", "1"); set("mms_received_stripped", "1");
} }
// ...and one we sent with no words "MMS Sent".
if (get("mms_sent_stripped") == null) {
db.execSQL("UPDATE messages SET body = '' WHERE media_json IS NOT NULL AND lower(trim(body)) = 'mms sent'");
set("mms_sent_stripped", "1");
}
if (get("unread_floor") == null) set("unread_floor", String.valueOf(System.currentTimeMillis())); if (get("unread_floor") == null) set("unread_floor", String.valueOf(System.currentTimeMillis()));
} }
@@ -226,32 +217,6 @@ final class Store {
db.execSQL("UPDATE messages SET status = 'failed', error = ? WHERE id = ?", new Object[] {error, tempId}); db.execSQL("UPDATE messages SET status = 'failed', error = ? WHERE id = ?", new Object[] {error, tempId});
} }
/**
* Sends left 'pending' by an earlier process (Android killed it, or it
* crashed, mid-send): their send loop died with it, so nothing will ever
* finish them. They become failed, shown as Not sent with Retry, never
* resent on their own (by now they may be stale). If one did go out, the
* next check still replaces it (reconcileSent matches failed rows too).
*/
List<Msg> failOrphanedSends() {
List<Long> ids = new ArrayList<>();
try (Cursor c = db.rawQuery("SELECT id FROM messages WHERE id < 0 AND status = 'pending' AND direction = 'out'", null)) {
while (c.moveToNext()) ids.add(c.getLong(0));
}
List<Msg> out = new ArrayList<>();
for (long id : ids) {
Msg m = getMessage(id);
if (m == null) continue;
// A SIM text may already be with the radio, which sends it whether or not we're alive.
markFailed(id, Sim.isSim(m.did) ? ORPHAN_SIM : ORPHAN);
out.add(getMessage(id));
}
return out;
}
static final String ORPHAN = "bubble stopped before this finished sending, so it most likely didn't go out.";
static final String ORPHAN_SIM = "bubble stopped before the SIM said whether this went out. Check before retrying.";
/** Sent messages that turned up in a poll replace our pending/failed copies. */ /** Sent messages that turned up in a poll replace our pending/failed copies. */
void reconcileSent(List<Msg> added) { void reconcileSent(List<Msg> added) {
List<Msg> sorted = new ArrayList<>(added); List<Msg> sorted = new ArrayList<>(added);
@@ -338,7 +303,6 @@ final class Store {
String did, contact, lastBody, lastDirection, lastSender, lastMediaJson, name; String did, contact, lastBody, lastDirection, lastSender, lastMediaJson, name;
long lastTs; long lastTs;
int unread; int unread;
int failed; // your texts here that didn't send
boolean archived, markedUnread; boolean archived, markedUnread;
} }
@@ -350,8 +314,7 @@ final class Store {
+ " SELECT l.did, l.contact, l.mts, last.body, last.direction, last.sender, last.media_json," + " SELECT l.did, l.contact, l.mts, last.body, last.direction, last.sender, last.media_json,"
+ " (SELECT COUNT(*) FROM messages m WHERE m.did = l.did AND m.contact = l.contact AND m.direction = 'in'" + " (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), CAST(? AS INTEGER)))," + " AND m.ts > MAX(COALESCE(r.last_read_ts, 0), CAST(? AS INTEGER))),"
+ " r.archived_at IS NOT NULL, COALESCE(r.marked_unread, 0), r.name," + " r.archived_at IS NOT NULL, COALESCE(r.marked_unread, 0), r.name"
+ " (SELECT COUNT(*) FROM messages m WHERE m.did = l.did AND m.contact = l.contact AND m.id < 0 AND m.status = 'failed')"
+ " FROM latest l JOIN messages last ON last.id =" + " 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)" + " (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" + " LEFT JOIN read_state r ON r.did = l.did AND r.contact = l.contact"
@@ -370,7 +333,6 @@ final class Store {
v.archived = c.getInt(8) != 0; v.archived = c.getInt(8) != 0;
v.markedUnread = c.getInt(9) != 0; v.markedUnread = c.getInt(9) != 0;
v.name = c.getString(10); v.name = c.getString(10);
v.failed = c.getInt(11);
if (archived == null || v.archived == archived) out.add(v); if (archived == null || v.archived == archived) out.add(v);
} }
} }
@@ -127,7 +127,7 @@ final class VoipMs {
for (String u : urls) refs.put(new JSONObject().put("url", u)); for (String u : urls) refs.put(new JSONObject().put("url", u));
m.mediaJson = refs.toString(); m.mediaJson = refs.toString();
// voip.ms's own stand-in text for a picture with no words, not the sender's. // voip.ms's own stand-in text for a picture with no words, not the sender's.
if (m.body.trim().equalsIgnoreCase("MMS Received") || m.body.trim().equalsIgnoreCase("MMS Sent")) m.body = ""; if (m.body.trim().equalsIgnoreCase("MMS Received")) m.body = "";
} else if (Phone.charCount(m.body) > Phone.SMS_TEXT_LIMIT) { } else if (Phone.charCount(m.body) > Phone.SMS_TEXT_LIMIT) {
m.kind = "mms"; m.kind = "mms";
} }
@@ -1,9 +1,11 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- Everything is https, except the relay server over tailscale (WireGuard <!-- Everything is https, except the relay on jai over tailscale (WireGuard
already encrypts that hop, and what it carries is sealed: Relay.java) and already encrypts that hop, and what it carries is sealed: Relay.java) and
localhost for testing it with adb reverse. Its address is a setting, so localhost for testing it with adb reverse. -->
cleartext can't be pinned to it here: Config only accepts http:// for a
tailscale (100.64/10) address or 127.0.0.1, and nothing else uses http. -->
<network-security-config> <network-security-config>
<base-config cleartextTrafficPermitted="true" /> <base-config cleartextTrafficPermitted="false" />
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">100.69.139.40</domain>
<domain includeSubdomains="false">127.0.0.1</domain>
</domain-config>
</network-security-config> </network-security-config>
+2 -2
View File
@@ -26,8 +26,8 @@ import sys
import zipfile import zipfile
from pathlib import Path from pathlib import Path
VERSION_NAME = "0.7.9" VERSION_NAME = "0.7.3"
VERSION_CODE = 17 VERSION_CODE = 11
PACKAGE = "me.teafry.voipmessages" PACKAGE = "me.teafry.voipmessages"
DEV_PACKAGE = PACKAGE + ".dev" DEV_PACKAGE = PACKAGE + ".dev"
-16
View File
@@ -17,9 +17,7 @@ import json
import os import os
import sqlite3 import sqlite3
import subprocess import subprocess
import struct
import tempfile import tempfile
import zlib
import time import time
from pathlib import Path from pathlib import Path
@@ -28,12 +26,6 @@ VOIP, GV = "5415550100", "5415550177"
GROUP = "5415550101,5415550102,5415550103" GROUP = "5415550101,5415550102,5415550103"
def gradient_png(w: int, h: int) -> bytes:
raw = b"".join(b"\0" + bytes(c for x in range(w) for c in (x * 255 // w, y * 255 // h, 160)) for y in range(h))
chunk = lambda t, b: struct.pack(">I", len(b)) + t + b + struct.pack(">I", zlib.crc32(t + b))
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
def push(local: Path, name: str): def push(local: Path, name: str):
with open(local, "rb") as f: with open(local, "rb") as f:
subprocess.run(["adb", "shell", f"run-as {PKG} sh -c 'cat > files/{name}'"], stdin=f, check=True) subprocess.run(["adb", "shell", f"run-as {PKG} sh -c 'cat > files/{name}'"], stdin=f, check=True)
@@ -92,12 +84,6 @@ def main():
rows.append((SIM_BASE + 1, "sim", "5415550150", "in", "Texting your SIM number now", now - 20 * m, None)) rows.append((SIM_BASE + 1, "sim", "5415550150", "in", "Texting your SIM number now", now - 20 * m, None))
rows.append((SIM_BASE + 2, "sim", "5415550150", "out", "Got it, this is the SIM", now - 19 * m, None)) rows.append((SIM_BASE + 2, "sim", "5415550150", "out", "Got it, this is the SIM", now - 19 * m, None))
con.executemany("INSERT INTO messages (id, did, contact, direction, body, ts, sender) VALUES (?,?,?,?,?,?,?)", rows) con.executemany("INSERT INTO messages (id, did, contact, direction, body, ts, sender) VALUES (?,?,?,?,?,?,?)", rows)
# Pictures both ways (a made-up gradient), to see their corners.
pic = Path(d) / "sandbox-pic.png"
pic.write_bytes(gradient_png(400, 300))
ref = json.dumps([{"file": "sandbox-pic.png", "mime": "image/png", "width": 400, "height": 300}])
con.execute("INSERT INTO messages (id, did, contact, direction, body, ts, kind, media_json) VALUES (1007, ?, '5415550110', 'in', 'Look at this', ?, 'mms', ?)", (VOIP, now - 280 * m, ref))
con.execute("INSERT INTO messages (id, did, contact, direction, body, ts, kind, media_json) VALUES (1008, ?, '5415550110', 'out', '', ?, 'mms', ?)", (VOIP, now - 279 * m, ref))
con.execute("INSERT INTO kv VALUES ('unread_floor', '0')") con.execute("INSERT INTO kv VALUES ('unread_floor', '0')")
con.execute("INSERT INTO gv_threads VALUES (?, ?, 'g.demo')", (GV, GROUP)) con.execute("INSERT INTO gv_threads VALUES (?, ?, 'g.demo')", (GV, GROUP))
con.commit() con.commit()
@@ -113,8 +99,6 @@ def main():
})) }))
push(db, "messages.db") push(db, "messages.db")
push(cfg, "config.json") push(cfg, "config.json")
subprocess.run(["adb", "shell", f"run-as {PKG} mkdir -p files/media"], check=True)
push(pic, "media/sandbox-pic.png")
subprocess.run(["adb", "shell", "am", "start", "-n", f"{PKG}/me.teafry.voipmessages.MainActivity"], check=True) subprocess.run(["adb", "shell", "am", "start", "-n", f"{PKG}/me.teafry.voipmessages.MainActivity"], check=True)
print("sandbox data pushed to", PKG) print("sandbox data pushed to", PKG)
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 145 KiB

+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "voipms-desktop", "name": "voipms-desktop",
"version": "0.9.5", "version": "0.7.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "voipms-desktop", "name": "voipms-desktop",
"version": "0.9.5", "version": "0.7.1",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"better-sqlite3": "^13.0.3" "better-sqlite3": "^13.0.3"
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "voipms-desktop", "name": "voipms-desktop",
"productName": "bubble", "productName": "bubble",
"version": "0.9.9", "version": "0.8.4",
"description": "Signal-style desktop SMS client for voip.ms", "description": "Signal-style desktop SMS client for voip.ms",
"author": "trav <trav@teafry.me>", "author": "trav <trav@teafry.me>",
"private": true, "private": true,
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
{"version_name": "0.7.9", "version_code": 17, "package": "me.teafry.voipmessages"} {"version_name": "0.7.3", "version_code": 11, "package": "me.teafry.voipmessages"}
+33
View File
@@ -0,0 +1,33 @@
#!/bin/bash
# Deploy bubble-relay to jai (see ~/Documents/shared-resources/jai.html#run).
# jai is production: this only ever touches ~/Documents/bubble-server and its
# own screen session, and installs nothing.
#
# scripts/deploy-jai.sh copy the code and (re)start the service
# scripts/deploy-jai.sh --stop stop it
# scripts/deploy-jai.sh --token print the bearer token, for Settings → Rabbit relay on the desktop
#
# What runs is server/run.sh, also started by jai's ~/startup.sh (re-run by its
# watchdog every 5 minutes), so it comes back after a crash or a reboot.
set -euo pipefail
HOST=${JAI_HOST:-jai-ext}
DIR=/home/jai/Documents/bubble-server
NAME=bubble-relay
cd "$(dirname "$0")/.."
case "${1:-}" in
--token) ssh "$HOST" "cat $DIR/data/token"; echo; exit 0 ;;
--stop) ssh "$HOST" "screen -S $NAME -X quit || true"; echo "stopped"; exit 0 ;;
esac
ssh "$HOST" "mkdir -p $DIR/app $DIR/data ~/service-logs && chmod 700 $DIR $DIR/data"
rsync -a server/bubble_relay.py server/run.sh "$HOST:$DIR/app/"
ssh "$HOST" bash -s <<REMOTE
set -e
screen -S $NAME -X quit 2>/dev/null || true
sleep 1
screen -dmS $NAME bash -c 'bash $DIR/app/run.sh 2>&1 | tee ~/service-logs/$NAME.log'
sleep 2
for pid in \$(pgrep -f bubble_relay.py); do echo 1000 > /proc/\$pid/oom_score_adj; done
curl -s -m 5 http://100.69.139.40:8080/health; echo
REMOTE
-36
View File
@@ -1,36 +0,0 @@
#!/bin/bash
# Deploy the relay server (server/bubble_relay.py) over ssh. Where it goes
# comes from scripts/relay.env (not in git; see scripts/relay.env.example).
# This only touches $RELAY_DIR and its own screen session, and installs nothing.
#
# scripts/deploy-relay.sh copy the code and (re)start it
# scripts/deploy-relay.sh --stop stop it
# scripts/deploy-relay.sh --token print the bearer token, for Settings → Relay server on the desktop
#
# What runs is server/run.sh; have the server start that at boot too, e.g.
# screen -dmS bubble-relay bash -c 'bash $RELAY_DIR/app/run.sh'
set -euo pipefail
cd "$(dirname "$0")/.."
[ -f scripts/relay.env ] || { echo "No scripts/relay.env: copy scripts/relay.env.example and fill it in." >&2; exit 1; }
. scripts/relay.env
: "${RELAY_SSH:?}" "${RELAY_DIR:?}" "${RELAY_BIND:?}"
PORT=${RELAY_PORT:-8080}
NAME=bubble-relay
case "${1:-}" in
--token) ssh "$RELAY_SSH" "cat $RELAY_DIR/data/token"; echo; exit 0 ;;
--stop) ssh "$RELAY_SSH" "screen -S $NAME -X quit || true"; echo "stopped"; exit 0 ;;
esac
ssh "$RELAY_SSH" "mkdir -p $RELAY_DIR/app $RELAY_DIR/data ~/service-logs && chmod 700 $RELAY_DIR $RELAY_DIR/data"
rsync -a server/bubble_relay.py server/run.sh "$RELAY_SSH:$RELAY_DIR/app/"
printf 'RELAY_BIND=%q\nRELAY_PORT=%q\n' "$RELAY_BIND" "$PORT" | ssh "$RELAY_SSH" "cat > $RELAY_DIR/app/relay.env"
ssh "$RELAY_SSH" bash -s <<REMOTE
set -e
screen -S $NAME -X quit 2>/dev/null || true
sleep 1
screen -dmS $NAME bash -c 'bash $RELAY_DIR/app/run.sh 2>&1 | tee ~/service-logs/$NAME.log'
sleep 2
for pid in \$(pgrep -f bubble_relay.py); do echo 1000 > /proc/\$pid/oom_score_adj; done
curl -s -m 5 http://$RELAY_BIND:$PORT/health; echo
REMOTE
-5
View File
@@ -1,5 +0,0 @@
# Copy to scripts/relay.env (git ignores it) for scripts/deploy-relay.sh.
RELAY_SSH=myserver # ssh host (an alias from ~/.ssh/config is fine)
RELAY_DIR=/home/me/bubble-server # on the server: app/ and data/ (token, mailbox) go here
RELAY_BIND=100.101.102.103 # the server's tailscale address; the desktop's Settings → Relay server uses http://<this>:<port>
RELAY_PORT=8080
Binary file not shown.
+3 -4
View File
@@ -1,9 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""bubble-relay: a mailbox between the desktop app and the Rabbit R1. Runs on a """bubble-relay: a mailbox between the desktop app and the Rabbit R1. Runs on jai.
server of yours that both can reach (a tailscale address is the easy way).
It never sees a message: every blob is AES-256-GCM sealed by the apps with a It never sees a message: every blob is AES-256-GCM sealed by the apps with a
key the server doesn't have (the desktop makes it and hands it to the Rabbit over key jai doesn't have (the desktop makes it and hands it to the Rabbit over
USB). This only stores opaque base64 strings, hands each device what the USB). This only stores opaque base64 strings, hands each device what the
other one posted, and forgets them once picked up (or after KEEP_DAYS). other one posted, and forgets them once picked up (or after KEEP_DAYS).
@@ -20,7 +19,7 @@ to it, which the other side posted, so those are deleted. `more` = there's
more than fits in one answer: call again with the new cursor. A cursor past more than fits in one answer: call again with the new cursor. A cursor past
anything this server ever issued (a wiped server) means "from the start". anything this server ever issued (a wiped server) means "from the start".
python3 bubble_relay.py --host <tailscale address> --port 8080 --data DIR python3 bubble_relay.py --host 100.69.139.40 --port 8080 --data DIR
""" """
import argparse import argparse
+3 -6
View File
@@ -1,7 +1,4 @@
#!/bin/bash #!/bin/bash
# The one real command line for the relay server (scripts/deploy-relay.sh runs # The one real command line for bubble-relay on jai (~/startup.sh and scripts/deploy-jai.sh both run this).
# it; run it at boot too). relay.env next to it, written by the deploy, says cd /home/jai/Documents/bubble-server/app || exit 1
# which address and port to listen on. exec python3 bubble_relay.py --host 100.69.139.40 --port 8080 --data /home/jai/Documents/bubble-server/data
cd "$(dirname "$(readlink -f "$0")")" || exit 1
. ./relay.env
exec python3 bubble_relay.py --host "$RELAY_BIND" --port "${RELAY_PORT:-8080}" --data ../data
+1 -21
View File
@@ -5,9 +5,8 @@ import path from 'node:path'
import type { Conversation, Direction, MediaRef, Message, MessageKind, 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 { SNIPPET_END, SNIPPET_START } from '@shared/types'
import { fixVoipDst } from './voipms' import { fixVoipDst } from './voipms'
import { SIM_DID } from '@shared/phone'
const SCHEMA_VERSION = 12 const SCHEMA_VERSION = 11
export interface ReadState { export interface ReadState {
did: string did: string
@@ -171,9 +170,6 @@ export class MessageDb {
// Received"; nobody wrote it, so it goes. // Received"; nobody wrote it, so it goes.
if (version >= 1 && version < 11) if (version >= 1 && version < 11)
this.db.exec(`UPDATE messages SET body = '' WHERE media_json IS NOT NULL AND lower(trim(body)) = 'mms received'`) this.db.exec(`UPDATE messages SET body = '' WHERE media_json IS NOT NULL AND lower(trim(body)) = 'mms received'`)
// v12: and one we sent with no words "MMS Sent".
if (version >= 1 && version < 12)
this.db.exec(`UPDATE messages SET body = '' WHERE media_json IS NOT NULL AND lower(trim(body)) = 'mms sent'`)
this.db.pragma(`user_version = ${SCHEMA_VERSION}`) this.db.pragma(`user_version = ${SCHEMA_VERSION}`)
} }
@@ -266,20 +262,6 @@ export class MessageDb {
this.db.prepare(`UPDATE messages SET status = 'failed', error = ? WHERE id = ?`).run(error ?? null, tempId) this.db.prepare(`UPDATE messages SET status = 'failed', error = ? WHERE id = ?`).run(error ?? null, tempId)
} }
// At startup: sends a previous run left 'pending' (it quit or crashed
// mid-send, and that send's retry loop died with it). Nothing will ever
// finish them, so they become failed: shown as Not sent with Retry, never
// resent on their own (by now they may be stale). If one did go out, the
// next poll still replaces it (reconcileSent matches failed rows too).
// Over the Rabbit's SIM they stay pending: those wait in relay_outbox.
failOrphanedSends(error: string): Message[] {
const rows = this.db
.prepare(`SELECT id FROM messages WHERE id < 0 AND status = 'pending' AND direction = 'out' AND did != ?`)
.all(SIM_DID) as { id: number }[]
for (const { id } of rows) this.markFailed(id, error)
return rows.map(({ id }) => this.getMessage(id)!).filter(Boolean)
}
// Sent messages that turned up in a poll take the place of our local // 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 // 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. // reply never came back may still have gone out; this is how we find out.
@@ -352,8 +334,6 @@ export class MessageDb {
json_extract(last.media_json, '$[0]') AS lastMedia, 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' (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,
(SELECT COUNT(*) FROM messages m WHERE m.did = l.did AND m.contact = l.contact AND m.id < 0
AND m.status = 'failed') AS failed,
r.archived_at IS NOT NULL AS archived, r.archived_at IS NOT NULL AS archived,
COALESCE(r.marked_unread, 0) AS markedUnread, COALESCE(r.marked_unread, 0) AS markedUnread,
r.name AS name r.name AS name
+13 -75
View File
@@ -16,7 +16,7 @@ import { MediaStore } from './media'
import { exportHtml, exportText, inRange, rangeLabel } from './export' import { exportHtml, exportText, inRange, rangeLabel } from './export'
import { extFor, guessMime } from '@shared/mime' import { extFor, guessMime } from '@shared/mime'
import { clearCredentials, loadCredentials, saveCredentials } from './secrets' import { clearCredentials, loadCredentials, saveCredentials } from './secrets'
import { getDataDir, loadSettings, moveToBubbleData, saveSettings, setDataDir } from './settings' import { getDataDir, loadSettings, saveSettings, setDataDir } from './settings'
import { SyncEngine } from './sync' import { SyncEngine } from './sync'
import { loadZoom, saveZoom } from './uistate' import { loadZoom, saveZoom } from './uistate'
import { sendWithRetry } from './send' import { sendWithRetry } from './send'
@@ -26,7 +26,7 @@ import { SendMediaType } from './gvoice/schema'
import { clearGvSession, exportCookies, gvTransport, hasGvSession, importCookies, parseCookies, signInWindow } from './gvoice/session' import { clearGvSession, exportCookies, gvTransport, hasGvSession, importCookies, parseCookies, signInWindow } from './gvoice/session'
import { gvMessageId, GvSyncEngine } from './gvoice/sync' import { gvMessageId, GvSyncEngine } from './gvoice/sync'
import { WaaSigner } from './gvoice/waa' import { WaaSigner } from './gvoice/waa'
import { clearNotifications, closeAllNotifications, notifyNew, notifyUnsent, sweepNotifications } from './notify' import { clearNotifications, notifyNew } from './notify'
import * as rabbit from './rabbit' import * as rabbit from './rabbit'
import { checkUrl, clearRelayConfig, loadRelayConfig, newKey, RelayEngine, saveRelayConfig, SIM_DID } from './relay' import { checkUrl, clearRelayConfig, loadRelayConfig, newKey, RelayEngine, saveRelayConfig, SIM_DID } from './relay'
@@ -49,7 +49,7 @@ let dids: Did[] = []
let gv: GVoice | undefined let gv: GVoice | undefined
let gvSync: GvSyncEngine | undefined let gvSync: GvSyncEngine | undefined
let waa: WaaSigner | undefined let waa: WaaSigner | undefined
// The relay server: the Rabbit's SIM, names and read state (relay.ts). // The relay through jai: the Rabbit's SIM, names and read state (relay.ts).
let relay: RelayEngine | undefined let relay: RelayEngine | undefined
const send = (channel: string, ...args: unknown[]): void => { const send = (channel: string, ...args: unknown[]): void => {
@@ -101,13 +101,6 @@ function onNewMessages(msgs: NewMessage[]): void {
if (settings.notifications && !win?.isFocused()) notifyNew(msgs, { db, contacts, onClick: openFromNotification }) if (settings.notifications && !win?.isFocused()) notifyNew(msgs, { db, contacts, onClick: openFromNotification })
} }
// Read/unread changed from outside the app: chats read elsewhere lose their
// notifications here too.
function readStateChanged(): void {
sweepNotifications((did, contact) => db.hasUnread(did, contact))
send('conversationsChanged')
}
function openFromNotification(key: { did: string; contact: string }): void { function openFromNotification(key: { did: string; contact: string }): void {
if (!win || win.isDestroyed()) return if (!win || win.isDestroyed()) return
if (win.isMinimized()) win.restore() if (win.isMinimized()) win.restore()
@@ -119,7 +112,7 @@ function openFromNotification(key: { did: string; contact: string }): void {
const gvNumber = (): string | undefined => db.get('gv_number') || undefined const gvNumber = (): string | undefined => db.get('gv_number') || undefined
// Every number we can text from: voip.ms's DIDs, then Google Voice's, then // Every number we can text from: voip.ms's DIDs, then Google Voice's, then
// the Rabbit's SIM (through the relay server). // the Rabbit's SIM (through jai).
function allDids(): Did[] { function allDids(): Did[] {
const n = gvNumber() const n = gvNumber()
const out: Did[] = n ? [...dids, { did: n, description: 'Google Voice', smsEnabled: true, provider: 'gvoice' }] : [...dids] const out: Did[] = n ? [...dids, { did: n, description: 'Google Voice', smsEnabled: true, provider: 'gvoice' }] : [...dids]
@@ -136,16 +129,15 @@ function startRelay(): void {
if (!cfg) return if (!cfg) return
relay = new RelayEngine(db, media, cfg, settings.pollSeconds) relay = new RelayEngine(db, media, cfg, settings.pollSeconds)
relay.on('messages', onNewMessages) relay.on('messages', onNewMessages)
relay.on('changed', readStateChanged) relay.on('changed', () => send('conversationsChanged'))
relay.on('status', () => send('relayStatus', relay?.status())) relay.on('status', () => send('relayStatus', relay?.status()))
relay.on('unsent', (m: Message) => alertUnsent([m]))
relay.start() relay.start()
} }
// A text over the Rabbit's SIM: pending here until the Rabbit's next check // A text over the Rabbit's SIM: pending here until the Rabbit's next check
// sends it and says how it went (relay.ts). // sends it and says how it went (relay.ts).
function relaySend(contact: string, text: string, refs: MediaRef[]): void { function relaySend(contact: string, text: string, refs: MediaRef[]): void {
if (!relay) throw new Error('The Rabbit relay is off: connect it in Settings → Relay server.') if (!relay) throw new Error('The Rabbit relay is off: connect it in Settings → jai.')
const kind = refs.length || isGroup(contact) ? 'mms' : 'sms' const kind = refs.length || isGroup(contact) ? 'mms' : 'sms'
const tempId = db.insertPending({ did: SIM_DID, contact, direction: 'out', body: text, ts: Date.now(), kind, ...(refs.length ? { media: refs } : {}) }) const tempId = db.insertPending({ did: SIM_DID, contact, direction: 'out', body: text, ts: Date.now(), kind, ...(refs.length ? { media: refs } : {}) })
relay.send(tempId, contact, text, refs) relay.send(tempId, contact, text, refs)
@@ -167,7 +159,7 @@ function startGvSync(): void {
gvSync = new GvSyncEngine(db, gv, { did, pollSeconds: settings.pollSeconds, backfillFloor: settings.backfillFloor }) gvSync = new GvSyncEngine(db, gv, { did, pollSeconds: settings.pollSeconds, backfillFloor: settings.backfillFloor })
gvSync.on('messages', onNewMessages) gvSync.on('messages', onNewMessages)
gvSync.on('status', () => send('syncStatus', syncStatus())) gvSync.on('status', () => send('syncStatus', syncStatus()))
gvSync.on('readChanged', readStateChanged) gvSync.on('readChanged', () => send('conversationsChanged'))
gvSync.start() gvSync.start()
} }
@@ -247,17 +239,13 @@ async function servePhoto(req: Request): Promise<Response> {
} }
} }
// ---- MMS attachments: mms-media://m/<messageId>/<index>[?thumb] ---- // ---- MMS attachments: mms-media://m/<messageId>/<index> ----
// ?thumb: a smaller copy of a still picture, for the chat and Get info.
async function serveMedia(req: Request): Promise<Response> { async function serveMedia(req: Request): Promise<Response> {
const url = new URL(req.url) const [id, index] = new URL(req.url).pathname.slice(1).split('/').map(Number)
const [id, index] = url.pathname.slice(1).split('/').map(Number)
const ref = await media.resolve(id, index) const ref = await media.resolve(id, index)
if (!ref?.file) return new Response(null, { status: 404 }) if (!ref?.file) return new Response(null, { status: 404 })
const thumb = url.searchParams.has('thumb') ? await media.thumb(ref).catch(() => undefined) : undefined const headers = { 'content-type': ref.mime ?? guessMime(ref.file) ?? 'application/octet-stream' }
const file = thumb ?? media.filePath(ref.file) return new Response(fs.readFileSync(media.filePath(ref.file)), { headers })
const mime = thumb ? (thumb.endsWith('.png') ? 'image/png' : 'image/jpeg') : (ref.mime ?? guessMime(ref.file) ?? 'application/octet-stream')
return new Response(await fs.promises.readFile(file), { headers: { 'content-type': mime } })
} }
async function saveMediaAs(id: number, index: number): Promise<void> { async function saveMediaAs(id: number, index: number): Promise<void> {
@@ -422,7 +410,6 @@ function enqueue<T>(key: string, job: () => Promise<T>): Promise<T> {
async function deliver(m: Omit<NewMessage, 'id'>, attempt: () => Promise<number>): Promise<void> { async function deliver(m: Omit<NewMessage, 'id'>, attempt: () => Promise<number>): Promise<void> {
const engine = providerOf(m.did) === 'gvoice' ? gvSync : sync const engine = providerOf(m.did) === 'gvoice' ? gvSync : sync
const tempId = db.insertPending(m) const tempId = db.insertPending(m)
sending.add(tempId)
send('conversationsChanged') send('conversationsChanged')
try { try {
await enqueue(`${m.did}:${m.contact}`, () => await enqueue(`${m.did}:${m.contact}`, () =>
@@ -434,49 +421,11 @@ async function deliver(m: Omit<NewMessage, 'id'>, attempt: () => Promise<number>
}) })
) )
} finally { } finally {
sending.delete(tempId)
const after = db.getMessage(tempId)
if (after?.status === 'failed') alertUnsent([after])
send('conversationsChanged') send('conversationsChanged')
engine?.burst() engine?.burst()
} }
} }
// voip.ms / Google Voice sends still being worked on (their retry loops live
// only in this process, so quitting now strands them).
const sending = new Set<number>()
// Always, whatever the notification setting, and even with the window focused:
// a text that didn't go out has to be impossible to miss.
function alertUnsent(msgs: Message[]): void {
if (!msgs.length) return
notifyUnsent(msgs, { db, contacts, onClick: openFromNotification })
if (win && !win.isDestroyed()) win.flashFrame(true)
}
// Closing or quitting with a text still on its way: ask first. Returns
// whether to go ahead.
let leaveAnyway = false
function okToLeave(): boolean {
if (leaveAnyway || !sending.size) return true
const n = sending.size
const opts: Electron.MessageBoxSyncOptions = {
type: 'warning',
title: 'Still sending',
message: n > 1 ? `${n} texts are still sending` : 'A text is still sending',
detail:
"If bubble closes now it can't finish, and it will most likely not go out. " +
'It will show as Not sent next time, with a Retry button.',
buttons: ['Keep bubble open', 'Quit anyway'],
defaultId: 0,
cancelId: 0
}
const choice = win && !win.isDestroyed() ? dialog.showMessageBoxSync(win, opts) : dialog.showMessageBoxSync(opts)
if (choice !== 1) return false
leaveAnyway = true
return true
}
const voipAttempt = (call: (api: VoipMs) => Promise<number>) => (): Promise<number> => { const voipAttempt = (call: (api: VoipMs) => Promise<number>) => (): Promise<number> => {
if (!api) throw new VoipMsError('not_signed_in') if (!api) throw new VoipMsError('not_signed_in')
return call(api) return call(api)
@@ -729,8 +678,8 @@ function registerIpc(): void {
signal: AbortSignal.timeout(15_000) signal: AbortSignal.timeout(15_000)
}).catch(() => undefined) }).catch(() => undefined)
if (!res) throw new Error(`Couldn't reach ${origin}. Is tailscale up?`) if (!res) throw new Error(`Couldn't reach ${origin}. Is tailscale up?`)
if (res.status === 401) throw new Error('The relay server turned down that token.') if (res.status === 401) throw new Error('jai turned down that token.')
if (!res.ok) throw new Error(`The relay server answered ${res.status}.`) if (!res.ok) throw new Error(`jai answered ${res.status}.`)
// Keep the key across reconnects so the Rabbit's copy stays good. // Keep the key across reconnects so the Rabbit's copy stays good.
saveRelayConfig({ url: origin, token: tok, key: loadRelayConfig()?.key ?? newKey() }) saveRelayConfig({ url: origin, token: tok, key: loadRelayConfig()?.key ?? newKey() })
startRelay() startRelay()
@@ -829,10 +778,6 @@ function createWindow(): void {
// from firing, leaving a windowless process holding the single-instance lock. // from firing, leaving a windowless process holding the single-instance lock.
for (const ev of ['maximize', 'unmaximize', 'enter-full-screen', 'leave-full-screen', 'resize', 'focus', 'blur'] as const) for (const ev of ['maximize', 'unmaximize', 'enter-full-screen', 'leave-full-screen', 'resize', 'focus', 'blur'] as const)
win.on(ev as 'resize', sendWindowState) win.on(ev as 'resize', sendWindowState)
win.on('close', (e) => {
if (!okToLeave()) e.preventDefault()
})
win.on('focus', () => win?.flashFrame(false))
win.on('closed', () => { win.on('closed', () => {
win = undefined win = undefined
app.quit() app.quit()
@@ -849,10 +794,8 @@ app.on('second-instance', () => {
}) })
app.whenReady().then(async () => { app.whenReady().then(async () => {
moveToBubbleData()
settings = loadSettings() settings = loadSettings()
db = new MessageDb(path.join(getDataDir(), 'messages.db')) db = new MessageDb(path.join(getDataDir(), 'messages.db'))
const orphans = db.failOrphanedSends("bubble closed before this finished sending, so it most likely didn't go out.")
if (SANDBOX) seedDemo(db) if (SANDBOX) seedDemo(db)
dids = JSON.parse(db.get('dids') ?? '[]') as Did[] dids = JSON.parse(db.get('dids') ?? '[]') as Did[]
media = new MediaStore(path.join(getDataDir(), 'media'), db, (url, at) => { media = new MediaStore(path.join(getDataDir(), 'media'), db, (url, at) => {
@@ -881,9 +824,6 @@ app.whenReady().then(async () => {
if (gvNumber() && (await hasGvSession())) startGvSync() if (gvNumber() && (await hasGvSession())) startGvSync()
startRelay() startRelay()
// Once contacts can name the chat.
if (orphans.length) setTimeout(() => alertUnsent(orphans), 3000)
void dailySnapshot() void dailySnapshot()
setInterval(() => void dailySnapshot(), 60 * 60 * 1000) setInterval(() => void dailySnapshot(), 60 * 60 * 1000)
}) })
@@ -892,9 +832,7 @@ let quitting = false
app.on('before-quit', (e) => { app.on('before-quit', (e) => {
if (quitting || !db) return if (quitting || !db) return
e.preventDefault() e.preventDefault()
if (!okToLeave()) return
quitting = true quitting = true
closeAllNotifications()
sync?.stop() sync?.stop()
stopGv() stopGv()
relay?.stop() relay?.stop()
-27
View File
@@ -9,9 +9,6 @@ import { extFor, guessMime } from '@shared/mime'
import type { MediaRef } from '@shared/types' import type { MediaRef } from '@shared/types'
import type { MessageDb, NewMessage } from './db' import type { MessageDb, NewMessage } from './db'
// Long edge of a thumbnail: twice the chat's largest picture box, for HiDPI.
const THUMB_EDGE = 720
export class MediaStore { export class MediaStore {
private inflight = new Map<string, Promise<MediaRef | undefined>>() private inflight = new Map<string, Promise<MediaRef | undefined>>()
@@ -26,30 +23,6 @@ export class MediaStore {
return path.join(this.dir, path.basename(file)) return path.join(this.dir, path.basename(file))
} }
// A smaller copy of a still picture for the chat and Get info, made once
// and kept in <dataDir>/thumbs (outside media/, so it never goes to the
// Rabbit or into backups as if it were an attachment). The chat shows
// pictures at most 300x360, so a phone's 4000 px photo was being decoded
// whole, again and again as rows scrolled in and out. Undefined = use the
// original: already small, animated (GIF), or a format nativeImage can't read.
async thumb(ref: MediaRef): Promise<string | undefined> {
if (!ref.file) return undefined
const mime = ref.mime ?? guessMime(ref.file) ?? ''
if (!mime.startsWith('image/') || mime === 'image/gif') return undefined
const png = mime === 'image/png' || mime === 'image/webp' // may be see-through
const out = path.join(this.dir, '..', 'thumbs', `${path.basename(ref.file)}.${THUMB_EDGE}.${png ? 'png' : 'jpg'}`)
if (fs.existsSync(out)) return out
const img = nativeImage.createFromPath(this.filePath(ref.file))
if (img.isEmpty()) return undefined
const { width, height } = img.getSize()
if (Math.max(width, height) <= THUMB_EDGE) return undefined
const scale = THUMB_EDGE / Math.max(width, height)
const small = img.resize({ width: Math.round(width * scale), height: Math.round(height * scale), quality: 'good' })
await fs.promises.mkdir(path.dirname(out), { recursive: true })
await fs.promises.writeFile(out, png ? small.toPNG() : small.toJPEG(85))
return out
}
save(data: Uint8Array, mime: string): string { save(data: Uint8Array, mime: string): string {
const file = `${crypto.createHash('sha1').update(data).digest('hex')}.${extFor(mime)}` const file = `${crypto.createHash('sha1').update(data).digest('hex')}.${extFor(mime)}`
fs.mkdirSync(this.dir, { recursive: true }) fs.mkdirSync(this.dir, { recursive: true })
+1 -47
View File
@@ -4,7 +4,6 @@ import { Notification } from 'electron'
import { formatNumber, groupMembers, isGroup } from '@shared/phone' import { formatNumber, groupMembers, isGroup } from '@shared/phone'
import type { ContactDirectory } from './contacts' import type { ContactDirectory } from './contacts'
import type { MessageDb, NewMessage } from './db' import type { MessageDb, NewMessage } from './db'
import type { Message } from '@shared/types'
import { reactionPreview } from '@shared/reactions' import { reactionPreview } from '@shared/reactions'
import { editPreview } from '@shared/edits' import { editPreview } from '@shared/edits'
@@ -22,9 +21,6 @@ export interface NotifyDeps {
// reading the conversation in the app can take them back out of the list. // reading the conversation in the app can take them back out of the list.
const live = new Map<string, Set<Notification>>() const live = new Map<string, Set<Notification>>()
// "Not sent" alerts, kept referenced for their click handlers.
const unsent = new Set<Notification>()
const convKey = (did: string, contact: string): string => `${did}\n${contact}` const convKey = (did: string, contact: string): string => `${did}\n${contact}`
// The conversation's been read: its notifications are stale. // The conversation's been read: its notifications are stale.
@@ -35,24 +31,6 @@ export function clearNotifications(did: string, contact: string): void {
for (const n of shown) n.close() for (const n of shown) n.close()
} }
// Read state changed somewhere else (the Rabbit, the phone, Google Voice's
// site): take down what's no longer unread, like the Android app's sweep.
export function sweepNotifications(isUnread: (did: string, contact: string) => boolean): void {
for (const key of [...live.keys()]) {
const [did, contact] = key.split('\n')
if (!isUnread(did, contact)) clearNotifications(did, contact)
}
}
// Quitting: once this process is gone nothing can close them (or answer
// their clicks), so they'd sit in the list for good. Take them all down.
export function closeAllNotifications(): void {
for (const shown of live.values()) for (const n of shown) n.close()
live.clear()
for (const n of unsent) n.close()
unsent.clear()
}
const nameOf = (contacts: ContactDirectory, n: string): string => contacts.lookup(n)?.name ?? formatNumber(n) 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 { export function conversationTitle(db: MessageDb, contacts: ContactDirectory, did: string, contact: string): string {
@@ -64,7 +42,7 @@ export function conversationTitle(db: MessageDb, contacts: ContactDirectory, did
.join(', ') .join(', ')
} }
function preview(m: Pick<NewMessage, 'body' | 'media'>): string { function preview(m: NewMessage): string {
const reaction = reactionPreview(m.body) const reaction = reactionPreview(m.body)
if (reaction) return reaction if (reaction) return reaction
const edit = editPreview(m.body) const edit = editPreview(m.body)
@@ -104,27 +82,3 @@ export function notifyNew(msgs: NewMessage[], { db, contacts, onClick }: NotifyD
n.show() n.show()
} }
} }
// Your text didn't go out. Normal urgency (new messages are low): it pops up
// unless Do Not Disturb is on, and stays in the list either way. Never
// critical, which would break through Do Not Disturb.
export function notifyUnsent(msgs: Message[], { db, contacts, onClick }: NotifyDeps): void {
if (!Notification.isSupported()) return
const byConv = new Map<string, Message[]>()
for (const m of msgs) byConv.set(convKey(m.did, m.contact), [...(byConv.get(convKey(m.did, m.contact)) ?? []), m])
for (const list of byConv.values()) {
const { did, contact } = list[0]
const who = conversationTitle(db, contacts, did, contact)
const n = new Notification({
title: list.length > 1 ? `${list.length} texts to ${who} weren't sent` : `Text to ${who} wasn't sent`,
body: list.length > 1 ? 'Open the chat to retry or delete them.' : `“${preview(list[0]) || 'Your message'}” · ${list[0].error ?? 'Open the chat to retry it.'}`,
urgency: 'normal'
})
// Kept referenced like the others so the click survives; not filed under
// `live`, so reading the chat doesn't take it back down.
unsent.add(n)
n.on('click', () => onClick({ did, contact }))
n.on('close', () => unsent.delete(n))
n.show()
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ export interface RabbitConfig {
gvoice: { number: string; cookies: Record<string, string> } | null gvoice: { number: string; cookies: Record<string, string> } | null
dids: Array<{ did: string; description: string }> dids: Array<{ did: string; description: string }>
defaultDid?: string defaultDid?: string
// The relay server (relay.ts): address, token, and the key that seals everything. // The relay through jai (relay.ts): address, token, and the key that seals everything.
relay?: { url: string; token: string; key: string } | null relay?: { url: string; token: string; key: string } | null
} }
+10 -13
View File
@@ -1,11 +1,11 @@
// The relay server: the Rabbit's SIM texts reach this computer, texts // The relay through jai: the Rabbit's SIM texts reach this computer, texts
// typed here go out over the Rabbit's SIM, and chat names and read/unread/ // typed here go out over the Rabbit's SIM, and chat names and read/unread/
// archived stay in step between the two, all without a USB cable. // archived stay in step between the two, all without a USB cable.
// //
// The relay server only ever holds sealed blobs: AES-256-GCM with a key made here and handed // jai only ever holds sealed blobs: AES-256-GCM with a key made here and handed
// to the Rabbit over USB (Install/Sync to Rabbit puts it in the app's private // to the Rabbit over USB (Install/Sync to Rabbit puts it in the app's private
// config.json). The bearer token only lets a device talk to the mailbox; the // config.json). The bearer token only lets a device talk to the mailbox; the
// key is what keeps the relay server (and anyone else on it) from reading or forging // key is what keeps jai (and anyone else on it) from reading or forging
// anything. Server: server/bubble_relay.py. Android side: Relay.java. // anything. Server: server/bubble_relay.py. Android side: Relay.java.
// //
// What travels (inside the seal; `t` is the kind): // What travels (inside the seal; `t` is the kind):
@@ -27,6 +27,7 @@ import type { MessageDb, NameChange, NewMessage, ReadState } from './db'
import type { MediaStore } from './media' import type { MediaStore } from './media'
export { SIM_DID } from '@shared/phone' export { SIM_DID } from '@shared/phone'
export const DEFAULT_URL = 'http://100.69.139.40:8080'
export interface RelayConfig { export interface RelayConfig {
url: string url: string
@@ -227,10 +228,10 @@ export class RelayEngine extends EventEmitter {
body: JSON.stringify({ device: 'desktop', since, push: push.map((r) => r.blob) }), body: JSON.stringify({ device: 'desktop', since, push: push.map((r) => r.blob) }),
signal: AbortSignal.timeout(120_000) signal: AbortSignal.timeout(120_000)
}) })
if (res.status === 401) throw new Error('The relay server turned down the token. Check it in Settings → Relay server.') if (res.status === 401) throw new Error('jai turned down the token. Check it in Settings → jai.')
if (!res.ok) throw new Error(`The relay server answered ${res.status}`) if (!res.ok) throw new Error(`jai answered ${res.status}`)
const body = (await res.json()) as { cursor: number; events: string[]; more: boolean } const body = (await res.json()) as { cursor: number; events: string[]; more: boolean }
// Only now that the relay server has them: out of the outbox. // Only now that jai has them: out of the outbox.
if (push.length) this.db.db.prepare('DELETE FROM relay_outbox WHERE seq <= ?').run(push.at(-1)!.seq) if (push.length) this.db.db.prepare('DELETE FROM relay_outbox WHERE seq <= ?').run(push.at(-1)!.seq)
for (const blob of body.events) this.handle(unseal(this.key, 'rabbit', blob) as Incoming | undefined) for (const blob of body.events) this.handle(unseal(this.key, 'rabbit', blob) as Incoming | undefined)
this.db.set('relay_cursor', String(body.cursor)) this.db.set('relay_cursor', String(body.cursor))
@@ -239,8 +240,8 @@ export class RelayEngine extends EventEmitter {
this.lastSync = Date.now() this.lastSync = Date.now()
this.error = undefined this.error = undefined
} catch (e) { } catch (e) {
// Can't reach the relay server: an ordinary, quiet outcome; try again next round. // Can't reach jai: an ordinary, quiet outcome; try again next round.
this.error = (e as Error).name === 'TimeoutError' ? "The relay server didn't answer" : (e as Error).message this.error = (e as Error).name === 'TimeoutError' ? "jai didn't answer" : (e as Error).message
} }
this.emit('status', this.status()) this.emit('status', this.status())
} }
@@ -297,11 +298,7 @@ export class RelayEngine extends EventEmitter {
if (temp === undefined || temp === null) return if (temp === undefined || temp === null) return
const tempId = Number(temp) const tempId = Number(temp)
if (isInt(p.msgId)) this.db.confirmPending(tempId, p.msgId) if (isInt(p.msgId)) this.db.confirmPending(tempId, p.msgId)
else { else this.db.markFailed(tempId, typeof p.error === 'string' ? `Rabbit: ${p.error}` : "The Rabbit couldn't send it.")
this.db.markFailed(tempId, typeof p.error === 'string' ? `Rabbit: ${p.error}` : "The Rabbit couldn't send it.")
const m = this.db.getMessage(tempId)
if (m) this.emit('unsent', m)
}
this.db.db.prepare('DELETE FROM kv WHERE key = ?').run(key) this.db.db.prepare('DELETE FROM kv WHERE key = ?').run(key)
this.emit('changed', 'sent') this.emit('changed', 'sent')
} }
+2 -42
View File
@@ -1,6 +1,6 @@
// Where the data lives + non-secret preferences. // Where the data lives + non-secret preferences.
// //
// The message database defaults to ~/Documents/bubble-data so Déjà Dup // The message database defaults to ~/Documents/voipms-desktop-data so Déjà Dup
// backs it up (it excludes ~/.config, ~/.local and ~/.cache). A small pointer // backs it up (it excludes ~/.config, ~/.local and ~/.cache). A small pointer
// file in Electron's userData remembers a custom location if one is chosen. // file in Electron's userData remembers a custom location if one is chosen.
import { app } from 'electron' import { app } from 'electron'
@@ -19,47 +19,7 @@ const DEFAULTS: Settings = {
const pointerFile = (): string => path.join(app.getPath('userData'), 'data-location.json') const pointerFile = (): string => path.join(app.getPath('userData'), 'data-location.json')
export function defaultDataDir(): string { export function defaultDataDir(): string {
return path.join(app.getPath('documents'), 'bubble-data') return path.join(app.getPath('documents'), 'voipms-desktop-data')
}
// Where it lived before the app was called bubble.
const OLD_NAME = 'voipms-desktop-data'
// Once, before anything opens the database: copy ~/Documents/voipms-desktop-data
// to ~/Documents/bubble-data (via a .partial folder, renamed only when the
// copy is whole) and use that. The old folder stays as a backup, with a note
// saying so, for its owner to delete. Only the default place moves: a folder
// chosen in Settings stays where it is. If the copy fails, carry on in the old
// folder rather than starting an empty history.
export function moveToBubbleData(): void {
if (process.env['VOIPMS_DATA_DIR']) return
const old = path.join(app.getPath('documents'), OLD_NAME)
const dest = defaultDataDir()
let pointed: string | undefined
try {
pointed = (JSON.parse(fs.readFileSync(pointerFile(), 'utf8')) as { dataDir?: string }).dataDir
} catch {
/* no pointer: the default place */
}
if (pointed && path.resolve(pointed) !== path.resolve(old)) return
if (!fs.existsSync(path.join(old, 'messages.db')) || fs.existsSync(dest)) return
const partial = `${dest}.partial`
try {
fs.rmSync(partial, { recursive: true, force: true }) // a copy cut short last time
console.log(`[data] copying ${old} to ${dest}`)
fs.cpSync(old, partial, { recursive: true, preserveTimestamps: true, errorOnExist: true })
fs.renameSync(partial, dest)
if (pointed) setDataDir(dest)
fs.writeFileSync(
path.join(old, 'MOVED TO bubble-data.txt'),
`bubble copied this folder to ${dest} on ${new Date().toString()} and uses that one now.\n` +
`This is the backup from before the move: once bubble looks right, it can be deleted.\n`
)
} catch (e) {
console.error('[data] copy to bubble-data failed; staying in the old folder:', e)
fs.rmSync(partial, { recursive: true, force: true })
setDataDir(old)
}
} }
export function getDataDir(): string { export function getDataDir(): string {
+1 -1
View File
@@ -18,7 +18,7 @@ function parseYmd(s: string): number {
return Date.parse(s + 'T00:00:00Z') return Date.parse(s + 'T00:00:00Z')
} }
export const isMmsPlaceholder = (body: string): boolean => /^mms (received|sent)$/.test(body.trim().toLowerCase()) export const isMmsPlaceholder = (body: string): boolean => body.trim().toLowerCase() === 'mms received'
export function toNewMessage(r: RawSms): NewMessage { export function toNewMessage(r: RawSms): NewMessage {
const m: NewMessage = { const m: NewMessage = {
+6 -27
View File
@@ -21,11 +21,6 @@ export interface Jump {
nonce: number nonce: number
} }
/** Which chats the sidebar lists. */
export type ListView = 'chats' | 'archived' | 'unread'
export const isUnread = (c: Conversation): boolean => c.unread > 0 || c.markedUnread
export const sameConv = (a?: ConvKey | null, b?: ConvKey | null): boolean => !!a && !!b && a.did === b.did && a.contact === b.contact export const sameConv = (a?: ConvKey | null, b?: ConvKey | null): boolean => !!a && !!b && a.did === b.did && a.contact === b.contact
export function App() { export function App() {
@@ -39,13 +34,7 @@ export function App() {
const [sync, setSync] = useState<SyncStatus>() const [sync, setSync] = useState<SyncStatus>()
const [settingsOpen, setSettingsOpen] = useState(false) const [settingsOpen, setSettingsOpen] = useState(false)
const [msgVersion, setMsgVersion] = useState(0) const [msgVersion, setMsgVersion] = useState(0)
const [view, setViewState] = useState<ListView>('chats') const [archiveView, setArchiveView] = useState(false)
// The chat opened from the unread view: it stays listed (read now) until another is opened.
const [kept, setKept] = useState<ConvKey | null>(null)
const setView = useCallback((v: ListView) => {
setViewState(v)
setKept(null)
}, [])
const [info, setInfo] = useState<ConvKey | null>(null) const [info, setInfo] = useState<ConvKey | null>(null)
const [exporting, setExporting] = useState<ConvKey | null>(null) const [exporting, setExporting] = useState<ConvKey | null>(null)
const [adding, setAdding] = useState<string | null>(null) const [adding, setAdding] = useState<string | null>(null)
@@ -71,7 +60,6 @@ export function App() {
window.api.onOpenConversation((key) => { window.api.onOpenConversation((key) => {
setMode('chats') setMode('chats')
setSelected(key) setSelected(key)
setKept(key)
setJump(undefined) setJump(undefined)
}) })
] ]
@@ -90,7 +78,6 @@ export function App() {
const open = useCallback((key: ConvKey, jumpTo?: number) => { const open = useCallback((key: ConvKey, jumpTo?: number) => {
setSelected(key) setSelected(key)
setKept(key)
setJump(jumpTo !== undefined ? { id: jumpTo, nonce: Date.now() } : undefined) setJump(jumpTo !== undefined ? { id: jumpTo, nonce: Date.now() } : undefined)
}, []) }, [])
@@ -98,14 +85,7 @@ export function App() {
const onMarkUnread = useCallback((key: ConvKey) => setSelected((cur) => (sameConv(cur, key) ? null : cur)), []) const onMarkUnread = useCallback((key: ConvKey) => setSelected((cur) => (sameConv(cur, key) ? null : cur)), [])
// The list currently shown in the sidebar (for Alt+↑/↓). // The list currently shown in the sidebar (for Alt+↑/↓).
// The unread view takes archived chats too. const listed = useMemo(() => conversations.filter((c) => c.archived === archiveView), [conversations, archiveView])
const listed = useMemo(
() =>
conversations.filter((c) =>
view === 'unread' ? isUnread(c) || sameConv(c, kept) : c.archived === (view === 'archived')
),
[conversations, view, kept]
)
useEffect(() => setTooltipsEnabled(state?.settings.showTooltips !== false), [state?.settings.showTooltips]) useEffect(() => setTooltipsEnabled(state?.settings.showTooltips !== false), [state?.settings.showTooltips])
// Which look the stylesheet draws (styles.css): the house look unless Signal vibes are chosen. // Which look the stylesheet draws (styles.css): the house look unless Signal vibes are chosen.
@@ -123,10 +103,10 @@ export function App() {
document.getElementById('sidebar-search')?.focus() document.getElementById('sidebar-search')?.focus()
} else if (c === 'newChat') setMode('compose') } else if (c === 'newChat') setMode('compose')
else if (c === 'preferences') setSettingsOpen(true) else if (c === 'preferences') setSettingsOpen(true)
else if (c === 'archived') setView(view === 'archived' ? 'chats' : 'archived') else if (c === 'archived') setArchiveView((v) => !v)
else if (c === 'checkNow') void window.api.pollNow() else if (c === 'checkNow') void window.api.pollNow()
}), }),
[state?.configured, view, setView] [state?.configured]
) )
// Keyboard shortcuts (Signal-like, plus the menu bar's). // Keyboard shortcuts (Signal-like, plus the menu bar's).
@@ -186,9 +166,8 @@ export function App() {
gvNumber={state.gvoiceNumber} gvNumber={state.gvoiceNumber}
defaultDid={state.settings.defaultDid ?? smsDids[0]?.did} defaultDid={state.settings.defaultDid ?? smsDids[0]?.did}
onSettings={() => setSettingsOpen(true)} onSettings={() => setSettingsOpen(true)}
view={view} archiveView={archiveView}
setView={setView} setArchiveView={setArchiveView}
listed={listed}
onMarkUnread={onMarkUnread} onMarkUnread={onMarkUnread}
onInfo={setInfo} onInfo={setInfo}
onExport={setExporting} onExport={setExporting}
+2 -32
View File
@@ -6,7 +6,7 @@ import type { ConvKey, Jump } from '../App'
import { chatsWith, convName, dayLabel, sameDay, senderName, senderShortName } from '../format' import { chatsWith, convName, dayLabel, sameDay, senderName, senderShortName } from '../format'
import { Avatar } from './Avatar' import { Avatar } from './Avatar'
import { Composer, type ComposerHandle } from './Composer' import { Composer, type ComposerHandle } from './Composer'
import { AlertIcon, CloseIcon, DownIcon, SearchIcon, UpIcon } from './Icons' import { CloseIcon, DownIcon, SearchIcon, UpIcon } from './Icons'
import { conversationMedia, Lightbox } from './Lightbox' import { conversationMedia, Lightbox } from './Lightbox'
import { MessageBubble } from './MessageBubble' import { MessageBubble } from './MessageBubble'
import { DEFAULT_QUICK_REACTIONS, reactionText, sameEmoji, type Reaction } from '@shared/reactions' import { DEFAULT_QUICK_REACTIONS, reactionText, sameEmoji, type Reaction } from '@shared/reactions'
@@ -166,22 +166,6 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam
return [{ label: sel ? 'Copy' : 'Copy text', onSelect: () => void navigator.clipboard.writeText(sel || m.body) }] return [{ label: sel ? 'Copy' : 'Copy text', onSelect: () => void navigator.clipboard.writeText(sel || m.body) }]
} }
const unsent = useMemo(() => (messages ?? []).filter((m) => m.status === 'failed'), [messages])
// Edit on a text that wasn't sent: its words (and pictures) go back into the
// box, and the failed copy goes, so what's sent next is the edited one.
const editFailed = useCallback(async (m: Message) => {
const files = await Promise.all(
(m.media ?? []).map(async (ref, i) => {
const { mime, data } = await window.api.readMedia(m.id, i)
return new File([data], ref.file ?? `photo-${i + 1}`, { type: mime })
})
).catch(() => undefined)
if (!files) return // keep it rather than lose its pictures
composer.current?.edit(m.body, files)
await window.api.deleteFailed(m.id)
}, [])
const indexOf = useCallback((id: number) => rows.findIndex((r) => r.kind === 'msg' && r.m.id === id), [rows]) const indexOf = useCallback((id: number) => rows.findIndex((r) => r.kind === 'msg' && r.m.id === id), [rows])
const flash = useCallback((id: number) => { const flash = useCallback((id: number) => {
@@ -193,10 +177,6 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam
(id: number) => { (id: number) => {
const index = indexOf(id) const index = indexOf(id)
if (index < 0) return if (index < 0) return
// Leaving the bottom: otherwise pictures that finish loading around the
// target (onMediaLoad) see the stale "at bottom" and snap back down
// before Virtuoso reports we've moved.
atBottom.current = false
virtuoso.current?.scrollToIndex({ index, align: 'center' }) virtuoso.current?.scrollToIndex({ index, align: 'center' })
flash(id) flash(id)
}, },
@@ -341,6 +321,7 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam
<input <input
ref={searchInput} ref={searchInput}
value={q} value={q}
placeholder="Search in chat"
aria-label="Search in chat (Ctrl+Shift+F)" aria-label="Search in chat (Ctrl+Shift+F)"
onChange={(e) => setQ(e.target.value)} onChange={(e) => setQ(e.target.value)}
onKeyDown={(e) => { onKeyDown={(e) => {
@@ -409,7 +390,6 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam
reactions={folded.reactions.get(r.m.id)} reactions={folded.reactions.get(r.m.id)}
onShowReactions={showReactions} onShowReactions={showReactions}
onMenu={showMsgMenu} onMenu={showMsgMenu}
onEditFailed={editFailed}
versions={folded.versions.get(r.m.id)} versions={folded.versions.get(r.m.id)}
onShowEdits={showEdits} onShowEdits={showEdits}
/> />
@@ -419,16 +399,6 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam
)} )}
</div> </div>
{unsent.length > 0 && (
<div className="unsent-banner" role="alert">
<AlertIcon />
<span className="unsent-text">
<b>{unsent.length > 1 ? `${unsent.length} of your texts weren't sent.` : "Your text wasn't sent."}</b> Retry or delete{' '}
{unsent.length > 1 ? 'them' : 'it'} below.
</span>
<button onClick={() => scrollTo(unsent[0].id)}>Show</button>
</div>
)}
<Composer ref={composer} conv={conv} isNew={isNew} smsDids={smsDids} gvNumber={gvNumber} onChangeDid={onChangeDid} /> <Composer ref={composer} conv={conv} isNew={isNew} smsDids={smsDids} gvNumber={gvNumber} onChangeDid={onChangeDid} />
{dragging && <div className="drop-hint">Drop to attach</div>} {dragging && <div className="drop-hint">Drop to attach</div>}
{lightbox && ( {lightbox && (
+1 -10
View File
@@ -17,8 +17,6 @@ const attachmentDrafts = new Map<string, Attachment[]>()
export interface ComposerHandle { export interface ComposerHandle {
addFiles: (files: File[]) => void addFiles: (files: File[]) => void
// Back into the box to change before sending again (a text that wasn't sent).
edit: (text: string, files: File[]) => void
} }
interface Props { interface Props {
@@ -120,14 +118,7 @@ export function Composer({ conv, isNew, smsDids, gvNumber, onChangeDid, ref }: P
textarea.current?.focus() textarea.current?.focus()
} }
const edit = (body: string, files: File[]): void => { useImperativeHandle(ref, () => ({ addFiles }))
// Anything already being typed stays, after it.
setText((cur) => (cur.trim() ? `${body}\n${cur}` : body))
if (files.length) addFiles(files)
textarea.current?.focus()
}
useImperativeHandle(ref, () => ({ addFiles, edit }))
const remove = (a: Attachment): void => { const remove = (a: Attachment): void => {
URL.revokeObjectURL(a.previewUrl) URL.revokeObjectURL(a.previewUrl)
@@ -8,7 +8,7 @@ import { CloseIcon } from './Icons'
import { Via } from './Via' import { Via } from './Via'
import { useAddContact } from './AddContact' import { useAddContact } from './AddContact'
import { conversationMedia, Lightbox, type MediaItem } from './Lightbox' import { conversationMedia, Lightbox, type MediaItem } from './Lightbox'
import { mediaSrc, thumbSrc } from './MessageBubble' import { mediaSrc } from './MessageBubble'
interface Props { interface Props {
conv: ConvKey conv: ConvKey
@@ -67,7 +67,7 @@ function MediaGrid({ conv }: { conv: ConvKey }) {
</span> </span>
</> </>
) : ( ) : (
<img src={thumbSrc(it.id, it.index)} alt="" loading="lazy" decoding="async" draggable={false} onError={() => setBroken((b) => new Set(b).add(key(it)))} /> <img src={mediaSrc(it.id, it.index)} alt="" loading="lazy" draggable={false} onError={() => setBroken((b) => new Set(b).add(key(it)))} />
)} )}
</div> </div>
))} ))}
@@ -117,15 +117,7 @@ const ConversationRow = memo(function ConversationRow({
<span className="row-time">{shortTime(conv.lastTs)}</span> <span className="row-time">{shortTime(conv.lastTs)}</span>
</div> </div>
<div className="row-bottom"> <div className="row-bottom">
<span className="row-preview"> <span className="row-preview">{preview}</span>
{conv.failed > 0 && <b className="row-unsent">Not sent · </b>}
{preview}
</span>
{conv.failed > 0 && (
<span className="badge unsent" title={conv.failed > 1 ? `${conv.failed} texts weren't sent` : "A text wasn't sent"}>
!
</span>
)}
{conv.unread > 0 ? ( {conv.unread > 0 ? (
<span className="badge">{conv.unread > 99 ? '99+' : conv.unread}</span> <span className="badge">{conv.unread > 99 ? '99+' : conv.unread}</span>
) : ( ) : (
-8
View File
@@ -90,14 +90,6 @@ export const ArchiveIcon = () => (
<path d="M5 9v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9M10 13h4" /> <path d="M5 9v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9M10 13h4" />
</svg> </svg>
) )
// Three outlined bubbles of different sizes: the unread view.
export const BubblesIcon = () => (
<svg {...base}>
<circle cx="8.5" cy="14.5" r="5.5" />
<circle cx="17" cy="6" r="3" />
<circle cx="20" cy="17" r="2" />
</svg>
)
export const GroupIcon = () => ( export const GroupIcon = () => (
<svg {...base}> <svg {...base}>
<circle cx="9" cy="8" r="3.5" /> <circle cx="9" cy="8" r="3.5" />
+5 -24
View File
@@ -30,8 +30,6 @@ function renderText(text: string, highlight: string): ReactNode[] {
} }
export const mediaSrc = (id: number, index: number): string => `mms-media://m/${id}/${index}` export const mediaSrc = (id: number, index: number): string => `mms-media://m/${id}/${index}`
// The smaller copy the chat and Get info show (the original if it's small already).
export const thumbSrc = (id: number, index: number): string => `${mediaSrc(id, index)}?thumb`
// Display box for an image: fit within 300×360, keeping the aspect ratio when // 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). // we know it (so the list doesn't jump when the image arrives).
@@ -43,8 +41,8 @@ function imageBox(ref: MediaRef): { width: number; height: number } | undefined
function Attachment({ id, index, media, onOpen, onMenu, onLoad }: { id: number; index: number; media: MediaRef; onOpen: () => void; onMenu: (e: React.MouseEvent) => void; onLoad: () => void }) { 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 [broken, setBroken] = useState(false)
const src = mediaSrc(id, index)
const kind = mediaKind(media) const kind = mediaKind(media)
const src = kind === 'image' ? thumbSrc(id, index) : mediaSrc(id, index)
// Still on the Rabbit (relayed history): asked for, it arrives after the Rabbit's next check. // Still on the Rabbit (relayed history): asked for, it arrives after the Rabbit's next check.
if (broken && media.url?.startsWith('mmspart:') && !media.file) return <div className="media-missing">On the Rabbit — it'll appear after its next check</div> if (broken && media.url?.startsWith('mmspart:') && !media.file) return <div className="media-missing">On the Rabbit — it'll appear after its next check</div>
if (broken) return <div className="media-missing">Media unavailable</div> if (broken) return <div className="media-missing">Media unavailable</div>
@@ -55,7 +53,6 @@ function Attachment({ id, index, media, onOpen, onMenu, onLoad }: { id: number;
src={src} src={src}
alt="" alt=""
draggable={false} draggable={false}
decoding="async"
style={imageBox(media) ?? { minHeight: 120, minWidth: 120 }} style={imageBox(media) ?? { minHeight: 120, minWidth: 120 }}
onClick={onOpen} onClick={onOpen}
onContextMenu={onMenu} onContextMenu={onMenu}
@@ -88,13 +85,9 @@ interface Props {
onOpenMedia: (id: number, index: number) => void onOpenMedia: (id: number, index: number) => void
onMediaMenu: (id: number, index: number, e: React.MouseEvent) => void onMediaMenu: (id: number, index: number, e: React.MouseEvent) => void
onMediaLoad: () => void onMediaLoad: () => void
onEditFailed?: (m: Message) => void
} }
// A send still going after this long gets a visible "Still sending…". export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMenu, reactions, onShowReactions, onMenu, versions, onShowEdits, groupStart, groupEnd, flash, highlight, onOpenMedia, onMediaMenu, onMediaLoad }: Props) {
const SLOW_SEND_MS = 15_000
export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMenu, reactions, onShowReactions, onMenu, versions, onShowEdits, groupStart, groupEnd, flash, highlight, onOpenMedia, onMediaMenu, onMediaLoad, onEditFailed }: Props) {
const media = m.media ?? [] const media = m.media ?? []
const cls = [ const cls = [
'msg', 'msg',
@@ -141,11 +134,6 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe
{m.status === 'pending' && ( {m.status === 'pending' && (
<span className="status" title="Sending…"> <span className="status" title="Sending…">
<ClockIcon /> <ClockIcon />
{/* Appears once a send has taken a while (the negative delay
counts time already spent, so it survives re-renders). */}
<span className="slow-send" style={{ animationDelay: `${SLOW_SEND_MS - (Date.now() - m.ts)}ms` }}>
Still sending…
</span>
</span> </span>
)} )}
</span> </span>
@@ -161,17 +149,10 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe
</button> </button>
)} )}
{m.status === 'failed' && ( {m.status === 'failed' && (
<div className="failed-row" role="alert"> <div className="failed-row">
<span className="failed-why"> <AlertIcon /> Not sent{m.error ? `: ${m.error}` : ''} ·
<AlertIcon /> <b>Not sent.</b> {m.error ?? ''} <button onClick={() => void window.api.retryFailed(m.id).catch(() => undefined)}>Retry</button>·
</span>
<span className="failed-actions">
<button className="failed-retry" onClick={() => void window.api.retryFailed(m.id).catch(() => undefined)}>
Retry
</button>
{onEditFailed && <button onClick={() => onEditFailed(m)}>Edit</button>}
<button onClick={() => void window.api.deleteFailed(m.id)}>Delete</button> <button onClick={() => void window.api.deleteFailed(m.id)}>Delete</button>
</span>
</div> </div>
)} )}
</div> </div>
@@ -225,7 +225,7 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
), ),
Contacts: <ContactsSection value={s.contactBook} onChange={(contactBook) => change({ ...s, contactBook })} />, Contacts: <ContactsSection value={s.contactBook} onChange={(contactBook) => change({ ...s, contactBook })} />,
Rabbit: <RabbitSection onChanged={onChanged} />, Rabbit: <RabbitSection onChanged={onChanged} />,
'Relay server': <RelaySection onChanged={onChanged} />, jai: <RelaySection onChanged={onChanged} />,
Storage: ( Storage: (
<section className="group"> <section className="group">
<h3>Storage &amp; backups</h3> <h3>Storage &amp; backups</h3>
@@ -499,10 +499,10 @@ function RabbitSection({ onChanged }: { onChanged: () => void }) {
) )
} }
// The Rabbit's SIM (and names + read status) through the relay server, no cable needed. // The Rabbit's SIM (and names + read status) through jai, no cable needed.
function RelaySection({ onChanged }: { onChanged: () => void }) { function RelaySection({ onChanged }: { onChanged: () => void }) {
const [st, setSt] = useState<RelayStatus>() const [st, setSt] = useState<RelayStatus>()
const [url, setUrl] = useState('') const [url, setUrl] = useState('http://100.69.139.40:8080')
const [token, setToken] = useState('') const [token, setToken] = useState('')
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [error, setError] = useState<string>() const [error, setError] = useState<string>()
@@ -550,10 +550,10 @@ function RelaySection({ onChanged }: { onChanged: () => void }) {
: undefined : undefined
return ( return (
<section className="group"> <section className="group">
<h3>Relay server</h3> <h3>Rabbit relay</h3>
<p className="muted small"> <p className="muted small">
Texts the Rabbit's SIM card sends and gets show up here, you can text from it here (as "Rabbit SIM"), and chat names and Texts the Rabbit's SIM card sends and gets show up here, you can text from it here (as "Rabbit SIM"), and chat names and
read/unread/archived stay in step with the Rabbit without plugging it in. It goes through your relay server (server/bubble_relay.py), which only passes on sealed messages read/unread/archived stay in step with the Rabbit without plugging it in. It goes through jai, which only passes on sealed messages
it can't read: the key stays on this computer and the Rabbit. A text sent from here goes out at the Rabbit's next background check it can't read: the key stays on this computer and the Rabbit. A text sent from here goes out at the Rabbit's next background check
(Settings there: how often), so it can take a while. (Settings there: how often), so it can take a while.
</p> </p>
@@ -583,7 +583,7 @@ function RelaySection({ onChanged }: { onChanged: () => void }) {
<> <>
<label className="field"> <label className="field">
Address Address
<input value={url} onChange={(e) => setUrl(e.target.value)} placeholder="http://100.x.y.z:8080" spellCheck={false} /> <input value={url} onChange={(e) => setUrl(e.target.value)} spellCheck={false} />
</label> </label>
<label className="field"> <label className="field">
Token Token
@@ -591,12 +591,12 @@ function RelaySection({ onChanged }: { onChanged: () => void }) {
type="password" type="password"
value={token} value={token}
onChange={(e) => setToken(e.target.value)} onChange={(e) => setToken(e.target.value)}
placeholder="from scripts/deploy-relay.sh --token" placeholder="from scripts/deploy-jai.sh --token"
autoComplete="off" autoComplete="off"
/> />
</label> </label>
<div className="btn-row"> <div className="btn-row">
<button className="primary" disabled={busy || !url.trim() || !token.trim()} onClick={connect}> <button className="primary" disabled={busy || !token.trim()} onClick={connect}>
Connect Connect
</button> </button>
</div> </div>
+14 -26
View File
@@ -1,20 +1,13 @@
import { useEffect, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react' import { useEffect, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react'
import type { ContactInfo, Conversation, Did, SyncStatus } from '@shared/types' import type { ContactInfo, Conversation, Did, SyncStatus } from '@shared/types'
import type { ConvKey, ListView } from '../App' import type { ConvKey } from '../App'
import { ConversationList } from './ConversationList' import { ConversationList } from './ConversationList'
import { SearchResults } from './SearchResults' import { SearchResults } from './SearchResults'
import { NewChat } from './NewChat' import { NewChat } from './NewChat'
import { ArchiveIcon, BackIcon, BubblesIcon, CloseIcon, ComposeIcon, GearIcon, RefreshIcon, SearchIcon } from './Icons' import { ArchiveIcon, BackIcon, CloseIcon, ComposeIcon, GearIcon, RefreshIcon, SearchIcon } from './Icons'
export type SidebarMode = 'chats' | 'search' | 'compose' export type SidebarMode = 'chats' | 'search' | 'compose'
const VIEW_TITLE = { unread: 'Unread chats', archived: 'Archived chats' } as const
const EMPTY_TEXT: Record<ListView, string> = {
chats: 'No conversations yet.',
archived: 'No archived chats. Right-click a chat to archive it.',
unread: 'No unread chats.'
}
// Dragging below the default width shrinks the sidebar's contents // Dragging below the default width shrinks the sidebar's contents
// proportionally (via --s) rather than dropping parts of each row. // proportionally (via --s) rather than dropping parts of each row.
const DEFAULT_WIDTH = 340 const DEFAULT_WIDTH = 340
@@ -107,10 +100,8 @@ interface Props {
gvNumber?: string gvNumber?: string
defaultDid?: string defaultDid?: string
onSettings: () => void onSettings: () => void
view: ListView archiveView: boolean
setView: (v: ListView) => void setArchiveView: (on: boolean) => void
/** The chats the current view shows. */
listed: Conversation[]
onMarkUnread: (key: ConvKey) => void onMarkUnread: (key: ConvKey) => void
onInfo: (key: ConvKey) => void onInfo: (key: ConvKey) => void
onExport: (key: ConvKey) => void onExport: (key: ConvKey) => void
@@ -185,20 +176,17 @@ export function Sidebar(p: Props) {
<ComposeIcon /> <ComposeIcon />
</button> </button>
<RefreshButton /> <RefreshButton />
{(['unread', 'archived'] as const).map((v) => (
<button <button
key={v} className={`icon-btn${p.archiveView ? ' on' : ''}`}
className={`icon-btn${p.view === v ? ' on' : ''}`} title={p.archiveView ? 'Back to chats' : 'Archived chats'}
title={p.view === v ? 'Back to chats' : VIEW_TITLE[v]} aria-pressed={p.archiveView}
aria-pressed={p.view === v}
onClick={() => { onClick={() => {
p.setView(p.view === v ? 'chats' : v) p.setArchiveView(!p.archiveView)
if (p.mode === 'search') clearSearch() if (p.mode === 'search') clearSearch()
}} }}
> >
{v === 'unread' ? <BubblesIcon /> : <ArchiveIcon />} <ArchiveIcon />
</button> </button>
))}
<button className="icon-btn" title="Preferences (Ctrl+,)" onClick={p.onSettings}> <button className="icon-btn" title="Preferences (Ctrl+,)" onClick={p.onSettings}>
<GearIcon /> <GearIcon />
</button> </button>
@@ -216,21 +204,21 @@ export function Sidebar(p: Props) {
/> />
) : ( ) : (
<> <>
{p.view !== 'chats' && ( {p.archiveView && (
<div className="archive-header"> <div className="archive-header">
<button className="icon-btn inline" title="Back to chats" onClick={() => p.setView('chats')}> <button className="icon-btn inline" title="Back to chats" onClick={() => p.setArchiveView(false)}>
<BackIcon /> <BackIcon />
</button> </button>
{VIEW_TITLE[p.view]} Archived chats
</div> </div>
)} )}
<ConversationList <ConversationList
conversations={p.listed} conversations={p.conversations.filter((c) => c.archived === p.archiveView)}
contactMap={p.contactMap} contactMap={p.contactMap}
selected={p.selected} selected={p.selected}
multiDid={p.multiDid} multiDid={p.multiDid}
gvNumber={p.gvNumber} gvNumber={p.gvNumber}
emptyText={EMPTY_TEXT[p.view]} emptyText={p.archiveView ? 'No archived chats. Right-click a chat to archive it.' : 'No conversations yet.'}
onOpen={p.onOpen} onOpen={p.onOpen}
onMarkUnread={p.onMarkUnread} onMarkUnread={p.onMarkUnread}
onInfo={p.onInfo} onInfo={p.onInfo}
+18 -149
View File
@@ -527,6 +527,9 @@ mark {
.msg.out:not(.g-end) .bubble { .msg.out:not(.g-end) .bubble {
border-bottom-right-radius: 4px; border-bottom-right-radius: 4px;
} }
.msg.failed .bubble {
opacity: 0.6;
}
.bubble a { .bubble a {
color: inherit; color: inherit;
text-decoration: underline; text-decoration: underline;
@@ -545,85 +548,21 @@ mark {
background: rgba(255, 255, 255, 0.9); background: rgba(255, 255, 255, 0.9);
color: #1b1b1b; color: #1b1b1b;
} }
/* A text that didn't go out: loud, never a quiet little icon. */
.msg.failed .bubble {
outline: 2px solid var(--danger);
outline-offset: 2px;
}
.failed-row { .failed-row {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: flex-end;
flex-wrap: wrap; flex-wrap: wrap;
gap: 6px 10px; gap: 4px;
max-width: 75%; font-size: 12px;
margin: 6px 0 4px auto;
padding: 6px 10px;
border-radius: 8px;
background: color-mix(in srgb, var(--danger) 14%, transparent);
color: var(--danger); color: var(--danger);
font-size: 13px; margin-top: 3px;
}
.failed-why {
display: inline-flex;
align-items: center;
gap: 5px;
}
.failed-actions {
display: inline-flex;
gap: 6px;
} }
.failed-row button { .failed-row button {
border: 1px solid var(--danger); border: 0;
border-radius: 6px;
background: none; background: none;
color: var(--danger); color: var(--danger);
font: inherit; text-decoration: underline;
font-weight: 600; padding: 0 2px;
padding: 2px 10px;
}
.failed-row button.failed-retry {
background: var(--danger);
color: #fff;
}
.slow-send {
margin-left: 3px;
opacity: 0;
animation: slow-send 0s forwards;
}
@keyframes slow-send {
to {
opacity: 1;
}
}
.unsent-banner {
flex: none;
display: flex;
align-items: center;
gap: 8px;
padding: 10px 16px;
background: var(--danger);
color: #fff;
font-size: 14px;
}
.unsent-banner .unsent-text {
flex: 1;
}
.unsent-banner button {
border: 1px solid #fff;
border-radius: 6px;
background: none;
color: #fff;
font: inherit;
font-weight: 600;
padding: 3px 12px;
}
.badge.unsent {
background: var(--danger);
color: #fff;
}
.row-unsent {
color: var(--danger);
} }
/* ---------- composer ---------- */ /* ---------- composer ---------- */
@@ -2351,6 +2290,9 @@ mark {
.msg.out:not(.g-end) .bubble { .msg.out:not(.g-end) .bubble {
border-bottom-right-radius: 4px; border-bottom-right-radius: 4px;
} }
.msg.failed .bubble {
opacity: 0.6;
}
.bubble a { .bubble a {
color: inherit; color: inherit;
text-decoration: underline; text-decoration: underline;
@@ -2369,80 +2311,21 @@ mark {
background: rgba(255, 255, 255, 0.9); background: rgba(255, 255, 255, 0.9);
color: #1b1b1b; color: #1b1b1b;
} }
/* A text that didn't go out: loud, never a quiet little icon. */
.msg.failed .bubble {
outline: 2px solid var(--danger);
outline-offset: 2px;
}
.failed-row { .failed-row {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: flex-end;
flex-wrap: wrap; flex-wrap: wrap;
gap: 6px 10px; gap: 4px;
max-width: 75%; font-size: 12px;
margin: 6px 0 4px auto;
padding: 6px 10px;
border-radius: 8px;
background: color-mix(in srgb, var(--danger) 14%, transparent);
color: var(--danger); color: var(--danger);
font-size: 13px; margin-top: 3px;
}
.failed-why {
display: inline-flex;
align-items: center;
gap: 5px;
}
.failed-actions {
display: inline-flex;
gap: 6px;
} }
.failed-row button { .failed-row button {
border: 1px solid var(--danger); border: 0;
border-radius: 6px;
background: none; background: none;
color: var(--danger); color: var(--danger);
font: inherit; text-decoration: underline;
font-weight: 600; padding: 0 2px;
padding: 2px 10px;
}
.failed-row button.failed-retry {
background: var(--danger);
color: #fff;
}
.slow-send {
margin-left: 3px;
opacity: 0;
animation: slow-send 0s forwards;
}
.unsent-banner {
flex: none;
display: flex;
align-items: center;
gap: 8px;
padding: 10px 16px;
background: var(--danger);
color: #fff;
font-size: 14px;
}
.unsent-banner .unsent-text {
flex: 1;
}
.unsent-banner button {
border: 1px solid #fff;
border-radius: 6px;
background: none;
color: #fff;
font: inherit;
font-weight: 600;
padding: 3px 12px;
}
.badge.unsent {
background: var(--danger);
color: #fff;
}
.row-unsent {
color: var(--danger);
} }
/* ---------- composer ---------- */ /* ---------- composer ---------- */
@@ -3545,14 +3428,6 @@ select {
background: var(--highlight-text); background: var(--highlight-text);
color: var(--highlight); color: var(--highlight);
} }
.row.active .badge.unsent {
background: var(--danger);
color: #fff;
box-shadow: 0 0 0 1.5px #fff;
}
.row.active .row-unsent {
color: inherit;
}
.sync-footer { .sync-footer {
border-top: 0; border-top: 0;
padding-top: 0; padding-top: 0;
@@ -3628,12 +3503,6 @@ select {
.media-file { .media-file {
border-radius: 8px; border-radius: 8px;
} }
/* A bubble round a picture follows its corner at the same 4 px gap as the
sides: the picture's 8 px plus the padding (Signal-style grouped corners
stay tighter). */
.bubble.has-media {
border-radius: 12px;
}
.media-img { .media-img {
cursor: pointer; cursor: pointer;
} }
+1 -1
View File
@@ -8,7 +8,7 @@ export function normalizeNumber(raw: string): string {
return digits return digits
} }
// The Rabbit's SIM, reached through the relay server (main/relay.ts): a number we text // The Rabbit's SIM, reached through jai (main/relay.ts): a number we text
// from that isn't a phone number here. // from that isn't a phone number here.
export const SIM_DID = 'sim' export const SIM_DID = 'sim'
-1
View File
@@ -61,7 +61,6 @@ export interface Conversation {
lastSender?: string // sender of the last message, in group chats lastSender?: string // sender of the last message, in group chats
name?: string // a name you gave the conversation (local only) name?: string // a name you gave the conversation (local only)
unread: number unread: number
failed: number // your texts here that didn't send (shown loudly until retried or deleted)
markedUnread: boolean // manually marked unread (shown as a dot) markedUnread: boolean // manually marked unread (shown as a dot)
archived: boolean archived: boolean
} }
-14
View File
@@ -203,20 +203,6 @@ describe('MessageDb', () => {
expect(db.getMessage(t)?.error).toBe('nope') expect(db.getMessage(t)?.error).toBe('nope')
}) })
it('fails sends a previous run left pending, except over the SIM, and counts them per chat', () => {
const t1 = db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body: 'stranded', ts: 1000 })
const t2 = db.insertPending({ did: 'sim', contact: 'a', direction: 'out', body: 'waits for the Rabbit', ts: 1001 })
const orphans = db.failOrphanedSends('closed mid-send')
expect(orphans.map((m) => m.id)).toEqual([t1])
expect(db.getMessage(t1)).toMatchObject({ status: 'failed', error: 'closed mid-send' })
expect(db.getMessage(t2)?.status).toBe('pending')
expect(db.listConversations().find((c) => c.did === '5550001111')?.failed).toBe(1)
expect(db.listConversations().find((c) => c.did === 'sim')?.failed).toBe(0)
// Still matched if it turns out it did go out.
expect(db.reconcileSent([{ ...msg(50, 'a', 'stranded', 1000, 'out') }])).toEqual([t1])
expect(db.listConversations().find((c) => c.did === '5550001111')?.failed).toBe(0)
})
describe('reconcileSent', () => { describe('reconcileSent', () => {
const MIN = 60_000 const MIN = 60_000
const pending = (body: string, ts: number): number => db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body, ts }) const pending = (body: string, ts: number): number => db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body, ts })
+5 -5
View File
@@ -3,16 +3,16 @@ import { charCount, formatNumber, normalizeNumber } from '@shared/phone'
describe('phone numbers', () => { describe('phone numbers', () => {
it('normalizes NANP numbers to 10 digits', () => { it('normalizes NANP numbers to 10 digits', () => {
expect(normalizeNumber('+1 (541) 555-0142')).toBe('5415550142') expect(normalizeNumber('+1 (541) 280-2626')).toBe('5412802626')
expect(normalizeNumber('15415550142')).toBe('5415550142') expect(normalizeNumber('15412802626')).toBe('5412802626')
expect(normalizeNumber('541.555.0142')).toBe('5415550142') expect(normalizeNumber('541.280.2626')).toBe('5412802626')
expect(normalizeNumber('tel:+15415550142')).toBe('5415550142') expect(normalizeNumber('tel:+15412802626')).toBe('5412802626')
}) })
it('leaves short codes alone', () => { it('leaves short codes alone', () => {
expect(normalizeNumber('72975')).toBe('72975') expect(normalizeNumber('72975')).toBe('72975')
}) })
it('formats', () => { it('formats', () => {
expect(formatNumber('5415550142')).toBe('(541) 555-0142') expect(formatNumber('5412802626')).toBe('(541) 280-2626')
expect(formatNumber('72975')).toBe('72975') expect(formatNumber('72975')).toBe('72975')
}) })
}) })
+1 -1
View File
@@ -1,7 +1,7 @@
// The relay against the dev app on a plugged-in Rabbit (DEVICE=1 npm test -- // The relay against the dev app on a plugged-in Rabbit (DEVICE=1 npm test --
// test/relay.device.test.ts). A throwaway local relay, reached from the Rabbit // test/relay.device.test.ts). A throwaway local relay, reached from the Rabbit
// through adb reverse; the dev app's made-up data (tools/push_sandbox.py). // through adb reverse; the dev app's made-up data (tools/push_sandbox.py).
// Never the real app, never the real relay server. // Never the real app, never jai.
import { execFileSync, spawn, type ChildProcess } from 'node:child_process' import { execFileSync, spawn, type ChildProcess } from 'node:child_process'
import fs from 'node:fs' import fs from 'node:fs'
import net from 'node:net' import net from 'node:net'
+2 -2
View File
@@ -73,7 +73,7 @@ describe('relay', () => {
}) })
it('only sends the token to tailscale or https', () => { it('only sends the token to tailscale or https', () => {
expect(checkUrl('http://100.101.102.103:8080/')).toBe('http://100.101.102.103:8080') expect(checkUrl('http://100.69.139.40:8080/')).toBe('http://100.69.139.40:8080')
expect(() => checkUrl('http://example.com')).toThrow() expect(() => checkUrl('http://example.com')).toThrow()
expect(checkUrl('https://example.com')).toBe('https://example.com') expect(checkUrl('https://example.com')).toBe('https://example.com')
}) })
@@ -143,7 +143,7 @@ describe('relay', () => {
const ref = await media.resolve(oldMms, 0) const ref = await media.resolve(oldMms, 0)
expect(fs.readFileSync(media.filePath(ref!.file!)).toString()).toBe('fake png') expect(fs.readFileSync(media.filePath(ref!.file!)).toString()).toBe('fake png')
// Picked up = gone from the relay server. // Picked up = gone from jai.
expect(await rabbit(key)).toEqual([]) expect(await rabbit(key)).toEqual([])
engine.stop() engine.stop()
db.close() db.close()
+4 -5
View File
@@ -24,7 +24,7 @@ const raw = (id: number, date: string, type = '1'): RawSms => ({
date: `${date} 12:00:00`, date: `${date} 12:00:00`,
type, type,
did: '15550001111', did: '15550001111',
contact: '5415550142', contact: '5412802626',
message: `m${id}` message: `m${id}`
}) })
@@ -33,7 +33,7 @@ describe('toNewMessage', () => {
expect(toNewMessage(raw(7, '2024-02-03', '0'))).toEqual({ expect(toNewMessage(raw(7, '2024-02-03', '0'))).toEqual({
id: 7, id: 7,
did: '5550001111', did: '5550001111',
contact: '5415550142', contact: '5412802626',
direction: 'out', direction: 'out',
body: 'm7', body: 'm7',
ts: Date.UTC(2024, 1, 3, 12) ts: Date.UTC(2024, 1, 3, 12)
@@ -53,7 +53,6 @@ describe('toNewMessage (MMS)', () => {
expect(toNewMessage({ ...mms, message: 'MMS Received', col_media1: url }).body).toBe('') expect(toNewMessage({ ...mms, message: 'MMS Received', col_media1: url }).body).toBe('')
expect(toNewMessage({ ...mms, message: ' mms received\n', col_media1: url }).body).toBe('') expect(toNewMessage({ ...mms, message: ' mms received\n', col_media1: url }).body).toBe('')
expect(toNewMessage({ ...mms, message: 'MMS Received, thanks', col_media1: url }).body).toBe('MMS Received, thanks') expect(toNewMessage({ ...mms, message: 'MMS Received, thanks', col_media1: url }).body).toBe('MMS Received, thanks')
expect(toNewMessage({ ...mms, message: 'MMS Sent', col_media1: url }).body).toBe('')
// Typed by a person, with no picture: kept. // Typed by a person, with no picture: kept.
expect(toNewMessage({ ...mms, message: 'MMS received', col_media1: '' }).body).toBe('MMS received') expect(toNewMessage({ ...mms, message: 'MMS received', col_media1: '' }).body).toBe('MMS received')
}) })
@@ -109,12 +108,12 @@ describe('SyncEngine poll', () => {
const db = new MessageDb(path.join(dir, 'm.db')) const db = new MessageDb(path.join(dir, 'm.db'))
db.set('backfill_done', '1') db.set('backfill_done', '1')
const sent = { ...raw(42, ymd(Date.now()), '0'), message: 'see you at 8' } const sent = { ...raw(42, ymd(Date.now()), '0'), message: 'see you at 8' }
const t = db.insertPending({ did: '5550001111', contact: '5415550142', direction: 'out', body: 'see you at 8', ts: toNewMessage(sent).ts }) const t = db.insertPending({ did: '5550001111', contact: '5412802626', direction: 'out', body: 'see you at 8', ts: toNewMessage(sent).ts })
db.markFailed(t, "voip.ms didn't respond in time.") db.markFailed(t, "voip.ms didn't respond in time.")
const engine = new SyncEngine(db, fakeApi([sent]) as unknown as VoipMs, { pollSeconds: 3600, dids: [], backfillFloor: '2010-01-01' }) const engine = new SyncEngine(db, fakeApi([sent]) as unknown as VoipMs, { pollSeconds: 3600, dids: [], backfillFloor: '2010-01-01' })
await engine.pollNow() await engine.pollNow()
expect(db.getMessage(t)).toBeUndefined() expect(db.getMessage(t)).toBeUndefined()
expect(db.getConversationMessages('5550001111', '5415550142').map((m) => [m.id, m.status])).toEqual([[42, 'delivered']]) expect(db.getConversationMessages('5550001111', '5412802626').map((m) => [m.id, m.status])).toEqual([[42, 'delivered']])
db.close() db.close()
fs.rmSync(dir, { recursive: true, force: true }) fs.rmSync(dir, { recursive: true, force: true })
}) })
+10 -10
View File
@@ -6,19 +6,19 @@ describe('parseVCard', () => {
const card = [ const card = [
'BEGIN:VCARD', 'BEGIN:VCARD',
'VERSION:3.0', 'VERSION:3.0',
'FN:Alex Example', 'FN:Collette Shade',
'N:Example;Alex;;;', 'N:Shade;Collette;;;',
'TEL;X-EVOLUTION-E164=4435550143,;VALUE=UNKNOWN;TYPE=CELL:(443) 555-0143', 'TEL;X-EVOLUTION-E164=4434655721,;VALUE=UNKNOWN;TYPE=CELL:(443) 465-5721',
'TEL;X-EVOLUTION-E164=5415550142,"+1";X-NC-SCOPE="v2-local";TYPE=VOICE:+1541', 'TEL;X-EVOLUTION-E164=5412802626,"+1";X-NC-SCOPE="v2-local";TYPE=VOICE:+1541',
' 5550142', ' 2802626',
'PHOTO;VALUE=BINARY:https://lh5.googleusercontent.com/-abc/photo.jpg', 'PHOTO;VALUE=BINARY:https://lh5.googleusercontent.com/-abc/photo.jpg',
'END:VCARD' 'END:VCARD'
].join('\r\n') ].join('\r\n')
const c = parseVCard(card) const c = parseVCard(card)
expect(c.name).toBe('Alex Example') expect(c.name).toBe('Collette Shade')
expect(c.tels).toEqual([ expect(c.tels).toEqual([
{ number: '4435550143', label: 'cell' }, { number: '4434655721', label: 'cell' },
{ number: '5415550142', label: undefined } { number: '5412802626', label: undefined }
]) ])
expect(c.photo).toEqual({ kind: 'url', url: 'https://lh5.googleusercontent.com/-abc/photo.jpg' }) expect(c.photo).toEqual({ kind: 'url', url: 'https://lh5.googleusercontent.com/-abc/photo.jpg' })
}) })
@@ -40,8 +40,8 @@ describe('parseVCard', () => {
}) })
it('handles grouped properties and escaped text', () => { it('handles grouped properties and escaped text', () => {
const c = parseVCard('BEGIN:VCARD\nitem1.FN:Smith\\, John\nitem1.TEL;type=CELL:+1 541 555 0142\nEND:VCARD') const c = parseVCard('BEGIN:VCARD\nitem1.FN:Smith\\, John\nitem1.TEL;type=CELL:+1 541 280 2626\nEND:VCARD')
expect(c.name).toBe('Smith, John') expect(c.name).toBe('Smith, John')
expect(c.tels[0]).toEqual({ number: '5415550142', label: 'cell' }) expect(c.tels[0]).toEqual({ number: '5412802626', label: 'cell' })
}) })
}) })