v0.2.0: bubble for Android 0.2.0 — chat search, swipe for unread, faster chat opening

Desktop:
- Search lists chats whose own name matches first, so a named group
  isn't pushed out of the top 8 by chats that merely include a member.

Android (Rabbit R1) app, 0.2.0:
- Pull the chat list past its top for a search box (name, person,
  number, then group members; archived chats too; Back clears it).
- Swipe right to left marks a chat unread / read over a magenta band;
  left to right still archives (SwipeActions replaces SwipeArchive).
- Google Voice chats don't offer voice notes in the paperclip bubble.
- Chats open with their newest 60 messages, then the full history;
  marking read (and the Google Voice network call) waits until they're
  on screen. Cached pictures show at once, and one slow download no
  longer blocks the other images. Fixed a contacts reload race.
- Sandbox data gains filler chats, a named group and a 4,000-message chat.

Also: the Android app, Google Voice support, media, export, emoji and
the other work since the first commit, and a CLAUDE.md carrying the
privacy rule.
This commit is contained in:
2026-11-06 02:19:56 -08:00
parent a2b8f764db
commit 8c84feaa91
114 changed files with 12987 additions and 379 deletions
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
# Claude Code Stop hook: when app sources are newer than the installed
# AppImage, rebuild and reinstall it so the desktop launcher runs the latest code.
set -uo pipefail
cd "$(dirname "$0")/../.."
# Set when Claude is already continuing because of this hook; don't loop.
retry=$(jq -r '.stop_hook_active // false' 2>/dev/null || echo false)
bin="$HOME/.local/bin/voipms-desktop.AppImage"
changed=$(find src resources package.json electron.vite.config.ts -newer "$bin" -type f -print -quit 2>/dev/null)
[ -f "$bin" ] && [ -z "$changed" ] && exit 0
log=$(mktemp -t voipms-install.XXXXXX.log)
if npm run install-desktop >"$log" 2>&1; then
msg="Rebuilt and reinstalled bubble. Quit and reopen the app to use the new version."
if pgrep -f "$bin" >/dev/null; then msg="$msg (It's running now, so restart it.)"; fi
printf '{"systemMessage": "%s"}\n' "$msg"
else
# Exit 2 hands the error back to Claude so it can fix the build.
echo "Automatic rebuild (npm run install-desktop) failed; log: $log" >&2
tail -30 "$log" >&2
[ "$retry" = true ] && exit 1
exit 2
fi
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Claude Code PreToolUse hook (Bash): package installs in this repo must go
# through Socket Firewall (sfw), which checks every package -- transitive ones
# included -- against socket.dev before npm downloads it.
set -uo pipefail
cmd=$(jq -r '.tool_input.command // ""' 2>/dev/null)
# A bare npm install/add/update/ci, not already wrapped in sfw.
if grep -Eq '(^|[;&|(]|\s)npm\s+(install|i|add|update|up|upgrade|ci)(\s|$)' <<<"$cmd" &&
! grep -Eq '(^|[;&|(]|\s)sfw\s+npm\s' <<<"$cmd"; then
echo "Package installs in this repo go through Socket Firewall: use 'sfw npm …' or 'npm run deps:install' / 'npm run deps:add -- <pkg>' / 'npm run deps:update'." >&2
exit 2
fi
exit 0
+4
View File
@@ -2,3 +2,7 @@ node_modules/
out/ out/
dist/ dist/
*.log *.log
.claude/settings.local.json
# Android build output
android/build/
+36 -4
View File
@@ -1,4 +1,4 @@
# voip.ms Messages # bubble
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 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.
@@ -10,7 +10,10 @@ A Signal Desktop–style SMS client for [voip.ms](https://voip.ms). It keeps you
- **New chat** (Ctrl+N), with autocomplete from your contacts by name or number. - **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. - 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. - 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. - Alt+↑/↓ moves between conversations.
- Ctrl +/− zooms and Ctrl 0 resets. Choose Light, Dark, or System under Settings → Appearance.
## Where your data lives ## Where your data lives
@@ -19,6 +22,7 @@ A Signal Desktop–style SMS client for [voip.ms](https://voip.ms). It keeps you
| Message database | `~/Documents/voipms-desktop-data/messages.db` | ✅ Déjà Dup covers `~/Documents` | | Message database | `~/Documents/voipms-desktop-data/messages.db` | ✅ Déjà Dup covers `~/Documents` |
| Daily snapshots, last 7 kept | `~/Documents/voipms-desktop-data/snapshots/` | ✅ | | Daily snapshots, last 7 kept | `~/Documents/voipms-desktop-data/snapshots/` | ✅ |
| Settings | `~/Documents/voipms-desktop-data/settings.json` | ✅ | | 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 | | 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 | | Contact photo cache | `~/.config/voipms-desktop/photo-cache/` | ❌ not needed |
@@ -34,10 +38,33 @@ In the voip.ms portal, go to **Main Menu → SOAP & REST/JSON API** and:
Then launch the app and enter your account email and API password. Then launch the app and enter your account email and API password.
### 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
curl -L -o ~/.local/share/fonts/AppleColorEmoji.ttf \
https://github.com/samuelngs/apple-emoji-linux/releases/latest/download/AppleColorEmoji-Linux.ttf
fc-cache -f
```
Alternatively, install the `fonts-apple-color-emoji.rpm` from the same release to make it available system-wide. Restart the app afterward.
## Development ## 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 ```bash
npm install
npm run dev # run with hot reload npm run dev # run with hot reload
npm test # unit tests (run under Electron's Node for better-sqlite3) 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 test:live # also reads your real EDS address books (read-only)
@@ -45,10 +72,15 @@ npm run typecheck
npm run install-desktop # build the AppImage and add a GNOME launcher npm run install-desktop # build the AppImage and add a GNOME launcher
``` ```
To work on the UI against fake data, without touching your real history, run: 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 ```bash
VOIPMS_DEMO=1 VOIPMS_DATA_DIR=/tmp/voipms-demo npm run dev VOIPMS_SANDBOX=/tmp/voipms-sandbox npm run dev # or VOIPMS_DEMO=1, same folder
rm -rf /tmp/voipms-sandbox # start over
``` ```
### Layout ### Layout
+78
View File
@@ -0,0 +1,78 @@
# bubble for Android (Rabbit R1)
The desktop app's companion: the same conversations, both numbers (voip.ms
and Google Voice), group chats, photos, and chat names, on a Rabbit R1. Plain
Java with no libraries and no Gradle, built like andTunes
(`~/Documents/lintunes/andtunes`, whose README and DEVICE.md cover the
toolchain and the R1's screen quirks: everything here is about double a
stock size).
## Getting it onto the Rabbit
Use the desktop app: **Settings → Rabbit → Install to Rabbit**. It installs
the APK bundled with the desktop app, exempts it from Doze (so background
checks keep their interval), and copies into the app's private storage:
- `files/config.json`: voip.ms API login, Google Voice number and sign-in
cookies, the voip.ms numbers to use, the default number
- `files/messages.db`: the desktop's history (same schema, minus the FTS5
search index Android's SQLite can't open)
- `files/media/`: cached photos and attachments
- `files/state-in.json`: chat names and read/unread/archived, merged both ways (newest change wins; the app keeps its side in `files/state.json`)
**Sync to Rabbit** copies the accounts again and merges names and read state without touching the
history. Everything goes in through `adb shell -T "run-as …"`, which is why
the APK is debuggable.
## Building
```sh
python3 android/build.py # -> android/build/release/VoipMessages.apk
python3 android/build.py --ship # ... + copy into resources/android/ (npm run android)
```
`npm run install-desktop` ships it before building the AppImage.
## Testing without real messages
A separate **dev** app (`me.teafry.voipmessages.dev`, "bubble (dev)" on the
launcher) has its own data, so it never touches the real one:
```sh
python3 android/build.py --dev --install
python3 android/tools/push_sandbox.py # made-up conversations; never goes online
```
Or run the desktop in its sandbox (`VOIPMS_SANDBOX=/tmp/x npm run dev`): its
Install/Sync buttons then target the dev app with the sandbox's made-up data.
## How it works
- `Store`: the desktop's SQLite schema; `Sync`: checks voip.ms (last day) and
Google Voice (thread list) like the desktop's polling; `Sender`: the
desktop's send-and-retry rules.
- `GVoice`/`Pb`/`Waa`: the desktop's Google Voice client ported to Java
(message ids hash identically, so copied history and new messages line up).
- Background: `Alarms` (AlarmManager, interval from Settings, "Never" = pull
to refresh only) → `PollJob` → notifications for new incoming messages.
- The launcher icon is `bubble.jpg` cut to just the bubble (transparent outside
an ellipse fitted to the rim's outer edge, pixels inside untouched), at 192 px
in `res/drawable-nodpi/ic_launcher.png`. The desktop's `resources/icon.png`
keeps the full square photo.
- 📎: press it and Camera / Photo / Voice note bubble out of it
(`AttachBubble`); drag onto one and let go, or tap the clip and then tap one. Camera
shots go through the Rabbit's camera app into MediaStore and are deleted
from the gallery once they're in the tray.
- Voice notes (📎 → Voice note): `VoiceActivity` records AAC `.m4a` (32 kbit/s,
3 min cap, under `Media.BUDGET`) and sends it as an MMS. voip.ms numbers
only: Google Voice's sendsms takes image types and nothing else, so a Google
Voice chat's bubble has no microphone.
- Search: pull the chat list down past its top for the search box (it hides
again on Back). Matches what a chat is called (your name for it, the
person, a number), then group chats with a matching member; archived too.
- Swipes (`SwipeActions`): left to right archives (blue band), right to left
marks unread or read (magenta band).
- Opening a chat shows its newest 60 messages first, then the full history;
marking it read (and telling Google Voice) waits until it's on screen.
- The scroll wheel is left alone: it stays the volume control (and volume
down + the side button still takes a screenshot).
+54
View File
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="me.teafry.voipmessages">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- Names come from the Rabbit's own synced contacts. -->
<uses-permission android:name="android.permission.READ_CONTACTS" />
<!-- Voice notes. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- Background checks: an alarm (the desktop installer exempts the app from
Doze) hands off to a job, and boot puts the alarm back. -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:label="@string/app_name"
android:icon="@drawable/ic_launcher"
android:theme="@android:style/Theme.DeviceDefault.NoActionBar"
android:allowBackup="false"
android:usesCleartextTraffic="false">
<activity
android:name="me.teafry.voipmessages.MainActivity"
android:exported="true"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize|stateHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="me.teafry.voipmessages.ChatActivity" android:exported="false"
android:windowSoftInputMode="adjustResize" />
<activity android:name="me.teafry.voipmessages.NewChatActivity" android:exported="false"
android:windowSoftInputMode="adjustResize" />
<activity android:name="me.teafry.voipmessages.SettingsActivity" android:exported="false" />
<activity android:name="me.teafry.voipmessages.InfoActivity" android:exported="false"
android:windowSoftInputMode="adjustResize" />
<activity android:name="me.teafry.voipmessages.ImageActivity" android:exported="false" />
<activity android:name="me.teafry.voipmessages.VoiceActivity" android:exported="false" />
<service android:name="me.teafry.voipmessages.PollJob"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false" />
<receiver android:name="me.teafry.voipmessages.Alarms" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
</application>
</manifest>
@@ -0,0 +1,46 @@
package me.teafry.voipmessages;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
/**
* Background checks: an alarm every N minutes (Settings) starts a one-off job
* that needs the network. The desktop installer exempts the app from Doze, so
* the alarm keeps its interval while the Rabbit sleeps. Boot and app updates
* put the alarm back.
*/
public final class Alarms extends BroadcastReceiver {
private static final String ACTION = "me.teafry.voipmessages.POLL";
private static final int JOB_ID = 1;
@Override
public void onReceive(Context c, Intent intent) {
if (ACTION.equals(intent.getAction())) runJobNow(c);
schedule(c);
}
static void schedule(Context c) {
AlarmManager am = c.getSystemService(AlarmManager.class);
Intent i = new Intent(c, Alarms.class).setAction(ACTION);
PendingIntent pi = PendingIntent.getBroadcast(c, 0, i, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pi);
int minutes = Config.pollMinutes(c);
if (minutes <= 0) return;
am.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + minutes * 60_000L, pi);
}
static void runJobNow(Context c) {
JobInfo job = new JobInfo.Builder(JOB_ID, new ComponentName(c, PollJob.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setOverrideDeadline(60_000)
.build();
c.getSystemService(JobScheduler.class).schedule(job);
}
}
@@ -0,0 +1,394 @@
package me.teafry.voipmessages;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
/**
* Hold the paperclip and the composer swells upward into a bubble while
* 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
* other apart and settle above and to the right of it. The thumb stays down:
* a soft spotlight follows it inside the bubble, leans toward whichever icon
* it's near (so it needn't be exact), and that icon gets a glowing blue ring.
* Let go on one to attach that; let go on none and they all slip back under
* the clip as the bubble sinks.
*
* <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
* 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.
*
* <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 {
interface OnPick {
void pick(int which);
}
static final int CAMERA = 0, PHOTO = 1, VOICE = 2;
private static final String[] GLYPHS = {"📷", "🎨", "🎤"};
private static final String[] LABELS = {"Camera", "Photo", "Voice note"};
// Physics, in dp and seconds (tuned offline: fanned out by ~180 ms, at rest by ~500 ms).
/** Where each icon comes to rest: degrees above the horizontal, and distance from the clip. */
private static final float[] HOME_DEG = {90, 62, 34};
private static final float HOME_DIST = 178;
/** When each leaves the clip (s) and which way it's thrown (degrees). */
private static final float[] LAUNCH_S = {0, 0.03f, 0.06f}, LAUNCH_DEG = {70, 62, 54};
private static final float LAUNCH_SPEED = 700, SPRING = 260, DAMPING = 22;
/** Push between icons, softened so two near each other aren't flung. */
private static final float REPEL = 2.4e6f, REPEL_SOFT = 36;
private static final float RETREAT_S = 0.2f;
private final View anchor, base;
private final OnPick onPick;
/** How many icons: the first two, or all three with the microphone. */
private final int n;
private final float dp;
private final float iconR, snapR, deadR, spotR, margin, corner, fillet;
private final Paint panel = new Paint(Paint.ANTI_ALIAS_FLAG), disk = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint glyph = new Paint(Paint.ANTI_ALIAS_FLAG), label = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint spot = new Paint(Paint.ANTI_ALIAS_FLAG), scrim = new Paint();
private final Paint ring = new Paint(Paint.ANTI_ALIAS_FLAG), glow = new Paint(Paint.ANTI_ALIAS_FLAG);
private final RadialGradient spotShader, glowShader;
private final Matrix m = new Matrix();
private final Path shape = new Path();
private float cx, cy, top; // the clip's centre and the composer's top edge, in px here
private float width; // the bubble's right edge
private float tx, ty; // the thumb
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.
private final float[] px = new float[3], py = new float[3], vx = new float[3], vy = new float[3];
private final float[] fromX = new float[3], fromY = new float[3];
private float age; // s since opening
private float retreat = -1; // s since letting go on nothing, or -1
private boolean picked, settled, gone;
private float rise; // how far the bubble stands above the composer, px
private long lastFrame;
private int selected = -1;
private float ringT; // the selection ring's pop, 0 .. 1
AttachBubble(Activity a, View anchor, View base, boolean voice, OnPick onPick) {
super(a);
n = voice ? 3 : 2;
this.anchor = anchor;
this.base = base;
this.onPick = onPick;
dp = a.getResources().getDisplayMetrics().density;
iconR = 36 * dp;
snapR = 92 * dp;
deadR = 56 * dp;
spotR = 80 * dp;
margin = 18 * dp;
corner = 84 * dp;
fillet = 28 * dp;
panel.setColor(Ui.PANEL);
scrim.setColor(0x33000000);
disk.setColor(Ui.INPUT);
glyph.setTextSize(34 * dp);
glyph.setTextAlign(Paint.Align.CENTER);
label.setTextSize(20 * dp);
label.setTextAlign(Paint.Align.CENTER);
label.setColor(Ui.TEXT);
label.setFakeBoldText(true);
ring.setStyle(Paint.Style.STROKE);
ring.setStrokeWidth(4 * dp);
ring.setColor(0xFF4F8BFF);
spotShader = new RadialGradient(0, 0, spotR, new int[] {0x55FFFFFF, 0x1CFFFFFF, 0x00FFFFFF}, new float[] {0, 0.45f, 1}, Shader.TileMode.CLAMP);
spot.setShader(spotShader);
float g = iconR + 22 * dp;
glowShader = new RadialGradient(0, 0, g,
new int[] {0x002C6BED, 0x002C6BED, 0xAA2C6BED, 0x002C6BED},
new float[] {0, (iconR - 2 * dp) / g, (iconR + 4 * dp) / g, 1}, Shader.TileMode.CLAMP);
glow.setShader(glowShader);
}
/** Put it on the window and start the icons on their way out. */
void show(Activity a) {
ViewGroup decor = (ViewGroup) a.getWindow().getDecorView();
decor.addView(this, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
int[] at = new int[2], me = new int[2];
decor.getLocationOnScreen(me);
anchor.getLocationOnScreen(at);
cx = at[0] - me[0] + anchor.getWidth() / 2f;
cy = at[1] - me[1] + anchor.getHeight() / 2f;
base.getLocationOnScreen(at);
top = at[1] - me[1];
// Wide enough for the right-most icon at rest, plus room around it.
width = cx + (float) Math.cos(Math.toRadians(HOME_DEG[n - 1])) * HOME_DIST * dp + iconR + margin;
tx = cx;
ty = cy;
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
invalidate();
}
private float iconX(int i) {
return cx + px[i] * dp;
}
private float iconY(int i) {
return cy - py[i] * dp;
}
/** How far out of the clip an icon is, 0 .. 1: it grows as it emerges. */
private float emerged(int i) {
return Math.min(1, (float) Math.hypot(px[i], py[i]) / (HOME_DIST * 0.6f));
}
private void step(float dt) {
if (retreat >= 0) {
retreat += dt;
float k = Math.min(1, retreat / RETREAT_S), e = k * k; // ease in: away, not bouncing
for (int i = 0; i < n; i++) {
px[i] = fromX[i] * (1 - e);
py[i] = fromY[i] * (1 - e);
}
if (k >= 1) gone = true;
return;
}
// Substeps keep the springs steady whatever the frame rate.
for (float left = dt; left > 0; left -= 1 / 240f) {
float h = Math.min(left, 1 / 240f);
float before = age;
age += h;
float speed = 0;
for (int i = 0; i < n; i++) {
if (age < LAUNCH_S[i]) continue;
if (before < LAUNCH_S[i] || before == 0) { // just launched
double a = Math.toRadians(LAUNCH_DEG[i]);
vx[i] = (float) Math.cos(a) * LAUNCH_SPEED;
vy[i] = (float) Math.sin(a) * LAUNCH_SPEED;
}
double home = Math.toRadians(HOME_DEG[i]);
float fx = SPRING * ((float) Math.cos(home) * HOME_DIST - px[i]) - DAMPING * vx[i];
float fy = SPRING * ((float) Math.sin(home) * HOME_DIST - py[i]) - DAMPING * vy[i];
for (int j = 0; j < n; j++) {
if (j == i || age < LAUNCH_S[j]) continue;
float dx = px[i] - px[j], dy = py[i] - py[j];
float d = Math.max(0.001f, (float) Math.hypot(dx, dy));
float push = REPEL / (d * d + REPEL_SOFT * REPEL_SOFT);
fx += push * dx / d;
fy += push * dy / d;
}
vx[i] += fx * h;
vy[i] += fy * h;
speed = Math.max(speed, (float) Math.hypot(vx[i], vy[i]));
}
for (int i = 0; i < n; i++) {
if (age < LAUNCH_S[i]) continue;
px[i] += vx[i] * h;
py[i] += vy[i] * h;
}
if (age > 0.3f && speed < 4) settled = true;
}
}
/** The thumb, in screen coordinates. */
void move(float rawX, float rawY) {
if (retreat >= 0 || picked) return;
int[] me = new int[2];
getLocationOnScreen(me);
tx = rawX - me[0];
ty = rawY - me[1];
if (Math.hypot(tx - cx, ty - cy) > 12 * dp) touched = true;
invalidate();
}
/** Nearest icon within reach of the thumb, once the thumb has left the clip. */
private void updateSelection() {
int pick = -1;
if (touched && Math.hypot(tx - cx, ty - cy) > deadR) {
float best = snapR;
for (int i = 0; i < n; i++) {
if (emerged(i) < 0.6f) continue;
float d = (float) Math.hypot(tx - iconX(i), ty - iconY(i));
if (d < best) {
best = d;
pick = i;
}
}
}
if (pick == selected) return;
selected = pick;
ringT = 0;
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
public boolean onTouchEvent(MotionEvent e) {
if (!sticky) return true;
switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
move(e.getRawX(), e.getRawY());
break;
case MotionEvent.ACTION_UP:
release();
break;
case MotionEvent.ACTION_CANCEL:
dismiss();
break;
default:
break;
}
return true;
}
/** The thumb came up: attach what it was on, or tuck everything away. */
void release() {
if (retreat >= 0 || picked) return;
updateSelection();
int pick = selected;
if (pick < 0) {
dismiss();
return;
}
// A quick fade, then the chosen thing opens.
picked = true;
animate().alpha(0).setDuration(140).withEndAction(() -> {
remove();
onPick.pick(pick);
}).start();
}
/** Icons back under the clip, bubble sinking with them. */
void dismiss() {
if (retreat >= 0 || picked) return;
selected = -1;
retreat = 0;
for (int i = 0; i < n; i++) {
fromX[i] = px[i];
fromY[i] = py[i];
}
invalidate();
}
private void remove() {
ViewGroup parent = (ViewGroup) getParent();
if (parent != null) parent.removeView(this);
}
@Override
protected void onDraw(Canvas c) {
long now = System.nanoTime();
float dt = lastFrame == 0 ? 0 : Math.min(1 / 30f, (now - lastFrame) / 1e9f);
lastFrame = now;
if (!picked) step(dt);
if (gone) {
remove();
return;
}
if (!picked && retreat < 0) updateSelection();
// The bubble stands as tall as the icons need, catching up quickly.
float need = 0;
for (int i = 0; i < n; i++) need = Math.max(need, top - (iconY(i) - iconR * emerged(i) - margin));
rise += (need - rise) * (1 - (float) Math.exp(-dt * 28));
if (retreat >= 0) rise = Math.min(rise, need);
// Everything above the composer dims a little; the bubble is the composer, grown.
c.drawRect(0, 0, getWidth(), top, scrim);
if (rise > 1) {
buildShape();
c.drawPath(shape, panel);
}
// The spotlight: under the thumb, leaning toward a chosen icon, kept inside the bubble.
if (touched && retreat < 0 && !picked && rise > 1) {
float sx = tx, sy = ty;
if (selected >= 0) {
sx += (iconX(selected) - sx) * 0.4f;
sy += (iconY(selected) - sy) * 0.4f;
}
c.save();
c.clipPath(shape);
m.setTranslate(sx, sy);
spotShader.setLocalMatrix(m);
c.drawCircle(sx, sy, spotR, spot);
c.restore();
}
// The icons, then the clip drawn again on top so they come out from under it.
Paint.FontMetrics fm = glyph.getFontMetrics();
if (selected >= 0) ringT = Math.min(1, ringT + dt / 0.16f);
float pop = 1 - (1 - ringT) * (1 - ringT);
for (int i = 0; i < n; i++) {
float s = emerged(i);
if (s <= 0.01f) continue;
float x = iconX(i), y = iconY(i);
if (i == selected) {
m.setTranslate(x, y);
glowShader.setLocalMatrix(m);
glow.setAlpha((int) (255 * pop));
c.drawCircle(x, y, iconR + 22 * dp, glow);
}
c.drawCircle(x, y, iconR * s, disk);
if (i == selected) {
ring.setAlpha((int) (255 * pop));
c.drawCircle(x, y, (iconR + 4 * dp) * (0.8f + 0.2f * pop), ring);
}
glyph.setAlpha((int) (255 * s));
c.save();
c.scale(s, s, x, y);
c.drawText(GLYPHS[i], x, y - (fm.ascent + fm.descent) / 2, glyph);
c.restore();
}
int[] at = new int[2], me = new int[2];
anchor.getLocationOnScreen(at);
getLocationOnScreen(me);
c.save();
c.translate(at[0] - me[0], at[1] - me[1]);
anchor.draw(c);
c.restore();
// What letting go will do, above the icon.
if (selected >= 0 && retreat < 0) {
label.setAlpha((int) (255 * pop));
c.drawText(LABELS[selected], iconX(selected), iconY(selected) - iconR - 14 * dp, label);
}
if (!settled || retreat >= 0 || (selected >= 0 && ringT < 1) || Math.abs(need - rise) > 0.5f) postInvalidateOnAnimation();
}
/**
* The composer's top edge bulging up over the clip: square to the screen's
* left edge, round at the top, and flowing back into the edge on the right.
*/
private void buildShape() {
float t = top - rise, r = Math.min(corner, rise), f = Math.min(fillet, rise);
shape.rewind();
shape.moveTo(0, top + 1);
shape.lineTo(0, t);
shape.lineTo(width - r, t);
shape.quadTo(width, t, width, t + r);
shape.lineTo(width, top - f);
shape.quadTo(width, top, width + f, top);
shape.lineTo(width + f, top + 1);
shape.close();
}
}
@@ -0,0 +1,36 @@
package me.teafry.voipmessages;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
/**
* What every screen shares: the dark window, redrawing when messages change,
* and not notifying while a screen is showing. (The scroll wheel is left to
* the system as volume, so volume down + the side button still screenshots.)
*/
abstract class BaseActivity extends Activity implements Sync.Listener {
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
Window w = getWindow();
w.setStatusBarColor(Ui.BG);
w.setNavigationBarColor(Ui.BG);
w.getDecorView().setBackgroundColor(Ui.BG);
}
@Override
protected void onResume() {
super.onResume();
Notifier.visible++;
Sync.listen(this);
changed();
}
@Override
protected void onPause() {
super.onPause();
Notifier.visible--;
Sync.unlisten(this);
}
}
@@ -0,0 +1,799 @@
package me.teafry.voipmessages;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.util.Linkify;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/** One conversation. */
public final class ChatActivity extends BaseActivity {
private static final int PICK = 1;
private static final int VOICE = 2;
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 String did, contact;
private boolean group;
private ListView list;
private TextView titleView, subView, counter, attach, send;
private EditText input;
private LinearLayout header, composerBox, tray, fromRow;
// The keyboard is up: the composer shrinks so what's being typed and the
// last few messages both fit above it (see setCompact).
private boolean compact;
private Spinner from;
private final List<Object> rows = new ArrayList<>(); // Long day-start or Store.Msg
private final List<Sender.Photo> photos = new ArrayList<>();
private java.util.Map<Long, List<Reactions.Reaction>> reactions = new java.util.HashMap<>();
private Adapter adapter;
private boolean firstLoad = true;
/** How many messages to show first when a chat opens (a few screens' worth). */
private static final int RECENT = 60;
// Audio playing in the list: one at a time, keyed "id/index".
private android.media.MediaPlayer player;
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.
private Uri shot;
static Intent intent(Context c, String did, String contact) {
return new Intent(c, ChatActivity.class).putExtra("did", did).putExtra("contact", contact)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
did = getIntent().getStringExtra("did");
if (b != null) shot = b.getParcelable("shot");
contact = getIntent().getStringExtra("contact");
group = Phone.isGroup(contact);
LinearLayout root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
header = new LinearLayout(this);
header.setOrientation(LinearLayout.VERTICAL);
header.setPadding(Ui.dp(this, 24), Ui.dp(this, 10), Ui.dp(this, 24), Ui.dp(this, 10));
header.setBackgroundColor(Ui.PANEL);
titleView = Ui.bold(Ui.text(this, "", Ui.T_NAME, Ui.TEXT));
titleView.setSingleLine();
titleView.setEllipsize(android.text.TextUtils.TruncateAt.END);
subView = Ui.text(this, "", Ui.T_TINY, Ui.MUTED);
subView.setSingleLine();
header.addView(titleView);
header.addView(subView);
if (group) header.setOnClickListener(v -> startActivity(InfoActivity.intent(this, did, contact)));
root.addView(header);
list = new ListView(this);
list.setDivider(null);
list.setSelector(android.R.color.transparent);
list.setStackFromBottom(true);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
list.setPadding(0, Ui.dp(this, 8), 0, Ui.dp(this, 8));
list.setClipToPadding(false);
adapter = new Adapter();
list.setAdapter(adapter);
root.addView(list, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1));
root.addView(composer());
setContentView(root);
root.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
Rect r = new Rect();
root.getWindowVisibleDisplayFrame(r);
int screen = root.getRootView().getHeight();
boolean keyboard = screen - r.bottom > screen / 4;
if (keyboard != compact) setCompact(keyboard);
});
}
/**
* The R1 has 640 px of height and the keyboard takes about half: with a
* photo attached, the full-size composer would push the text box under
* 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.
*/
private void setCompact(boolean 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));
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);
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());
if (on) list.post(this::showLatest);
}
/** The end of the last message at the bottom (setSelection alone shows its top). */
private void showLatest() {
list.setSelection(rows.size() - 1);
list.post(() -> {
View last = list.getChildAt(list.getChildCount() - 1);
if (last != null) list.scrollListBy(last.getBottom() - (list.getHeight() - list.getPaddingBottom()));
});
}
private LinearLayout.LayoutParams thumbParams() {
int s = Ui.dp(this, compact ? 64 : 120);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(s, s);
lp.rightMargin = Ui.dp(this, compact ? 6 : 10);
lp.bottomMargin = Ui.dp(this, compact ? 4 : 10);
return lp;
}
private View composer() {
LinearLayout box = composerBox = new LinearLayout(this);
box.setOrientation(LinearLayout.VERTICAL);
box.setBackgroundColor(Ui.PANEL);
box.setPadding(Ui.dp(this, 12), Ui.dp(this, 10), Ui.dp(this, 12), Ui.dp(this, 10));
// From-number picker, only for a conversation with nothing in it yet.
fromRow = new LinearLayout(this);
fromRow.setGravity(Gravity.CENTER_VERTICAL);
fromRow.addView(Ui.text(this, "From ", Ui.T_SMALL, Ui.MUTED));
from = new Spinner(this);
fromRow.addView(from);
fromRow.setVisibility(View.GONE);
box.addView(fromRow);
HorizontalScrollView trayScroll = new HorizontalScrollView(this);
tray = new LinearLayout(this);
trayScroll.addView(tray);
box.addView(trayScroll);
LinearLayout row = new LinearLayout(this);
row.setGravity(Gravity.BOTTOM);
attach = Ui.headerButton(this, "📎");
attach.setOnTouchListener((v, e) -> attachTouch(e));
input = new EditText(this);
input.setHint("Message");
input.setHintTextColor(Ui.FAINT);
input.setTextColor(Ui.TEXT);
input.setTextSize(TypedValue.COMPLEX_UNIT_SP, Ui.T_BODY);
input.setMaxLines(4);
input.setBackground(Ui.round(Ui.INPUT, Ui.dp(this, 36)));
input.setPadding(Ui.dp(this, 24), Ui.dp(this, 14), Ui.dp(this, 24), Ui.dp(this, 14));
send = Ui.headerButton(this, "➤");
send.setTextColor(Ui.ACCENT);
send.setOnClickListener(v -> submit());
row.addView(attach);
row.addView(input, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
row.addView(send);
box.addView(row);
counter = Ui.text(this, "", Ui.T_TINY, Ui.MUTED);
counter.setGravity(Gravity.END);
counter.setVisibility(View.GONE);
box.addView(counter);
// An unsent message stays in the box, across app restarts, until sent or cleared.
String draft = drafts().getString(contact, "");
input.setText(draft);
input.setSelection(draft.length());
if (!draft.isEmpty()) updateCounter();
input.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int a, int b, int c) {}
public void onTextChanged(CharSequence s, int a, int b, int c) {}
public void afterTextChanged(Editable s) {
updateCounter();
saveDraft(s.toString());
}
});
return box;
}
private android.content.SharedPreferences drafts() {
return getSharedPreferences("drafts", MODE_PRIVATE);
}
private void saveDraft(String text) {
if (text.trim().isEmpty()) drafts().edit().remove(contact).apply();
else drafts().edit().putString(contact, text).apply();
}
private void updateCounter() {
int len = Phone.charCount(input.getText().toString().trim());
boolean gv = Config.get(this).isGv(did);
boolean show = !gv && len > 0;
counter.setVisibility(show ? View.VISIBLE : View.GONE);
if (show) counter.setText(len > Phone.SMS_TEXT_LIMIT || !photos.isEmpty() ? "MMS · " + len + "/2048" : len + "/160");
}
@Override
protected void onResume() {
super.onResume();
Notifier.clear(this, did, contact);
}
@Override
protected void onPause() {
super.onPause();
stopAudio();
}
@Override
public void changed() {
if (list == null) return;
boolean first = firstLoad;
MainActivity.bg.execute(() -> {
Store store = Store.get(this);
String name = store.getName(did, contact);
Contacts.all(this); // load names here, not on the main thread in show()
// Opening: the newest screenful first, so the chat appears at once
// however long its history; everything else follows right after.
if (first) {
List<Store.Msg> recent = store.recentMessages(did, contact, RECENT);
if (recent.size() == RECENT) post(recent, name, false);
}
post(store.messages(did, contact), name, true);
// Marking read (and telling Google Voice) waits until the messages are up.
if (store.hasUnread(did, contact)) {
StateSync.markRead(this, did, contact);
// Clear the badge on the phone / web too.
String thread = Config.get(this).isGv(did) ? store.gvThread(did, contact) : null;
if (thread != null) try {
new GVoice(Config.get(this)).markRead(thread);
} catch (Exception ignored) {
}
}
});
}
/** Off the main thread: fold the tapbacks, then show. */
private void post(List<Store.Msg> msgs, String name, boolean complete) {
// iPhone tapbacks ("Loved “…”") become reactions on the message they quote.
java.util.Map<Long, List<Reactions.Reaction>> folded = Reactions.fold(msgs);
runOnUiThread(() -> {
reactions = folded;
show(msgs, name, complete);
});
}
/** `complete` is false for just the newest few, shown while the rest loads. */
private void show(List<Store.Msg> msgs, String name, boolean complete) {
titleView.setText(Contacts.title(this, contact, name));
String sub = group ? Phone.members(contact).size() + " people" : Contacts.lookup(this, contact) != null ? Phone.format(contact) : "";
if (Config.get(this).dids.size() > 1) sub += (sub.isEmpty() ? "" : " · ") + Ui.via(this, did);
subView.setText(sub);
subView.setVisibility(sub.isEmpty() || compact ? View.GONE : View.VISIBLE);
boolean atBottom = list.getLastVisiblePosition() >= rows.size() - 2;
// Not at the bottom: keep the message at the top of the screen where it is
// (older history may have just arrived above it).
int firstPos = list.getFirstVisiblePosition();
View firstView = list.getChildAt(0);
Object anchor = !atBottom && firstPos < rows.size() ? rows.get(firstPos) : null;
int anchorTop = firstView == null ? 0 : firstView.getTop();
rows.clear();
for (int i = 0; i < msgs.size(); i++) {
Store.Msg m = msgs.get(i);
if (i == 0 || !Ui.sameDay(msgs.get(i - 1).ts, m.ts)) rows.add(m.ts);
rows.add(m);
}
adapter.notifyDataSetChanged();
if (firstLoad || atBottom) list.setSelection(rows.size() - 1);
else if (anchor instanceof Store.Msg) {
long id = ((Store.Msg) anchor).id;
for (int i = 0; i < rows.size(); i++)
if (rows.get(i) instanceof Store.Msg && ((Store.Msg) rows.get(i)).id == id) {
list.setSelectionFromTop(i, anchorTop);
break;
}
}
if (complete) firstLoad = false;
// A conversation with nothing in it yet can still pick its number.
Config cfg = Config.get(this);
List<Config.Did> choices = new ArrayList<>();
for (Config.Did d : cfg.dids) if (!group || d.gv) choices.add(d);
if (msgs.isEmpty() && choices.size() > 1 && fromRow.getVisibility() != View.VISIBLE) {
List<String> labels = new ArrayList<>();
int sel = 0;
for (int i = 0; i < choices.size(); i++) {
labels.add(Phone.format(choices.get(i).did) + (choices.get(i).gv ? " — Google Voice" : ""));
if (choices.get(i).did.equals(did)) sel = i;
}
ArrayAdapter<String> a = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, labels);
from.setAdapter(a);
from.setSelection(sel);
from.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
public void onItemSelected(android.widget.AdapterView<?> p, View v, int pos, long id) {
did = choices.get(pos).did;
updateCounter();
}
public void onNothingSelected(android.widget.AdapterView<?> p) {}
});
fromRow.setVisibility(View.VISIBLE);
} else if (!msgs.isEmpty()) {
fromRow.setVisibility(View.GONE);
}
}
private void submit() {
String text = input.getText().toString().trim();
if (text.isEmpty() && photos.isEmpty()) return;
if (!Config.get(this).isGv(did) && Phone.charCount(text) > 2048) {
Toast.makeText(this, "Too long for an MMS (2048 characters max).", Toast.LENGTH_SHORT).show();
return;
}
Sender.send(this, did, contact, text, new ArrayList<>(photos));
input.setText("");
photos.clear();
tray.removeAllViews();
fromRow.setVisibility(View.GONE);
list.setSelection(rows.size() - 1);
}
@Override
protected void onSaveInstanceState(Bundle out) {
super.onSaveInstanceState(out);
out.putParcelable("shot", shot);
}
/**
* Press the paperclip and the bubble is out at once: drag to a choice and
* let go. A quick tap leaves it open to tap a choice (or anywhere else to close).
*/
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.
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) {
if (which == AttachBubble.CAMERA) takePhoto();
else if (which == AttachBubble.PHOTO) pickPhotos();
else recordVoice();
}
// ---- voice notes ----
private void recordVoice() {
if (Config.get(this).isGv(did)) {
// sendsms only takes image types (see GVoice.mediaType).
new AlertDialog.Builder(this)
.setTitle("Voice note")
.setMessage("Google Voice only lets apps send photos, so voice notes can only go from a voip.ms number.")
.setPositiveButton("OK", null)
.show();
return;
}
startActivityForResult(new Intent(this, VoiceActivity.class), VOICE);
}
/** Play attachment `index` of message `id`, or stop it if it's the one playing. */
private void toggleAudio(long id, int index) {
String key = id + "/" + index;
boolean wasPlaying = key.equals(playing);
stopAudio();
if (wasPlaying) return;
playing = key;
adapter.notifyDataSetChanged();
MainActivity.bg.execute(() -> {
File f = Media.resolve(this, id, index);
runOnUiThread(() -> {
if (!key.equals(playing)) return;
android.media.MediaPlayer p = new android.media.MediaPlayer();
try {
if (f == null) throw new java.io.IOException();
p.setDataSource(f.getPath());
p.prepare();
} catch (Exception e) {
p.release();
stopAudio();
Toast.makeText(this, "Couldn't play that audio.", Toast.LENGTH_SHORT).show();
return;
}
p.setOnCompletionListener(x -> stopAudio());
p.start();
player = p;
});
});
}
private void stopAudio() {
if (player != null) player.release();
player = null;
if (playing != null) {
playing = null;
adapter.notifyDataSetChanged();
}
}
// ---- photos ----
private void pickPhotos() {
if (photos.size() >= MAX_PHOTOS) {
Toast.makeText(this, "At most " + MAX_PHOTOS + " photos per message.", Toast.LENGTH_SHORT).show();
return;
}
Intent i = new Intent(Intent.ACTION_GET_CONTENT).setType("image/*").addCategory(Intent.CATEGORY_OPENABLE)
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
try {
startActivityForResult(Intent.createChooser(i, "Attach photos"), PICK);
} catch (Exception e) {
Toast.makeText(this, "No app on the Rabbit can pick photos.", Toast.LENGTH_SHORT).show();
}
}
/**
* The Rabbit's camera app, writing straight into a new MediaStore photo;
* once that's copied into the tray it's deleted again, so pictures taken
* for a message don't pile up in the gallery.
*/
private void takePhoto() {
if (photos.size() >= MAX_PHOTOS) {
Toast.makeText(this, "At most " + MAX_PHOTOS + " photos per message.", Toast.LENGTH_SHORT).show();
return;
}
android.content.ContentValues v = new android.content.ContentValues();
v.put(android.provider.MediaStore.Images.Media.DISPLAY_NAME, "bubble-" + System.currentTimeMillis() + ".jpg");
v.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
v.put(android.provider.MediaStore.Images.Media.RELATIVE_PATH, "Pictures/bubble");
try {
shot = getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, v);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, shot)
.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(i, CAMERA);
} catch (Exception e) {
deleteShot(shot);
shot = null;
Toast.makeText(this, "Couldn't open the camera.", Toast.LENGTH_SHORT).show();
}
}
private void deleteShot(Uri u) {
if (u != null) MainActivity.bg.execute(() -> {
try {
getContentResolver().delete(u, null, null);
} catch (Exception ignored) {
}
});
}
@Override
protected void onActivityResult(int req, int res, Intent data) {
super.onActivityResult(req, res, data);
if (req == CAMERA) {
Uri u = shot;
shot = null;
if (u == null) return;
if (res == RESULT_OK) attachPhoto(u, () -> deleteShot(u));
else deleteShot(u);
return;
}
if (req == VOICE && res == RESULT_OK && data != null) {
List<Sender.Photo> note = new ArrayList<>();
note.add(new Sender.Photo(data.getStringExtra("file"), data.getStringExtra("mime"), 0, 0));
Sender.send(this, did, contact, "", note);
fromRow.setVisibility(View.GONE);
list.setSelection(rows.size() - 1);
return;
}
if (req != PICK || res != RESULT_OK || data == null) return;
List<Uri> uris = new ArrayList<>();
ClipData clip = data.getClipData();
if (clip != null) for (int i = 0; i < clip.getItemCount(); i++) uris.add(clip.getItemAt(i).getUri());
else if (data.getData() != null) uris.add(data.getData());
for (Uri u : uris) {
if (photos.size() >= MAX_PHOTOS) break;
attachPhoto(u, null);
}
}
/** Shrink a photo to send, keep a copy, and put it in the tray; {@code after} runs (on the UI thread) either way. */
private void attachPhoto(Uri u, Runnable after) {
MainActivity.bg.execute(() -> {
try {
Object[] p = Media.prepare(this, u);
byte[] bytes = (byte[]) p[0];
String mime = (String) p[1];
String file = Media.save(this, bytes, mime);
android.graphics.BitmapFactory.Options o = new android.graphics.BitmapFactory.Options();
o.inJustDecodeBounds = true;
android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.length, o);
Sender.Photo photo = new Sender.Photo(file, mime, o.outWidth, o.outHeight);
runOnUiThread(() -> addToTray(photo));
} catch (Exception e) {
runOnUiThread(() -> Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show());
}
if (after != null) runOnUiThread(after);
});
}
private void addToTray(Sender.Photo p) {
if (photos.size() >= MAX_PHOTOS) return;
photos.add(p);
ImageView iv = new ImageView(this);
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setImageBitmap(Media.bitmap(new File(Media.dir(this), p.file), Ui.dp(this, 120)));
iv.setOnClickListener(v -> {
photos.remove(p);
tray.removeView(iv);
updateCounter();
});
tray.addView(iv, thumbParams());
updateCounter();
}
// ---- the list ----
private final class Adapter extends BaseAdapter {
@Override
public int getCount() {
return rows.size();
}
@Override
public Object getItem(int i) {
return rows.get(i);
}
@Override
public long getItemId(int i) {
Object r = rows.get(i);
return r instanceof Store.Msg ? ((Store.Msg) r).id : -(Long) r;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int i) {
return rows.get(i) instanceof Store.Msg ? 1 : 0;
}
@Override
public boolean isEnabled(int i) {
return false;
}
@Override
public View getView(int i, View cv, ViewGroup parent) {
Object r = rows.get(i);
if (!(r instanceof Store.Msg)) {
TextView t = cv instanceof TextView ? (TextView) cv : Ui.bold(Ui.text(ChatActivity.this, "", Ui.T_TINY, Ui.MUTED));
t.setGravity(Gravity.CENTER);
t.setPadding(0, Ui.dp(ChatActivity.this, 18), 0, Ui.dp(ChatActivity.this, 10));
t.setText(Ui.dayLabel((Long) r));
return t;
}
Bubble b = cv instanceof Bubble ? (Bubble) cv : new Bubble(ChatActivity.this);
Store.Msg m = (Store.Msg) r;
Object prev = i > 0 ? rows.get(i - 1) : null;
boolean runStart = !(prev instanceof Store.Msg) || !((Store.Msg) prev).direction.equals(m.direction)
|| !java.util.Objects.equals(((Store.Msg) prev).sender, m.sender) || m.ts - ((Store.Msg) prev).ts > 5 * 60_000;
b.bind(m, group && m.in() && m.sender != null && runStart);
return b;
}
}
private final class Bubble extends LinearLayout {
final TextView sender, body, meta, failed, reacts;
final LinearLayout bubble, media;
Store.Msg m;
Bubble(Context c) {
super(c);
setOrientation(VERTICAL);
setPadding(Ui.dp(c, 16), Ui.dp(c, 3), Ui.dp(c, 16), Ui.dp(c, 3));
sender = Ui.text(c, "", Ui.T_TINY, Ui.MUTED);
sender.setPadding(Ui.dp(c, 14), Ui.dp(c, 10), 0, Ui.dp(c, 4));
bubble = new LinearLayout(c);
bubble.setOrientation(VERTICAL);
bubble.setPadding(Ui.dp(c, 20), Ui.dp(c, 12), Ui.dp(c, 20), Ui.dp(c, 12));
media = new LinearLayout(c);
media.setOrientation(VERTICAL);
body = Ui.text(c, "", Ui.T_BODY, Ui.TEXT);
body.setAutoLinkMask(Linkify.WEB_URLS);
body.setLinkTextColor(0xFFFFFFFF);
meta = Ui.text(c, "", Ui.T_TINY, 0xB3FFFFFF);
meta.setGravity(Gravity.END);
bubble.addView(media);
bubble.addView(body);
bubble.addView(meta);
failed = Ui.text(c, "", Ui.T_TINY, Ui.DANGER);
reacts = Ui.text(c, "", Ui.T_SMALL, Ui.TEXT);
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.setOnClickListener(v -> showReactions(m));
addView(sender);
addView(bubble, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
LayoutParams rlp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rlp.topMargin = -Ui.dp(c, 10);
rlp.leftMargin = Ui.dp(c, 16);
rlp.rightMargin = Ui.dp(c, 16);
addView(reacts, rlp);
addView(failed);
// Long-press copies the text. The body has its own listener because
// autolinked text takes its own touches and the bubble never sees them.
View.OnLongClickListener copy = v -> {
if (m == null) return true;
if (!m.body.isEmpty()) copyText(m.body);
else if ("failed".equals(m.status)) failedMenu(m);
return true;
};
bubble.setOnLongClickListener(copy);
body.setOnLongClickListener(copy);
bubble.setOnClickListener(v -> {
if (m != null && "failed".equals(m.status)) failedMenu(m);
});
}
void bind(Store.Msg msg, boolean showSender) {
m = msg;
Context c = getContext();
boolean out = !msg.in();
setGravity(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.setAlpha("failed".equals(msg.status) ? 0.6f : 1f);
bubble.setMinimumWidth(0);
// Keep bubbles to ~80% of the width.
body.setMaxWidth(Math.round(getResources().getDisplayMetrics().widthPixels * 0.72f));
sender.setVisibility(showSender ? VISIBLE : GONE);
if (showSender) sender.setText(Contacts.name(c, msg.sender));
body.setText(msg.body);
body.setVisibility(msg.body.isEmpty() ? GONE : VISIBLE);
String status = "pending".equals(msg.status) ? " 🕓" : "";
meta.setText(Ui.timeOfDay(c, msg.ts) + status);
meta.setTextColor(out ? 0xB3FFFFFF : Ui.MUTED);
failed.setVisibility("failed".equals(msg.status) ? VISIBLE : GONE);
failed.setText("⚠ Not sent" + (msg.error != null ? ": " + msg.error : "") + " · tap to retry");
List<Reactions.Reaction> rs = reactions.get(msg.id);
reacts.setVisibility(rs == null ? GONE : VISIBLE);
if (rs != null) {
java.util.LinkedHashSet<String> emojis = new java.util.LinkedHashSet<>();
for (Reactions.Reaction r : rs) emojis.add(r.emoji);
reacts.setText(String.join("", emojis) + (rs.size() > 1 ? " " + rs.size() : ""));
((LayoutParams) reacts.getLayoutParams()).gravity = out ? Gravity.END : Gravity.START;
}
media.removeAllViews();
List<JSONObject> refs = msg.media();
for (int i = 0; i < refs.size(); i++) media.addView(image(msg.id, i, refs.get(i)));
}
private View image(long id, int index, JSONObject ref) {
Context c = getContext();
int maxW = Ui.dp(c, 300), maxH = Ui.dp(c, 360);
int w = ref.optInt("width"), h = ref.optInt("height");
float scale = w > 0 && h > 0 ? Math.min(1f, Math.min(maxW / (float) w, maxH / (float) h)) : 1f;
int bw = w > 0 ? Math.round(w * scale) : Ui.dp(c, 200), bh = h > 0 ? Math.round(h * scale) : Ui.dp(c, 200);
String mime = ref.optString("mime", "");
if (mime.startsWith("audio/")) {
TextView t = Ui.bold(Ui.text(c, ((id + "/" + index).equals(playing) ? "⏸" : "▶") + " Voice note",
Ui.T_SMALL, Ui.TEXT));
t.setPadding(0, Ui.dp(c, 10), Ui.dp(c, 20), Ui.dp(c, 10));
t.setOnClickListener(v -> toggleAudio(id, index));
return t;
}
if (!mime.isEmpty() && !mime.startsWith("image/")) {
TextView t = Ui.text(c, mime.startsWith("video/") ? "🎥 Video" : "📎 Attachment", Ui.T_SMALL, Ui.TEXT);
t.setPadding(0, Ui.dp(c, 6), 0, Ui.dp(c, 6));
return t;
}
ImageView iv = new ImageView(c);
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setBackgroundColor(0x22FFFFFF);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(bw, bh);
iv.setLayoutParams(new LinearLayout.LayoutParams(bw, bh));
String tag = id + "/" + index;
iv.setTag(tag);
// Seen already: show it now rather than blank-then-pop on every redraw.
Bitmap hit = Media.cached(ref, Math.max(maxW, maxH));
if (hit != null) {
iv.setImageBitmap(hit);
File f = new File(Media.dir(c), new File(ref.optString("file")).getName());
iv.setOnClickListener(v -> startActivity(new Intent(c, ImageActivity.class).putExtra("file", f.getPath())));
return iv;
}
MainActivity.bg.execute(() -> {
File f = Media.resolve(c, id, index);
Bitmap bm = f == null ? null : Media.bitmap(f, Math.max(maxW, maxH));
iv.post(() -> {
if (!tag.equals(iv.getTag())) return;
if (bm != null) {
iv.setImageBitmap(bm);
iv.setOnClickListener(v -> startActivity(new Intent(c, ImageActivity.class).putExtra("file", f.getPath())));
}
});
});
return iv;
}
}
/** Who reacted with what. */
private void showReactions(Store.Msg m) {
List<Reactions.Reaction> rs = m == null ? null : reactions.get(m.id);
if (rs == null) return;
String[] lines = new String[rs.size()];
for (int i = 0; i < rs.size(); i++)
lines[i] = rs.get(i).emoji + " " + ("me".equals(rs.get(i).from) ? "You" : Contacts.name(this, rs.get(i).from));
new AlertDialog.Builder(this).setTitle("Reactions").setItems(lines, null).setPositiveButton("OK", null).show();
}
/** Copies a message's text. Android 13 shows its own "copied" popup, so no toast of ours. */
private void copyText(String text) {
android.content.ClipboardManager cm = getSystemService(android.content.ClipboardManager.class);
cm.setPrimaryClip(ClipData.newPlainText("Message", text));
}
private void failedMenu(Store.Msg m) {
new AlertDialog.Builder(this)
.setTitle("Not sent")
.setMessage(m.error == null ? "This message didn't go out." : m.error)
.setPositiveButton("Retry", (d, w) -> MainActivity.bg.execute(() -> Sender.retry(this, m.id)))
.setNegativeButton("Delete", (d, w) -> {
Store.get(this).deleteMessage(m.id);
changed();
})
.setNeutralButton("Cancel", null)
.show();
}
}
@@ -0,0 +1,146 @@
package me.teafry.voipmessages;
import android.content.Context;
import android.content.SharedPreferences;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Accounts, copied over by the desktop's "Install to Rabbit" into the app's
* private files dir (files/config.json, which no other app can read):
*
* {"voipms": {"username", "password"} | null,
* "gvoice": {"number", "cookies": {name: value}} | null,
* "dids": [{"did", "description"}], "defaultDid": "..."}
*
* Google rotates some cookies as we use them; those go back into the file.
*/
final class Config {
static final class Did {
final String did, description;
final boolean gv;
Did(String did, String description, boolean gv) {
this.did = did;
this.description = description;
this.gv = gv;
}
}
String voipUser, voipPass;
String gvNumber;
final Map<String, String> gvCookies = new LinkedHashMap<>();
final List<Did> dids = new ArrayList<>();
String defaultDid;
/** Made-up data for testing (android/tools/push_sandbox.py): never goes online. */
boolean sandbox;
private final File file;
private JSONObject raw;
private Config(File file) {
this.file = file;
}
private static Config cached;
static synchronized Config get(Context c) {
File f = new File(c.getFilesDir(), "config.json");
if (cached == null || cached.stale()) cached = load(f);
return cached;
}
private long loadedAt;
private boolean stale() {
return file.lastModified() > loadedAt;
}
private static Config load(File f) {
Config cfg = new Config(f);
cfg.loadedAt = f.lastModified();
try {
JSONObject o = new JSONObject(new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8));
cfg.raw = o;
JSONObject v = o.optJSONObject("voipms");
if (v != null) {
cfg.voipUser = v.optString("username", null);
cfg.voipPass = v.optString("password", null);
}
JSONObject g = o.optJSONObject("gvoice");
if (g != null) {
cfg.gvNumber = Phone.normalize(g.optString("number"));
JSONObject ck = g.optJSONObject("cookies");
if (ck != null)
for (Iterator<String> it = ck.keys(); it.hasNext(); ) {
String k = it.next();
cfg.gvCookies.put(k, ck.getString(k));
}
}
JSONArray ds = o.optJSONArray("dids");
if (ds != null)
for (int i = 0; i < ds.length(); i++) {
JSONObject d = ds.getJSONObject(i);
cfg.dids.add(new Did(Phone.normalize(d.getString("did")), d.optString("description"), false));
}
if (cfg.gvNumber != null && !cfg.gvNumber.isEmpty()) cfg.dids.add(new Did(cfg.gvNumber, "Google Voice", true));
cfg.defaultDid = o.optString("defaultDid", null);
cfg.sandbox = o.optBoolean("sandbox", false);
} catch (IOException | JSONException e) {
cfg.raw = new JSONObject();
}
if (cfg.defaultDid == null && !cfg.dids.isEmpty()) cfg.defaultDid = cfg.dids.get(0).did;
return cfg;
}
boolean configured() {
return voipUser != null || gvNumber != null;
}
boolean isGv(String did) {
return gvNumber != null && gvNumber.equals(did);
}
/** Persist cookies Google rotated. */
synchronized void saveCookies() {
try {
JSONObject g = raw.optJSONObject("gvoice");
if (g == null) return;
JSONObject ck = new JSONObject();
for (Map.Entry<String, String> e : gvCookies.entrySet()) ck.put(e.getKey(), e.getValue());
g.put("cookies", ck);
File tmp = new File(file.getPath() + ".tmp");
try (FileOutputStream out = new FileOutputStream(tmp)) {
out.write(raw.toString().getBytes(StandardCharsets.UTF_8));
}
if (tmp.renameTo(file)) loadedAt = file.lastModified();
} catch (IOException | JSONException ignored) {
}
}
// ---- settings that belong to this device ----
static SharedPreferences prefs(Context c) {
return c.getSharedPreferences("settings", Context.MODE_PRIVATE);
}
/** Minutes between background checks; 0 = never (pull to refresh only). */
static int pollMinutes(Context c) {
return prefs(c).getInt("pollMinutes", 15);
}
static boolean notifications(Context c) {
return prefs(c).getBoolean("notifications", true);
}
}
@@ -0,0 +1,95 @@
package me.teafry.voipmessages;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.ContactsContract;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Names from the Rabbit's own synced contacts (READ_CONTACTS). */
final class Contacts {
private Contacts() {}
static final class Entry {
final String name, number, label;
Entry(String name, String number, String label) {
this.name = name;
this.number = number;
this.label = label;
}
}
private static Map<String, Entry> byNumber;
private static List<Entry> all;
static boolean allowed(Context c) {
return c.checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
}
/** Reload on next use (e.g. when the app comes back to the front). */
static synchronized void invalidate() {
byNumber = null;
all = null;
}
/** Returns the map, so a reader keeps hold of it even if invalidate() runs mid-read. */
private static synchronized Map<String, Entry> load(Context c) {
if (byNumber != null) return byNumber;
Map<String, Entry> byNumber = new HashMap<>();
List<Entry> all = new ArrayList<>();
Contacts.all = all;
Contacts.byNumber = byNumber;
if (!allowed(c)) return byNumber;
String[] cols = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.LABEL};
try (Cursor cur = c.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, cols, null, null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE")) {
if (cur == null) return byNumber;
while (cur.moveToNext()) {
String name = cur.getString(0), number = Phone.normalize(cur.getString(1));
if (name == null || number.isEmpty() || byNumber.containsKey(number)) continue;
CharSequence label = ContactsContract.CommonDataKinds.Phone.getTypeLabel(c.getResources(), cur.getInt(2), cur.getString(3));
Entry e = new Entry(name, number, label == null ? null : label.toString().toLowerCase());
byNumber.put(number, e);
all.add(e);
}
} catch (SecurityException ignored) {
}
return byNumber;
}
static Entry lookup(Context c, String number) {
return load(c).get(number);
}
static synchronized List<Entry> all(Context c) {
load(c);
return all;
}
static String name(Context c, String number) {
Entry e = lookup(c, number);
return e != null ? e.name : Phone.format(number);
}
static String firstName(Context c, String number) {
Entry e = lookup(c, number);
return e != null ? e.name.split("\\s+")[0] : Phone.format(number);
}
/** The chat's title: your name for it, the person, or the members ("Sam, Alex +2"). */
static String title(Context c, String contact, String ownName) {
if (ownName != null && !ownName.isEmpty()) return ownName;
if (!Phone.isGroup(contact)) return name(c, contact);
List<String> names = new ArrayList<>();
for (String n : Phone.members(contact)) names.add(firstName(c, n));
if (names.size() > 3) return String.join(", ", names.subList(0, 3)) + " +" + (names.size() - 3);
return String.join(", ", names);
}
}
@@ -0,0 +1,333 @@
package me.teafry.voipmessages;
import android.util.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Google Voice's private web API -- a port of the desktop's
* src/main/gvoice/client.ts (itself after mautrix-gvoice). Unofficial: it can
* break when Google changes things, and then only Google Voice stops.
*/
final class GVoice {
static final String ORIGIN = "https://voice.google.com";
private static final String API = "https://clients6.google.com/voice/v1/voiceclient";
private static final String WAA = "https://waa-pa.clients6.google.com/$rpc/google.internal.waa.v1.Waa";
private static final String API_KEY = "AIzaSyDTYc1N4xiODyrQYK0Kl6g_y279LjYkrBg";
private static final String WAA_API_KEY = "AIzaSyBGb5fGAyC-pRcRU6MUHb__b_vKha71HRE";
static final String WAA_REQUEST_KEY = "/JR8jsAkqotcKsEKhXic";
static final String USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36";
private static final String CLIENT_DETAILS = "appVersion=5.0+%28X11%29&platform=Linux+x86_64&userAgent=" + enc(USER_AGENT);
private static final String PBLITE = "application/json+protobuf";
static final int SMS_IN = 10, SMS_OUT = 11;
static final class Failure extends Exception {
final int status; // HTTP status, 0 when Google never answered
Failure(String msg, int status) {
super(msg);
this.status = status;
}
boolean signedOut() {
return status == 401 || status == 403;
}
}
private final Config cfg;
GVoice(Config cfg) {
this.cfg = cfg;
}
private static String enc(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (Exception e) {
return s;
}
}
static String sapisidHash(String sapisid, long nowMs) {
long ts = nowMs / 1000;
try {
byte[] h = MessageDigest.getInstance("SHA-1").digest((ts + " " + sapisid + " " + ORIGIN).getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : h) sb.append(String.format("%02x", b));
return "SAPISIDHASH " + ts + "_" + sb;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
private String sapisid() {
String v = cfg.gvCookies.get("SAPISID");
return v != null ? v : cfg.gvCookies.get("__Secure-3PAPISID");
}
private Http.Response request(String method, String url, byte[] body, String contentType) throws Failure {
boolean api = url.startsWith("https://clients6.google.com/");
if (api) url += (url.contains("?") ? "&" : "?") + "key=" + API_KEY + "&alt=proto";
String sapisid = sapisid();
if (sapisid == null) throw new Failure("Google Voice isn't connected. Reinstall from the desktop to copy the sign-in.", 401);
Map<String, String> h = new HashMap<>();
h.put("User-Agent", USER_AGENT);
h.put("X-Goog-AuthUser", "0");
h.put("Origin", ORIGIN);
h.put("Referer", ORIGIN + "/");
h.put("Accept", "*/*");
h.put("Authorization", sapisidHash(sapisid, System.currentTimeMillis()));
if (contentType != null) h.put("Content-Type", contentType);
if (api) {
h.put("X-Client-Version", "665865172");
h.put("X-ClientDetails", CLIENT_DETAILS);
h.put("X-JavaScript-User-Agent", "google-api-javascript-client/1.1.0");
h.put("X-Requested-With", "XMLHttpRequest");
h.put("X-Goog-Encode-Response-If-Executable", "base64");
} else if (url.startsWith(WAA)) {
h.put("X-Goog-Api-Key", WAA_API_KEY);
h.put("X-User-Agent", "grpc-web-javascript/0.1");
}
StringBuilder cookie = new StringBuilder();
synchronized (cfg) {
for (Map.Entry<String, String> e : cfg.gvCookies.entrySet()) {
if (cookie.length() > 0) cookie.append("; ");
cookie.append(e.getKey()).append('=').append(e.getValue());
}
}
h.put("Cookie", cookie.toString());
Http.Response r;
try {
r = Http.request(method, url, h, body, 120_000);
} catch (IOException e) {
throw new Failure(Http.notSent(e) ? "Couldn't reach Google Voice. Check the internet connection." : "The connection to Google Voice was interrupted.", 0);
}
updateCookies(r);
if (r.status >= 400) throw new Failure(httpMessage(r.status), r.status);
return r;
}
// Google rotates some cookies through Set-Cookie; keep them current.
private void updateCookies(Http.Response r) {
boolean changed = false;
synchronized (cfg) {
for (String sc : r.headers("Set-Cookie")) {
String first = sc.split(";", 2)[0];
int eq = first.indexOf('=');
if (eq <= 0) continue;
String name = first.substring(0, eq).trim(), value = first.substring(eq + 1).trim();
String lower = sc.toLowerCase();
boolean expired = lower.contains("max-age=0") || lower.contains("max-age=-") || lower.contains("expires=thu, 01 jan 1970");
if (expired) changed |= cfg.gvCookies.remove(name) != null;
else if (!value.equals(cfg.gvCookies.get(name))) {
cfg.gvCookies.put(name, value);
changed = true;
}
}
}
if (changed) cfg.saveCookies();
}
private static String httpMessage(int status) {
if (status == 401 || status == 403) return "Google Voice signed out. Reconnect it on the desktop, then Sync to Rabbit.";
if (status == 429) return "Google Voice is rate-limiting messages. Try again in a bit.";
if (status == 404) return "Google Voice could not find that conversation.";
if (status >= 500) return "Google Voice had a server error (" + status + ").";
return "Google Voice rejected the request (" + status + ").";
}
/** Decodes a binary-protobuf response, unwrapping the base64 text chunk form. */
static Pb readProto(Http.Response r) {
String plain = r.header("Content-Type");
plain = plain == null ? "" : plain.split(";")[0].trim();
if (plain.equals("text/plain")) {
String text = r.text();
int nl = text.indexOf('\n');
String chunk = text;
if (nl > 0) {
try {
int len = Integer.parseInt(text.substring(0, nl).trim());
chunk = text.substring(nl + 1, Math.min(text.length(), nl + 1 + len));
} catch (NumberFormatException ignored) {
}
}
return Pb.parse(Base64.decode(chunk, Base64.DEFAULT));
}
return Pb.parse(r.body);
}
private Pb call(String endpoint, JSONArray pblite) throws Failure {
return readProto(request("POST", endpoint, pblite.toString().getBytes(StandardCharsets.UTF_8), PBLITE));
}
/** A pblite array: field N at index N-1, nulls elsewhere. */
static JSONArray pblite(Object... byField) {
JSONArray a = new JSONArray();
for (Object v : byField) a.put(v == null ? org.json.JSONObject.NULL : v);
return a;
}
// ---- threads ----
static final class Thread {
String id, paginationToken;
boolean read;
List<Pb> messages; // newest first; fields in schema.ts Message
List<String> phoneNumbers;
static Thread of(Pb p) {
Thread t = new Thread();
t.id = p.str(1);
t.read = p.bool(2);
t.messages = p.msgs(3);
t.paginationToken = p.str(4);
t.phoneNumbers = p.strs(9);
return t;
}
}
/** One page of text threads; [threads, nextToken]. */
Object[] listThreads(String token) throws Failure {
// folder TEXT_THREADS=2, page sizes 20/15, unknownWrapper [null,1,1]
Pb r = call(API + "/api2thread/list", pblite(2, 20, 15, token.isEmpty() ? null : token, null, pblite(null, 1, 1)));
List<Thread> threads = new ArrayList<>();
for (Pb t : r.msgs(1)) threads.add(Thread.of(t));
return new Object[] {threads, r.str(2)};
}
Thread getThread(String id, int count, String token) throws Failure {
Pb r = call(API + "/api2thread/get", pblite(id, count, token.isEmpty() ? null : token, pblite(null, 1, 1)));
return Thread.of(r.msg(1));
}
/** Returns [threadId, threadItemId]. */
String[] sendSms(String threadId, List<String> recipients, String text, String mime, byte[] image, long txn, String tracking) throws Failure {
Object media = null;
if (image != null) {
int type = mediaType(mime);
if (type == 0) throw new Failure("Google Voice can only send photos.", 400);
media = pblite(type, Base64.encodeToString(image, Base64.NO_WRAP));
}
JSONArray recips = new JSONArray();
if (threadId.isEmpty()) for (String r : recipients) recips.put(r);
Pb r = call(API + "/api2thread/sendsms", pblite(null, null, null, null,
text.isEmpty() ? null : text, threadId.isEmpty() ? null : threadId, recips.length() == 0 ? null : recips,
null, pblite(txn), media, pblite(tracking == null || tracking.isEmpty() ? "!" : tracking)));
return new String[] {r.str(2), r.str(3)};
}
static int mediaType(String mime) {
if (mime == null) return 0;
switch (mime) {
case "image/jpeg": return 1;
case "image/png": return 2;
case "image/tiff": return 3;
case "image/gif": return 4;
case "image/bmp": return 5;
case "image/webp": return 6;
default: return 0;
}
}
void markRead(String threadId) throws Failure {
call(API + "/thread/updateattributes", pblite(pblite(threadId, null, null, true), pblite(null, null, null, true), 1));
}
/** [bytes, mime] */
Object[] download(String mediaId) throws Failure {
Http.Response r = request("GET", ORIGIN + "/u/0/a/i/" + enc(mediaId) + "?s=1", null, null);
return new Object[] {r.body, r.header("Content-Type")};
}
// ---- WAA (message signing), see Waa.java ----
/** [interpreterUrl, interpreterHash, program, globalName] from pblite. */
String[] createWaa() throws Failure, JSONException {
Http.Response r = request("POST", WAA + "/Create", pblite(WAA_REQUEST_KEY).toString().getBytes(StandardCharsets.UTF_8), PBLITE);
JSONArray w = new JSONArray(r.text()).getJSONArray(0);
JSONArray url = w.optJSONArray(2);
return new String[] {url == null ? "" : url.optString(3), w.optString(3), w.optString(4), w.optString(5)};
}
void pingWaa(String payload) throws Failure {
request("POST", WAA + "/Ping", pblite(WAA_REQUEST_KEY, payload, 72, (long) (Math.random() * 2e9)).toString().getBytes(StandardCharsets.UTF_8), PBLITE);
}
// ---- mapping into the store (same ids and keys as the desktop) ----
private static final long GV_ID_BASE = 1L << 52;
static long messageId(String gvId) {
try {
byte[] h = MessageDigest.getInstance("SHA-256").digest(gvId.getBytes(StandardCharsets.UTF_8));
long v = 0;
for (int i = 0; i < 6; i++) v = (v << 8) | (h[i] & 0xff);
return GV_ID_BASE + v;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
static String threadContact(Thread t, String self) {
List<String> others = new ArrayList<>();
for (String n : t.phoneNumbers) {
String d = Phone.normalize(n);
if (!d.isEmpty() && !d.equals(self)) others.add(d);
}
if (others.size() > 1) return Phone.groupKey(others);
return others.isEmpty() ? "" : others.get(0);
}
/** Null for calls and voicemail. */
static Store.Msg toMsg(Pb m, String did, String contact, boolean group) {
long type = m.num(5);
if (type != SMS_IN && type != SMS_OUT) return null;
Store.Msg out = new Store.Msg();
out.id = messageId(m.str(1));
out.did = did;
out.contact = contact;
out.direction = type == SMS_OUT ? "out" : "in";
out.ts = m.num(2);
Pb mms = m.msg(15);
String text = m.has(15) && !mms.str(1).isEmpty() ? mms.str(1) : m.str(10);
String subject = mms.str(2);
out.body = subject.isEmpty() ? text : subject + "\n" + text;
JSONArray media = new JSONArray();
for (Pb a : mms.msgs(3)) {
if (a.str(2).isEmpty() || a.num(3) == 3) continue; // NOT_SUPPORTED
try {
org.json.JSONObject ref = new org.json.JSONObject().put("url", "gv:" + a.str(2));
if (!a.str(1).isEmpty()) ref.put("mime", a.str(1));
Pb best = null;
for (Pb meta : a.msgs(4)) {
if (meta.num(1) == 1) { // ORIGINAL
best = meta;
break;
}
if (best == null || meta.num(2) > best.num(2)) best = meta;
}
if (best != null && best.num(2) > 0) ref.put("width", best.num(2)).put("height", best.num(3));
media.put(ref);
} catch (JSONException ignored) {
}
}
if (media.length() > 0) {
out.kind = "mms";
out.mediaJson = media.toString();
}
if (group && "in".equals(out.direction)) {
String sender = Phone.normalize(!mms.str(5).isEmpty() ? mms.str(5) : m.msg(4).str(2));
if (!sender.isEmpty()) out.sender = sender;
}
return out;
}
}
@@ -0,0 +1,83 @@
package me.teafry.voipmessages;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.NoRouteToHostException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
/** HttpURLConnection, minus the ceremony. */
final class Http {
private Http() {}
static final class Response {
final int status;
final Map<String, List<String>> headers;
final byte[] body;
Response(int status, Map<String, List<String>> headers, byte[] body) {
this.status = status;
this.headers = headers;
this.body = body;
}
String header(String name) {
for (Map.Entry<String, List<String>> e : headers.entrySet())
if (e.getKey() != null && e.getKey().equalsIgnoreCase(name) && !e.getValue().isEmpty()) return e.getValue().get(0);
return null;
}
List<String> headers(String name) {
for (Map.Entry<String, List<String>> e : headers.entrySet())
if (e.getKey() != null && e.getKey().equalsIgnoreCase(name)) return e.getValue();
return java.util.Collections.emptyList();
}
String text() {
return new String(body, java.nio.charset.StandardCharsets.UTF_8);
}
}
static Response request(String method, String url, Map<String, String> headers, byte[] body, int timeoutMs) throws IOException {
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
c.setRequestMethod(method);
c.setConnectTimeout(20_000);
c.setReadTimeout(timeoutMs);
c.setInstanceFollowRedirects(true);
if (headers != null) for (Map.Entry<String, String> h : headers.entrySet()) c.setRequestProperty(h.getKey(), h.getValue());
if (body != null) {
c.setDoOutput(true);
c.setFixedLengthStreamingMode(body.length);
try (OutputStream out = c.getOutputStream()) {
out.write(body);
}
}
int status = c.getResponseCode();
InputStream in = status >= 400 ? c.getErrorStream() : c.getInputStream();
byte[] data = in == null ? new byte[0] : readAll(in);
Response r = new Response(status, c.getHeaderFields(), data);
c.disconnect();
return r;
}
static byte[] readAll(InputStream in) throws IOException {
try (InputStream is = in) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[16384];
int n;
while ((n = is.read(buf)) > 0) out.write(buf, 0, n);
return out.toByteArray();
}
}
/** True when the request certainly never reached the server. */
static boolean notSent(Throwable e) {
return e instanceof UnknownHostException || e instanceof ConnectException || e instanceof NoRouteToHostException;
}
}
@@ -0,0 +1,134 @@
package me.teafry.voipmessages;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.ImageView;
import java.io.File;
/** A photo, full screen. Pinch or double-tap to zoom, drag to pan, tap to close. */
public final class ImageActivity extends BaseActivity {
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
Zoom iv = new Zoom(this);
iv.setBackgroundColor(0xFF000000);
iv.setImageBitmap(Media.bitmap(new File(getIntent().getStringExtra("file")), 2048));
setContentView(iv);
}
@Override
public void changed() {}
private final class Zoom extends ImageView {
private static final float MAX = 6f, DOUBLE_TAP = 2.5f;
private final Matrix m = new Matrix();
private final float[] v = new float[9];
private float fit = 1f; // the scale that fits the whole photo on screen
private final ScaleGestureDetector pinch;
private final GestureDetector gestures;
Zoom(Context c) {
super(c);
setScaleType(ScaleType.MATRIX);
pinch = new ScaleGestureDetector(c, new ScaleGestureDetector.SimpleOnScaleGestureListener() {
@Override
public boolean onScale(ScaleGestureDetector d) {
zoomBy(d.getScaleFactor(), d.getFocusX(), d.getFocusY());
return true;
}
});
gestures = new GestureDetector(c, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float dx, float dy) {
if (pinch.isInProgress()) return true;
m.postTranslate(-dx, -dy);
settle();
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
finish();
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
// Zoomed in: back to fit; at fit: zoom in on the tapped spot.
float target = scale() > fit * 1.05f ? fit : fit * DOUBLE_TAP;
zoomBy(target / scale(), e.getX(), e.getY());
return true;
}
});
}
@Override
protected void onSizeChanged(int w, int h, int ow, int oh) {
super.onSizeChanged(w, h, ow, oh);
reset();
}
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
reset();
}
/** Whole photo, centred. */
private void reset() {
if (getDrawable() == null || getWidth() == 0) return;
float dw = getDrawable().getIntrinsicWidth(), dh = getDrawable().getIntrinsicHeight();
fit = Math.min(getWidth() / dw, getHeight() / dh);
m.setScale(fit, fit);
m.postTranslate((getWidth() - dw * fit) / 2, (getHeight() - dh * fit) / 2);
setImageMatrix(m);
}
private float scale() {
m.getValues(v);
return v[Matrix.MSCALE_X];
}
private void zoomBy(float f, float x, float y) {
float s = scale();
f = Math.max(fit / s, Math.min(fit * MAX / s, f));
m.postScale(f, f, x, y);
settle();
}
/** No black gaps at an edge: centre what's smaller than the screen, clamp what's bigger. */
private void settle() {
if (getDrawable() == null) return;
RectF r = new RectF(0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight());
m.mapRect(r);
float dx = 0, dy = 0, w = getWidth(), h = getHeight();
if (r.width() <= w) dx = (w - r.width()) / 2 - r.left;
else if (r.left > 0) dx = -r.left;
else if (r.right < w) dx = w - r.right;
if (r.height() <= h) dy = (h - r.height()) / 2 - r.top;
else if (r.top > 0) dy = -r.top;
else if (r.bottom < h) dy = h - r.bottom;
m.postTranslate(dx, dy);
setImageMatrix(m);
}
@Override
public boolean onTouchEvent(MotionEvent e) {
pinch.onTouchEvent(e);
gestures.onTouchEvent(e);
return true;
}
}
}
@@ -0,0 +1,92 @@
package me.teafry.voipmessages;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
/** "Get info" for a group chat: its members, and a name of your own for it. */
public final class InfoActivity extends BaseActivity {
private String did, contact;
private LinearLayout members;
private EditText name;
static Intent intent(Context c, String did, String contact) {
return new Intent(c, InfoActivity.class).putExtra("did", did).putExtra("contact", contact);
}
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
did = getIntent().getStringExtra("did");
contact = getIntent().getStringExtra("contact");
ScrollView scroll = new ScrollView(this);
LinearLayout box = new LinearLayout(this);
box.setOrientation(LinearLayout.VERTICAL);
box.setPadding(Ui.dp(this, 28), Ui.dp(this, 12), Ui.dp(this, 28), Ui.dp(this, 28));
scroll.addView(box);
box.addView(Ui.bold(Ui.text(this, "Chat info", Ui.T_TITLE, Ui.TEXT)));
TextView label = Ui.bold(Ui.text(this, "NAME", Ui.T_TINY, Ui.MUTED));
label.setPadding(0, Ui.dp(this, 24), 0, Ui.dp(this, 6));
box.addView(label);
name = new EditText(this);
name.setText(Store.get(this).getName(did, contact));
name.setHint(Contacts.title(this, contact, null));
name.setHintTextColor(Ui.FAINT);
name.setTextColor(Ui.TEXT);
name.setTextSize(TypedValue.COMPLEX_UNIT_SP, Ui.T_BODY);
name.setSingleLine();
name.setBackground(Ui.round(Ui.INPUT, Ui.dp(this, 16)));
name.setPadding(Ui.dp(this, 20), Ui.dp(this, 14), Ui.dp(this, 20), Ui.dp(this, 14));
box.addView(name);
TextView note = Ui.text(this, "Only you see this name. It syncs with the desktop app.", Ui.T_TINY, Ui.FAINT);
note.setPadding(0, Ui.dp(this, 6), 0, Ui.dp(this, 10));
box.addView(note);
TextView save = Ui.button(this, "Save name", true);
save.setOnClickListener(v -> {
StateSync.rename(this, did, contact, name.getText().toString());
finish();
});
box.addView(save);
TextView m = Ui.bold(Ui.text(this, "MEMBERS", Ui.T_TINY, Ui.MUTED));
m.setPadding(0, Ui.dp(this, 28), 0, Ui.dp(this, 6));
box.addView(m);
members = new LinearLayout(this);
members.setOrientation(LinearLayout.VERTICAL);
box.addView(members);
setContentView(scroll);
}
@Override
public void changed() {
if (members == null) return;
members.removeAllViews();
for (String n : Phone.members(contact)) {
Contacts.Entry e = Contacts.lookup(this, n);
LinearLayout row = new LinearLayout(this);
row.setGravity(Gravity.CENTER_VERTICAL);
row.setPadding(0, Ui.dp(this, 10), 0, Ui.dp(this, 10));
View av = new View(this);
av.setBackground(Ui.avatar(n, e == null ? null : e.name, false));
int s = Ui.dp(this, 64);
LinearLayout.LayoutParams alp = new LinearLayout.LayoutParams(s, s);
alp.rightMargin = Ui.dp(this, 16);
row.addView(av, alp);
LinearLayout t = new LinearLayout(this);
t.setOrientation(LinearLayout.VERTICAL);
t.addView(Ui.text(this, e == null ? Phone.format(n) : e.name, Ui.T_SMALL + 2, Ui.TEXT));
if (e != null) t.addView(Ui.text(this, Phone.format(n), Ui.T_TINY, Ui.MUTED));
row.addView(t, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
members.addView(row);
}
}
}
@@ -0,0 +1,431 @@
package me.teafry.voipmessages;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/** The conversation list. */
public final class MainActivity extends BaseActivity {
static final ExecutorService bg = Executors.newCachedThreadPool();
private ListView list;
private PullRefresh pull;
private TextView status, title;
private final List<Store.Conv> convs = new ArrayList<>(); // what the list shows
private final List<Store.Conv> loaded = new ArrayList<>(); // every conversation, archived or not
private EditText search;
private View searchBox;
private TextView noMatches;
// Keep the search box tucked above the top until the list is next touched
// (re-applied on every redraw, since a redraw before the list has laid out
// would otherwise put it back where it was).
private boolean hideSearch = true;
private boolean archived;
private Adapter adapter;
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
LinearLayout root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
LinearLayout header = new LinearLayout(this);
header.setGravity(Gravity.CENTER_VERTICAL);
header.setPadding(Ui.dp(this, 24), Ui.dp(this, 8), Ui.dp(this, 8), Ui.dp(this, 8));
title = Ui.bold(Ui.text(this, "Messages", Ui.T_TITLE, Ui.TEXT));
header.addView(title, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
TextView compose = Ui.headerButton(this, "✎");
compose.setOnClickListener(v -> startActivity(new Intent(this, NewChatActivity.class)));
TextView archive = Ui.headerButton(this, "🗄");
archive.setOnClickListener(v -> {
archived = !archived;
hideSearch = true;
changed();
});
TextView settings = Ui.headerButton(this, "⚙");
settings.setOnClickListener(v -> startActivity(new Intent(this, SettingsActivity.class)));
header.addView(compose);
header.addView(archive);
header.addView(settings);
root.addView(header);
status = Ui.text(this, "", Ui.T_SMALL, Ui.DANGER);
status.setPadding(Ui.dp(this, 24), 0, Ui.dp(this, 24), Ui.dp(this, 8));
status.setVisibility(View.GONE);
root.addView(status);
list = new ListView(this);
list.setDivider(null);
list.setSelector(android.R.color.transparent);
adapter = new Adapter();
list.setItemsCanFocus(true);
list.addHeaderView(searchBox(), null, false);
FrameLayout footer = new FrameLayout(this);
noMatches = Ui.text(this, "No chats match", Ui.T_SMALL, Ui.MUTED);
noMatches.setGravity(Gravity.CENTER);
noMatches.setPadding(0, Ui.dp(this, 40), 0, Ui.dp(this, 40));
noMatches.setVisibility(View.GONE);
footer.addView(noMatches, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT));
list.addFooterView(footer, null, false);
list.setAdapter(adapter);
list.setOnItemClickListener((p, v, pos, id) -> {
Store.Conv c = conv(pos);
if (c != null) startActivity(ChatActivity.intent(this, c.did, c.contact));
});
list.setOnItemLongClickListener((p, v, pos, id) -> {
Store.Conv c = conv(pos);
if (c != null) menu(c);
return c != null;
});
list.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int state) {
// Scrolling through results: the keyboard (half the R1's screen) gets out of the way.
if (state == SCROLL_STATE_TOUCH_SCROLL) hideSearch = false;
if (state == SCROLL_STATE_TOUCH_SCROLL && search.hasFocus()) hideKeyboard();
if (state == SCROLL_STATE_IDLE) snapSearch();
}
@Override
public void onScroll(AbsListView view, int first, int visible, int total) {}
});
new SwipeActions(list, (pos, rightward) -> {
Store.Conv c = conv(pos);
if (c == null) return;
if (rightward) StateSync.setArchived(this, c.did, c.contact, !c.archived);
else if (c.unread > 0 || c.markedUnread) StateSync.markRead(this, c.did, c.contact);
else StateSync.markUnread(this, c.did, c.contact);
changed();
});
pull = new PullRefresh(this, list);
pull.onRefresh = this::refresh;
root.addView(pull, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1));
setContentView(root);
// The screen holds focus, not the search box: a focused box would
// scroll itself into view (and up comes the keyboard).
root.setFocusableInTouchMode(true);
root.requestFocus();
Alarms.schedule(this);
if (!Config.get(this).configured()) {
new AlertDialog.Builder(this)
.setTitle("Not set up yet")
.setMessage("Install from the desktop app (Settings → Rabbit → Install to Rabbit) to copy your accounts and history here.")
.setPositiveButton("OK", null)
.show();
}
}
@Override
protected void onResume() {
super.onResume();
Contacts.invalidate();
// Catch up whenever the app comes to the front.
refresh();
}
private void refresh() {
bg.execute(() -> {
Sync.poll(this);
runOnUiThread(() -> pull.setRefreshing(false));
});
}
/** The conversation at a list position (which counts the search box above them), or null. */
private Store.Conv conv(int pos) {
int i = pos - list.getHeaderViewsCount();
return i >= 0 && i < convs.size() ? convs.get(i) : null;
}
/**
* Above the first chat, out of sight until the list is pulled down past
* its top. Matches what a chat is called (your name for it, the person),
* then group chats with a matching member, archived ones too.
*/
private View searchBox() {
LinearLayout box = new LinearLayout(this);
box.setPadding(Ui.dp(this, 20), Ui.dp(this, 6), Ui.dp(this, 20), Ui.dp(this, 10));
search = new EditText(this);
search.setHint("🔍 Search");
search.setHintTextColor(Ui.FAINT);
search.setTextColor(Ui.TEXT);
search.setTextSize(TypedValue.COMPLEX_UNIT_SP, Ui.T_SMALL);
search.setSingleLine();
search.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
search.setBackground(Ui.round(Ui.INPUT, Ui.dp(this, 30)));
search.setPadding(Ui.dp(this, 24), Ui.dp(this, 12), Ui.dp(this, 24), Ui.dp(this, 12));
search.setOnEditorActionListener((v, action, e) -> {
hideKeyboard();
return true;
});
search.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int a, int b, int c) {}
public void onTextChanged(CharSequence s, int a, int b, int c) {}
public void afterTextChanged(Editable s) {
filter();
}
});
box.addView(search, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
searchBox = box;
return box;
}
private String query() {
return search.getText().toString().trim();
}
private void hideKeyboard() {
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(search.getWindowToken(), 0);
search.clearFocus();
}
/** Let go with the search box half showing: all the way out, or back out of sight. */
private void snapSearch() {
if (list.getFirstVisiblePosition() != 0 || !query().isEmpty() || search.hasFocus()) return;
int top = searchBox.getTop(), bottom = searchBox.getBottom();
if (top >= 0 || bottom <= 0) return;
list.smoothScrollBy(bottom > searchBox.getHeight() / 2 ? top : bottom, 150);
}
@Override
public void onBackPressed() {
if (!query().isEmpty() || search.hasFocus()) {
hideSearch = true;
search.setText("");
hideKeyboard();
return;
}
super.onBackPressed();
}
/** Everything that starts with or contains each word typed; a number by its digits. */
static boolean matches(String query, String name, String number) {
String q = query.trim().toLowerCase();
if (q.isEmpty()) return false;
String digits = q.replaceAll("\\D", "");
if (digits.length() >= 3 && q.matches("[\\d\\s()+.-]+") && number.contains(digits.replaceFirst("^1(?=\\d{10}$)", ""))) return true;
String n = name.toLowerCase();
for (String w : q.split("\\s+")) if (!n.contains(w)) return false;
return true;
}
/** What the list shows: this view's chats, or everything matching the search. */
private void filter() {
String q = query();
convs.clear();
if (q.isEmpty()) {
for (Store.Conv c : loaded) if (c.archived == archived) convs.add(c);
} else {
// Chats whose own name matches come first, so one you named isn't
// buried under every chat that merely includes a matching person.
List<Store.Conv> byMember = new ArrayList<>();
for (Store.Conv c : loaded) {
if (matches(q, Contacts.title(this, c.contact, c.name), c.contact)) {
convs.add(c);
continue;
}
for (String m : Phone.members(c.contact))
if (matches(q, Contacts.name(this, m), m)) {
byMember.add(c);
break;
}
}
convs.addAll(byMember);
}
noMatches.setVisibility(!q.isEmpty() && convs.isEmpty() ? View.VISIBLE : View.GONE);
adapter.notifyDataSetChanged();
if (hideSearch && q.isEmpty()) list.setSelection(list.getHeaderViewsCount());
}
@Override
public void changed() {
if (list == null) return;
bg.execute(() -> {
StateSync.importPending(this);
List<Store.Conv> fresh = Store.get(this).conversations(null);
Contacts.all(this); // load names here, not on the main thread while drawing rows
runOnUiThread(() -> {
loaded.clear();
loaded.addAll(fresh);
filter();
title.setText(archived ? "Archived" : "Messages");
String err = Sync.gvSignedOut ? "Google Voice signed out. Reconnect it on the desktop, then Sync to Rabbit."
: Sync.voipError != null ? "voip.ms: " + Sync.voipError : Sync.gvError != null ? "Google Voice: " + Sync.gvError : null;
status.setText(err == null ? "" : "⚠ " + err);
status.setVisibility(err == null ? View.GONE : View.VISIBLE);
});
});
}
private void menu(Store.Conv c) {
List<String> labels = new ArrayList<>();
List<Runnable> actions = new ArrayList<>();
Store store = Store.get(this);
if (Phone.isGroup(c.contact)) {
labels.add("Get info");
actions.add(() -> startActivity(InfoActivity.intent(this, c.did, c.contact)));
}
labels.add(c.unread > 0 || c.markedUnread ? "Mark as read" : "Mark as unread");
actions.add(() -> {
if (c.unread > 0 || c.markedUnread) StateSync.markRead(this, c.did, c.contact);
else StateSync.markUnread(this, c.did, c.contact);
changed();
});
labels.add(c.archived ? "Unarchive" : "Archive");
actions.add(() -> {
StateSync.setArchived(this, c.did, c.contact, !c.archived);
changed();
});
new AlertDialog.Builder(this)
.setTitle(Contacts.title(this, c.contact, c.name))
.setItems(labels.toArray(new String[0]), (d, i) -> actions.get(i).run())
.show();
}
private final class Adapter extends BaseAdapter {
@Override
public int getCount() {
return convs.size();
}
@Override
public Object getItem(int i) {
return convs.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View convertView, ViewGroup parent) {
Context ctx = MainActivity.this;
Row row = convertView instanceof Row ? (Row) convertView : new Row(ctx);
row.bind(convs.get(i));
return row;
}
}
/**
* One conversation: avatar, name + time, preview + unread badge, "via";
* over a band that a swipe uncovers (see SwipeActions).
*/
private final class Row extends FrameLayout implements SwipeActions.Row {
Store.Conv conv;
final LinearLayout front;
final TextView under;
final View avatar;
final TextView name, time, preview, badge, via;
Row(Context c) {
super(c);
under = Ui.bold(Ui.text(c, "", Ui.T_SMALL, 0xFFFFFFFF));
under.setGravity(Gravity.CENTER_VERTICAL);
under.setPadding(Ui.dp(c, 28), 0, Ui.dp(c, 28), 0);
addView(under, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
front = new LinearLayout(c);
front.setBackgroundColor(Ui.BG);
front.setGravity(Gravity.CENTER_VERTICAL);
front.setPadding(Ui.dp(c, 20), Ui.dp(c, 14), Ui.dp(c, 20), Ui.dp(c, 14));
addView(front);
avatar = new View(c);
int size = Ui.dp(c, 84);
LinearLayout.LayoutParams alp = new LinearLayout.LayoutParams(size, size);
alp.rightMargin = Ui.dp(c, 18);
front.addView(avatar, alp);
LinearLayout main = new LinearLayout(c);
main.setOrientation(LinearLayout.VERTICAL);
LinearLayout top = new LinearLayout(c);
name = Ui.bold(Ui.text(c, "", Ui.T_NAME, Ui.TEXT));
name.setSingleLine();
name.setEllipsize(TextUtils.TruncateAt.END);
time = Ui.text(c, "", Ui.T_TINY, Ui.MUTED);
time.setPadding(Ui.dp(c, 8), 0, 0, 0);
top.addView(name, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1));
top.addView(time);
LinearLayout bottom = new LinearLayout(c);
bottom.setGravity(Gravity.CENTER_VERTICAL);
preview = Ui.text(c, "", Ui.T_SMALL, Ui.MUTED);
preview.setMaxLines(2);
preview.setEllipsize(TextUtils.TruncateAt.END);
badge = Ui.bold(Ui.text(c, "", Ui.T_TINY, 0xFFFFFFFF));
badge.setGravity(Gravity.CENTER);
badge.setMinWidth(Ui.dp(c, 40));
badge.setPadding(Ui.dp(c, 10), Ui.dp(c, 2), Ui.dp(c, 10), Ui.dp(c, 2));
badge.setBackground(Ui.round(Ui.ACCENT, Ui.dp(c, 20)));
bottom.addView(preview, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1));
LinearLayout.LayoutParams blp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
blp.leftMargin = Ui.dp(c, 8);
bottom.addView(badge, blp);
via = Ui.text(c, "", Ui.T_TINY, Ui.FAINT);
main.addView(top);
main.addView(bottom);
main.addView(via);
front.addView(main, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1));
}
@Override
public View front() {
return front;
}
@Override
public View under() {
return under;
}
@Override
public void reveal(boolean rightward) {
boolean unread = conv.unread > 0 || conv.markedUnread;
under.setText(rightward ? (conv.archived ? "↩ Unarchive" : "🗄 Archive") : unread ? "✓ Read" : "✉ Unread");
under.setGravity(Gravity.CENTER_VERTICAL | (rightward ? Gravity.START : Gravity.END));
}
void bind(Store.Conv c) {
Context ctx = getContext();
conv = c;
SwipeActions.reset(this);
boolean group = Phone.isGroup(c.contact);
String title = Contacts.title(ctx, c.contact, c.name);
avatar.setBackground(Ui.avatar(c.contact, group ? null : Contacts.lookup(ctx, c.contact) == null ? null : title, group));
name.setText(title);
time.setText(Ui.shortTime(ctx, c.lastTs));
String reaction = Reactions.preview(c.lastBody);
String body = reaction != null ? reaction : c.lastBody == null ? "" : c.lastBody.replaceAll("\\s+", " ").trim();
if (body.isEmpty() && c.lastMediaJson != null) body = "📷 Photo";
String who = "out".equals(c.lastDirection) ? "You: " : group && c.lastSender != null ? Contacts.firstName(ctx, c.lastSender) + ": " : "";
preview.setText(who + body);
boolean unread = c.unread > 0 || c.markedUnread;
preview.setTextColor(unread ? Ui.TEXT : Ui.MUTED);
badge.setVisibility(unread ? VISIBLE : GONE);
badge.setText(c.unread > 99 ? "99+" : c.unread > 0 ? String.valueOf(c.unread) : "•");
via.setText(Config.get(ctx).dids.size() > 1 ? Ui.via(ctx, c.did) : "");
via.setVisibility(Config.get(ctx).dids.size() > 1 ? VISIBLE : GONE);
}
}
}
@@ -0,0 +1,194 @@
package me.teafry.voipmessages;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.LruCache;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.util.List;
/**
* Attachments, cached in files/media named by content hash -- the same layout
* as the desktop's <dataDir>/media, which the installer copies over, so the
* MediaRef.file names in the copied history resolve as-is.
*/
final class Media {
private Media() {}
/** voip.ms takes ~1.2 MB per file and carriers are stricter. */
static final int BUDGET = 900 * 1024;
static File dir(Context c) {
File d = new File(c.getFilesDir(), "media");
d.mkdirs();
return d;
}
static String ext(String mime) {
if (mime == null) return "bin";
switch (mime) {
case "image/jpeg": return "jpg";
case "image/png": return "png";
case "image/gif": return "gif";
case "image/webp": return "webp";
case "video/mp4": return "mp4";
case "audio/mpeg": return "mp3";
case "audio/mp4": return "m4a";
default: {
int slash = mime.indexOf('/');
return slash > 0 ? mime.substring(slash + 1).replaceAll("[^a-z0-9]", "") : "bin";
}
}
}
static String save(Context c, byte[] data, String mime) throws IOException {
String name;
try {
byte[] h = MessageDigest.getInstance("SHA-1").digest(data);
StringBuilder sb = new StringBuilder();
for (byte b : h) sb.append(String.format("%02x", b));
name = sb + "." + ext(mime);
} catch (Exception e) {
throw new IOException(e);
}
File f = new File(dir(c), name);
if (!f.exists()) try (FileOutputStream out = new FileOutputStream(f)) {
out.write(data);
}
return name;
}
/** The local file for attachment `index` of message `id`, downloading it first if needed. */
static File resolve(Context c, long id, int index) {
// Already here: no need to wait behind someone else's download.
File have = local(c, id, index);
if (have != null) return have;
synchronized (Media.class) {
return download(c, id, index);
}
}
private static File local(Context c, long id, int index) {
Store.Msg m = Store.get(c).getMessage(id);
List<JSONObject> refs = m == null ? null : m.media();
if (refs == null || index >= refs.size()) return null;
String file = refs.get(index).optString("file", "");
if (file.isEmpty()) return null;
File f = new File(dir(c), new File(file).getName());
return f.exists() ? f : null;
}
private static File download(Context c, long id, int index) {
Store store = Store.get(c);
Store.Msg m = store.getMessage(id);
if (m == null) return null;
List<JSONObject> refs = m.media();
if (index >= refs.size()) return null;
JSONObject ref = refs.get(index);
String file = ref.optString("file", "");
if (!file.isEmpty()) {
File f = new File(dir(c), new File(file).getName());
if (f.exists()) return f;
}
String url = ref.optString("url", "");
if (url.isEmpty()) return null;
try {
byte[] data;
String mime;
if (url.startsWith("gv:")) {
Object[] r = new GVoice(Config.get(c)).download(url.substring(3));
data = (byte[]) r[0];
mime = (String) r[1];
} else {
Http.Response r = Http.request("GET", url, null, null, 60_000);
if (r.status >= 400) return null;
data = r.body;
mime = r.header("Content-Type");
}
if (mime != null) mime = mime.split(";")[0].trim();
if ("text/html".equals(mime)) return null; // expired voip.ms media answers with a page
if (mime == null || mime.equals("application/octet-stream")) mime = ref.optString("mime", "application/octet-stream");
String name = save(c, data, mime);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, o);
store.setMediaFile(id, index, name, mime, o.outWidth, o.outHeight);
return new File(dir(c), name);
} catch (Exception e) {
return null;
}
}
private static final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(24 * 1024 * 1024) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
/** An attachment's bitmap if it's already decoded, without touching the disk. */
static Bitmap cached(JSONObject ref, int maxEdge) {
String file = ref.optString("file", "");
return file.isEmpty() ? null : cache.get(new File(file).getName() + "@" + maxEdge);
}
/** A bitmap no bigger than maxEdge on its long side. */
static Bitmap bitmap(File f, int maxEdge) {
String key = f.getName() + "@" + maxEdge;
Bitmap b = cache.get(key);
if (b != null) return b;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(f.getPath(), o);
int sample = 1;
while (Math.max(o.outWidth, o.outHeight) / (sample * 2) >= maxEdge) sample *= 2;
o = new BitmapFactory.Options();
o.inSampleSize = sample;
b = BitmapFactory.decodeFile(f.getPath(), o);
if (b != null) cache.put(key, b);
return b;
}
/**
* A picked photo, ready to send: under BUDGET, JPEG unless it was already a
* small JPEG/PNG/GIF. Returns [bytes, mime].
*/
static Object[] prepare(Context c, Uri uri) throws IOException {
String mime = c.getContentResolver().getType(uri);
byte[] original;
try (InputStream in = c.getContentResolver().openInputStream(uri)) {
if (in == null) throw new IOException("Couldn't open that photo.");
original = Http.readAll(in);
}
boolean passthrough = "image/jpeg".equals(mime) || "image/png".equals(mime) || "image/gif".equals(mime);
if (passthrough && original.length <= BUDGET) return new Object[] {original, mime};
Bitmap full = BitmapFactory.decodeByteArray(original, 0, original.length);
if (full == null) throw new IOException("That file isn't a photo the Rabbit can read.");
int[] edges = {2048, 1600, 1280, 1024, 800, 640};
int[] qualities = {85, 72, 60};
for (int edge : edges) {
float scale = Math.min(1f, edge / (float) Math.max(full.getWidth(), full.getHeight()));
Bitmap b = scale < 1f ? Bitmap.createScaledBitmap(full, Math.round(full.getWidth() * scale), Math.round(full.getHeight() * scale), true) : full;
for (int q : qualities) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, q, out);
if (out.size() <= BUDGET) return new Object[] {out.toByteArray(), "image/jpeg"};
}
}
throw new IOException("That photo is too big to send, even shrunk.");
}
static byte[] read(File f) throws IOException {
return Files.readAllBytes(f.toPath());
}
}
@@ -0,0 +1,250 @@
package me.teafry.voipmessages;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Start a conversation: pick the number to send from, then a contact or a
* typed number. From the Google Voice number, "+ Group" starts a group.
*/
public final class NewChatActivity extends BaseActivity {
private ListView list;
private EditText to;
private TextView toLabel, start;
private LinearLayout chips;
private String from;
private boolean fromChosen;
private final List<String> members = new ArrayList<>();
private final List<String[]> options = new ArrayList<>(); // [number, name or null, label]
private Adapter adapter;
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
Config cfg = Config.get(this);
from = cfg.defaultDid;
LinearLayout root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
root.setPadding(Ui.dp(this, 16), Ui.dp(this, 8), Ui.dp(this, 16), 0);
LinearLayout header = new LinearLayout(this);
header.setGravity(Gravity.CENTER_VERTICAL);
TextView title = Ui.bold(Ui.text(this, "New chat", Ui.T_TITLE, Ui.TEXT));
header.addView(title, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
start = Ui.button(this, "Start", true);
start.setVisibility(View.GONE);
start.setOnClickListener(v -> open(members.size() > 1 ? Phone.groupKey(members) : members.get(0)));
header.addView(start);
root.addView(header);
if (cfg.dids.size() > 1) {
LinearLayout fromRow = new LinearLayout(this);
fromRow.setGravity(Gravity.CENTER_VERTICAL);
fromRow.addView(Ui.text(this, "From ", Ui.T_SMALL, Ui.MUTED));
Spinner sp = new Spinner(this);
List<String> labels = new ArrayList<>();
int sel = 0;
for (int i = 0; i < cfg.dids.size(); i++) {
Config.Did d = cfg.dids.get(i);
labels.add(Phone.format(d.did) + (d.gv ? " — Google Voice" : ""));
if (d.did.equals(from)) sel = i;
}
sp.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, labels));
sp.setSelection(sel);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> p, View v, int pos, long id) {
if (!cfg.dids.get(pos).did.equals(from)) fromChosen = true;
from = cfg.dids.get(pos).did;
if (!cfg.isGv(from)) {
members.clear();
renderChips();
}
adapter.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> p) {}
});
fromRow.addView(sp);
root.addView(fromRow);
}
chips = new LinearLayout(this);
chips.setOrientation(LinearLayout.VERTICAL);
root.addView(chips);
LinearLayout toRow = new LinearLayout(this);
toRow.setGravity(Gravity.CENTER_VERTICAL);
toRow.setBackground(Ui.round(Ui.INPUT, Ui.dp(this, 20)));
toRow.setPadding(Ui.dp(this, 20), 0, Ui.dp(this, 12), 0);
toLabel = Ui.text(this, "To:", Ui.T_SMALL, Ui.MUTED);
to = new EditText(this);
to.setHint("Name or number");
to.setHintTextColor(Ui.FAINT);
to.setTextColor(Ui.TEXT);
to.setTextSize(TypedValue.COMPLEX_UNIT_SP, Ui.T_BODY);
to.setBackground(null);
to.setSingleLine();
toRow.addView(toLabel);
toRow.addView(to, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
LinearLayout.LayoutParams tlp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tlp.topMargin = Ui.dp(this, 8);
tlp.bottomMargin = Ui.dp(this, 8);
root.addView(toRow, tlp);
list = new ListView(this);
list.setDivider(null);
adapter = new Adapter();
list.setAdapter(adapter);
list.setOnItemClickListener((p, v, pos, id) -> pick(options.get(pos)[0]));
root.addView(list, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1));
setContentView(root);
to.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int a, int b, int c) {}
public void onTextChanged(CharSequence s, int a, int b, int c) {}
public void afterTextChanged(Editable s) {
filter();
}
});
to.setOnEditorActionListener((v, action, e) -> {
if (!options.isEmpty()) pick(options.get(0)[0]);
return true;
});
filter();
}
@Override
public void changed() {}
private void filter() {
String q = to.getText().toString().trim().toLowerCase(Locale.ROOT);
options.clear();
String digits = Phone.normalize(q);
boolean typedNumber = q.matches("[\\d\\s()+.-]+") && (digits.length() == 10 || (digits.length() >= 3 && digits.length() <= 6));
List<Contacts.Entry> all = Contacts.all(this);
boolean typedIsContact = false;
for (Contacts.Entry e : all) {
if (members.contains(e.number)) continue;
boolean match = q.isEmpty() || e.name.toLowerCase(Locale.ROOT).contains(q) || (digits.length() >= 3 && e.number.contains(digits));
if (match) {
options.add(new String[] {e.number, e.name, e.label});
if (e.number.equals(digits)) typedIsContact = true;
}
if (options.size() >= 100) break;
}
if (typedNumber && !typedIsContact && !members.contains(digits)) options.add(0, new String[] {digits, null, null});
adapter.notifyDataSetChanged();
}
private void pick(String number) {
if (!members.isEmpty()) addMember(number);
else open(number);
}
private void addMember(String number) {
if (!members.contains(number)) members.add(number);
to.setText("");
renderChips();
}
private void renderChips() {
chips.removeAllViews();
for (String n : members) {
TextView chip = Ui.text(this, Contacts.name(this, n) + " ✕", Ui.T_SMALL, Ui.TEXT);
chip.setBackground(Ui.round(Ui.INPUT, Ui.dp(this, 24)));
chip.setPadding(Ui.dp(this, 18), Ui.dp(this, 8), Ui.dp(this, 18), Ui.dp(this, 8));
chip.setOnClickListener(v -> {
members.remove(n);
renderChips();
filter();
});
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.topMargin = Ui.dp(this, 6);
chips.addView(chip, lp);
}
start.setVisibility(members.isEmpty() ? View.GONE : View.VISIBLE);
toLabel.setText(members.isEmpty() ? "To:" : "Add:");
adapter.notifyDataSetChanged();
}
private void open(String contact) {
if (from == null) return;
startActivity(ChatActivity.intent(this, existingDid(contact), contact));
finish();
}
/**
* Reuse an existing conversation with this person: from the chosen number,
* or from any number if none was chosen.
*/
private String existingDid(String contact) {
if (fromChosen) return from;
for (Store.Conv c : Store.get(this).conversations(false)) if (c.contact.equals(contact)) return c.did;
return from;
}
private final class Adapter extends BaseAdapter {
@Override
public int getCount() {
return options.size();
}
@Override
public Object getItem(int i) {
return options.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View cv, ViewGroup parent) {
Context c = NewChatActivity.this;
String[] o = options.get(i);
LinearLayout row = new LinearLayout(c);
row.setGravity(Gravity.CENTER_VERTICAL);
row.setPadding(Ui.dp(c, 8), Ui.dp(c, 12), Ui.dp(c, 8), Ui.dp(c, 12));
View av = new View(c);
av.setBackground(Ui.avatar(o[0], o[1], false));
int s = Ui.dp(c, 72);
LinearLayout.LayoutParams alp = new LinearLayout.LayoutParams(s, s);
alp.rightMargin = Ui.dp(c, 16);
row.addView(av, alp);
LinearLayout main = new LinearLayout(c);
main.setOrientation(LinearLayout.VERTICAL);
main.addView(Ui.bold(Ui.text(c, o[1] != null ? o[1] : Phone.format(o[0]), Ui.T_NAME, Ui.TEXT)));
main.addView(Ui.text(c, o[1] != null ? Phone.format(o[0]) + (o[2] != null ? " · " + o[2] : "") : "Send to this number", Ui.T_SMALL, Ui.MUTED));
row.addView(main, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
if (Config.get(c).isGv(from) && members.isEmpty()) {
TextView plus = Ui.text(c, "+ Group", Ui.T_TINY, Ui.MUTED);
plus.setBackground(Ui.round(Ui.INPUT, Ui.dp(c, 24)));
plus.setPadding(Ui.dp(c, 16), Ui.dp(c, 10), Ui.dp(c, 16), Ui.dp(c, 10));
plus.setOnClickListener(v -> addMember(o[0]));
row.addView(plus);
}
return row;
}
}
}
@@ -0,0 +1,88 @@
package me.teafry.voipmessages;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.StatusBarNotification;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** One notification per conversation with new incoming messages. */
final class Notifier {
private Notifier() {}
private static final String CHANNEL = "messages";
// Only messages this recent notify (not a big catch-up after being offline).
private static final long RECENT = 6 * 60 * 60_000L;
/** Screens in front; while one is, new messages don't notify. */
static int visible;
static void notifyNew(Context c, List<Store.Msg> added) {
if (!Config.notifications(c) || visible > 0) return;
NotificationManager nm = c.getSystemService(NotificationManager.class);
nm.createNotificationChannel(new NotificationChannel(CHANNEL, "Messages", NotificationManager.IMPORTANCE_HIGH));
long now = System.currentTimeMillis();
Map<String, List<Store.Msg>> byConv = new LinkedHashMap<>();
for (Store.Msg m : added)
if (m.in() && m.ts > now - RECENT) 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 last = list.get(0);
for (Store.Msg m : list) if (m.ts > last.ts) last = m;
String title = Contacts.title(c, last.contact, store.getName(last.did, last.contact));
String reaction = Reactions.preview(last.body);
String body = reaction != null ? reaction : last.body.trim().isEmpty() && last.mediaJson != null ? "📷 Photo" : last.body.trim();
if (Phone.isGroup(last.contact) && last.sender != null) body = Contacts.firstName(c, last.sender) + ": " + body;
if (list.size() > 1) body += " (+" + (list.size() - 1) + " more)";
Intent open = ChatActivity.intent(c, last.did, last.contact);
int id = (last.did + last.contact).hashCode();
PendingIntent pi = PendingIntent.getActivity(c, id, open, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
Notification n = new Notification.Builder(c, CHANNEL)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setStyle(new Notification.BigTextStyle().bigText(body))
.setWhen(last.ts)
.setShowWhen(true)
.setAutoCancel(true)
.setContentIntent(pi)
.addExtras(conversation(last.did, last.contact))
.build();
nm.notify(id, n);
}
}
static void clear(Context c, String did, String contact) {
c.getSystemService(NotificationManager.class).cancel((did + contact).hashCode());
}
private static Bundle conversation(String did, String contact) {
Bundle b = new Bundle();
b.putString("did", did);
b.putString("contact", contact);
return b;
}
/**
* Take down the notification of every conversation that's been read since,
* here or anywhere else (the desktop, the phone, the web), so the shade
* only holds what's still unread. Call after read state changes.
*/
static void sweep(Context c) {
NotificationManager nm = c.getSystemService(NotificationManager.class);
Store store = Store.get(c);
for (StatusBarNotification sbn : nm.getActiveNotifications()) {
Bundle x = sbn.getNotification().extras;
String did = x.getString("did"), contact = x.getString("contact");
if (did != null && contact != null && !store.hasUnread(did, contact)) nm.cancel(sbn.getId());
}
}
}
@@ -0,0 +1,110 @@
package me.teafry.voipmessages;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A decoded protobuf message, read by field number (Google Voice responses;
* field numbers are in the desktop's src/main/gvoice/schema.ts). Unknown and
* missing fields read as defaults, like proto3.
*/
final class Pb {
private final Map<Integer, List<Object>> fields = new HashMap<>();
static Pb parse(byte[] buf) {
Pb p = new Pb();
int[] pos = {0};
while (pos[0] < buf.length) {
long tag = varint(buf, pos);
int num = (int) (tag >>> 3), wire = (int) (tag & 7);
Object v;
switch (wire) {
case 0:
v = varint(buf, pos);
break;
case 1:
v = fixed(buf, pos, 8);
break;
case 2: {
int len = (int) varint(buf, pos);
byte[] b = new byte[len];
System.arraycopy(buf, pos[0], b, 0, len);
pos[0] += len;
v = b;
break;
}
case 5:
v = fixed(buf, pos, 4);
break;
default:
throw new IllegalArgumentException("protobuf: wire type " + wire);
}
p.fields.computeIfAbsent(num, k -> new ArrayList<>()).add(v);
}
return p;
}
private static long varint(byte[] b, int[] pos) {
long r = 0;
int shift = 0;
while (true) {
if (pos[0] >= b.length) throw new IllegalArgumentException("protobuf: truncated");
int x = b[pos[0]++] & 0xff;
r |= (long) (x & 0x7f) << shift;
if ((x & 0x80) == 0) return r;
shift += 7;
}
}
private static long fixed(byte[] b, int[] pos, int n) {
long r = 0;
for (int i = 0; i < n; i++) r |= (long) (b[pos[0] + i] & 0xff) << (8 * i);
pos[0] += n;
return r;
}
private Object last(int n) {
List<Object> l = fields.get(n);
return l == null || l.isEmpty() ? null : l.get(l.size() - 1);
}
String str(int n) {
Object v = last(n);
return v instanceof byte[] ? new String((byte[]) v, StandardCharsets.UTF_8) : "";
}
long num(int n) {
Object v = last(n);
return v instanceof Long ? (Long) v : 0;
}
boolean bool(int n) {
return num(n) != 0;
}
Pb msg(int n) {
Object v = last(n);
return v instanceof byte[] ? parse((byte[]) v) : new Pb();
}
boolean has(int n) {
return fields.containsKey(n);
}
List<Pb> msgs(int n) {
List<Pb> out = new ArrayList<>();
List<Object> l = fields.get(n);
if (l != null) for (Object v : l) if (v instanceof byte[]) out.add(parse((byte[]) v));
return out;
}
List<String> strs(int n) {
List<String> out = new ArrayList<>();
List<Object> l = fields.get(n);
if (l != null) for (Object v : l) if (v instanceof byte[]) out.add(new String((byte[]) v, StandardCharsets.UTF_8));
return out;
}
}
@@ -0,0 +1,55 @@
package me.teafry.voipmessages;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
/** Phone number helpers, matching the desktop's src/shared/phone.ts. */
final class Phone {
private Phone() {}
/** Bare 10-digit NANP numbers where possible, else plain digits. */
static String normalize(String raw) {
if (raw == null) return "";
String d = raw.replaceAll("\\D", "");
if (d.length() == 11 && d.startsWith("1")) d = d.substring(1);
return d;
}
static String format(String n) {
String d = normalize(n);
if (d.length() == 10) return "(" + d.substring(0, 3) + ") " + d.substring(3, 6) + "-" + d.substring(6);
return n;
}
static String e164(String n) {
String d = normalize(n);
return d.length() == 10 ? "+1" + d : "+" + d;
}
/** Group chats are keyed by their members' numbers, sorted and comma-joined. */
static String groupKey(List<String> numbers) {
TreeSet<String> set = new TreeSet<>();
for (String n : numbers) {
String d = normalize(n);
if (!d.isEmpty()) set.add(d);
}
return String.join(",", set);
}
static boolean isGroup(String contact) {
return contact.contains(",");
}
static List<String> members(String contact) {
return new ArrayList<>(Arrays.asList(contact.split(",")));
}
/** voip.ms sends at most 160 characters as one SMS; longer goes as one MMS. */
static final int SMS_TEXT_LIMIT = 160;
static int charCount(String s) {
return s.codePointCount(0, s.length());
}
}
@@ -0,0 +1,24 @@
package me.teafry.voipmessages;
import android.app.job.JobParameters;
import android.app.job.JobService;
import java.util.List;
/** One background check of both providers. */
public final class PollJob extends JobService {
@Override
public boolean onStartJob(JobParameters params) {
new Thread(() -> {
List<Store.Msg> added = Sync.poll(this);
Notifier.notifyNew(this, added);
jobFinished(params, false);
}, "poll").start();
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
return true;
}
}
@@ -0,0 +1,94 @@
package me.teafry.voipmessages;
import android.content.Context;
import android.view.Gravity;
import android.view.MotionEvent;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.TextView;
/**
* Pull down on a list that's already at the top to check for new messages.
* (The framework has no SwipeRefreshLayout without androidx.)
*/
final class PullRefresh extends FrameLayout {
interface OnRefresh {
void refresh();
}
private final AbsListView list;
private final TextView hint;
private final int threshold;
private float startY = -1;
private boolean pulling, refreshing;
OnRefresh onRefresh;
PullRefresh(Context c, AbsListView list) {
super(c);
this.list = list;
threshold = Ui.dp(c, 140);
hint = Ui.text(c, "", Ui.T_SMALL, Ui.MUTED);
hint.setGravity(Gravity.CENTER);
hint.setPadding(0, Ui.dp(c, 16), 0, Ui.dp(c, 16));
hint.setVisibility(GONE);
addView(list, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
addView(hint, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.TOP));
hint.setBackgroundColor(Ui.PANEL);
}
private boolean atTop() {
return list.getChildCount() == 0 || (list.getFirstVisiblePosition() == 0 && list.getChildAt(0).getTop() >= list.getPaddingTop());
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
if (refreshing) return false;
switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
startY = atTop() ? e.getY() : -1;
pulling = false;
break;
case MotionEvent.ACTION_MOVE:
if (startY >= 0 && e.getY() - startY > Ui.dp(getContext(), 24) && atTop()) {
pulling = true;
return true;
}
break;
default:
break;
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent e) {
if (!pulling) return false;
float d = e.getY() - startY;
switch (e.getActionMasked()) {
case MotionEvent.ACTION_MOVE:
hint.setVisibility(VISIBLE);
hint.setText(d > threshold ? "Release to check for messages" : "Pull to check for messages");
list.setTranslationY(Math.min(d, threshold * 1.4f) / 2);
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
pulling = false;
list.animate().translationY(0).setDuration(150).start();
if (d > threshold && e.getActionMasked() == MotionEvent.ACTION_UP && onRefresh != null) {
setRefreshing(true);
onRefresh.refresh();
} else {
hint.setVisibility(GONE);
}
return true;
default:
return true;
}
}
void setRefreshing(boolean on) {
refreshing = on;
hint.setText("Checking for messages…");
hint.setVisibility(on ? VISIBLE : GONE);
}
}
@@ -0,0 +1,154 @@
package me.teafry.voipmessages;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* iPhone tapbacks ("Loved “see you at 9”") folded into emoji reactions on the
* message they quote -- a port of the desktop's src/shared/reactions.ts.
*/
final class Reactions {
private Reactions() {}
static final class Parsed {
final String emoji, text; // text null = reacting to a photo
final boolean removed;
Parsed(String emoji, String text, boolean removed) {
this.emoji = emoji;
this.text = text;
this.removed = removed;
}
}
static final class Reaction {
final String emoji, from; // number, or "me"
final long ts;
Reaction(String emoji, String from, long ts) {
this.emoji = emoji;
this.from = from;
this.ts = ts;
}
}
private static final Map<String, String> VERBS = new HashMap<>();
private static final Map<String, String> REMOVED = new HashMap<>();
static {
VERBS.put("loved", "❤️");
VERBS.put("liked", "👍");
VERBS.put("disliked", "👎");
VERBS.put("laughed at", "😂");
VERBS.put("emphasized", "‼️");
VERBS.put("questioned", "❓");
REMOVED.put("a heart", "❤️");
REMOVED.put("a like", "👍");
REMOVED.put("a dislike", "👎");
REMOVED.put("a laugh", "😂");
REMOVED.put("an exclamation", "‼️");
REMOVED.put("an exclamation mark", "‼️");
REMOVED.put("a question mark", "❓");
}
private static final String TAIL = " (?:[“\"”]([\\s\\S]*)[”\"“]|(.+))$";
private static final Pattern VERB = Pattern.compile("^(Loved|Liked|Disliked|Laughed at|Emphasized|Questioned)" + TAIL);
private static final Pattern REACTED = Pattern.compile("^Reacted (.+?) to" + TAIL);
private static final Pattern REMOVE = Pattern.compile("^Removed (an? .+?) from" + TAIL);
private static final Pattern MEDIA = Pattern.compile("^(?:an? )?(?:image|photo|picture|movie|video|attachment|audio message|gif|sticker)$",
Pattern.CASE_INSENSITIVE);
/** [ok, text] where text null means media. */
private static Object[] target(Matcher m) {
if (m.group(2) != null) return new Object[] {true, m.group(2)};
if (m.group(3) != null && MEDIA.matcher(m.group(3).trim()).matches()) return new Object[] {true, null};
return new Object[] {false, null};
}
static Parsed parse(String body) {
if (body == null) return null;
String s = body.trim();
Matcher m = VERB.matcher(s);
if (m.matches()) {
Object[] t = target(m);
return (boolean) t[0] ? new Parsed(VERBS.get(m.group(1).toLowerCase()), (String) t[1], false) : null;
}
m = REACTED.matcher(s);
if (m.matches() && m.group(1).codePointCount(0, m.group(1).length()) <= 4) {
Object[] t = target(m);
return (boolean) t[0] ? new Parsed(m.group(1), (String) t[1], false) : null;
}
m = REMOVE.matcher(s);
if (m.matches()) {
String kind = m.group(1).toLowerCase();
String emoji = REMOVED.get(kind);
if (emoji == null) {
Matcher e = Pattern.compile("^an? (.{1,4})$").matcher(m.group(1));
if (e.matches()) emoji = e.group(1);
}
Object[] t = target(m);
return emoji != null && (boolean) t[0] ? new Parsed(emoji, (String) t[1], true) : null;
}
return null;
}
private static String norm(String s) {
return s.replaceAll("[‘’]", "'").replaceAll("\\s+", " ").trim();
}
private static boolean matches(String body, String quoted) {
String b = norm(body), q = norm(quoted);
if (q.isEmpty()) return false;
if (b.equals(q)) return true;
String cut = q.replaceAll("(…|\\.\\.\\.)$", "").trim();
return !cut.equals(q) && cut.length() >= 8 && b.startsWith(cut);
}
/** Reaction texts we could place are dropped from `msgs`; returns reactions by message id. */
static Map<Long, List<Reaction>> fold(List<Store.Msg> msgs) {
Set<Long> hidden = new HashSet<>();
Map<Long, LinkedHashMap<String, Reaction>> byTarget = new HashMap<>();
for (int i = 0; i < msgs.size(); i++) {
Store.Msg m = msgs.get(i);
Parsed r = parse(m.body);
if (r == null) continue;
Store.Msg found = null;
for (int j = i - 1; j >= 0 && found == null; j--) {
Store.Msg c = msgs.get(j);
if (hidden.contains(c.id) || parse(c.body) != null) continue;
if (r.text == null ? c.mediaJson != null : matches(c.body, r.text)) found = c;
}
if (found == null) continue;
hidden.add(m.id);
String from = m.in() ? (m.sender != null ? m.sender : m.contact) : "me";
LinkedHashMap<String, Reaction> mine = byTarget.computeIfAbsent(found.id, k -> new LinkedHashMap<>());
if (r.removed) {
Reaction cur = mine.get(from);
if (cur != null && cur.emoji.equals(r.emoji)) mine.remove(from);
} else {
mine.remove(from);
mine.put(from, new Reaction(r.emoji, from, m.ts));
}
}
Map<Long, List<Reaction>> out = new HashMap<>();
for (Map.Entry<Long, LinkedHashMap<String, Reaction>> e : byTarget.entrySet())
if (!e.getValue().isEmpty()) out.put(e.getKey(), new ArrayList<>(e.getValue().values()));
if (!hidden.isEmpty()) msgs.removeIf(m -> hidden.contains(m.id));
return out;
}
/** "❤️ to “see you at 9”", or null for an ordinary text. */
static String preview(String body) {
Parsed r = parse(body);
if (r == null) return null;
String what = r.text == null ? "a photo" : "“" + norm(r.text) + "”";
return r.removed ? "Removed " + r.emoji + " from " + what : r.emoji + " to " + what;
}
}
@@ -0,0 +1,221 @@
package me.teafry.voipmessages;
import android.content.Context;
import android.util.Base64;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Sending, like the desktop's deliver()/sendWithRetry: the pending bubble
* appears at once; one conversation's sends go out in order; a send that
* certainly didn't go out is retried, and one that may have gone out is
* looked for in a fresh check before sending it again.
*/
final class Sender {
private Sender() {}
// One thread: sends go out in the order they were typed.
private static final ExecutorService queue = Executors.newSingleThreadExecutor();
private static final int MAX_ATTEMPTS = 3;
private static final long[] RETRY_DELAYS = {3000, 10_000};
private static final long[] CHECK_DELAYS = {5000, 15_000};
/** A photo already saved into files/media. */
static final class Photo {
final String file, mime;
final int width, height;
Photo(String file, String mime, int width, int height) {
this.file = file;
this.mime = mime;
this.width = width;
this.height = height;
}
JSONObject ref() {
JSONObject o = new JSONObject();
try {
o.put("file", file).put("mime", mime);
if (width > 0) o.put("width", width).put("height", height);
} catch (Exception ignored) {
}
return o;
}
}
private interface Attempt {
long run() throws Exception;
}
static void send(Context ctx, String did, String contact, String text, List<Photo> photos) {
Context c = ctx.getApplicationContext();
Config cfg = Config.get(c);
if (cfg.sandbox) {
// Pretend it went out.
Store.Msg m = pending(did, contact, text, photos);
Store store = Store.get(c);
long id = store.insertPending(m);
store.confirmPending(id, 9_000_000_000L + (System.currentTimeMillis() % 1_000_000_000L));
Sync.changed();
return;
}
if (cfg.isGv(did)) {
if (photos.isEmpty()) {
enqueue(c, pending(did, contact, text, null), () -> gvSend(c, did, contact, text, null), true);
} else {
// Google Voice carries one photo per message: the text rides with the first.
for (int i = 0; i < photos.size(); i++) {
String body = i == 0 ? text : "";
Photo p = photos.get(i);
List<Photo> one = new ArrayList<>();
one.add(p);
Store.Msg m = pending(did, contact, body, one);
m.ts += i;
enqueue(c, m, () -> gvSend(c, did, contact, body, p), true);
}
}
return;
}
boolean mms = !photos.isEmpty() || Phone.charCount(text) > Phone.SMS_TEXT_LIMIT;
Store.Msg m = pending(did, contact, text, photos);
if (mms) m.kind = "mms";
enqueue(c, m, () -> {
VoipMs api = new VoipMs(cfg.voipUser, cfg.voipPass);
if (!mms) return api.sendSms(did, contact, text);
List<String> media = new ArrayList<>();
for (Photo p : photos)
media.add("data:" + p.mime + ";base64," + Base64.encodeToString(Media.read(new File(Media.dir(c), p.file)), Base64.NO_WRAP));
return api.sendMms(did, contact, text, media);
}, false);
}
private static Store.Msg pending(String did, String contact, String text, List<Photo> photos) {
Store.Msg m = new Store.Msg();
m.did = did;
m.contact = contact;
m.direction = "out";
m.body = text;
m.ts = System.currentTimeMillis();
if (photos != null && !photos.isEmpty()) {
JSONArray a = new JSONArray();
for (Photo p : photos) a.put(p.ref());
m.mediaJson = a.toString();
m.kind = "mms";
}
return m;
}
private static void enqueue(Context c, Store.Msg m, Attempt attempt, boolean gv) {
Store store = Store.get(c);
long tempId = store.insertPending(m);
Sync.changed();
queue.execute(() -> {
deliver(c, store, tempId, attempt, gv);
Sync.changed();
});
}
private static void deliver(Context c, Store store, long tempId, Attempt attempt, boolean gv) {
for (int n = 1; ; n++) {
try {
store.confirmPending(tempId, attempt.run());
return;
} catch (Exception e) {
if (store.getMessage(tempId) == null) return; // a check found it already sent
String kind = classify(e, gv);
if (kind.equals("unknown")) {
for (long ms : CHECK_DELAYS) {
sleep(ms);
Sync.poll(c);
if (store.getMessage(tempId) == null) return;
}
}
if (kind.equals("fatal") || n >= MAX_ATTEMPTS) {
store.markFailed(tempId, e.getMessage());
return;
}
if (kind.equals("safe")) sleep(RETRY_DELAYS[Math.min(n - 1, RETRY_DELAYS.length - 1)]);
}
}
}
private static String classify(Exception e, boolean gv) {
if (e instanceof GVoice.Failure) {
int s = ((GVoice.Failure) e).status;
if (s == 0) return e.getMessage() != null && e.getMessage().startsWith("Couldn't reach") ? "safe" : "unknown";
if (s == 429) return "safe";
if (s >= 500) return "unknown";
return "fatal";
}
if (e instanceof VoipMs.Failure) {
String st = ((VoipMs.Failure) e).status;
return st.equals("sms_failed") || st.equals("mms_failed") ? "safe" : "fatal";
}
return Http.notSent(e) ? "safe" : "unknown";
}
private static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException ignored) {
}
}
/** One Google Voice send; returns the id the message has in GV's own listing. */
private static long gvSend(Context c, String did, String contact, String text, Photo photo) throws Exception {
Config cfg = Config.get(c);
GVoice gv = new GVoice(cfg);
Store store = Store.get(c);
List<String> recipients = new ArrayList<>();
for (String n : Phone.members(contact)) recipients.add(Phone.e164(n));
String threadId = store.gvThread(did, contact);
if (threadId == null) threadId = "";
if (threadId.isEmpty() && !Phone.isGroup(contact)) {
// A 1:1 thread's id is predictable, but only exists once either side texted.
try {
threadId = gv.getThread("t." + recipients.get(0), 1, "").id;
} catch (GVoice.Failure e) {
if (e.status != 404) throw e;
}
}
long txn = (long) (Math.random() * 1e14);
String tracking = Waa.sign(c, gv, threadId, recipients, txn);
byte[] image = photo == null ? null : Media.read(new File(Media.dir(c), photo.file));
String[] r = gv.sendSms(threadId, recipients, text, photo == null ? null : photo.mime, image, txn, tracking);
String thread = !r[0].isEmpty() ? r[0] : threadId;
if (!thread.isEmpty()) store.setGvThread(did, contact, thread);
// Find our message by transaction id: the listing is what later checks see.
String listed = null;
if (!thread.isEmpty()) {
try {
for (Pb m : gv.getThread(thread, 10, "").messages)
if (m.num(18) == txn) {
listed = m.str(1);
break;
}
} catch (GVoice.Failure ignored) {
}
}
return GVoice.messageId(listed != null ? listed : r[1]);
}
/** Send a failed message again. */
static void retry(Context c, long id) {
Store store = Store.get(c);
Store.Msg m = store.getMessage(id);
if (m == null || !"failed".equals(m.status)) return;
store.deleteMessage(id);
List<Photo> photos = new ArrayList<>();
for (JSONObject ref : m.media())
photos.add(new Photo(ref.optString("file"), ref.optString("mime"), ref.optInt("width"), ref.optInt("height")));
send(c, m.did, m.contact, m.body, photos);
}
}
@@ -0,0 +1,123 @@
package me.teafry.voipmessages;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TextView;
/** Background checks, notifications, and what's connected. */
public final class SettingsActivity extends BaseActivity {
private static final int[] INTERVALS = {0, 5, 10, 15, 30, 60, 120};
private LinearLayout box;
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
ScrollView scroll = new ScrollView(this);
box = new LinearLayout(this);
box.setOrientation(LinearLayout.VERTICAL);
box.setPadding(Ui.dp(this, 28), Ui.dp(this, 12), Ui.dp(this, 28), Ui.dp(this, 28));
scroll.addView(box);
setContentView(scroll);
}
private static String intervalLabel(int m) {
if (m == 0) return "Never (pull to refresh)";
if (m < 60) return "Every " + m + " minutes";
return m == 60 ? "Every hour" : "Every " + (m / 60) + " hours";
}
@Override
public void changed() {
if (box == null) return;
Context c = this;
box.removeAllViews();
box.addView(Ui.bold(Ui.text(c, "Settings", Ui.T_TITLE, Ui.TEXT)));
section("Checking for messages");
int current = Config.pollMinutes(c);
row("In the background", intervalLabel(current), v -> {
String[] labels = new String[INTERVALS.length];
int sel = 0;
for (int i = 0; i < INTERVALS.length; i++) {
labels[i] = intervalLabel(INTERVALS[i]);
if (INTERVALS[i] == current) sel = i;
}
new AlertDialog.Builder(c).setTitle("Check in the background").setSingleChoiceItems(labels, sel, (d, i) -> {
Config.prefs(c).edit().putInt("pollMinutes", INTERVALS[i]).apply();
Alarms.schedule(c);
d.dismiss();
changed();
}).show();
});
String last = Store.get(c).get("last_poll");
note(last == null ? "Not checked yet. Pull down on the chat list to check now."
: "Last checked " + Ui.shortTime(c, Long.parseLong(last)).toLowerCase() + ". Pull down on the chat list to check now.");
Switch notify = new Switch(c);
notify.setText("Notifications for new messages");
notify.setTextColor(Ui.TEXT);
notify.setTextSize(Ui.T_SMALL + 2);
notify.setChecked(Config.notifications(c));
notify.setPadding(0, Ui.dp(c, 16), 0, Ui.dp(c, 16));
notify.setOnCheckedChangeListener((v, on) -> Config.prefs(c).edit().putBoolean("notifications", on).apply());
box.addView(notify);
section("Accounts");
Config cfg = Config.get(c);
kv("voip.ms", cfg.voipUser == null ? "Not set up" : Sync.voipError != null ? "⚠ " + Sync.voipError : cfg.voipUser);
for (Config.Did d : cfg.dids) if (!d.gv) kv(" Number", Phone.format(d.did) + (d.description.isEmpty() ? "" : " · " + d.description));
kv("Google Voice", cfg.gvNumber == null ? "Not set up"
: Sync.gvSignedOut ? "⚠ Signed out" : Sync.gvError != null ? "⚠ " + Sync.gvError : Phone.format(cfg.gvNumber));
note("Accounts come from the desktop app: Settings → Rabbit → Sync to Rabbit copies them here again (e.g. after reconnecting Google Voice there).");
section("About");
String version = "?";
try {
PackageInfo p = getPackageManager().getPackageInfo(getPackageName(), 0);
version = p.versionName;
} catch (Exception ignored) {
}
kv("Version", version);
}
private void section(String title) {
TextView t = Ui.bold(Ui.text(this, title.toUpperCase(), Ui.T_TINY, Ui.MUTED));
t.setPadding(0, Ui.dp(this, 28), 0, Ui.dp(this, 6));
box.addView(t);
}
private void note(String s) {
TextView t = Ui.text(this, s, Ui.T_TINY, Ui.FAINT);
t.setPadding(0, Ui.dp(this, 4), 0, Ui.dp(this, 8));
box.addView(t);
}
private void kv(String k, String v) {
LinearLayout r = new LinearLayout(this);
r.setPadding(0, Ui.dp(this, 8), 0, Ui.dp(this, 8));
r.addView(Ui.text(this, k, Ui.T_SMALL, Ui.TEXT), new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
TextView val = Ui.text(this, v, Ui.T_SMALL, Ui.MUTED);
val.setGravity(Gravity.END);
r.addView(val, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.4f));
box.addView(r);
}
private void row(String label, String value, View.OnClickListener onClick) {
LinearLayout r = new LinearLayout(this);
r.setOrientation(LinearLayout.VERTICAL);
r.setPadding(Ui.dp(this, 20), Ui.dp(this, 14), Ui.dp(this, 20), Ui.dp(this, 14));
r.setBackground(Ui.round(Ui.INPUT, Ui.dp(this, 16)));
r.addView(Ui.text(this, label, Ui.T_SMALL, Ui.TEXT));
r.addView(Ui.text(this, value, Ui.T_SMALL, Ui.ACCENT));
r.setOnClickListener(onClick);
box.addView(r);
}
}
@@ -0,0 +1,75 @@
package me.teafry.voipmessages;
import android.content.Context;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
/**
* Chat names and read/unread/archived state, kept in step with the desktop.
* Changes here are written to files/state.json; the desktop's "Sync to
* Rabbit" reads that, merges it with its own (newest change wins), and leaves
* the result in files/state-in.json, applied here on the next start or check.
*/
final class StateSync {
private StateSync() {}
/** Write files/state.json; call after any rename or read/unread/archive change. */
static void export(Context c) {
try {
Store store = Store.get(c);
JSONObject state = new JSONObject().put("names", store.namesExport()).put("read", store.readStateExport());
File tmp = new File(c.getFilesDir(), "state.json.tmp");
try (FileOutputStream out = new FileOutputStream(tmp)) {
out.write(state.toString().getBytes(StandardCharsets.UTF_8));
}
tmp.renameTo(new File(c.getFilesDir(), "state.json"));
} catch (Exception ignored) {
}
}
static void importPending(Context c) {
File in = new File(c.getFilesDir(), "state-in.json");
if (!in.exists()) return;
try {
JSONObject state = new JSONObject(new String(Files.readAllBytes(in.toPath()), StandardCharsets.UTF_8));
Store store = Store.get(c);
JSONArray names = state.optJSONArray("names");
JSONArray read = state.optJSONArray("read");
if (names != null) store.namesImport(names);
if (read != null) store.readStateImport(read);
in.delete();
export(c);
Notifier.sweep(c);
Sync.changed();
} catch (Exception ignored) {
}
}
static void rename(Context c, String did, String contact, String name) {
Store.get(c).setName(did, contact, name, System.currentTimeMillis());
export(c);
Sync.changed();
}
static void markRead(Context c, String did, String contact) {
Store.get(c).markRead(did, contact);
export(c);
Notifier.sweep(c);
}
static void markUnread(Context c, String did, String contact) {
Store.get(c).markUnread(did, contact);
export(c);
}
static void setArchived(Context c, String did, String contact, boolean archived) {
Store.get(c).setArchived(did, contact, archived);
export(c);
}
}
@@ -0,0 +1,472 @@
package me.teafry.voipmessages;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* The message store: the same SQLite schema as the desktop app (src/main/db.ts),
* so the history the desktop copies over at install opens as-is. The desktop
* strips its full-text index first (Android's SQLite has no FTS5).
*/
final class Store {
private static Store instance;
final SQLiteDatabase db;
// How far a sent message's server time can be from our local stamp and
// still count as the same message (as on the desktop).
private static final long MATCH_BEFORE = 2 * 60_000L;
private static final long MATCH_AFTER = 15 * 60_000L;
static synchronized Store get(Context c) {
if (instance == null) instance = new Store(c.getApplicationContext());
return instance;
}
static File dbFile(Context c) {
return new File(c.getFilesDir(), "messages.db");
}
private Store(Context c) {
lockDown(c.getFilesDir());
db = SQLiteDatabase.openOrCreateDatabase(dbFile(c), null);
db.enableWriteAheadLogging();
migrate();
}
/** Files copied in over adb arrive world-readable; make them ours alone. */
static void lockDown(File dir) {
dir.setReadable(false, false);
dir.setWritable(false, false);
dir.setExecutable(false, false);
dir.setReadable(true, true);
dir.setWritable(true, true);
dir.setExecutable(true, true);
File[] files = dir.listFiles();
if (files == null) return;
for (File f : files) {
if (f.isDirectory()) {
lockDown(f);
continue;
}
f.setReadable(false, false);
f.setWritable(false, false);
f.setReadable(true, true);
f.setWritable(true, true);
}
}
private boolean hasColumn(String table, String col) {
try (Cursor cur = db.rawQuery("PRAGMA table_info(" + table + ")", null)) {
while (cur.moveToNext()) if (col.equals(cur.getString(1))) return true;
}
return false;
}
private void migrate() {
db.execSQL("CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, did TEXT NOT NULL, contact TEXT NOT NULL,"
+ " direction TEXT NOT NULL, body TEXT NOT NULL, ts INTEGER NOT NULL, kind TEXT NOT NULL DEFAULT 'sms',"
+ " status TEXT NOT NULL DEFAULT 'delivered', media_json TEXT, error TEXT, sender TEXT)");
db.execSQL("CREATE INDEX IF NOT EXISTS messages_conv ON messages (did, contact, ts)");
db.execSQL("CREATE INDEX IF NOT EXISTS messages_ts ON messages (ts)");
db.execSQL("CREATE TABLE IF NOT EXISTS read_state (did TEXT NOT NULL, contact TEXT NOT NULL, last_read_ts INTEGER NOT NULL,"
+ " archived_at INTEGER, marked_unread INTEGER NOT NULL DEFAULT 0, name TEXT, PRIMARY KEY (did, contact))");
db.execSQL("CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)");
db.execSQL("CREATE TABLE IF NOT EXISTS gv_threads (did TEXT NOT NULL, contact TEXT NOT NULL, thread_id TEXT NOT NULL,"
+ " PRIMARY KEY (did, contact))");
if (!hasColumn("messages", "error")) db.execSQL("ALTER TABLE messages ADD COLUMN error TEXT");
if (!hasColumn("messages", "sender")) db.execSQL("ALTER TABLE messages ADD COLUMN sender TEXT");
if (!hasColumn("read_state", "name")) db.execSQL("ALTER TABLE read_state ADD COLUMN name TEXT");
if (!hasColumn("read_state", "name_ts")) db.execSQL("ALTER TABLE read_state ADD COLUMN name_ts INTEGER");
if (!hasColumn("read_state", "unread_ts")) db.execSQL("ALTER TABLE read_state ADD COLUMN unread_ts INTEGER");
if (!hasColumn("read_state", "archived_ts")) db.execSQL("ALTER TABLE read_state ADD COLUMN archived_ts INTEGER");
if (get("unread_floor") == null) set("unread_floor", String.valueOf(System.currentTimeMillis()));
}
// ---- key/value ----
String get(String key) {
try (Cursor c = db.rawQuery("SELECT value FROM kv WHERE key = ?", new String[] {key})) {
return c.moveToFirst() ? c.getString(0) : null;
}
}
void set(String key, String value) {
db.execSQL("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
new Object[] {key, value});
}
// ---- messages ----
static final class Msg {
long id;
String did, contact, direction, body = "", kind = "sms", status = "delivered", mediaJson, error, sender;
long ts;
boolean in() {
return "in".equals(direction);
}
List<JSONObject> media() {
List<JSONObject> out = new ArrayList<>();
if (mediaJson == null) return out;
try {
JSONArray a = new JSONArray(mediaJson);
for (int i = 0; i < a.length(); i++) out.add(a.getJSONObject(i));
} catch (JSONException ignored) {
}
return out;
}
}
private static final String COLS = "id, did, contact, direction, body, ts, kind, status, media_json, error, sender";
private static Msg row(Cursor c) {
Msg m = new Msg();
m.id = c.getLong(0);
m.did = c.getString(1);
m.contact = c.getString(2);
m.direction = c.getString(3);
m.body = c.getString(4);
m.ts = c.getLong(5);
m.kind = c.getString(6);
m.status = c.getString(7);
m.mediaJson = c.getString(8);
m.error = c.getString(9);
m.sender = c.getString(10);
return m;
}
/** Inserts messages we haven't seen; returns the new ones. */
List<Msg> upsert(List<Msg> msgs) {
List<Msg> added = new ArrayList<>();
db.beginTransaction();
try {
for (Msg m : msgs) {
ContentValues v = new ContentValues();
v.put("id", m.id);
v.put("did", m.did);
v.put("contact", m.contact);
v.put("direction", m.direction);
v.put("body", m.body == null ? "" : m.body);
v.put("ts", m.ts);
v.put("status", m.status);
v.put("kind", m.kind);
v.put("media_json", m.mediaJson);
v.put("sender", m.sender);
if (db.insertWithOnConflict("messages", null, v, SQLiteDatabase.CONFLICT_IGNORE) != -1) {
added.add(m);
// Anything newer than the archiving brings a conversation back.
db.execSQL("UPDATE read_state SET archived_at = NULL WHERE did = ? AND contact = ? AND archived_at IS NOT NULL AND archived_at < ?",
new Object[] {m.did, m.contact, m.ts});
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return added;
}
long insertPending(Msg m) {
try (Cursor c = db.rawQuery("SELECT MIN(id) FROM messages", null)) {
long min = c.moveToFirst() && !c.isNull(0) ? c.getLong(0) : 0;
m.id = Math.min(-1, min - 1);
}
m.status = "pending";
List<Msg> one = new ArrayList<>();
one.add(m);
upsert(one);
return m.id;
}
/** Replace a local pending row with the id the provider assigned. */
void confirmPending(long tempId, long realId) {
db.beginTransaction();
try {
if (getMessage(realId) != null) {
// A poll beat us to it: keep our local copies of attachments.
Msg pending = getMessage(tempId);
if (pending != null && pending.mediaJson != null)
db.execSQL("UPDATE messages SET media_json = ? WHERE id = ?", new Object[] {pending.mediaJson, realId});
db.execSQL("DELETE FROM messages WHERE id = ?", new Object[] {tempId});
} else {
db.execSQL("UPDATE messages SET id = ?, status = 'delivered' WHERE id = ?", new Object[] {realId, tempId});
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
void markFailed(long tempId, String error) {
db.execSQL("UPDATE messages SET status = 'failed', error = ? WHERE id = ?", new Object[] {error, tempId});
}
/** Sent messages that turned up in a poll replace our pending/failed copies. */
void reconcileSent(List<Msg> added) {
List<Msg> sorted = new ArrayList<>(added);
sorted.sort(Comparator.comparingLong(a -> a.ts));
for (Msg m : sorted) {
if (m.in() || m.id < 0) continue;
try (Cursor c = db.rawQuery("SELECT id FROM messages WHERE id < 0 AND status IN ('pending','failed') AND direction = 'out'"
+ " AND did = ? AND contact = ? AND body = ? AND ts BETWEEN ? AND ? ORDER BY ts, id DESC LIMIT 1",
new String[] {m.did, m.contact, m.body, String.valueOf(m.ts - MATCH_AFTER), String.valueOf(m.ts + MATCH_BEFORE)})) {
if (c.moveToFirst()) confirmPending(c.getLong(0), m.id);
}
}
}
void deleteMessage(long id) {
db.execSQL("DELETE FROM messages WHERE id = ?", new Object[] {id});
}
Msg getMessage(long id) {
try (Cursor c = db.rawQuery("SELECT " + COLS + " FROM messages WHERE id = ?", new String[] {String.valueOf(id)})) {
return c.moveToFirst() ? row(c) : null;
}
}
List<Msg> messages(String did, String contact) {
List<Msg> out = new ArrayList<>();
try (Cursor c = db.rawQuery("SELECT " + COLS + " FROM messages WHERE did = ? AND contact = ? ORDER BY ts, id",
new String[] {did, contact})) {
while (c.moveToNext()) out.add(row(c));
}
return out;
}
/** The newest `limit` messages, oldest first: enough to fill the screen while the rest loads. */
List<Msg> recentMessages(String did, String contact, int limit) {
List<Msg> out = new ArrayList<>();
try (Cursor c = db.rawQuery("SELECT * FROM (SELECT " + COLS + " FROM messages WHERE did = ? AND contact = ? ORDER BY ts DESC, id DESC LIMIT "
+ limit + ") ORDER BY ts, id", new String[] {did, contact})) {
while (c.moveToNext()) out.add(row(c));
}
return out;
}
void setMediaFile(long id, int index, String file, String mime, int width, int height) {
Msg m = getMessage(id);
if (m == null) return;
try {
JSONArray a = new JSONArray(m.mediaJson);
JSONObject ref = a.getJSONObject(index);
ref.put("file", file);
if (mime != null) ref.put("mime", mime);
if (width > 0) {
ref.put("width", width);
ref.put("height", height);
}
db.execSQL("UPDATE messages SET media_json = ? WHERE id = ?", new Object[] {a.toString(), id});
} catch (JSONException ignored) {
}
}
// ---- conversations ----
static final class Conv {
String did, contact, lastBody, lastDirection, lastSender, lastMediaJson, name;
long lastTs;
int unread;
boolean archived, markedUnread;
}
/** Archived or not; null for every conversation. */
List<Conv> conversations(Boolean archived) {
long floor = Long.parseLong(get("unread_floor") == null ? "0" : get("unread_floor"));
List<Conv> out = new ArrayList<>();
String sql = "WITH latest AS (SELECT did, contact, MAX(ts) AS mts FROM messages GROUP BY did, contact)"
+ " 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'"
+ " 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"
+ " FROM latest l JOIN messages last ON last.id ="
+ " (SELECT id FROM messages m WHERE m.did = l.did AND m.contact = l.contact ORDER BY ts DESC, id DESC LIMIT 1)"
+ " LEFT JOIN read_state r ON r.did = l.did AND r.contact = l.contact"
+ " ORDER BY l.mts DESC";
try (Cursor c = db.rawQuery(sql, new String[] {String.valueOf(floor)})) {
while (c.moveToNext()) {
Conv v = new Conv();
v.did = c.getString(0);
v.contact = c.getString(1);
v.lastTs = c.getLong(2);
v.lastBody = c.getString(3);
v.lastDirection = c.getString(4);
v.lastSender = c.getString(5);
v.lastMediaJson = c.getString(6);
v.unread = c.getInt(7);
v.archived = c.getInt(8) != 0;
v.markedUnread = c.getInt(9) != 0;
v.name = c.getString(10);
if (archived == null || v.archived == archived) out.add(v);
}
}
return out;
}
boolean hasUnread(String did, String contact) {
long floor = Long.parseLong(get("unread_floor") == null ? "0" : get("unread_floor"));
try (Cursor c = db.rawQuery("SELECT EXISTS (SELECT 1 FROM messages m LEFT JOIN read_state r ON r.did = m.did AND r.contact = m.contact"
+ " WHERE m.did = ? AND m.contact = ? AND m.direction = 'in' AND m.ts > MAX(COALESCE(r.last_read_ts, 0), CAST(? AS INTEGER)))",
new String[] {did, contact, String.valueOf(floor)})) {
return c.moveToFirst() && c.getInt(0) != 0;
}
}
// Each records when it happened (unread_ts / archived_ts) so the desktop
// and the Rabbit can merge: the newer change wins.
void markRead(String did, String contact) {
db.execSQL("INSERT INTO read_state (did, contact, last_read_ts, unread_ts) SELECT ?, ?, COALESCE(MAX(ts), 0), ? FROM messages WHERE did = ? AND contact = ?"
+ " ON CONFLICT(did, contact) DO UPDATE SET last_read_ts = MAX(last_read_ts, excluded.last_read_ts), marked_unread = 0,"
+ " unread_ts = excluded.unread_ts",
new Object[] {did, contact, System.currentTimeMillis(), did, contact});
}
void markUnread(String did, String contact) {
db.execSQL("INSERT INTO read_state (did, contact, last_read_ts, marked_unread, unread_ts) VALUES (?, ?, 0, 1, ?)"
+ " ON CONFLICT(did, contact) DO UPDATE SET marked_unread = 1, unread_ts = excluded.unread_ts",
new Object[] {did, contact, System.currentTimeMillis()});
}
void setArchived(String did, String contact, boolean archived) {
long now = System.currentTimeMillis();
db.execSQL("INSERT INTO read_state (did, contact, last_read_ts, archived_at, archived_ts) VALUES (?, ?, 0, ?, ?)"
+ " ON CONFLICT(did, contact) DO UPDATE SET archived_at = excluded.archived_at, archived_ts = excluded.archived_ts",
new Object[] {did, contact, archived ? now : null, now});
}
/** Read/unread and archived state of every conversation (same shape as the desktop's). */
JSONArray readStateExport() {
JSONArray out = new JSONArray();
try (Cursor c = db.rawQuery("SELECT did, contact, last_read_ts, marked_unread, unread_ts, archived_at, archived_ts FROM read_state", null)) {
while (c.moveToNext()) {
try {
out.put(new JSONObject().put("did", c.getString(0)).put("contact", c.getString(1)).put("lastRead", c.getLong(2))
.put("markedUnread", c.getInt(3) != 0)
.put("unreadTs", c.isNull(4) ? JSONObject.NULL : c.getLong(4))
.put("archivedAt", c.isNull(5) ? JSONObject.NULL : c.getLong(5))
.put("archivedTs", c.isNull(6) ? JSONObject.NULL : c.getLong(6)));
} catch (JSONException ignored) {
}
}
}
return out;
}
/** Merge the desktop's: later read point; newer unread/archived change. */
void readStateImport(JSONArray rows) throws JSONException {
db.beginTransaction();
try {
for (int i = 0; i < rows.length(); i++) {
JSONObject t = rows.getJSONObject(i);
String did = t.getString("did"), contact = t.getString("contact");
long lastRead = 0, unreadTs = 0, archivedTs = 0;
int marked = 0;
Long archivedAt = null;
try (Cursor c = db.rawQuery("SELECT last_read_ts, marked_unread, COALESCE(unread_ts, 0), archived_at, COALESCE(archived_ts, 0)"
+ " FROM read_state WHERE did = ? AND contact = ?", new String[] {did, contact})) {
if (c.moveToFirst()) {
lastRead = c.getLong(0);
marked = c.getInt(1);
unreadTs = c.getLong(2);
archivedAt = c.isNull(3) ? null : c.getLong(3);
archivedTs = c.getLong(4);
}
}
long theirUnreadTs = t.isNull("unreadTs") ? 0 : t.optLong("unreadTs");
long theirArchivedTs = t.isNull("archivedTs") ? 0 : t.optLong("archivedTs");
if (theirUnreadTs > unreadTs) {
marked = t.optBoolean("markedUnread") ? 1 : 0;
unreadTs = theirUnreadTs;
}
if (theirArchivedTs > archivedTs) {
archivedAt = t.isNull("archivedAt") ? null : t.optLong("archivedAt");
archivedTs = theirArchivedTs;
}
lastRead = Math.max(lastRead, t.optLong("lastRead"));
db.execSQL("INSERT INTO read_state (did, contact, last_read_ts, marked_unread, unread_ts, archived_at, archived_ts) VALUES (?, ?, ?, ?, ?, ?, ?)"
+ " ON CONFLICT(did, contact) DO UPDATE SET last_read_ts = excluded.last_read_ts, marked_unread = excluded.marked_unread,"
+ " unread_ts = excluded.unread_ts, archived_at = excluded.archived_at, archived_ts = excluded.archived_ts",
new Object[] {did, contact, lastRead, marked, unreadTs == 0 ? null : unreadTs, archivedAt, archivedTs == 0 ? null : archivedTs});
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
// ---- names (kept in step with the desktop: newest rename wins) ----
String getName(String did, String contact) {
try (Cursor c = db.rawQuery("SELECT name FROM read_state WHERE did = ? AND contact = ?", new String[] {did, contact})) {
return c.moveToFirst() ? c.getString(0) : null;
}
}
void setName(String did, String contact, String name, long ts) {
String n = name == null || name.trim().isEmpty() ? null : name.trim();
db.execSQL("INSERT INTO read_state (did, contact, last_read_ts, name, name_ts) VALUES (?, ?, 0, ?, ?)"
+ " ON CONFLICT(did, contact) DO UPDATE SET name = excluded.name, name_ts = excluded.name_ts",
new Object[] {did, contact, n, ts});
}
/** Every rename ever made here or imported, for the desktop to merge. */
JSONArray namesExport() {
JSONArray out = new JSONArray();
try (Cursor c = db.rawQuery("SELECT did, contact, name, name_ts FROM read_state WHERE name_ts IS NOT NULL", null)) {
while (c.moveToNext()) {
JSONObject o = new JSONObject();
try {
o.put("did", c.getString(0)).put("contact", c.getString(1)).put("name", c.isNull(2) ? JSONObject.NULL : c.getString(2)).put("ts", c.getLong(3));
} catch (JSONException ignored) {
}
out.put(o);
}
}
return out;
}
/** Apply names from the desktop, keeping whichever rename is newer. */
void namesImport(JSONArray names) throws JSONException {
for (int i = 0; i < names.length(); i++) {
JSONObject o = names.getJSONObject(i);
String did = o.getString("did"), contact = o.getString("contact");
long ts = o.getLong("ts");
long mine = 0;
try (Cursor c = db.rawQuery("SELECT COALESCE(name_ts, 0) FROM read_state WHERE did = ? AND contact = ?", new String[] {did, contact})) {
if (c.moveToFirst()) mine = c.getLong(0);
}
if (ts > mine) setName(did, contact, o.isNull("name") ? null : o.getString("name"), ts);
}
}
// ---- Google Voice threads ----
String gvThread(String did, String contact) {
try (Cursor c = db.rawQuery("SELECT thread_id FROM gv_threads WHERE did = ? AND contact = ?", new String[] {did, contact})) {
return c.moveToFirst() ? c.getString(0) : null;
}
}
void setGvThread(String did, String contact, String threadId) {
db.execSQL("INSERT INTO gv_threads (did, contact, thread_id) VALUES (?, ?, ?)"
+ " ON CONFLICT(did, contact) DO UPDATE SET thread_id = excluded.thread_id", new Object[] {did, contact, threadId});
}
/** Plain-text search (Android's SQLite has no FTS5); fine for one person's history. */
List<Msg> search(String q, int limit) {
List<Msg> out = new ArrayList<>();
String like = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%";
try (Cursor c = db.rawQuery("SELECT " + COLS + " FROM messages WHERE body LIKE ? ESCAPE '\\' ORDER BY ts DESC LIMIT " + limit,
new String[] {like})) {
while (c.moveToNext()) out.add(row(c));
}
return out;
}
}
@@ -0,0 +1,141 @@
package me.teafry.voipmessages;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.ListView;
/**
* Swipe a conversation sideways: left to right archives it (in Archived,
* brings it back) over a blue band; right to left marks it unread (or read)
* over a magenta one. The row slides along under the thumb uncovering the
* band; let go past {@link #COMMIT} of the way across and it's done (an
* archived row slides off, an unread one springs back), short of that it
* just springs back.
*/
final class SwipeActions implements View.OnTouchListener {
/** A row that can be swiped: the part that moves, and the band it uncovers. */
interface Row {
View front();
View under();
/** Label the band for the way it's being swiped (rightward = archive). */
void reveal(boolean rightward);
}
interface OnSwiped {
/** `position` is the adapter's (headers counted); rightward = archive, else unread. */
void swiped(int position, boolean rightward);
}
private static final float COMMIT = 0.35f;
private static final int ARCHIVE_DIM = 0xFF1D3F87, ARCHIVE_LIT = Ui.ACCENT;
private static final int UNREAD_DIM = 0xFF6B1A5E, UNREAD_LIT = 0xFFD0249F;
private final ListView list;
private final OnSwiped onSwiped;
private final int slop;
private float downX, downY;
private int position;
private Row row;
private boolean swiping, rightward, past;
SwipeActions(ListView list, OnSwiped onSwiped) {
this.list = list;
this.onSwiped = onSwiped;
slop = ViewConfiguration.get(list.getContext()).getScaledTouchSlop();
list.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent e) {
float dx = e.getX() - downX, dy = e.getY() - downY;
switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
downX = e.getX();
downY = e.getY();
swiping = false;
position = list.pointToPosition((int) downX, (int) downY);
View child = position == AdapterView.INVALID_POSITION ? null : list.getChildAt(position - list.getFirstVisiblePosition());
row = child instanceof Row ? (Row) child : null;
return false;
case MotionEvent.ACTION_MOVE:
if (row == null) return false;
if (!swiping) {
// Mostly sideways, or it's the list's (a scroll, a pull, a tap).
if (Math.abs(dy) > slop) row = null;
if (row == null || Math.abs(dx) < slop || Math.abs(dy) > Math.abs(dx) / 2) return false;
swiping = true;
rightward = dx > 0;
past = false;
row.reveal(rightward);
row.under().setBackgroundColor(dim());
list.getParent().requestDisallowInterceptTouchEvent(true);
// Call off the list's own handling of this touch (its pending tap / long press).
MotionEvent cancel = MotionEvent.obtain(e);
cancel.setAction(MotionEvent.ACTION_CANCEL);
list.onTouchEvent(cancel);
cancel.recycle();
}
// Locked to the way it started: back past the start just stops at zero.
drag(rightward ? Math.max(0, dx) : Math.min(0, dx));
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (!swiping) {
row = null;
return false;
}
swiping = false;
release(e.getActionMasked() == MotionEvent.ACTION_UP && past);
return true;
default:
return swiping;
}
}
private int dim() {
return rightward ? ARCHIVE_DIM : UNREAD_DIM;
}
private void drag(float dx) {
View front = row.front();
front.setTranslationX(dx);
boolean nowPast = Math.abs(dx) > front.getWidth() * COMMIT;
if (nowPast != past) {
past = nowPast;
row.under().setBackgroundColor(past ? (rightward ? ARCHIVE_LIT : UNREAD_LIT) : dim());
if (past) front.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
}
}
private void release(boolean commit) {
Row r = row;
int pos = position;
boolean right = rightward;
int dimColor = dim();
row = null;
View front = r.front();
if (commit && right) {
// Archived: it leaves the list, so it slides off.
front.animate().translationX(front.getWidth()).setDuration(140)
.withEndAction(() -> onSwiped.swiped(pos, true)).start();
} else {
// Unread stays in the list: back into place, then marked.
front.animate().translationX(0).setDuration(160).withEndAction(() -> {
r.under().setBackgroundColor(dimColor);
if (commit) onSwiped.swiped(pos, false);
}).start();
}
}
/** For a recycled row: back in place, band dimmed. */
static void reset(Row r) {
r.front().animate().cancel();
r.front().setTranslationX(0);
r.under().setBackgroundColor(ARCHIVE_DIM);
}
}
@@ -0,0 +1,134 @@
package me.teafry.voipmessages;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Checking both providers for new messages. History arrives with the install
* (the desktop copies its database), so this only ever looks at what's recent,
* like the desktop's polling.
*/
final class Sync {
private static final String TAG = "Sync";
private static final long DAY = 86_400_000L;
/** Screens listen for changes to redraw. Called on the main thread. */
interface Listener {
void changed();
}
private static final List<Listener> listeners = new CopyOnWriteArrayList<>();
private static final Handler main = new Handler(Looper.getMainLooper());
static void listen(Listener l) {
listeners.add(l);
}
static void unlisten(Listener l) {
listeners.remove(l);
}
static void changed() {
main.post(() -> {
for (Listener l : listeners) l.changed();
});
}
/** Last problem per provider, shown in Settings and the list header. */
static String voipError, gvError;
static boolean gvSignedOut;
/** Polls both; returns the messages that were new. Call off the main thread. */
static synchronized List<Store.Msg> poll(Context c) {
Config cfg = Config.get(c);
Store store = Store.get(c);
StateSync.importPending(c);
List<Store.Msg> added = new ArrayList<>();
if (cfg.sandbox) {
store.set("last_poll", String.valueOf(System.currentTimeMillis()));
changed();
return added;
}
if (cfg.voipUser != null) {
try {
long now = System.currentTimeMillis();
Set<String> wanted = new HashSet<>();
for (Config.Did d : cfg.dids) if (!d.gv) wanted.add(d.did);
List<Store.Msg> rows = new ArrayList<>();
for (Store.Msg m : new VoipMs(cfg.voipUser, cfg.voipPass).messages(VoipMs.ymd(now - DAY), VoipMs.ymd(now + DAY)))
if (wanted.isEmpty() || wanted.contains(m.did)) rows.add(m);
List<Store.Msg> a = store.upsert(rows);
store.reconcileSent(a);
added.addAll(a);
voipError = null;
} catch (Exception e) {
Log.w(TAG, "voip.ms poll failed", e);
voipError = e.getMessage();
}
}
if (cfg.gvNumber != null) {
try {
added.addAll(pollGv(cfg, store));
gvError = null;
gvSignedOut = false;
} catch (GVoice.Failure e) {
Log.w(TAG, "GV poll failed", e);
gvError = e.getMessage();
gvSignedOut = e.signedOut();
} catch (Exception e) {
Log.w(TAG, "GV poll failed", e);
gvError = e.getMessage();
}
}
store.set("last_poll", String.valueOf(System.currentTimeMillis()));
if (!added.isEmpty()) StateSync.export(c);
// Threads read on the phone or the web came back read (see storeThread).
Notifier.sweep(c);
changed();
return added;
}
@SuppressWarnings("unchecked")
private static List<Store.Msg> pollGv(Config cfg, Store store) throws GVoice.Failure {
GVoice gv = new GVoice(cfg);
List<Store.Msg> added = new ArrayList<>();
List<GVoice.Thread> threads = (List<GVoice.Thread>) gv.listThreads("")[0];
for (GVoice.Thread t : threads) {
if (t.messages.isEmpty()) continue;
String contact = GVoice.threadContact(t, cfg.gvNumber);
if (contact.isEmpty()) continue;
boolean known = false;
for (Pb m : t.messages) if (store.getMessage(GVoice.messageId(m.str(1))) != null) known = true;
boolean hasHistory = t.id.equals(store.gvThread(cfg.gvNumber, contact));
List<Store.Msg> a = storeThread(store, cfg.gvNumber, contact, t, t.messages);
// The list only carries each thread's latest few; fetch the rest of a gap.
if (!known && hasHistory && !t.paginationToken.isEmpty())
a.addAll(storeThread(store, cfg.gvNumber, contact, t, gv.getThread(t.id, 100, "").messages));
added.addAll(a);
}
return added;
}
private static List<Store.Msg> storeThread(Store store, String did, String contact, GVoice.Thread t, List<Pb> messages) {
store.setGvThread(did, contact, t.id);
boolean group = Phone.isGroup(contact);
List<Store.Msg> msgs = new ArrayList<>();
for (Pb m : messages) {
Store.Msg x = GVoice.toMsg(m, did, contact, group);
if (x != null) msgs.add(x);
}
List<Store.Msg> added = store.upsert(msgs);
store.reconcileSent(added);
// Already read on the phone or the web: not unread here either.
if (!added.isEmpty() && t.read) store.markRead(did, contact);
return added;
}
}
@@ -0,0 +1,197 @@
package me.teafry.voipmessages;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.text.format.DateFormat;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Calendar;
import java.util.Date;
/**
* Sizes, colours and small view helpers. The Rabbit's density is overridden
* to 160 on a ~278 ppi panel, so one dp is about half its usual size: every
* size here is roughly double a stock phone value (see andTunes' DEVICE.md).
*/
final class Ui {
private Ui() {}
// Desktop's dark palette.
static final int BG = 0xFF121212, PANEL = 0xFF1B1B1D, ROW_ACTIVE = 0xFF333336, BORDER = 0xFF2E2E30;
static final int TEXT = 0xFFE9E9E9, MUTED = 0xFFA3A3A3, FAINT = 0xFF7C7C7C;
static final int ACCENT = 0xFF2C6BED, BUBBLE_IN = 0xFF3B3B3B, DANGER = 0xFFE05252, INPUT = 0xFF2E2E30;
// Text sizes (sp).
static final float T_TITLE = 30, T_NAME = 27, T_BODY = 26, T_SMALL = 21, T_TINY = 18;
static int dp(Context c, float v) {
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, v, c.getResources().getDisplayMetrics()));
}
static TextView text(Context c, String s, float sp, int color) {
TextView t = new TextView(c);
t.setText(s);
t.setTextSize(TypedValue.COMPLEX_UNIT_SP, sp);
t.setTextColor(color);
return t;
}
static TextView bold(TextView t) {
t.setTypeface(Typeface.DEFAULT_BOLD);
return t;
}
static GradientDrawable round(int color, float radiusPx) {
GradientDrawable g = new GradientDrawable();
g.setColor(color);
g.setCornerRadius(radiusPx);
return g;
}
static Button button(Context c, String label, boolean primary) {
Button b = new Button(c);
b.setText(label);
b.setAllCaps(false);
b.setTextSize(TypedValue.COMPLEX_UNIT_SP, T_SMALL + 2);
b.setTextColor(primary ? 0xFFFFFFFF : TEXT);
b.setBackground(round(primary ? ACCENT : INPUT, dp(c, 16)));
b.setPadding(dp(c, 24), 0, dp(c, 24), 0);
b.setMinHeight(dp(c, 72));
b.setGravity(Gravity.CENTER);
return b;
}
/** A flat icon-ish text button for headers. */
static TextView headerButton(Context c, String glyph) {
TextView t = text(c, glyph, 34, TEXT);
t.setGravity(Gravity.CENTER);
t.setMinWidth(dp(c, 80));
t.setMinHeight(dp(c, 80));
t.setBackground(round(0x00000000, dp(c, 40)));
return t;
}
// ---- avatars (desktop's format.ts palette) ----
private static final int[] AV_BG = {0xFFE3B5A4, 0xFFA4C9E3, 0xFFB5E3A4, 0xFFE3A4D6, 0xFFE3D6A4, 0xFFA4E3D4, 0xFFC2A4E3, 0xFFE3A4A4, 0xFFA4B0E3, 0xFFD4E3A4};
private static final int[] AV_FG = {0xFF5C2A17, 0xFF16405C, 0xFF2A5C17, 0xFF5C1750, 0xFF5C4A17, 0xFF175C4C, 0xFF3C175C, 0xFF5C1717, 0xFF17245C, 0xFF4A5C17};
static String initials(String name) {
String[] words = name.replaceAll("[^\\p{L}\\p{N}\\s]", "").trim().split("\\s+");
if (words.length == 0 || words[0].isEmpty()) return "";
if (words.length == 1) return words[0].substring(0, words[0].offsetByCodePoints(0, 1)).toUpperCase();
String a = words[0], b = words[words.length - 1];
return (a.substring(0, a.offsetByCodePoints(0, 1)) + b.substring(0, b.offsetByCodePoints(0, 1))).toUpperCase();
}
/** A coloured circle with initials, or a person / group glyph. */
static Drawable avatar(String key, String name, boolean group) {
int h = 0;
for (int i = 0; i < key.length(); i++) h = h * 31 + key.charAt(i);
int i = Math.abs(h) % AV_BG.length;
String label = group ? "👥" : (name == null ? "" : initials(name));
return new Avatar(AV_BG[i], AV_FG[i], label.isEmpty() ? "👤" : label);
}
private static final class Avatar extends Drawable {
private final Paint bg = new Paint(Paint.ANTI_ALIAS_FLAG), fg = new Paint(Paint.ANTI_ALIAS_FLAG);
private final String label;
Avatar(int bgColor, int fgColor, String label) {
this.label = label;
bg.setColor(bgColor);
fg.setColor(fgColor);
fg.setTypeface(Typeface.DEFAULT_BOLD);
fg.setTextAlign(Paint.Align.CENTER);
}
@Override
public void draw(Canvas canvas) {
Rect b = getBounds();
float r = Math.min(b.width(), b.height()) / 2f;
canvas.drawCircle(b.exactCenterX(), b.exactCenterY(), r, bg);
fg.setTextSize(r * (label.length() > 2 ? 0.8f : 0.85f));
Paint.FontMetrics fm = fg.getFontMetrics();
canvas.drawText(label, b.exactCenterX(), b.exactCenterY() - (fm.ascent + fm.descent) / 2, fg);
}
@Override
public void setAlpha(int alpha) {}
@Override
public void setColorFilter(ColorFilter cf) {}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
static View avatarView(Context c, String key, String name, boolean group, int sizeDp) {
View v = new View(c);
v.setBackground(avatar(key, name, group));
v.setMinimumWidth(dp(c, sizeDp));
v.setMinimumHeight(dp(c, sizeDp));
return v;
}
// ---- times (desktop's format.ts) ----
private static long startOfDay(long ms) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ms);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
static String timeOfDay(Context c, long ms) {
return DateFormat.getTimeFormat(c).format(new Date(ms));
}
/** Conversation list: "Now", "5m", "3:04 PM", "Tue", "Mar 3", "3/3/22". */
static String shortTime(Context c, long ms) {
long now = System.currentTimeMillis(), diff = now - ms;
if (diff < 60_000) return "Now";
if (diff < 3_600_000) return (diff / 60_000) + "m";
if (ms >= startOfDay(now)) return timeOfDay(c, ms);
if (ms >= startOfDay(now) - 6 * 86_400_000L) return DateFormat.format("EEE", ms).toString();
Calendar a = Calendar.getInstance(), b = Calendar.getInstance();
a.setTimeInMillis(ms);
b.setTimeInMillis(now);
if (a.get(Calendar.YEAR) == b.get(Calendar.YEAR)) return DateFormat.format("MMM d", ms).toString();
return DateFormat.format("M/d/yy", ms).toString();
}
/** Chat date separators. */
static String dayLabel(long ms) {
long today = startOfDay(System.currentTimeMillis()), day = startOfDay(ms);
if (day == today) return "Today";
if (day == today - 86_400_000L) return "Yesterday";
if (day > today - 7 * 86_400_000L) return DateFormat.format("EEEE", ms).toString();
Calendar a = Calendar.getInstance(), b = Calendar.getInstance();
a.setTimeInMillis(ms);
b.setTimeInMillis(System.currentTimeMillis());
return DateFormat.format(a.get(Calendar.YEAR) == b.get(Calendar.YEAR) ? "EEE, MMM d" : "EEE, MMM d, yyyy", ms).toString();
}
static boolean sameDay(long a, long b) {
return startOfDay(a) == startOfDay(b);
}
/** "via (541) 555-0100" / "via GV (484) …" */
static String via(Context c, String did) {
return "via " + (Config.get(c).isGv(did) ? "GV " : "") + Phone.format(did);
}
}
@@ -0,0 +1,354 @@
package me.teafry.voipmessages;
import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Record a voice note, play it back, then send it or record again. Hands the
* saved files/media name back to ChatActivity ("file", "mime").
*
* AAC in an .m4a: phones, iPhones and the desktop's <audio> all play it, and
* voip.ms takes MP4 for MMS. At 32 kbit/s the 3-minute cap stays under
* Media.BUDGET.
*/
public final class VoiceActivity extends BaseActivity {
static final String MIME = "audio/mp4";
private static final int MAX_MS = 180_000;
private static final int PERMISSION = 1;
private final Handler tick = new Handler(Looper.getMainLooper());
private final List<Float> levels = new ArrayList<>();
private File file;
private MediaRecorder recorder;
private MediaPlayer player;
private long startedAt, recordedMs;
private TextView status, timer;
private View dot;
private ObjectAnimator pulse;
private Wave wave;
private Button left, middle, right;
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
file = new File(getCacheDir(), "voice-note.m4a");
LinearLayout root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
root.setGravity(Gravity.CENTER_HORIZONTAL);
root.setPadding(Ui.dp(this, 32), Ui.dp(this, 28), Ui.dp(this, 32), Ui.dp(this, 28));
TextView title = Ui.bold(Ui.text(this, "Voice note", Ui.T_TITLE, Ui.TEXT));
title.setGravity(Gravity.CENTER);
root.addView(title);
status = Ui.text(this, "", Ui.T_SMALL, Ui.MUTED);
status.setPadding(0, Ui.dp(this, 6), 0, 0);
status.setGravity(Gravity.CENTER);
root.addView(status);
// The pulsing dot, breathing while the mic is on.
FrameLayout dotBox = new FrameLayout(this);
dot = new View(this);
dot.setBackground(Ui.round(Ui.DANGER, Ui.dp(this, 40)));
int ds = Ui.dp(this, 80);
dotBox.addView(dot, new FrameLayout.LayoutParams(ds, ds, Gravity.CENTER));
LinearLayout.LayoutParams dlp = new LinearLayout.LayoutParams(Ui.dp(this, 140), Ui.dp(this, 140));
dlp.topMargin = Ui.dp(this, 20);
root.addView(dotBox, dlp);
pulse = ObjectAnimator.ofPropertyValuesHolder(dot,
PropertyValuesHolder.ofFloat("scaleX", 1f, 1.5f),
PropertyValuesHolder.ofFloat("scaleY", 1f, 1.5f),
PropertyValuesHolder.ofFloat("alpha", 1f, 0.45f));
pulse.setDuration(700);
pulse.setRepeatCount(ValueAnimator.INFINITE);
pulse.setRepeatMode(ValueAnimator.REVERSE);
timer = Ui.bold(Ui.text(this, "0:00", Ui.T_TITLE + 10, Ui.TEXT));
timer.setPadding(0, Ui.dp(this, 8), 0, Ui.dp(this, 8));
timer.setGravity(Gravity.CENTER);
root.addView(timer);
wave = new Wave(this);
root.addView(wave, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1));
LinearLayout buttons = new LinearLayout(this);
buttons.setPadding(0, Ui.dp(this, 20), 0, 0);
left = Ui.button(this, "", false);
middle = Ui.button(this, "", false);
right = Ui.button(this, "", true);
for (Button btn : new Button[] {left, middle, right}) {
btn.setSingleLine();
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
lp.leftMargin = lp.rightMargin = Ui.dp(this, 6);
buttons.addView(btn, lp);
}
root.addView(buttons, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
setContentView(root);
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) record();
else requestPermissions(new String[] {Manifest.permission.RECORD_AUDIO}, PERMISSION);
}
@Override
public void onRequestPermissionsResult(int req, String[] perms, int[] results) {
if (req != PERMISSION) return;
if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) record();
else {
Toast.makeText(this, "Voice notes need the microphone.", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void changed() {}
// ---- recording ----
private void record() {
stopPlaying();
levels.clear();
file.delete();
recorder = new MediaRecorder();
try {
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
recorder.setAudioChannels(1);
recorder.setAudioSamplingRate(22050);
recorder.setAudioEncodingBitRate(32000);
recorder.setMaxDuration(MAX_MS);
recorder.setMaxFileSize(Media.BUDGET);
recorder.setOutputFile(file.getPath());
recorder.setOnInfoListener((r, what, extra) -> {
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED
|| what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) stopRecording();
});
recorder.prepare();
recorder.start();
} catch (Exception e) {
recorder.release();
recorder = null;
Toast.makeText(this, "Couldn't start the microphone.", Toast.LENGTH_LONG).show();
finish();
return;
}
startedAt = System.currentTimeMillis();
pulse.start();
status.setText("Recording…");
setButtons("Cancel", v -> finish(), null, null, "Stop", v -> stopRecording());
tick.post(ticker);
}
private void stopRecording() {
if (recorder == null) return;
recordedMs = System.currentTimeMillis() - startedAt;
boolean ok = true;
try {
recorder.stop();
} catch (RuntimeException e) {
ok = false; // stopped before any audio was captured
}
recorder.release();
recorder = null;
pulse.cancel();
dot.setScaleX(1f);
dot.setScaleY(1f);
dot.setAlpha(0.35f);
if (!ok || recordedMs < 500) {
status.setText("Too short, try again.");
setButtons("Cancel", v -> finish(), null, null, "Record", v -> record());
return;
}
wave.progress = 0;
wave.invalidate();
timer.setText(clock(recordedMs));
status.setText("Listen back, then send it.");
idleButtons();
}
private void idleButtons() {
setButtons("Redo", v -> record(), "Play", v -> play(), "Send", v -> send());
}
// ---- playback ----
private void play() {
if (player != null) {
if (player.isPlaying()) {
player.pause();
middle.setText("Play");
} else {
player.start();
middle.setText("Pause");
tick.post(ticker);
}
return;
}
player = new MediaPlayer();
try {
player.setDataSource(file.getPath());
player.prepare();
} catch (Exception e) {
stopPlaying();
Toast.makeText(this, "Couldn't play it back.", Toast.LENGTH_SHORT).show();
return;
}
player.setOnCompletionListener(p -> {
stopPlaying();
wave.progress = 0;
wave.invalidate();
timer.setText(clock(recordedMs));
});
player.start();
middle.setText("Pause");
tick.post(ticker);
}
private void stopPlaying() {
if (player == null) return;
player.release();
player = null;
if (middle != null) middle.setText("Play");
}
private final Runnable ticker = new Runnable() {
@Override
public void run() {
if (recorder != null) {
// getMaxAmplitude: the loudest sample since the last call, 0..32767.
float level = (float) Math.sqrt(recorder.getMaxAmplitude() / 32767f);
levels.add(Math.min(1f, level));
long ms = System.currentTimeMillis() - startedAt;
timer.setText(clock(ms) + " / " + clock(MAX_MS));
wave.invalidate();
tick.postDelayed(this, 60);
} else if (player != null && player.isPlaying()) {
int pos = player.getCurrentPosition(), dur = Math.max(1, player.getDuration());
wave.progress = pos / (float) dur;
wave.invalidate();
timer.setText(clock(pos) + " / " + clock(dur));
tick.postDelayed(this, 60);
}
}
};
// ---- done ----
private void send() {
stopPlaying();
try {
String name = Media.save(this, Media.read(file), MIME);
setResult(RESULT_OK, new Intent().putExtra("file", name).putExtra("mime", MIME));
} catch (Exception e) {
Toast.makeText(this, "Couldn't save the voice note.", Toast.LENGTH_LONG).show();
return;
}
finish();
}
@Override
protected void onPause() {
super.onPause();
// Leaving mid-recording keeps what was said so far.
if (recorder != null) stopRecording();
if (player != null && player.isPlaying()) {
player.pause();
middle.setText("Play");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
tick.removeCallbacks(ticker);
pulse.cancel();
if (recorder != null) {
recorder.release();
recorder = null;
}
stopPlaying();
if (isFinishing()) file.delete();
}
private void setButtons(String l, View.OnClickListener lc, String m, View.OnClickListener mc, String r, View.OnClickListener rc) {
left.setText(l);
left.setOnClickListener(lc);
middle.setVisibility(m == null ? View.GONE : View.VISIBLE);
if (m != null) {
middle.setText(m);
middle.setOnClickListener(mc);
}
right.setText(r);
right.setOnClickListener(rc);
}
static String clock(long ms) {
long s = ms / 1000;
return s / 60 + ":" + String.format(java.util.Locale.US, "%02d", s % 60);
}
/**
* Level bars: while recording, the newest on the right scrolling left;
* afterwards the whole note squeezed to fit, the played part in accent.
*/
private final class Wave extends View {
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final int bar, gap;
float progress = -1;
Wave(Context c) {
super(c);
bar = Ui.dp(c, 6);
gap = Ui.dp(c, 4);
}
@Override
protected void onDraw(Canvas canvas) {
int n = Math.max(1, (getWidth() + gap) / (bar + gap));
float mid = getHeight() / 2f, minH = bar, maxH = getHeight() * 0.9f;
boolean live = recorder != null;
int count = levels.size();
for (int i = 0; i < n; i++) {
float level;
if (live) {
int k = count - n + i;
if (k < 0) continue;
level = levels.get(k);
paint.setColor(Ui.DANGER);
} else {
if (count == 0) return;
// Loudest of the samples this bar covers.
int from = i * count / n, to = Math.max(from + 1, (i + 1) * count / n);
level = 0;
for (int k = from; k < Math.min(to, count); k++) level = Math.max(level, levels.get(k));
paint.setColor(progress >= 0 && i < progress * n ? Ui.ACCENT : Ui.FAINT);
}
float h = Math.max(minH, level * maxH);
float x = i * (bar + gap);
canvas.drawRoundRect(x, mid - h / 2, x + bar, mid + h / 2, bar / 2f, bar / 2f, paint);
}
}
}
}
@@ -0,0 +1,174 @@
package me.teafry.voipmessages;
import android.net.Uri;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
/** The voip.ms REST API, as the desktop's src/main/voipms.ts uses it. */
final class VoipMs {
private static final String ENDPOINT = "https://voip.ms/api/v1/rest.php";
static final class Failure extends Exception {
final String status;
Failure(String status) {
super(FRIENDLY.containsKey(status) ? FRIENDLY.get(status) : "voip.ms error: " + status);
this.status = status;
}
}
private static final Map<String, String> FRIENDLY = new HashMap<>();
static {
FRIENDLY.put("invalid_credentials", "voip.ms didn't accept the API login. Reinstall from the desktop to copy it again.");
FRIENDLY.put("ip_not_enabled", "This network's IP address isn't allowed in voip.ms's API settings.");
FRIENDLY.put("sms_failed", "voip.ms failed to send the message.");
FRIENDLY.put("mms_failed", "voip.ms failed to send the MMS.");
FRIENDLY.put("sms_toolong", "Message is too long.");
FRIENDLY.put("mms_toolong", "Message is too long for an MMS (2048 characters max).");
FRIENDLY.put("invalid_dst", "Invalid destination number.");
FRIENDLY.put("invalid_media", "voip.ms rejected the attachment.");
FRIENDLY.put("media_toolarge", "The attachment is too large for voip.ms MMS.");
}
private final String user, pass;
VoipMs(String user, String pass) {
this.user = user;
this.pass = pass;
}
private JSONObject call(String method, Map<String, String> params, boolean post) throws IOException, Failure, JSONException {
Map<String, String> all = new java.util.LinkedHashMap<>();
all.put("api_username", user);
all.put("api_password", pass);
all.put("method", method);
all.putAll(params);
Http.Response r;
if (post) {
// Multipart: base64 media is far too big for a query string.
String boundary = "----voip" + System.nanoTime();
ByteArrayOutputStream body = new ByteArrayOutputStream();
for (Map.Entry<String, String> e : all.entrySet()) {
body.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + e.getKey() + "\"\r\n\r\n").getBytes(StandardCharsets.UTF_8));
body.write(e.getValue().getBytes(StandardCharsets.UTF_8));
body.write("\r\n".getBytes(StandardCharsets.UTF_8));
}
body.write(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8));
Map<String, String> h = new HashMap<>();
h.put("Content-Type", "multipart/form-data; boundary=" + boundary);
r = Http.request("POST", ENDPOINT, h, body.toByteArray(), 120_000);
} else {
Uri.Builder b = Uri.parse(ENDPOINT).buildUpon();
for (Map.Entry<String, String> e : all.entrySet()) b.appendQueryParameter(e.getKey(), e.getValue());
r = Http.request("GET", b.build().toString(), null, null, method.startsWith("send") ? 120_000 : 60_000);
}
if (r.status >= 400) throw new IOException("voip.ms HTTP " + r.status);
JSONObject o = new JSONObject(r.text());
String status = o.optString("status");
if (!"success".equals(status)) throw new Failure(status);
return o;
}
/** SMS and MMS in [from, to] (YYYY-MM-DD, UTC days). */
List<Store.Msg> messages(String from, String to) throws IOException, Failure, JSONException {
Map<String, String> p = new HashMap<>();
p.put("from", from);
p.put("to", to);
p.put("limit", "10000");
p.put("timezone", "0");
p.put("all_messages", "1");
JSONObject o;
try {
o = call("getMMS", p, false);
} catch (Failure e) {
if ("no_sms".equals(e.status) || "no_mms".equals(e.status)) return new ArrayList<>();
throw e;
}
JSONArray rows = o.optJSONArray("sms");
List<Store.Msg> out = new ArrayList<>();
if (rows == null) return out;
for (int i = 0; i < rows.length(); i++) out.add(toMsg(rows.getJSONObject(i)));
return out;
}
static Store.Msg toMsg(JSONObject r) throws JSONException {
Store.Msg m = new Store.Msg();
m.id = Long.parseLong(r.getString("id"));
m.did = Phone.normalize(r.getString("did"));
m.contact = Phone.normalize(r.getString("contact"));
m.direction = "1".equals(r.optString("type")) ? "in" : "out";
m.body = r.optString("message", "");
m.ts = parseDate(r.getString("date"));
List<String> urls = new ArrayList<>();
JSONArray media = r.optJSONArray("media");
if (media != null && media.length() > 0) {
for (int i = 0; i < media.length(); i++) if (!media.optString(i).isEmpty()) urls.add(media.optString(i));
} else {
for (String k : new String[] {"col_media1", "col_media2", "col_media3"}) if (!r.optString(k).isEmpty()) urls.add(r.optString(k));
}
if (!urls.isEmpty()) {
m.kind = "mms";
JSONArray refs = new JSONArray();
for (String u : urls) refs.put(new JSONObject().put("url", u));
m.mediaJson = refs.toString();
} else if (Phone.charCount(m.body) > Phone.SMS_TEXT_LIMIT) {
m.kind = "mms";
}
return m;
}
long sendSms(String did, String dst, String message) throws IOException, Failure, JSONException {
Map<String, String> p = new HashMap<>();
p.put("did", did);
p.put("dst", dst);
p.put("message", message);
return Long.parseLong(call("sendSMS", p, false).get("sms").toString());
}
/** media: data: URLs, at most 3. */
long sendMms(String did, String dst, String message, List<String> media) throws IOException, Failure, JSONException {
Map<String, String> p = new HashMap<>();
p.put("did", did);
p.put("dst", dst);
p.put("message", message);
for (int i = 0; i < Math.min(3, media.size()); i++) p.put("media" + (i + 1), media.get(i));
return Long.parseLong(call("sendMMS", p, true).get("mms").toString());
}
// voip.ms's timezone=0 adds its own daylight-saving hour for dates inside
// US daylight time; undo it so times are true UTC (see voipms.ts).
private static final TimeZone EASTERN = TimeZone.getTimeZone("America/New_York");
static long parseDate(String s) {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
f.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
long ms = f.parse(s).getTime();
long hour = 3_600_000L;
return EASTERN.inDaylightTime(new java.util.Date(ms - hour)) ? ms - hour : ms;
} catch (ParseException e) {
return System.currentTimeMillis();
}
}
static String ymd(long ms) {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
f.setTimeZone(TimeZone.getTimeZone("UTC"));
return f.format(new java.util.Date(ms));
}
}
@@ -0,0 +1,161 @@
package me.teafry.voipmessages;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Message signing ("WAA" / BotGuard), as the desktop's src/main/gvoice/waa.ts:
* Google Voice's web client signs each text with an obfuscated script Google
* serves; we run that script in a hidden WebView that can load nothing else.
* Best-effort: on any failure the text goes out unsigned (which works, but
* gets rate-limited sooner).
*/
final class Waa {
private static final String TAG = "Waa";
private static final long EXPIRY = 60 * 60_000L;
private static final String ABOUT = "https://voice.google.com/about";
private static WebView web;
private static long initedAt;
private static String program, globalName, scriptUrl = "";
private static final Handler main = new Handler(Looper.getMainLooper());
private static final AtomicInteger ids = new AtomicInteger();
private static final Map<Integer, String[]> results = new ConcurrentHashMap<>();
private static final Map<Integer, CountDownLatch> latches = new ConcurrentHashMap<>();
private Waa() {}
/** Called by the page's JS when a promise settles. */
static final class Bridge {
@JavascriptInterface
public void done(int id, String result, String error) {
results.put(id, new String[] {result, error});
CountDownLatch l = latches.remove(id);
if (l != null) l.countDown();
}
}
/** Run JS that calls Bridge.done(id, ...) when finished; wait for it. */
private static String await(String jsTemplate, long timeoutMs) throws Exception {
int id = ids.incrementAndGet();
CountDownLatch l = new CountDownLatch(1);
latches.put(id, l);
String js = jsTemplate.replace("__ID__", String.valueOf(id));
main.post(() -> web.evaluateJavascript(js, null));
if (!l.await(timeoutMs, TimeUnit.MILLISECONDS)) throw new Exception("timed out");
String[] r = results.remove(id);
if (r == null || (r[1] != null && !r[1].isEmpty())) throw new Exception(r == null ? "no result" : r[1]);
return r[0];
}
@SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
private static void open(Context c) throws Exception {
if (web != null) return;
CountDownLatch loaded = new CountDownLatch(1);
main.post(() -> {
web = new WebView(c.getApplicationContext());
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setUserAgentString(GVoice.USER_AGENT);
web.addJavascriptInterface(new Bridge(), "Bridge");
web.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest req) {
String url = req.getUrl().toString();
if (url.equals(scriptUrl)) return null; // Google's signer script: let it load
if (url.equals(ABOUT)) {
// Fetch the page ourselves so its CSP doesn't block the injected script.
try {
Map<String, String> h = new HashMap<>();
h.put("User-Agent", GVoice.USER_AGENT);
Http.Response r = Http.request("GET", ABOUT, h, null, 30_000);
return new WebResourceResponse("text/html", "utf-8", new ByteArrayInputStream(r.body));
} catch (Exception e) {
return blocked();
}
}
return blocked();
}
@Override
public void onPageFinished(WebView view, String url) {
loaded.countDown();
}
});
web.loadUrl(ABOUT);
});
if (!loaded.await(30, TimeUnit.SECONDS)) throw new Exception("page didn't load");
}
private static WebResourceResponse blocked() {
return new WebResourceResponse("text/plain", "utf-8", 403, "Blocked", new HashMap<>(), new ByteArrayInputStream(new byte[0]));
}
private static void init(Context c, GVoice gv) throws Exception {
String[] w = gv.createWaa();
open(c);
program = w[2];
globalName = w[3];
String url = w[0].startsWith("//") ? "https:" + w[0] : w[0];
if (!url.equals(scriptUrl)) {
scriptUrl = url;
await("(function(){var s=document.createElement('script');s.src=" + JSONObject.quote(url)
+ ";s.onload=function(){Bridge.done(__ID__,'ok','')};s.onerror=function(){Bridge.done(__ID__,'','load failed')};"
+ "document.head.appendChild(s)})()", 20_000);
}
initedAt = System.currentTimeMillis();
try {
gv.pingWaa(run(null));
} catch (Exception ignored) {
}
}
private static String run(JSONObject payload) throws Exception {
String p = payload == null ? "undefined" : payload.toString();
return await("(function(){try{var vm=window[" + JSONObject.quote(globalName) + "];vm.a(" + JSONObject.quote(program)
+ ",function(f1){f1(function(r){Bridge.done(__ID__,String(r),'')},[" + p + ",undefined,undefined,undefined])},"
+ "true,undefined,function(){})}catch(e){Bridge.done(__ID__,'',String(e))}})()", 10_000);
}
private static String b64sha256(String s) throws Exception {
byte[] h = MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8));
return Base64.encodeToString(h, Base64.NO_WRAP);
}
/** A signature for a send, or null. Call off the main thread. */
static synchronized String sign(Context c, GVoice gv, String threadId, List<String> recipients, long txn) {
try {
if (web == null || System.currentTimeMillis() - initedAt > EXPIRY) init(c, gv);
JSONObject payload = new JSONObject();
payload.put("message_ids", b64sha256(String.valueOf(txn)));
payload.put("destinations", b64sha256(String.join("|", recipients)));
payload.put("thread_id", b64sha256(threadId));
String sig = run(payload);
return sig == null || sig.isEmpty() ? null : sig;
} catch (Exception e) {
Log.w(TAG, "signing failed, sending unsigned: " + e.getMessage());
return null;
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">bubble</string>
</resources>
+162
View File
@@ -0,0 +1,162 @@
#!/usr/bin/env python3
"""Build the bubble Android app (for the Rabbit R1) without Gradle.
Same approach as andTunes (~/Documents/lintunes/andtunes/build.py): the app
links no libraries, so the five SDK steps run directly -- aapt2 compile/link,
javac against android.jar, R8, zipalign, apksigner.
python3 android/build.py # -> android/build/VoipMessages.apk
python3 android/build.py --ship # ... + copy to resources/android/ for the desktop installer
python3 android/build.py --dev --install
# a separate "bubble (dev)" app (its own
# package, its own data) for testing on
# the device without touching the real one
The APK is debuggable on purpose: the desktop installer copies the logins and
history into the app's private storage with `run-as`, which needs it.
Stdlib only.
"""
import argparse
import json
import os
import shutil
import subprocess
import sys
import zipfile
from pathlib import Path
VERSION_NAME = "0.2.0"
VERSION_CODE = 2
PACKAGE = "me.teafry.voipmessages"
DEV_PACKAGE = PACKAGE + ".dev"
MIN_SDK = 26
TARGET_SDK = 33
BUILD_TOOLS = "34.0.0"
HERE = Path(__file__).resolve().parent
SRC = HERE / "app" / "src" / "main"
OUT = HERE / "build"
APK_NAME = "VoipMessages.apk"
SHIP_TO = HERE.parent / "resources" / "android" / APK_NAME
# Committed on purpose, like andTunes': every build must be signed the same
# way or `adb install -r` refuses the update.
KEYSTORE = HERE / "voipmessages.keystore"
KEY_ALIAS = "voipmessages"
KEY_PASS = "voipmessages"
def _sdk() -> Path:
for env in ("ANDROID_HOME", "ANDROID_SDK_ROOT"):
if os.environ.get(env):
return Path(os.environ[env])
return Path.home() / "Android" / "Sdk"
def _java_home() -> Path:
if os.environ.get("JAVA_HOME"):
return Path(os.environ["JAVA_HOME"])
return Path("/usr/lib/jvm/java-21-openjdk")
def run(*cmd):
printable = " ".join(str(c) for c in cmd)
print(f" $ {printable[:160]}{'…' if len(printable) > 160 else ''}")
subprocess.run([str(c) for c in cmd], check=True)
def build(dev: bool) -> Path:
sdk = _sdk()
bt = sdk / "build-tools" / BUILD_TOOLS
android_jar = sdk / "platforms" / f"android-{TARGET_SDK}" / "android.jar"
jbin = _java_home() / "bin"
for need in (bt / "aapt2", android_jar, jbin / "javac"):
if not need.exists():
sys.exit(f"missing {need} -- see android/README.md")
out = OUT / ("dev" if dev else "release")
if out.exists():
shutil.rmtree(out)
gen, classes, dex = out / "gen", out / "classes", out / "dex"
for d in (gen, classes, dex):
d.mkdir(parents=True)
print("resources")
run(bt / "aapt2", "compile", "--dir", SRC / "res", "-o", out / "res.zip")
link = [bt / "aapt2", "link", "-o", out / "base.apk",
"-I", android_jar, "--manifest", SRC / "AndroidManifest.xml",
"--java", gen, "--proguard", out / "aapt-rules.pro",
"--min-sdk-version", MIN_SDK, "--target-sdk-version", TARGET_SDK,
"--version-code", VERSION_CODE, "--version-name", VERSION_NAME,
"--debug-mode", "--auto-add-overlay"]
if dev:
# Same code, different app: its own package (so its own data) and label.
link += ["--rename-manifest-package", DEV_PACKAGE]
if dev:
# ...and its own name on the launcher (res-dev overrides app_name).
run(bt / "aapt2", "compile", "--dir", HERE / "res-dev", "-o", out / "res-dev.zip")
link += ["-R", out / "res-dev.zip"]
run(*link, out / "res.zip")
print("java")
sources = sorted(str(p) for p in (SRC / "java").rglob("*.java"))
sources += sorted(str(p) for p in gen.rglob("*.java"))
run(jbin / "javac", "--release", "11", "-Xlint:-options", "-nowarn",
"-encoding", "UTF-8", "-cp", android_jar, "-d", classes, *sources)
classes_jar = out / "classes.jar"
with zipfile.ZipFile(classes_jar, "w") as jar:
for f in classes.rglob("*.class"):
jar.write(f, f.relative_to(classes).as_posix())
print("r8")
run(jbin / "java", "-cp", bt / "lib" / "d8.jar", "com.android.tools.r8.R8",
"--release", "--min-api", MIN_SDK, "--lib", android_jar,
"--pg-conf", out / "aapt-rules.pro", "--pg-conf", HERE / "proguard.pro",
"--output", dex, classes_jar)
print("package")
unsigned = out / "unsigned.apk"
shutil.copyfile(out / "base.apk", unsigned)
with zipfile.ZipFile(unsigned, "a", zipfile.ZIP_DEFLATED) as apk:
apk.write(dex / "classes.dex", "classes.dex")
aligned = out / "aligned.apk"
run(bt / "zipalign", "-f", "-p", "4", unsigned, aligned)
final = out / (("Dev" if dev else "") + APK_NAME)
env_java = dict(os.environ, JAVA_HOME=str(_java_home()),
PATH=f"{jbin}:{os.environ.get('PATH', '')}")
print(f" $ apksigner sign … {final.name}")
subprocess.run([str(bt / "apksigner"), "sign", "--ks", str(KEYSTORE),
"--ks-key-alias", KEY_ALIAS,
"--ks-pass", f"pass:{KEY_PASS}",
"--key-pass", f"pass:{KEY_PASS}",
"--out", str(final), str(aligned)],
check=True, env=env_java)
print(f"built {final} ({final.stat().st_size // 1024} KiB, v{VERSION_NAME} / {VERSION_CODE})")
return final
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--dev", action="store_true", help="build the separate dev app (me.teafry.voipmessages.dev)")
ap.add_argument("--install", action="store_true", help="adb install -r the result and launch it")
ap.add_argument("--ship", action="store_true", help="copy the APK to resources/android/ for the desktop installer")
args = ap.parse_args()
if args.ship and args.dev:
sys.exit("--ship is for the real app, not --dev")
apk = build(args.dev)
if args.ship:
SHIP_TO.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(apk, SHIP_TO)
SHIP_TO.with_suffix(".json").write_text(json.dumps(
{"version_name": VERSION_NAME, "version_code": VERSION_CODE, "package": PACKAGE}) + "\n")
print(f"shipped to {SHIP_TO}")
if args.install:
pkg = DEV_PACKAGE if args.dev else PACKAGE
run("adb", "install", "-r", "-g", apk)
run("adb", "shell", "am", "start", "-n", f"{pkg}/{PACKAGE}.MainActivity")
if __name__ == "__main__":
main()
+9
View File
@@ -0,0 +1,9 @@
# aapt2 --proguard already keeps everything the manifest names (activities,
# the service). This file only adds what R8 can't see from there.
# Keep real class and method names, so a logcat stack trace reads.
-dontobfuscate
# Not `-keepattributes SourceFile,LineNumberTable`: R8 8.2 (build-tools 34)
# dies with an internal NPE on javac 21's debug info for an anonymous class.
# Class + method names are enough to find a crash in an app this size.
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">bubble (dev)</string>
</resources>
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Fill the *dev* app (me.teafry.voipmessages.dev) on a connected device with
made-up conversations, for testing without anyone's real messages or accounts.
Its config is marked sandbox, so the app never goes online.
python3 android/build.py --dev --install && python3 android/tools/push_sandbox.py
Uses the same copy-in mechanism as the desktop installer: files are piped
through `adb shell run-as` into the app's private storage.
"""
import json
import sqlite3
import subprocess
import tempfile
import time
from pathlib import Path
PKG = "me.teafry.voipmessages.dev"
VOIP, GV = "5415550100", "5415550177"
GROUP = "5415550101,5415550102,5415550103"
def push(local: Path, name: str):
with open(local, "rb") as f:
subprocess.run(["adb", "shell", f"run-as {PKG} sh -c 'cat > files/{name}'"], stdin=f, check=True)
def main():
subprocess.run(["adb", "shell", "am", "force-stop", PKG], check=True)
subprocess.run(["adb", "shell", f"run-as {PKG} sh -c 'mkdir -p files && rm -f files/messages.db*'"], check=True)
with tempfile.TemporaryDirectory() as d:
db = Path(d) / "messages.db"
con = sqlite3.connect(db)
con.executescript("""
CREATE TABLE messages (id INTEGER PRIMARY KEY, did TEXT NOT NULL, contact TEXT NOT NULL, direction TEXT NOT NULL,
body TEXT NOT NULL, ts INTEGER NOT NULL, kind TEXT NOT NULL DEFAULT 'sms', status TEXT NOT NULL DEFAULT 'delivered',
media_json TEXT, error TEXT, sender TEXT);
CREATE TABLE read_state (did TEXT NOT NULL, contact TEXT NOT NULL, last_read_ts INTEGER NOT NULL, archived_at INTEGER,
marked_unread INTEGER NOT NULL DEFAULT 0, name TEXT, name_ts INTEGER, PRIMARY KEY (did, contact));
CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE gv_threads (did TEXT NOT NULL, contact TEXT NOT NULL, thread_id TEXT NOT NULL, PRIMARY KEY (did, contact));
""")
now = int(time.time() * 1000)
m = 60_000
rows = [
(1001, VOIP, "5415550110", "in", "Are we still on for Saturday?", now - 300 * m, None),
(1002, VOIP, "5415550110", "out", "Yep! 10am at the market", now - 290 * m, None),
(1003, VOIP, "5415550111", "in", "Your table is ready", now - 2000 * m, None),
(2**52 + 1, GV, "5415550120", "in", "Package left at the front door", now - 90 * m, None),
(2**52 + 2, GV, "5415550120", "out", "Thanks!", now - 85 * m, None),
(2**52 + 3, GV, GROUP, "in", "Who is bringing snacks to the hike?", now - 40 * m, "5415550101"),
(2**52 + 4, GV, GROUP, "in", "I can do chips", now - 38 * m, "5415550102"),
(2**52 + 5, GV, GROUP, "in", "and salsa", now - 37 * m, "5415550102"),
(2**52 + 6, GV, GROUP, "out", "I'll bring cookies 🍪", now - 30 * m, None),
(2**52 + 7, GV, GROUP, "in", "Perfect, see everyone at 9. This one is a longer message to check how wrapping looks on the little screen.", now - 5 * m, "5415550103"),
]
# Enough chats that the list scrolls (the search box hides above the top).
for i in range(12):
rows.append((3000 + i, VOIP, f"54155502{i:02d}", "in", f"Filler chat number {i + 1}", now - (3000 + i * 400) * m, None))
# A long history, to see how fast a big chat opens.
LONG = "5415550130"
for i in range(4000):
rows.append((10_000 + i, VOIP, LONG, "in" if i % 3 else "out", f"Message {i + 1} of a long chat", now - (8000 - i) * 30_000, None))
# A group you've named, whose members match other searches too.
NAMED = "5415550101,5415550140"
rows.append((2**52 + 20, GV, NAMED, "in", "Booked the cabin!", now - 600 * m, "5415550140"))
con.execute("INSERT INTO read_state (did, contact, last_read_ts, name, name_ts) VALUES (?, ?, 0, 'Cabin trip', ?)", (GV, NAMED, now))
con.executemany("INSERT INTO messages (id, did, contact, direction, body, ts, sender) VALUES (?,?,?,?,?,?,?)", rows)
con.execute("INSERT INTO kv VALUES ('unread_floor', '0')")
con.execute("INSERT INTO gv_threads VALUES (?, ?, 'g.demo')", (GV, GROUP))
con.commit()
con.close()
cfg = Path(d) / "config.json"
cfg.write_text(json.dumps({
"sandbox": True,
"voipms": {"username": "sandbox", "password": "sandbox"},
"gvoice": {"number": GV, "cookies": {}},
"dids": [{"did": VOIP, "description": "Demo"}],
"defaultDid": VOIP,
}))
push(db, "messages.db")
push(cfg, "config.json")
subprocess.run(["adb", "shell", "am", "start", "-n", f"{PKG}/me.teafry.voipmessages.MainActivity"], check=True)
print("sandbox data pushed to", PKG)
if __name__ == "__main__":
main()
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

+10 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "voipms-desktop", "name": "voipms-desktop",
"version": "0.1.0", "version": "0.2.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "voipms-desktop", "name": "voipms-desktop",
"version": "0.1.0", "version": "0.2.0",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"better-sqlite3": "^13.0.3" "better-sqlite3": "^13.0.3"
@@ -20,6 +20,7 @@
"electron": "^44.4.2", "electron": "^44.4.2",
"electron-builder": "^26.15.3", "electron-builder": "^26.15.3",
"electron-vite": "^5.0.0", "electron-vite": "^5.0.0",
"emoji-datasource": "^16.0.0",
"react": "^19.3.0", "react": "^19.3.0",
"react-dom": "^19.3.0", "react-dom": "^19.3.0",
"react-virtuoso": "^4.18.13", "react-virtuoso": "^4.18.13",
@@ -3554,6 +3555,13 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/emoji-datasource": {
"version": "16.0.0",
"resolved": "https://registry.npmjs.org/emoji-datasource/-/emoji-datasource-16.0.0.tgz",
"integrity": "sha512-/qHKqK5Nr3+8zhgO6kHmF43Fm5C8HNn0AaFRIpgw8HF3+uF0Vfc8jgLI1ZQS5ba1vBzksS8NBCjHejwLb2D/Sg==",
"dev": true,
"license": "MIT"
},
"node_modules/emoji-regex": { "node_modules/emoji-regex": {
"version": "8.0.0", "version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+21 -7
View File
@@ -1,7 +1,7 @@
{ {
"name": "voipms-desktop", "name": "voipms-desktop",
"productName": "voip.ms Messages", "productName": "bubble",
"version": "0.1.0", "version": "0.2.0",
"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,
@@ -14,8 +14,13 @@
"test": "ELECTRON_RUN_AS_NODE=1 electron node_modules/vitest/vitest.mjs run", "test": "ELECTRON_RUN_AS_NODE=1 electron node_modules/vitest/vitest.mjs run",
"postinstall": "electron-builder install-app-deps", "postinstall": "electron-builder install-app-deps",
"dist": "electron-vite build && electron-builder --linux AppImage", "dist": "electron-vite build && electron-builder --linux AppImage",
"install-desktop": "npm run dist && ./scripts/install-desktop.sh", "install-desktop": "npm run android && npm run dist && ./scripts/install-desktop.sh",
"test:live": "LIVE=1 npm test" "test:live": "LIVE=1 npm test",
"gen:emoji": "node scripts/gen-emoji.mjs",
"deps:install": "sfw npm install --prefer-online",
"deps:add": "sfw npm install --prefer-online",
"deps:update": "sfw npm update --prefer-online",
"android": "python3 android/build.py --ship"
}, },
"dependencies": { "dependencies": {
"better-sqlite3": "^13.0.3" "better-sqlite3": "^13.0.3"
@@ -29,6 +34,7 @@
"electron": "^44.4.2", "electron": "^44.4.2",
"electron-builder": "^26.15.3", "electron-builder": "^26.15.3",
"electron-vite": "^5.0.0", "electron-vite": "^5.0.0",
"emoji-datasource": "^16.0.0",
"react": "^19.3.0", "react": "^19.3.0",
"react-dom": "^19.3.0", "react-dom": "^19.3.0",
"react-virtuoso": "^4.18.13", "react-virtuoso": "^4.18.13",
@@ -38,7 +44,7 @@
}, },
"build": { "build": {
"appId": "me.teafry.voipms-desktop", "appId": "me.teafry.voipms-desktop",
"productName": "voip.ms Messages", "productName": "bubble",
"directories": { "directories": {
"output": "dist", "output": "dist",
"buildResources": "resources" "buildResources": "resources"
@@ -52,6 +58,14 @@
{ {
"from": "resources/eds-sources.py", "from": "resources/eds-sources.py",
"to": "eds-sources.py" "to": "eds-sources.py"
},
{
"from": "resources/eds-add-contact.py",
"to": "eds-add-contact.py"
},
{
"from": "resources/android",
"to": "android"
} }
], ],
"linux": { "linux": {
@@ -63,9 +77,9 @@
"executableName": "voipms-desktop", "executableName": "voipms-desktop",
"desktop": { "desktop": {
"entry": { "entry": {
"Name": "voip.ms Messages", "Name": "bubble",
"Comment": "Text messages via voip.ms", "Comment": "Text messages via voip.ms",
"StartupWMClass": "voip.ms Messages" "StartupWMClass": "bubble"
} }
}, },
"syncDesktopName": true, "syncDesktopName": true,
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
{"version_name": "0.2.0", "version_code": 2, "package": "me.teafry.voipmessages"}
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""Add a contact to an Evolution Data Server address book (which syncs it on,
e.g. to Nextcloud via CardDAV).
eds-add-contact.py books -> JSON {"books": [...], "default": uid or null}
eds-add-contact.py add -> reads JSON {first, last, org, number, book?}
on stdin, prints JSON {"uid": ...}
The default book is the one GNOME Contacts uses for new contacts (folks'
primary store), else EDS's own default address book.
"""
import json
import sys
import gi
gi.require_version("EDataServer", "1.2")
gi.require_version("EBookContacts", "1.2")
gi.require_version("EBook", "1.2")
from gi.repository import EBook, EBookContacts, EDataServer as EDS, Gio # noqa: E402
# Server-generated or automatic books nobody adds contacts to by hand.
SKIP_NAMES = {"accounts", "recently contacted", "recent"}
def esc(v):
return v.replace("\\", "\\\\").replace(";", "\\;").replace(",", "\\,").replace("\n", "\\n")
def default_uid(reg):
try:
if "org.freedesktop.folks" in Gio.Settings.list_schemas():
store = Gio.Settings.new("org.freedesktop.folks").get_string("primary-store")
if store.startswith("eds:"):
return store[4:]
except Exception:
pass
src = reg.ref_default_address_book()
return src.get_uid() if src else None
def books(reg):
out = []
for s in reg.list_enabled(EDS.SOURCE_EXTENSION_ADDRESS_BOOK):
if s.get_display_name().lower() in SKIP_NAMES:
continue
ext = s.get_extension(EDS.SOURCE_EXTENSION_ADDRESS_BOOK)
if ext.get_backend_name() == "ldap":
continue
parent = reg.ref_source(s.get_parent()) if s.get_parent() else None
out.append({
"uid": s.get_uid(),
"name": s.get_display_name(),
"account": parent.get_display_name() if parent else "",
})
return out
def add(reg, req):
uid = req.get("book") or default_uid(reg)
source = reg.ref_source(uid) if uid else None
if source is None:
raise SystemExit("No address book to add the contact to.")
client = EBook.BookClient.connect_sync(source, 30, None)
if client.is_readonly():
raise SystemExit(f"The address book \"{source.get_display_name()}\" is read-only.")
first, last, org = (req.get(k, "").strip() for k in ("first", "last", "org"))
full = " ".join(p for p in (first, last) if p) or org or req["number"]
lines = ["BEGIN:VCARD", "VERSION:3.0", f"N:{esc(last)};{esc(first)};;;", f"FN:{esc(full)}"]
if org:
lines.append(f"ORG:{esc(org)}")
lines += [f"TEL;TYPE=CELL:{req['number']}", "END:VCARD"]
contact = EBookContacts.Contact.new_from_vcard("\r\n".join(lines))
ok, new_uid = client.add_contact_sync(contact, EBookContacts.BookOperationFlags.NONE, None)
json.dump({"uid": new_uid, "book": source.get_display_name()}, sys.stdout)
def main():
reg = EDS.SourceRegistry.new_sync(None)
cmd = sys.argv[1] if len(sys.argv) > 1 else "books"
if cmd == "books":
json.dump({"books": books(reg), "default": default_uid(reg)}, sys.stdout)
elif cmd == "add":
add(reg, json.load(sys.stdin))
else:
raise SystemExit(f"unknown command {cmd}")
main()
+54
View File
@@ -0,0 +1,54 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#eef6ff"/>
<stop offset="1" stop-color="#dcebfb"/>
</linearGradient>
<linearGradient id="tub" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#ffb8c6"/>
<stop offset="1" stop-color="#f59fb3"/>
</linearGradient>
</defs>
<rect x="32" y="32" width="448" height="448" rx="104" fill="url(#bg)"/>
<!-- ground shadow -->
<ellipse cx="270" cy="430" rx="190" ry="16" fill="#c8dcf1"/>
<!-- handles + frame rail (behind the tub) -->
<path d="M64 236 L382 380" stroke="#b49ad8" stroke-width="16" stroke-linecap="round" fill="none"/>
<path d="M64 236 L96 250" stroke="#7f8fb8" stroke-width="22" stroke-linecap="round"/>
<!-- back leg -->
<path d="M196 312 L184 418 M166 420 L204 420" stroke="#b49ad8" stroke-width="14" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
<!-- wheel -->
<circle cx="382" cy="376" r="54" fill="#7f8fb8"/>
<circle cx="382" cy="376" r="32" fill="#cfe9dd"/>
<circle cx="382" cy="376" r="11" fill="#7f8fb8"/>
<!-- tub -->
<path d="M100 150 L444 138 Q458 138 453 151 L398 318 Q394 330 381 330 L186 332 Q174 332 169 321 L96 162 Q92 150 100 150 Z" fill="url(#tub)"/>
<!-- rim -->
<path d="M96 150 L450 137" stroke="#ee8fa6" stroke-width="18" stroke-linecap="round"/>
<!-- little highlight -->
<path d="M134 176 L150 212" stroke="#ffe0e8" stroke-width="8" stroke-linecap="round" opacity="0.8"/>
<!-- "VOIP" scrawled in white marker: uneven sizes, bouncy baseline, wobbly strokes -->
<g fill="none" stroke="#ffffff" stroke-width="13" stroke-linecap="round" stroke-linejoin="round" transform="rotate(-7 280 250)">
<!-- V: big, leaning, with a flick at the end -->
<path d="M142 198 C150 228 164 262 181 294 C190 262 202 230 217 200 C220 194 224 191 229 190" transform="rotate(-3 180 245)"/>
<!-- O: doesn't quite close, overshoots at the top -->
<path d="M285 206 C262 196 242 218 243 249 C244 281 262 298 282 293 C303 288 309 262 307 239 C305 216 293 202 274 207"/>
<!-- I: tall stem, a little crooked -->
<path d="M333 199 C336 230 332 263 336 296"/>
<!-- P: long stem, lopsided bowl -->
<path d="M366 203 C368 235 365 268 368 300"/>
<path d="M367 208 C385 192 418 198 416 225 C414 250 388 255 369 246"/>
<!-- marker pause blobs where strokes start -->
<g fill="#ffffff" stroke="none">
<circle cx="142" cy="198" r="8"/>
<circle cx="333" cy="199" r="7.5"/>
<circle cx="366" cy="203" r="7.5"/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 222 KiB

+49 -8
View File
@@ -1,13 +1,54 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"> <svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
<defs> <defs>
<linearGradient id="g" x1="0" y1="0" x2="0" y2="1"> <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#3a78f2"/> <stop offset="0" stop-color="#fff6e8"/>
<stop offset="1" stop-color="#2257d6"/> <stop offset="1" stop-color="#f6e2c6"/>
</linearGradient>
<linearGradient id="tub" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#f2622f"/>
<stop offset="1" stop-color="#d9481f"/>
</linearGradient> </linearGradient>
</defs> </defs>
<rect x="32" y="32" width="448" height="448" rx="104" fill="url(#g)"/> <rect x="32" y="32" width="448" height="448" rx="104" fill="url(#bg)"/>
<path d="M256 120c-86 0-150 55-150 124 0 38 19 71 50 94l-12 58 60-32c16 4 34 6 52 6 86 0 150-55 150-126S342 120 256 120z" fill="#fff"/>
<circle cx="196" cy="246" r="18" fill="#2c6bed"/> <!-- ground shadow -->
<circle cx="256" cy="246" r="18" fill="#2c6bed"/> <ellipse cx="270" cy="430" rx="190" ry="16" fill="#e3c9a6"/>
<circle cx="316" cy="246" r="18" fill="#2c6bed"/>
<!-- handles + frame rail (behind the tub) -->
<path d="M64 236 L382 380" stroke="#8e2b12" stroke-width="16" stroke-linecap="round" fill="none"/>
<path d="M64 236 L96 250" stroke="#2f2320" stroke-width="22" stroke-linecap="round"/>
<!-- back leg -->
<path d="M196 312 L184 418 M166 420 L204 420" stroke="#8e2b12" stroke-width="14" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
<!-- wheel -->
<circle cx="382" cy="376" r="54" fill="#2f2320"/>
<circle cx="382" cy="376" r="32" fill="#9a8c85"/>
<circle cx="382" cy="376" r="11" fill="#2f2320"/>
<!-- tub -->
<path d="M100 150 L444 138 Q458 138 453 151 L398 318 Q394 330 381 330 L186 332 Q174 332 169 321 L96 162 Q92 150 100 150 Z" fill="url(#tub)"/>
<!-- rim -->
<path d="M96 150 L450 137" stroke="#b8391b" stroke-width="18" stroke-linecap="round"/>
<!-- little highlight -->
<path d="M134 176 L150 212" stroke="#ff8c5a" stroke-width="8" stroke-linecap="round" opacity="0.8"/>
<!-- "VOIP" scrawled in white marker: uneven sizes, bouncy baseline, wobbly strokes -->
<g fill="none" stroke="#fffdf8" stroke-width="13" stroke-linecap="round" stroke-linejoin="round" transform="rotate(-7 280 250)">
<!-- V: big, leaning, with a flick at the end -->
<path d="M142 198 C150 228 164 262 181 294 C190 262 202 230 217 200 C220 194 224 191 229 190" transform="rotate(-3 180 245)"/>
<!-- O: doesn't quite close, overshoots at the top -->
<path d="M285 206 C262 196 242 218 243 249 C244 281 262 298 282 293 C303 288 309 262 307 239 C305 216 293 202 274 207"/>
<!-- I: tall stem, a little crooked -->
<path d="M333 199 C336 230 332 263 336 296"/>
<!-- P: long stem, lopsided bowl -->
<path d="M366 203 C368 235 365 268 368 300"/>
<path d="M367 208 C385 192 418 198 416 225 C414 250 388 255 369 246"/>
<!-- marker pause blobs where strokes start -->
<g fill="#fffdf8" stroke="none">
<circle cx="142" cy="198" r="8"/>
<circle cx="333" cy="199" r="7.5"/>
<circle cx="366" cy="203" r="7.5"/>
</g>
</g>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 651 B

After

Width:  |  Height:  |  Size: 2.6 KiB

+19
View File
@@ -0,0 +1,19 @@
// Builds src/renderer/src/emoji-data.json — a compact [emoji, shortnames[]]
// list in picker order — from emoji-datasource (the shortcode set Signal and
// Slack use). Run with `npm run gen:emoji` after bumping emoji-datasource.
import { readFileSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
const source = JSON.parse(readFileSync(require.resolve('emoji-datasource/emoji.json'), 'utf8'))
const toChar = (unified) => String.fromCodePoint(...unified.split('-').map((h) => parseInt(h, 16)))
const data = source
.filter((e) => e.has_img_apple && !e.obsoleted_by)
.sort((a, b) => a.sort_order - b.sort_order)
.map((e) => [toChar(e.unified), e.short_names])
const out = new URL('../src/renderer/src/emoji-data.json', import.meta.url)
writeFileSync(out, JSON.stringify(data) + '\n')
console.log(`wrote ${data.length} emoji`)
+5 -2
View File
@@ -15,14 +15,17 @@ mkdir -p "$(dirname "$desktop")"
cat > "$desktop" <<DESKTOP cat > "$desktop" <<DESKTOP
[Desktop Entry] [Desktop Entry]
Type=Application Type=Application
Name=voip.ms Messages Name=bubble
Comment=Text messages via voip.ms Comment=Text messages via voip.ms
Exec=$bin %U Exec=$bin %U
Icon=voipms-desktop Icon=voipms-desktop
Terminal=false Terminal=false
Categories=Network;InstantMessaging; Categories=Network;InstantMessaging;
StartupWMClass=voip.ms Messages StartupWMClass=bubble
DESKTOP DESKTOP
update-desktop-database "$(dirname "$desktop")" 2>/dev/null || true update-desktop-database "$(dirname "$desktop")" 2>/dev/null || true
# GNOME caches icons by name; refresh so a new icon shows up in the dash.
touch "$HOME/.local/share/icons/hicolor"
gtk-update-icon-cache -q -t -f "$HOME/.local/share/icons/hicolor" 2>/dev/null || true
echo "Installed: $bin" echo "Installed: $bin"
echo "Launcher: $desktop" echo "Launcher: $desktop"
+38 -6
View File
@@ -1,5 +1,6 @@
// Reads contacts from GNOME's Evolution Data Server caches (read-only) and maps // Reads contacts from GNOME's Evolution Data Server caches (read-only) and maps
// phone numbers to names + photos. // phone numbers to names + photos. Adding a contact goes through EDS itself
// (resources/eds-add-contact.py), which syncs it on to e.g. Nextcloud.
import Database from 'better-sqlite3' import Database from 'better-sqlite3'
import { execFile } from 'node:child_process' import { execFile } from 'node:child_process'
import { EventEmitter } from 'node:events' import { EventEmitter } from 'node:events'
@@ -7,7 +8,7 @@ import fs from 'node:fs'
import os from 'node:os' import os from 'node:os'
import path from 'node:path' import path from 'node:path'
import { normalizeNumber } from '@shared/phone' import { normalizeNumber } from '@shared/phone'
import type { ContactInfo } from '@shared/types' import type { AddressBook, ContactInfo, NewContact } from '@shared/types'
export interface BookSource { export interface BookSource {
uid: string uid: string
@@ -130,10 +131,32 @@ export function parseVCard(vcard: string): VCardContact {
// ---------- EDS sources ---------- // ---------- EDS sources ----------
function helperPath(): string { function helperPath(name = 'eds-sources.py'): string {
// In a packaged app the helper ships in resources/, in dev it's in the repo. // In a packaged app the helpers ship in resources/, in dev they're in the repo.
const packaged = path.join(process.resourcesPath ?? '', 'eds-sources.py') const packaged = path.join(process.resourcesPath ?? '', name)
return fs.existsSync(packaged) ? packaged : path.join(__dirname, '../../resources/eds-sources.py') return fs.existsSync(packaged) ? packaged : path.join(__dirname, '../../resources', name)
}
function runAddHelper(args: string[], input?: string): Promise<string> {
return new Promise((resolve, reject) => {
const child = execFile('python3', [helperPath('eds-add-contact.py'), ...args], { timeout: 60_000 }, (err, stdout, stderr) => {
if (err) reject(new Error(stderr.trim().split('\n').pop() || err.message))
else resolve(stdout)
})
if (input !== undefined) child.stdin?.end(input)
})
}
// Address books a contact can be added to, and the one GNOME Contacts uses.
export async function listAddressBooks(): Promise<{ books: AddressBook[]; default?: string }> {
const r = JSON.parse(await runAddHelper(['books'])) as { books: AddressBook[]; default: string | null }
return { books: r.books, ...(r.default ? { default: r.default } : {}) }
}
// Adds the contact; resolves with the name of the book it went into.
export async function addToAddressBook(c: NewContact): Promise<string> {
const r = JSON.parse(await runAddHelper(['add'], JSON.stringify(c))) as { book: string }
return r.book
} }
export function listSources(): Promise<BookSource[]> { export function listSources(): Promise<BookSource[]> {
@@ -273,6 +296,15 @@ export class ContactDirectory extends EventEmitter {
return this.all return this.all
} }
// Show a just-added contact right away; the next load() (when EDS writes
// its cache) replaces it with the real entry.
addLocal(info: ContactInfo): void {
if (this.byNumber.has(info.number)) return
this.byNumber.set(info.number, { info, rank: 0 })
this.all = [...this.all, info].sort((a, b) => a.name.localeCompare(b.name))
this.emit('changed')
}
lookup(number: string): ContactInfo | undefined { lookup(number: string): ContactInfo | undefined {
return this.byNumber.get(normalizeNumber(number))?.info return this.byNumber.get(normalizeNumber(number))?.info
} }
+342 -37
View File
@@ -2,10 +2,28 @@
import Database from 'better-sqlite3' import Database from 'better-sqlite3'
import fs from 'node:fs' import fs from 'node:fs'
import path from 'node:path' import path from 'node:path'
import type { Conversation, Direction, Message, MessageStatus, SearchHit } from '@shared/types' import type { Conversation, Direction, MediaRef, Message, MessageKind, MessageStatus, SearchHit } from '@shared/types'
import { SNIPPET_END, SNIPPET_START } from '@shared/types' import { SNIPPET_END, SNIPPET_START } from '@shared/types'
import { fixVoipDst } from './voipms'
const SCHEMA_VERSION = 1 const SCHEMA_VERSION = 10
export interface ReadState {
did: string
contact: string
lastRead: number // read up to this message time
markedUnread: boolean
unreadTs?: number | null // when read/unread last changed
archivedAt?: number | null
archivedTs?: number | null // when archived/unarchived last changed
}
export interface NameChange {
did: string
contact: string
name: string | null
ts: number
}
export interface NewMessage { export interface NewMessage {
id: number id: number
@@ -15,17 +33,27 @@ export interface NewMessage {
body: string body: string
ts: number ts: number
status?: MessageStatus status?: MessageStatus
kind?: MessageKind
media?: MediaRef[]
sender?: string
} }
interface MessageRow { type MessageRow = Omit<Message, 'media' | 'error' | 'sender'> & { media_json: string | null; error: string | null; sender: string | null }
id: number
did: string const MESSAGE_COLS = 'id, did, contact, direction, body, ts, kind, status, media_json, error, sender'
contact: string
direction: Direction // How far a sent message's voip.ms time can be from the time we stamped it
body: string // locally and still count as the same message (sends can queue and retry).
ts: number const MATCH_BEFORE = 2 * 60_000
kind: 'sms' | 'mms' const MATCH_AFTER = 15 * 60_000
status: MessageStatus
function fromRow({ media_json, error, sender, ...m }: MessageRow): Message {
return {
...m,
...(media_json ? { media: JSON.parse(media_json) as MediaRef[] } : {}),
...(error ? { error } : {}),
...(sender ? { sender } : {})
}
} }
export class MessageDb { export class MessageDb {
@@ -43,7 +71,7 @@ export class MessageDb {
private migrate(): void { private migrate(): void {
const version = this.db.pragma('user_version', { simple: true }) as number const version = this.db.pragma('user_version', { simple: true }) as number
if (version >= SCHEMA_VERSION) return if (version >= SCHEMA_VERSION) return
this.db.exec(` if (version < 1) this.db.exec(`
CREATE TABLE IF NOT EXISTS messages ( CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY, -- voip.ms id (negative = local pending) id INTEGER PRIMARY KEY, -- voip.ms id (negative = local pending)
did TEXT NOT NULL, did TEXT NOT NULL,
@@ -51,9 +79,9 @@ export class MessageDb {
direction TEXT NOT NULL CHECK (direction IN ('in','out')), direction TEXT NOT NULL CHECK (direction IN ('in','out')),
body TEXT NOT NULL, body TEXT NOT NULL,
ts INTEGER NOT NULL, -- epoch ms UTC ts INTEGER NOT NULL, -- epoch ms UTC
kind TEXT NOT NULL DEFAULT 'sms', -- 'sms' | 'mms' (future) kind TEXT NOT NULL DEFAULT 'sms', -- 'sms' | 'mms'
status TEXT NOT NULL DEFAULT 'delivered', status TEXT NOT NULL DEFAULT 'delivered',
media_json TEXT -- MMS attachments (future) media_json TEXT -- MMS attachments: MediaRef[]
); );
CREATE INDEX IF NOT EXISTS messages_conv ON messages (did, contact, ts); CREATE INDEX IF NOT EXISTS messages_conv ON messages (did, contact, ts);
CREATE INDEX IF NOT EXISTS messages_ts ON messages (ts); CREATE INDEX IF NOT EXISTS messages_ts ON messages (ts);
@@ -78,6 +106,52 @@ export class MessageDb {
); );
CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL);
`) `)
// v2: sync switched from getSMS to getMMS (which also returns MMS). Redo the
// history import once so past MMS show up; existing rows dedupe by id.
if (version === 1) this.db.exec(`DELETE FROM kv WHERE key IN ('backfill_cursor', 'backfill_empty', 'backfill_done')`)
// v3: per-conversation archive + manual "mark as unread".
if (version < 3)
this.db.exec(`
ALTER TABLE read_state ADD COLUMN archived_at INTEGER; -- epoch ms; NULL = not archived
ALTER TABLE read_state ADD COLUMN marked_unread INTEGER NOT NULL DEFAULT 0;
`)
// v4: times from voip.ms were an hour late during US daylight time, and
// every getMMS row was labelled 'mms'. Times from voip.ms are whole seconds;
// ones stamped locally on send carry milliseconds and were right.
if (version >= 1 && version < 4) {
const rows = this.db.prepare('SELECT id, ts FROM messages WHERE ts % 1000 = 0').all() as Array<{ id: number; ts: number }>
const update = this.db.prepare('UPDATE messages SET ts = ? WHERE id = ?')
this.db.transaction(() => {
for (const r of rows) {
const fixed = fixVoipDst(r.ts)
if (fixed !== r.ts) update.run(fixed, r.id)
}
this.db.exec(`UPDATE messages SET kind = 'sms' WHERE kind = 'mms' AND media_json IS NULL`)
})()
}
// v5: texts too long for one SMS came in as text-only MMS but were labelled
// 'sms' (only rows with media counted as MMS).
if (version >= 1 && version < 5) this.db.exec(`UPDATE messages SET kind = 'mms' WHERE kind = 'sms' AND length(body) > 160`)
// v6: why a send failed, shown on the message.
const cols = this.db.pragma('table_info(messages)') as Array<{ name: string }>
if (!cols.some((c) => c.name === 'error')) this.db.exec(`ALTER TABLE messages ADD COLUMN error TEXT`)
// v7: Google Voice. Who sent each incoming group message, and which GV
// thread each conversation is (group threads have opaque ids).
if (!cols.some((c) => c.name === 'sender')) this.db.exec(`ALTER TABLE messages ADD COLUMN sender TEXT`)
this.db.exec(`
CREATE TABLE IF NOT EXISTS gv_threads (
did TEXT NOT NULL, contact TEXT NOT NULL, thread_id TEXT NOT NULL,
PRIMARY KEY (did, contact)
);
`)
// v8: a name of your own for a conversation (group chats), kept locally.
const rsCols = this.db.pragma('table_info(read_state)') as Array<{ name: string }>
if (!rsCols.some((c) => c.name === 'name')) this.db.exec(`ALTER TABLE read_state ADD COLUMN name TEXT`)
// v9: when a name was set, so renames on the desktop and the Rabbit merge (newest wins).
if (!rsCols.some((c) => c.name === 'name_ts')) this.db.exec(`ALTER TABLE read_state ADD COLUMN name_ts INTEGER`)
// v10: when read/unread and archived last changed, so they merge with the Rabbit too.
if (!rsCols.some((c) => c.name === 'unread_ts')) this.db.exec(`ALTER TABLE read_state ADD COLUMN unread_ts INTEGER`)
if (!rsCols.some((c) => c.name === 'archived_ts')) this.db.exec(`ALTER TABLE read_state ADD COLUMN archived_ts INTEGER`)
this.db.pragma(`user_version = ${SCHEMA_VERSION}`) this.db.pragma(`user_version = ${SCHEMA_VERSION}`)
} }
@@ -90,17 +164,48 @@ export class MessageDb {
this.db.prepare('INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, value) this.db.prepare('INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, value)
} }
// ---- unsent drafts, one per contact ----
getDrafts(): Record<string, string> {
const rows = this.db.prepare("SELECT key, value FROM kv WHERE key LIKE 'draft:%'").all() as { key: string; value: string }[]
return Object.fromEntries(rows.map((r) => [r.key.slice('draft:'.length), r.value]))
}
setDraft(contact: string, text: string): void {
if (text.trim()) this.set(`draft:${contact}`, text)
else this.db.prepare('DELETE FROM kv WHERE key = ?').run(`draft:${contact}`)
}
// ---- messages ---- // ---- messages ----
// Inserts messages we haven't seen; returns the ones that were new. // Inserts messages we haven't seen; returns the ones that were new.
upsertMessages(msgs: NewMessage[]): NewMessage[] { upsertMessages(msgs: NewMessage[]): NewMessage[] {
const insert = this.db.prepare( const insert = this.db.prepare(
`INSERT OR IGNORE INTO messages (id, did, contact, direction, body, ts, status) `INSERT OR IGNORE INTO messages (id, did, contact, direction, body, ts, status, kind, media_json, sender)
VALUES (@id, @did, @contact, @direction, @body, @ts, @status)` VALUES (@id, @did, @contact, @direction, @body, @ts, @status, @kind, @media_json, @sender)`
)
// Any message newer than the archiving brings a conversation back (older
// ones arriving via the history import don't).
const unarchive = this.db.prepare(
`UPDATE read_state SET archived_at = NULL
WHERE did = ? AND contact = ? AND archived_at IS NOT NULL AND archived_at < ?`
) )
const added: NewMessage[] = [] const added: NewMessage[] = []
this.db.transaction(() => { this.db.transaction(() => {
for (const m of msgs) { for (const m of msgs) {
if (insert.run({ ...m, status: m.status ?? 'delivered' }).changes) added.push(m) const row = {
id: m.id,
did: m.did,
contact: m.contact,
direction: m.direction,
body: m.body,
ts: m.ts,
status: m.status ?? 'delivered',
kind: m.kind ?? 'sms',
media_json: m.media?.length ? JSON.stringify(m.media) : null,
sender: m.sender ?? null
}
if (insert.run(row).changes) {
added.push(m)
unarchive.run(m.did, m.contact, m.ts)
}
} }
})() })()
return added return added
@@ -116,8 +221,18 @@ export class MessageDb {
// Replace a local pending row with the id voip.ms assigned. // Replace a local pending row with the id voip.ms assigned.
confirmPending(tempId: number, realId: number): void { confirmPending(tempId: number, realId: number): void {
this.db.transaction(() => { this.db.transaction(() => {
const exists = this.db.prepare('SELECT 1 FROM messages WHERE id = ?').get(realId) const exists = this.getMessage(realId)
if (exists) { if (exists) {
// Poll beat us to it: keep our local copies of any attachments so they
// don't need downloading again, and our kind (a text-only MMS of 160
// characters or less looks like an SMS in the listing).
const pending = this.getMessage(tempId)
if (pending) this.db.prepare('UPDATE messages SET kind = ? WHERE id = ?').run(pending.kind, realId)
const local = pending?.media
if (local && exists.media) {
const merged = exists.media.map((ref, i) => (local[i]?.file ? { ...ref, ...local[i] } : ref))
this.db.prepare('UPDATE messages SET media_json = ? WHERE id = ?').run(JSON.stringify(merged), realId)
}
this.db.prepare('DELETE FROM messages WHERE id = ?').run(tempId) this.db.prepare('DELETE FROM messages WHERE id = ?').run(tempId)
} else { } else {
this.db.prepare(`UPDATE messages SET id = ?, status = 'delivered' WHERE id = ?`).run(realId, tempId) this.db.prepare(`UPDATE messages SET id = ?, status = 'delivered' WHERE id = ?`).run(realId, tempId)
@@ -125,8 +240,32 @@ export class MessageDb {
})() })()
} }
markFailed(tempId: number): void { markFailed(tempId: number, error?: string): void {
this.db.prepare(`UPDATE messages SET status = 'failed' WHERE id = ?`).run(tempId) this.db.prepare(`UPDATE messages SET status = 'failed', error = ? WHERE id = ?`).run(error ?? null, tempId)
}
// Sent messages that turned up in a poll take the place of our local
// pending/failed copies (same text, sent around the same time). A send whose
// reply never came back may still have gone out; this is how we find out.
// Returns the local ids that were replaced.
reconcileSent(added: NewMessage[]): number[] {
const find = this.db.prepare(
`SELECT id FROM messages
WHERE id < 0 AND status IN ('pending', 'failed') AND direction = 'out'
AND did = ? AND contact = ? AND body = ? AND ts BETWEEN ? AND ?
ORDER BY ts, id DESC LIMIT 1`
)
const claimed: number[] = []
this.db.transaction(() => {
for (const m of [...added].sort((a, b) => a.ts - b.ts || a.id - b.id)) {
if (m.direction !== 'out' || m.id < 0) continue
const row = find.get(m.did, m.contact, m.body, m.ts - MATCH_AFTER, m.ts + MATCH_BEFORE) as { id: number } | undefined
if (!row) continue
this.confirmPending(row.id, m.id)
claimed.push(row.id)
}
})()
return claimed
} }
deleteMessage(id: number): void { deleteMessage(id: number): void {
@@ -134,18 +273,25 @@ export class MessageDb {
} }
getMessage(id: number): Message | undefined { getMessage(id: number): Message | undefined {
return this.db.prepare('SELECT id, did, contact, direction, body, ts, kind, status FROM messages WHERE id = ?').get(id) as const row = this.db.prepare(`SELECT ${MESSAGE_COLS} FROM messages WHERE id = ?`).get(id) as MessageRow | undefined
| MessageRow return row && fromRow(row)
| undefined
} }
getConversationMessages(did: string, contact: string): Message[] { getConversationMessages(did: string, contact: string): Message[] {
return this.db const rows = this.db
.prepare( .prepare(`SELECT ${MESSAGE_COLS} FROM messages WHERE did = ? AND contact = ? ORDER BY ts, id`)
`SELECT id, did, contact, direction, body, ts, kind, status FROM messages
WHERE did = ? AND contact = ? ORDER BY ts, id`
)
.all(did, contact) as MessageRow[] .all(did, contact) as MessageRow[]
return rows.map(fromRow)
}
// Record that attachment `index` of message `id` is now cached locally.
setMediaFile(id: number, index: number, patch: MediaRef): void {
this.db.transaction(() => {
const media = this.getMessage(id)?.media
if (!media?.[index]) return
media[index] = { ...media[index], ...patch }
this.db.prepare('UPDATE messages SET media_json = ? WHERE id = ?').run(JSON.stringify(media), id)
})()
} }
count(): number { count(): number {
@@ -156,31 +302,190 @@ export class MessageDb {
listConversations(): Conversation[] { listConversations(): Conversation[] {
// Messages from before the initial history import never count as unread. // Messages from before the initial history import never count as unread.
const floor = Number(this.get('unread_floor') ?? 0) const floor = Number(this.get('unread_floor') ?? 0)
return this.db const rows = this.db
.prepare( .prepare(
`WITH latest AS ( `WITH latest AS (
SELECT did, contact, MAX(ts) AS mts FROM messages GROUP BY did, contact SELECT did, contact, MAX(ts) AS mts FROM messages GROUP BY did, contact
) )
SELECT l.did, l.contact, l.mts AS lastTs, SELECT l.did, l.contact, l.mts AS lastTs,
(SELECT body FROM messages m WHERE m.did = l.did AND m.contact = l.contact ORDER BY ts DESC, id DESC LIMIT 1) AS lastBody, last.body AS lastBody, last.direction AS lastDirection, last.kind AS lastKind, last.sender AS lastSender,
(SELECT direction FROM messages m WHERE m.did = l.did AND m.contact = l.contact ORDER BY ts DESC, id DESC LIMIT 1) AS lastDirection, 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,
r.archived_at IS NOT NULL AS archived,
COALESCE(r.marked_unread, 0) AS markedUnread,
r.name AS name
FROM latest l FROM latest l
JOIN messages last ON last.id =
(SELECT id FROM messages m WHERE m.did = l.did AND m.contact = l.contact ORDER BY ts DESC, id DESC LIMIT 1)
LEFT JOIN read_state r ON r.did = l.did AND r.contact = l.contact LEFT JOIN read_state r ON r.did = l.did AND r.contact = l.contact
ORDER BY l.mts DESC` ORDER BY l.mts DESC`
) )
.all({ floor }) as Conversation[] .all({ floor }) as Array<
Omit<Conversation, 'lastMedia' | 'archived' | 'markedUnread' | 'lastSender' | 'name'> & {
lastMedia: string | null
archived: number
markedUnread: number
lastSender: string | null
name: string | null
}
>
return rows.map(({ lastMedia, archived, markedUnread, lastSender, name, ...c }) => ({
...c,
...(name ? { name } : {}),
...(lastSender ? { lastSender } : {}),
archived: !!archived,
markedUnread: !!markedUnread,
...(lastMedia ? { lastMedia: JSON.parse(lastMedia) as MediaRef } : {})
}))
}
// Whether anything has arrived since the conversation was last read.
hasUnread(did: string, contact: string): boolean {
const floor = Number(this.get('unread_floor') ?? 0)
const r = this.db
.prepare(
`SELECT EXISTS (
SELECT 1 FROM messages m LEFT JOIN read_state r ON r.did = m.did AND r.contact = m.contact
WHERE m.did = @did AND m.contact = @contact AND m.direction = 'in'
AND m.ts > MAX(COALESCE(r.last_read_ts, 0), @floor)
) AS any`
)
.get({ did, contact, floor }) as { any: number }
return !!r.any
} }
markRead(did: string, contact: string): void { markRead(did: string, contact: string): void {
this.db this.db
.prepare( .prepare(
`INSERT INTO read_state (did, contact, last_read_ts) `INSERT INTO read_state (did, contact, last_read_ts, unread_ts)
SELECT @did, @contact, COALESCE(MAX(ts), 0) FROM messages WHERE did = @did AND contact = @contact SELECT @did, @contact, COALESCE(MAX(ts), 0), @now FROM messages WHERE did = @did AND contact = @contact
ON CONFLICT(did, contact) DO UPDATE SET last_read_ts = excluded.last_read_ts` ON CONFLICT(did, contact) DO UPDATE SET last_read_ts = MAX(last_read_ts, excluded.last_read_ts), marked_unread = 0,
unread_ts = excluded.unread_ts`
) )
.run({ did, contact }) .run({ did, contact, now: Date.now() })
}
markUnread(did: string, contact: string): void {
this.db
.prepare(
`INSERT INTO read_state (did, contact, last_read_ts, marked_unread, unread_ts) VALUES (?, ?, 0, 1, ?)
ON CONFLICT(did, contact) DO UPDATE SET marked_unread = 1, unread_ts = excluded.unread_ts`
)
.run(did, contact, Date.now())
}
// Name a conversation (null/empty clears it, back to the members' names).
setName(did: string, contact: string, name: string | null, ts = Date.now()): void {
this.db
.prepare(
`INSERT INTO read_state (did, contact, last_read_ts, name, name_ts) VALUES (?, ?, 0, ?, ?)
ON CONFLICT(did, contact) DO UPDATE SET name = excluded.name, name_ts = excluded.name_ts`
)
.run(did, contact, name?.trim() || null, ts)
}
// Every rename (including clearing one), for merging with the Rabbit.
namesExport(): NameChange[] {
return this.db.prepare('SELECT did, contact, name, name_ts AS ts FROM read_state WHERE name_ts IS NOT NULL').all() as NameChange[]
}
// Apply renames made elsewhere, keeping whichever is newer. Returns how many changed.
namesImport(changes: NameChange[]): number {
let n = 0
const mine = this.db.prepare('SELECT COALESCE(name_ts, 0) AS ts FROM read_state WHERE did = ? AND contact = ?')
this.db.transaction(() => {
for (const c of changes) {
const cur = (mine.get(c.did, c.contact) as { ts: number } | undefined)?.ts ?? 0
if (c.ts > cur) {
this.setName(c.did, c.contact, c.name, c.ts)
n++
}
}
})()
return n
}
getName(did: string, contact: string): string | undefined {
const r = this.db.prepare('SELECT name FROM read_state WHERE did = ? AND contact = ?').get(did, contact) as { name: string | null } | undefined
return r?.name ?? undefined
}
setArchived(did: string, contact: string, archived: boolean, now = Date.now()): void {
this.db
.prepare(
`INSERT INTO read_state (did, contact, last_read_ts, archived_at, archived_ts) VALUES (?, ?, 0, ?, ?)
ON CONFLICT(did, contact) DO UPDATE SET archived_at = excluded.archived_at, archived_ts = excluded.archived_ts`
)
.run(did, contact, archived ? now : null, now)
}
// Read/unread and archived state of every conversation, for merging with the Rabbit.
readStateExport(): ReadState[] {
return (
this.db
.prepare(
`SELECT did, contact, last_read_ts AS lastRead, marked_unread AS markedUnread, unread_ts AS unreadTs,
archived_at AS archivedAt, archived_ts AS archivedTs FROM read_state`
)
.all() as Array<Omit<ReadState, 'markedUnread'> & { markedUnread: number }>
).map((r) => ({ ...r, markedUnread: !!r.markedUnread }))
}
// Merge the other device's state: "read up to" takes the later of the two;
// marked-unread and archived take whichever changed more recently.
// Returns how many conversations changed here.
readStateImport(rows: ReadState[]): number {
let n = 0
const mine = this.db.prepare(
`SELECT last_read_ts AS lastRead, marked_unread AS markedUnread, COALESCE(unread_ts, 0) AS unreadTs,
archived_at AS archivedAt, COALESCE(archived_ts, 0) AS archivedTs FROM read_state WHERE did = ? AND contact = ?`
)
const upsert = this.db.prepare(
`INSERT INTO read_state (did, contact, last_read_ts, marked_unread, unread_ts, archived_at, archived_ts)
VALUES (@did, @contact, @lastRead, @markedUnread, @unreadTs, @archivedAt, @archivedTs)
ON CONFLICT(did, contact) DO UPDATE SET last_read_ts = excluded.last_read_ts, marked_unread = excluded.marked_unread,
unread_ts = excluded.unread_ts, archived_at = excluded.archived_at, archived_ts = excluded.archived_ts`
)
this.db.transaction(() => {
for (const t of rows) {
const m = mine.get(t.did, t.contact) as
| { lastRead: number; markedUnread: number; unreadTs: number; archivedAt: number | null; archivedTs: number }
| undefined
const cur = m ?? { lastRead: 0, markedUnread: 0, unreadTs: 0, archivedAt: null, archivedTs: 0 }
const theirsUnread = (t.unreadTs ?? 0) > cur.unreadTs
const theirsArchived = (t.archivedTs ?? 0) > cur.archivedTs
const next = {
did: t.did,
contact: t.contact,
lastRead: Math.max(cur.lastRead, t.lastRead ?? 0),
markedUnread: theirsUnread ? (t.markedUnread ? 1 : 0) : cur.markedUnread,
unreadTs: theirsUnread ? t.unreadTs : cur.unreadTs || null,
archivedAt: theirsArchived ? (t.archivedAt ?? null) : cur.archivedAt,
archivedTs: theirsArchived ? t.archivedTs : cur.archivedTs || null
}
if (next.lastRead !== cur.lastRead || theirsUnread || theirsArchived) {
upsert.run(next)
n++
}
}
})()
return n
}
// ---- Google Voice threads ----
setGvThread(did: string, contact: string, threadId: string): void {
this.db
.prepare(
`INSERT INTO gv_threads (did, contact, thread_id) VALUES (?, ?, ?)
ON CONFLICT(did, contact) DO UPDATE SET thread_id = excluded.thread_id`
)
.run(did, contact, threadId)
}
getGvThread(did: string, contact: string): string | undefined {
const r = this.db.prepare('SELECT thread_id FROM gv_threads WHERE did = ? AND contact = ?').get(did, contact) as { thread_id: string } | undefined
return r?.thread_id
} }
// ---- search ---- // ---- search ----
+112
View File
@@ -0,0 +1,112 @@
// "Export chat": a conversation, or the days of it between two dates, as plain
// text or as a page (printed to PDF by index.ts), optionally with its photos.
import { formatNumber, isGroup } from '@shared/phone'
import type { ChatExport, MediaRef, Message } from '@shared/types'
import { localDay } from './db'
// The messages in the export's dates (inclusive, local days); failed sends
// never went anywhere, so they're left out.
export function inRange(msgs: Message[], opts: Pick<ChatExport, 'from' | 'to'>): Message[] {
return msgs.filter((m) => {
if (m.status === 'failed') return false
const day = localDay(new Date(m.ts))
return (!opts.from || day >= opts.from) && (!opts.to || day <= opts.to)
})
}
const dayHeading = (ts: number): string =>
new Date(ts).toLocaleDateString(undefined, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })
const time = (ts: number): string => new Date(ts).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })
const shortDate = (day: string): string =>
new Date(`${day}T00:00`).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
export function rangeLabel(opts: Pick<ChatExport, 'from' | 'to'>): string {
if (!opts.from && !opts.to) return 'All messages'
if (opts.from && opts.to) return opts.from === opts.to ? shortDate(opts.from) : `${shortDate(opts.from)} – ${shortDate(opts.to)}`
return opts.from ? `From ${shortDate(opts.from)}` : `Up to ${shortDate(opts.to!)}`
}
// The chat's name, with the number after it for a one-to-one chat with someone in contacts.
function heading(contact: string, opts: ChatExport): string {
const number = formatNumber(contact)
return isGroup(contact) || opts.title === number ? opts.title : `${opts.title} (${number})`
}
function who(m: Message, contact: string, opts: ChatExport): string {
if (m.direction === 'out') return 'Me'
if (isGroup(contact) && m.sender) return opts.names[m.sender] ?? formatNumber(m.sender)
return opts.title
}
export function attachmentLabel(ref: MediaRef): string {
const mime = ref.mime ?? ''
return mime.startsWith('image/') ? '[Photo]' : mime.startsWith('audio/') ? '[Audio]' : mime.startsWith('video/') ? '[Video]' : '[Attachment]'
}
export function exportText(contact: string, msgs: Message[], opts: ChatExport): string {
const out = [`Chat with ${heading(contact, opts)}`, `${rangeLabel(opts)} · exported ${shortDate(localDay())}`]
let day = ''
for (const m of msgs) {
const d = localDay(new Date(m.ts))
if (d !== day) {
day = d
out.push('', `— ${dayHeading(m.ts)} —`, '')
}
const lead = `${time(m.ts)} ${who(m, contact, opts)}: `
const lines = [...(m.body.trim() ? m.body.trim().split('\n') : []), ...(m.media ?? []).map(attachmentLabel)]
const pad = ' '.repeat(lead.length)
lines.forEach((l, i) => out.push((i === 0 ? lead : pad) + l))
}
return out.join('\n') + '\n'
}
const esc = (s: string): string => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
// The page the PDF is printed from. `photo(m, i)` gives the src for an image
// attachment to show, or undefined to show its label instead.
export function exportHtml(contact: string, msgs: Message[], opts: ChatExport, photo: (m: Message, index: number) => string | undefined): string {
const group = isGroup(contact)
const body: string[] = []
let day = ''
let prev: Message | undefined
for (const m of msgs) {
const d = localDay(new Date(m.ts))
if (d !== day) {
day = d
prev = undefined
body.push(`<div class="day">${esc(dayHeading(m.ts))}</div>`)
}
const showSender = group && m.direction === 'in' && (prev?.direction !== 'in' || prev.sender !== m.sender)
const parts: string[] = []
if (showSender) parts.push(`<div class="sender">${esc(who(m, contact, opts))}</div>`)
;(m.media ?? []).forEach((ref, i) => {
const src = photo(m, i)
parts.push(src ? `<img src="${esc(src)}">` : `<div class="att">${attachmentLabel(ref)}</div>`)
})
if (m.body.trim()) parts.push(`<div class="text">${esc(m.body.trim())}</div>`)
parts.push(`<div class="time">${esc(time(m.ts))}</div>`)
body.push(`<div class="msg ${m.direction}">${parts.join('')}</div>`)
prev = m
}
return `<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>${esc(opts.title)}</title><style>
@page { margin: 16mm 14mm; }
body { font: 10.5pt system-ui, sans-serif; color: #1b1b1d; margin: 0; }
h1 { font-size: 16pt; margin: 0 0 2pt; }
.sub { color: #707070; font-size: 9pt; margin-bottom: 10pt; }
.day { text-align: center; color: #707070; font-size: 8.5pt; margin: 14pt 0 6pt; break-after: avoid; }
.msg { max-width: 72%; width: fit-content; margin: 3pt 0; padding: 5pt 9pt; border-radius: 11pt; break-inside: avoid; }
.msg.in { background: #ececee; }
.msg.out { background: #2c6bed; color: #fff; margin-left: auto; }
.sender { font-size: 8.5pt; font-weight: 600; color: #555; margin-bottom: 2pt; }
.text { white-space: pre-wrap; overflow-wrap: anywhere; }
.time { font-size: 7.5pt; opacity: 0.65; text-align: right; margin-top: 2pt; }
.att { font-style: italic; opacity: 0.8; }
img { display: block; max-width: 100%; max-height: 240pt; border-radius: 7pt; margin: 2pt 0; }
</style></head><body>
<h1>${esc(heading(contact, opts))}</h1>
<div class="sub">${esc(rangeLabel(opts))} · exported ${esc(shortDate(localDay()))}</div>
${body.join('\n')}
</body></html>
`
}
+265
View File
@@ -0,0 +1,265 @@
// Google Voice's private web API (what voice.google.com itself calls), as
// worked out by mautrix-gvoice. Unofficial: Google can change it at any time,
// so everything here fails soft and only ever takes Google Voice down.
//
// Requests go through an Electron session that holds the Google sign-in
// cookies (see ./session.ts); this class only needs a fetch that sends them
// and a way to read the SAPISID cookie for the Authorization header.
import crypto from 'node:crypto'
import { decode, fromPblite, toPblite, type Decoded, type Schema } from './proto'
import * as S from './schema'
export const ORIGIN = 'https://voice.google.com'
const API_BASE = 'https://clients6.google.com/voice/v1/voiceclient'
const WAA_BASE = 'https://waa-pa.clients6.google.com/$rpc/google.internal.waa.v1.Waa'
// Constants from the web client (pkg/libgv/constants.go).
const API_KEY = 'AIzaSyDTYc1N4xiODyrQYK0Kl6g_y279LjYkrBg'
const WAA_API_KEY = 'AIzaSyBGb5fGAyC-pRcRU6MUHb__b_vKha71HRE'
export const WAA_REQUEST_KEY = '/JR8jsAkqotcKsEKhXic'
const CLIENT_VERSION = '665865172'
export const USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36'
const CLIENT_DETAILS = new URLSearchParams({ appVersion: '5.0 (X11)', platform: 'Linux x86_64', userAgent: USER_AGENT }).toString()
const PBLITE = 'application/json+protobuf'
const PROTOBUF = 'application/x-protobuf'
export interface Transport {
fetch: (url: string, init: RequestInit) => Promise<Response>
cookie: (name: string) => Promise<string | undefined>
}
export class GVoiceError extends Error {
constructor(
message: string,
readonly status?: number, // HTTP status, when Google answered
readonly code?: string // Chromium network error, when it didn't
) {
super(message)
}
get signedOut(): boolean {
return this.status === 401 || this.status === 403
}
}
export function sapisidHash(sapisid: string, now = Date.now(), origin = ORIGIN): string {
const ts = Math.floor(now / 1000)
const hash = crypto.createHash('sha1').update(`${ts} ${sapisid} ${origin}`).digest('hex')
return `SAPISIDHASH ${ts}_${hash}`
}
// A random id below 10^14, like the web client's.
export function transactionId(): number {
return Math.floor(Math.random() * 1e14)
}
// GV wants E.164; we store bare 10-digit NANP numbers.
export function toE164(n: string): string {
const d = n.replace(/\D/g, '')
if (d.length === 10) return `+1${d}`
return `+${d}`
}
// Text responses wrap the payload as "<length>\n<data>", the length counted in
// UTF-16 code units (JS string units), and protobuf inside them is base64.
export async function readBody(res: Response): Promise<{ mime: string; data: Uint8Array | string }> {
const plain = (res.headers.get('content-type') ?? '').split(';')[0].trim()
const safety = (res.headers.get('x-goog-safety-content-type') ?? '').split(';')[0].trim()
const mime = safety || plain
if (plain === 'text/plain') {
const text = await res.text()
const nl = text.indexOf('\n')
const len = Number(text.slice(0, nl))
const chunk = nl > 0 && Number.isFinite(len) ? text.slice(nl + 1, nl + 1 + len) : text
return { mime, data: mime === PROTOBUF ? new Uint8Array(Buffer.from(chunk, 'base64')) : chunk }
}
if (mime === PROTOBUF) return { mime, data: new Uint8Array(await res.arrayBuffer()) }
return { mime, data: await res.text() }
}
export function decodeBody(schema: Schema, { mime, data }: { mime: string; data: Uint8Array | string }): Decoded {
if (data instanceof Uint8Array) return decode(schema, data)
if (mime === PBLITE || mime === 'application/json' || mime === 'text/plain') return fromPblite(schema, JSON.parse(data) as unknown[])
throw new GVoiceError(`Google Voice sent an unexpected response (${mime || 'no content type'}).`)
}
export interface SendSmsRequest {
threadId: string // '' to start a new thread with `recipients`
recipients: string[] // E.164
text: string
media?: { mime: string; data: Uint8Array }
transactionId: number
trackingData?: string
}
export class GVoice {
constructor(private t: Transport) {}
private async headers(url: URL, contentType?: string): Promise<Record<string, string>> {
// Origin is added by the session (see session.ts): Chromium refuses it here.
const h: Record<string, string> = {
'X-Goog-AuthUser': '0',
Referer: ORIGIN + '/',
Accept: '*/*'
}
if (contentType) h['Content-Type'] = contentType
if (url.host === 'clients6.google.com') {
h['X-Client-Version'] = CLIENT_VERSION
h['X-ClientDetails'] = CLIENT_DETAILS
h['X-JavaScript-User-Agent'] = 'google-api-javascript-client/1.1.0'
h['X-Requested-With'] = 'XMLHttpRequest'
h['X-Goog-Encode-Response-If-Executable'] = 'base64'
} else if (url.host.startsWith('waa-pa.')) {
h['X-Goog-Api-Key'] = WAA_API_KEY
h['X-User-Agent'] = 'grpc-web-javascript/0.1'
}
const sapisid = await this.t.cookie('SAPISID')
if (!sapisid) throw new GVoiceError('Not signed in to Google Voice.', 401)
h['Authorization'] = sapisidHash(sapisid)
return h
}
private async request(url: string, init: { method?: string; body?: string; contentType?: string } = {}): Promise<Response> {
const u = new URL(url)
if (u.host === 'clients6.google.com') {
u.searchParams.set('key', API_KEY)
u.searchParams.set('alt', 'proto')
}
let res: Response
try {
res = await this.t.fetch(u.toString(), {
method: init.method ?? 'POST',
headers: await this.headers(u, init.contentType),
body: init.body,
credentials: 'include'
})
} catch (e) {
if (e instanceof GVoiceError) throw e
const msg = (e as Error).message ?? String(e)
throw new GVoiceError(msg, undefined, /net::(ERR_\w+)/.exec(msg)?.[1] ?? (e as Error).name)
}
if (!res.ok) {
const detail = await res.text().catch(() => '')
console.warn(`[gvoice] ${u.pathname} → ${res.status}`, detail.slice(0, 300))
throw new GVoiceError(httpMessage(res.status), res.status)
}
return res
}
private async call(endpoint: string, reqSchema: Schema, req: Decoded, respSchema: Schema): Promise<Decoded> {
const res = await this.request(endpoint, { body: JSON.stringify(toPblite(reqSchema, req)), contentType: PBLITE })
return decodeBody(respSchema, await readBody(res))
}
// Our Google Voice number, E.164.
async getAccount(): Promise<string> {
const r = await this.call(`${API_BASE}/account/get`, S.ReqGetAccount, { unknownInt2: 1 }, S.RespGetAccount)
const acc = r.account as { primaryDestinationId: string; phones: Array<{ accountPhone?: { phoneNumber?: { e164: string } } }> }
const number = acc.phones.map((p) => p.accountPhone?.phoneNumber?.e164).find(Boolean) ?? acc.primaryDestinationId
if (!number) throw new GVoiceError("This Google account doesn't have a Google Voice number.")
return number
}
async listThreads(paginationToken = ''): Promise<{ threads: S.GvThread[]; paginationToken: string }> {
const r = await this.call(
`${API_BASE}/api2thread/list`,
S.ReqListThreads,
{ folder: S.ThreadFolder.TEXT_THREADS, unknownInt2: 20, unknownInt3: 15, paginationToken, unknownWrapper: { unknownInt2: 1, unknownInt3: 1 } },
S.RespListThreads
)
return { threads: r.threads as S.GvThread[], paginationToken: r.paginationToken as string }
}
async getThread(threadId: string, count = 100, paginationToken = ''): Promise<S.GvThread> {
const r = await this.call(
`${API_BASE}/api2thread/get`,
S.ReqGetThread,
{ threadId, maybeMessageCount: count, paginationToken, unknownWrapper: { unknownInt2: 1, unknownInt3: 1 } },
S.RespGetThread
)
return r.thread as S.GvThread
}
async sendSms(req: SendSmsRequest): Promise<{ threadId: string; threadItemId: string; timestampMs: number }> {
const body: Decoded = {
text: req.text,
threadId: req.threadId,
recipients: req.threadId ? [] : req.recipients,
transactionId: { id: req.transactionId },
trackingData: { data: req.trackingData || '!' }
}
if (req.media) {
const type = S.SendMediaType[req.media.mime]
if (!type) throw new GVoiceError(`Google Voice can't send ${req.media.mime} attachments, only photos.`, 400)
body.media = { type, data: req.media.data }
}
const r = await this.call(`${API_BASE}/api2thread/sendsms`, S.ReqSendSMS, body, S.RespSendSMS)
return r as { threadId: string; threadItemId: string; timestampMs: number }
}
async markRead(threadId: string): Promise<void> {
await this.call(
`${API_BASE}/thread/updateattributes`,
S.ReqUpdateAttributes,
{ attributes: { threadId, read: true }, otherAttributes: { read: true }, unknownInt: 1 },
S.RespEmpty
)
}
async downloadMedia(id: string): Promise<Response> {
return this.request(`${ORIGIN}/u/0/a/i/${encodeURIComponent(id)}?s=${S.SizeSpec.ORIGINAL}`, { method: 'GET' })
}
// ---- WAA (BotGuard) signing, see ./waa.ts ----
async createWaa(): Promise<{ interpreterUrl: string; interpreterHash: string; program: string; globalName: string }> {
const r = await this.call(`${WAA_BASE}/Create`, S.ReqCreateWaa, { requestKey: WAA_REQUEST_KEY }, S.RespCreateWaa)
const w = r.waa as { interpreterUrl: { url: string }; interpreterHash: string; program: string; globalName: string }
return { interpreterUrl: w.interpreterUrl.url, interpreterHash: w.interpreterHash, program: w.program, globalName: w.globalName }
}
async pingWaa(payload: string): Promise<void> {
await this.call(
`${WAA_BASE}/Ping`,
S.ReqPingWaa,
{ requestKey: WAA_REQUEST_KEY, payload, i1: 72, i2: Math.floor(Math.random() * 2e9) },
S.RespEmpty
)
}
}
function httpMessage(status: number): string {
if (status === 401 || status === 403) return 'Google Voice signed out. Reconnect it in Settings.'
if (status === 429) return 'Google Voice is rate-limiting messages. Try again in a bit.'
if (status === 404) return 'Google Voice could not find that conversation.'
if (status >= 500) return `Google Voice had a server error (${status}).`
return `Google Voice rejected the request (${status}).`
}
// Network errors where the request certainly never reached Google.
const NOT_SENT = new Set([
'ERR_INTERNET_DISCONNECTED',
'ERR_NAME_NOT_RESOLVED',
'ERR_NAME_RESOLUTION_FAILED',
'ERR_CONNECTION_REFUSED',
'ERR_ADDRESS_UNREACHABLE',
'ERR_PROXY_CONNECTION_FAILED'
])
// For sendWithRetry: 'safe' = certainly not sent, retry; 'unknown' = may have
// gone out, look before resending; 'fatal' = give up.
export function classifyGvError(e: unknown): 'safe' | 'unknown' | 'fatal' {
if (!(e instanceof GVoiceError)) return 'unknown'
if (e.status === undefined) return e.code && NOT_SENT.has(e.code) ? 'safe' : 'unknown'
if (e.status === 429) return 'safe'
if (e.status >= 500) return 'unknown'
return 'fatal'
}
export function gvErrorMessage(e: unknown): string {
const err = e as Error
if (err instanceof GVoiceError) {
if (err.status === undefined && err.code && NOT_SENT.has(err.code)) return "Couldn't reach Google Voice. Check your internet connection."
return err.message
}
return err?.message || String(e)
}
+223
View File
@@ -0,0 +1,223 @@
// Just enough protobuf for Google Voice's web API, without a dependency:
// binary decoding (responses) plus "pblite" (requests, and the WAA endpoint),
// Google's JSON form where a message is an array and field N sits at index N-1.
//
// Messages are described by small schemas mapping field names to numbers and
// types; unknown fields are skipped.
export type Scalar = 'string' | 'bytes' | 'int' | 'bool' | 'float' | 'double'
export type FieldType = Scalar | Schema
export interface FieldDef {
n: number
t: FieldType
rep?: boolean
}
export type Schema = { [name: string]: FieldDef }
// The decoded form: plain objects with every field present (proto3 defaults
// for missing ones), so callers can read nested fields without checks.
export type Decoded = { [name: string]: unknown }
function defaultFor(def: FieldDef): unknown {
if (def.rep) return []
switch (def.t) {
case 'string':
return ''
case 'bytes':
return new Uint8Array()
case 'int':
case 'float':
case 'double':
return 0
case 'bool':
return false
default:
return undefined
}
}
function withDefaults(schema: Schema): Decoded {
const out: Decoded = {}
for (const [name, def] of Object.entries(schema)) out[name] = defaultFor(def)
return out
}
// ---- binary ----
class Reader {
pos = 0
constructor(readonly buf: Uint8Array) {}
varint(): bigint {
let result = 0n
let shift = 0n
for (;;) {
if (this.pos >= this.buf.length) throw new Error('protobuf: truncated varint')
const b = this.buf[this.pos++]
result |= BigInt(b & 0x7f) << shift
if (!(b & 0x80)) return result
shift += 7n
}
}
bytes(len: number): Uint8Array {
if (this.pos + len > this.buf.length) throw new Error('protobuf: truncated field')
const out = this.buf.subarray(this.pos, this.pos + len)
this.pos += len
return out
}
}
const utf8 = new TextDecoder()
function scalarFromVarint(t: Scalar, v: bigint): unknown {
if (t === 'bool') return v !== 0n
return Number(BigInt.asIntN(64, v))
}
function scalarFromFixed(t: Scalar, b: Uint8Array): unknown {
const view = new DataView(b.buffer, b.byteOffset, b.byteLength)
if (b.length === 4) return t === 'float' ? view.getFloat32(0, true) : view.getInt32(0, true)
return t === 'double' ? view.getFloat64(0, true) : Number(view.getBigInt64(0, true))
}
export function decode(schema: Schema, buf: Uint8Array): Decoded {
const byNum = new Map<number, [string, FieldDef]>()
for (const [name, def] of Object.entries(schema)) byNum.set(def.n, [name, def])
const out = withDefaults(schema)
const r = new Reader(buf)
while (r.pos < buf.length) {
const tag = Number(r.varint())
const num = tag >>> 3
const wire = tag & 7
let raw: bigint | Uint8Array
if (wire === 0) raw = r.varint()
else if (wire === 1) raw = r.bytes(8)
else if (wire === 2) raw = r.bytes(Number(r.varint()))
else if (wire === 5) raw = r.bytes(4)
else throw new Error(`protobuf: unsupported wire type ${wire}`)
const field = byNum.get(num)
if (!field) continue
const [name, def] = field
let values: unknown[]
if (typeof raw === 'bigint') values = [scalarFromVarint(def.t as Scalar, raw)]
else if (typeof def.t === 'object') values = [decode(def.t, raw)]
else if (def.t === 'string') values = [utf8.decode(raw)]
else if (def.t === 'bytes') values = [raw.slice()]
else if (wire === 2) values = unpack(def.t, raw) // packed repeated numbers
else values = [scalarFromFixed(def.t, raw)]
if (def.rep) (out[name] as unknown[]).push(...values)
else out[name] = values[values.length - 1]
}
return out
}
function unpack(t: Scalar, buf: Uint8Array): unknown[] {
const r = new Reader(buf)
const out: unknown[] = []
while (r.pos < buf.length) {
if (t === 'float') out.push(scalarFromFixed(t, r.bytes(4)))
else if (t === 'double') out.push(scalarFromFixed(t, r.bytes(8)))
else out.push(scalarFromVarint(t, r.varint()))
}
return out
}
// ---- pblite ----
const isSet = (v: unknown): boolean =>
v !== undefined && v !== null && v !== '' && v !== 0 && v !== false && !(Array.isArray(v) && !v.length) && !(v instanceof Uint8Array && !v.length)
function encodeValue(t: FieldType, v: unknown): unknown {
if (typeof t === 'object') return toPblite(t, v as Decoded)
if (t === 'bytes') return Buffer.from(v as Uint8Array).toString('base64')
return v
}
// Every array is as long as the schema's highest field number (unset fields
// are null), matching what Google's own client sends.
export function toPblite(schema: Schema, msg: Decoded): unknown[] {
const max = Math.max(0, ...Object.values(schema).map((d) => d.n))
const out: unknown[] = new Array(max).fill(null)
for (const [name, def] of Object.entries(schema)) {
const v = msg[name]
if (!isSet(v)) continue
out[def.n - 1] = def.rep ? (v as unknown[]).map((x) => encodeValue(def.t, x)) : encodeValue(def.t, v)
}
return out
}
function decodeValue(t: FieldType, v: unknown): unknown {
if (typeof t === 'object') return Array.isArray(v) ? fromPblite(t, v) : withDefaults(t)
switch (t) {
case 'bytes':
return typeof v === 'string' ? new Uint8Array(Buffer.from(v, 'base64')) : new Uint8Array()
case 'string':
return typeof v === 'string' ? v : String(v ?? '')
case 'bool':
return v === true || v === 1
default:
return Number(v ?? 0) // int64s may arrive as strings
}
}
export function fromPblite(schema: Schema, arr: unknown[]): Decoded {
// Sparse high-numbered fields come as a trailing {"<n>": value} object.
let extra: Record<string, unknown> = {}
const last = arr[arr.length - 1]
if (last && typeof last === 'object' && !Array.isArray(last)) {
extra = last as Record<string, unknown>
arr = arr.slice(0, -1)
}
const out = withDefaults(schema)
for (const [name, def] of Object.entries(schema)) {
const v = arr[def.n - 1] ?? extra[String(def.n)]
if (v === null || v === undefined) continue
out[name] = def.rep ? (Array.isArray(v) ? v.map((x) => decodeValue(def.t, x)) : []) : decodeValue(def.t, v)
}
return out
}
// ---- binary encoding (test fixtures) ----
function writeVarint(out: number[], v: bigint): void {
let x = BigInt.asUintN(64, v)
do {
let b = Number(x & 0x7fn)
x >>= 7n
if (x) b |= 0x80
out.push(b)
} while (x)
}
const utf8enc = new TextEncoder()
// Binary protobuf encoding; the app only needs it to build test fixtures, but
// it lives here so encode and decode stay in step.
export function encode(schema: Schema, msg: Decoded): Uint8Array {
const out: number[] = []
for (const def of Object.values(schema).sort((a, b) => a.n - b.n)) {
const name = Object.keys(schema).find((k) => schema[k] === def)!
const v = msg[name]
if (!isSet(v)) continue
for (const x of def.rep ? (v as unknown[]) : [v]) {
const t = def.t
if (typeof t === 'object' || t === 'string' || t === 'bytes') {
const body = typeof t === 'object' ? encode(t, x as Decoded) : t === 'string' ? utf8enc.encode(x as string) : (x as Uint8Array)
writeVarint(out, BigInt((def.n << 3) | 2))
writeVarint(out, BigInt(body.length))
out.push(...body)
} else if (t === 'float' || t === 'double') {
const b = new DataView(new ArrayBuffer(t === 'float' ? 4 : 8))
if (t === 'float') b.setFloat32(0, x as number, true)
else b.setFloat64(0, x as number, true)
writeVarint(out, BigInt((def.n << 3) | (t === 'float' ? 5 : 1)))
out.push(...new Uint8Array(b.buffer))
} else {
writeVarint(out, BigInt(def.n << 3))
writeVarint(out, BigInt(t === 'bool' ? (x ? 1 : 0) : (x as number)))
}
}
}
return new Uint8Array(out)
}
+206
View File
@@ -0,0 +1,206 @@
// Google Voice web API message shapes, from the reverse-engineered definitions
// in mautrix-gvoice (pkg/libgv/gvproto). Only the fields we use are listed.
import type { Schema } from './proto'
export const ThreadFolder = { ALL_THREADS: 1, TEXT_THREADS: 2 } as const
export const MessageType = {
MISSED_CALL: 0,
INCOMING_CALL: 1,
VOICEMAIL: 2,
OUTGOING_CALL: 7,
SMS_IN: 10,
SMS_OUT: 11,
OUTGOING_CALL_CANCELLED: 14
} as const
export const AttachmentStatus = { AVAILABLE: 1, NOT_SUPPORTED: 3 } as const
export const SizeSpec = { ORIGINAL: 1 } as const
// Media types sendsms accepts, by MIME type.
export const SendMediaType: Record<string, number> = {
'image/jpeg': 1,
'image/png': 2,
'image/tiff': 3,
'image/gif': 4,
'image/bmp': 5,
'image/webp': 6
}
const Contact: Schema = {
name: { n: 1, t: 'string' },
phoneNumber: { n: 2, t: 'string' },
blocked: { n: 7, t: 'bool' }
}
const AttachmentMetadata: Schema = {
size: { n: 1, t: 'int' },
width: { n: 2, t: 'int' },
height: { n: 3, t: 'int' }
}
const Attachment: Schema = {
mimeType: { n: 1, t: 'string' },
id: { n: 2, t: 'string' },
status: { n: 3, t: 'int' },
metadata: { n: 4, t: AttachmentMetadata, rep: true },
mediaType: { n: 5, t: 'int' }
}
const MMSMessage: Schema = {
text: { n: 1, t: 'string' },
subject: { n: 2, t: 'string' },
attachments: { n: 3, t: Attachment, rep: true },
participants: { n: 4, t: Contact, rep: true },
senderPhoneNumber: { n: 5, t: 'string' }
}
export const Message: Schema = {
id: { n: 1, t: 'string' },
timestamp: { n: 2, t: 'int' }, // epoch ms
contact: { n: 4, t: Contact },
type: { n: 5, t: 'int' },
status: { n: 6, t: 'int' },
text: { n: 10, t: 'string' },
mms: { n: 15, t: MMSMessage },
transactionId: { n: 18, t: 'int' }
}
export const Thread: Schema = {
id: { n: 1, t: 'string' },
read: { n: 2, t: 'bool' },
messages: { n: 3, t: Message, rep: true }, // newest first
paginationToken: { n: 4, t: 'string' },
contacts: { n: 5, t: Contact, rep: true },
isText: { n: 8, t: 'bool' },
phoneNumbers: { n: 9, t: 'string', rep: true }
}
export const ThreadAttributes: Schema = {
threadId: { n: 1, t: 'string' },
read: { n: 4, t: 'bool' }
}
const UnknownWrapper: Schema = {
unknownInt2: { n: 2, t: 'int' },
unknownInt3: { n: 3, t: 'int' }
}
// ---- requests (sent as pblite) ----
export const ReqGetAccount: Schema = { unknownInt2: { n: 2, t: 'int' } }
export const ReqListThreads: Schema = {
folder: { n: 1, t: 'int' },
unknownInt2: { n: 2, t: 'int' },
unknownInt3: { n: 3, t: 'int' },
paginationToken: { n: 4, t: 'string' },
versionToken: { n: 5, t: 'string' },
unknownWrapper: { n: 6, t: UnknownWrapper }
}
export const ReqGetThread: Schema = {
threadId: { n: 1, t: 'string' },
maybeMessageCount: { n: 2, t: 'int' },
paginationToken: { n: 3, t: 'string' },
unknownWrapper: { n: 4, t: UnknownWrapper }
}
export const ReqSendSMS: Schema = {
text: { n: 5, t: 'string' },
threadId: { n: 6, t: 'string' },
recipients: { n: 7, t: 'string', rep: true },
transactionId: { n: 9, t: { id: { n: 1, t: 'int' } } },
media: { n: 10, t: { type: { n: 1, t: 'int' }, data: { n: 2, t: 'bytes' } } },
trackingData: { n: 11, t: { data: { n: 1, t: 'string' } } }
}
export const ReqUpdateAttributes: Schema = {
attributes: { n: 1, t: ThreadAttributes },
otherAttributes: { n: 2, t: ThreadAttributes },
unknownInt: { n: 3, t: 'int' }
}
export const ReqCreateWaa: Schema = { requestKey: { n: 1, t: 'string' } }
export const ReqPingWaa: Schema = {
requestKey: { n: 1, t: 'string' },
payload: { n: 2, t: 'string' },
i1: { n: 3, t: 'int' },
i2: { n: 4, t: 'int' }
}
// ---- responses (binary protobuf, except WAA's pblite) ----
const PhoneNumber: Schema = { e164: { n: 1, t: 'string' } }
export const RespGetAccount: Schema = {
account: {
n: 1,
t: {
primaryDestinationId: { n: 1, t: 'string' },
phones: { n: 3, t: { accountPhone: { n: 1, t: { phoneNumber: { n: 1, t: PhoneNumber } } } }, rep: true }
}
}
}
export const RespListThreads: Schema = {
threads: { n: 1, t: Thread, rep: true },
paginationToken: { n: 2, t: 'string' },
versionToken: { n: 3, t: 'string' }
}
export const RespGetThread: Schema = { thread: { n: 1, t: Thread } }
export const RespSendSMS: Schema = {
threadId: { n: 2, t: 'string' },
threadItemId: { n: 3, t: 'string' },
timestampMs: { n: 4, t: 'int' }
}
export const RespEmpty: Schema = {}
export const RespCreateWaa: Schema = {
waa: {
n: 1,
t: {
respId: { n: 1, t: 'string' },
interpreterUrl: { n: 3, t: { url: { n: 4, t: 'string' } } },
interpreterHash: { n: 4, t: 'string' },
program: { n: 5, t: 'string' },
globalName: { n: 6, t: 'string' }
}
}
}
// ---- typed views of decoded messages ----
export interface GvContact {
name: string
phoneNumber: string
blocked: boolean
}
export interface GvAttachment {
mimeType: string
id: string
status: number
metadata: Array<{ size: number; width: number; height: number }>
}
export interface GvMessage {
id: string
timestamp: number
contact?: GvContact
type: number
text: string
mms?: { text: string; subject: string; attachments: GvAttachment[]; senderPhoneNumber: string; participants: GvContact[] }
transactionId: number
}
export interface GvThread {
id: string
read: boolean
messages: GvMessage[]
paginationToken: string
contacts: GvContact[]
isText: boolean
phoneNumbers: string[]
}
+138
View File
@@ -0,0 +1,138 @@
// The Google sign-in that Google Voice requests ride on: a persistent Electron
// session (cookies live in userData, outside the backed-up data folder, like
// the voip.ms password). Chromium keeps the cookie jar, including the rotation
// Google does through Set-Cookie, so we never handle most cookies ourselves.
import { BrowserWindow, session, type Session } from 'electron'
import { ORIGIN, USER_AGENT, type Transport } from './client'
const PARTITION = 'persist:gvoice'
const SIGN_IN_URL = 'https://voice.google.com/u/0/messages'
let ses: Session | undefined
export function gvSession(): Session {
if (!ses) {
ses = session.fromPartition(PARTITION)
// Google turns away sign-ins from browsers that say they're Electron.
ses.setUserAgent(USER_AGENT)
// The API only answers requests from voice.google.com. fetch() won't let
// us set Origin ourselves, so add it on the way out.
ses.webRequest.onBeforeSendHeaders(
{ urls: ['https://clients6.google.com/*', 'https://*.clients6.google.com/*', 'https://voice.google.com/u/*'] },
(d, cb) => cb({ requestHeaders: d.requestHeaders['Origin'] ? d.requestHeaders : { ...d.requestHeaders, Origin: ORIGIN } })
)
}
return ses
}
export function gvTransport(): Transport {
return {
fetch: (url, init) => gvSession().fetch(url, init),
cookie: async (name) => {
const jar = await gvSession().cookies.get({ domain: 'google.com' })
const find = (n: string): string | undefined => jar.find((c) => c.name === n)?.value
// SAPISID and __Secure-3PAPISID carry the same value; Google sometimes
// only sets the latter.
return find(name) ?? (name === 'SAPISID' ? find('__Secure-3PAPISID') : undefined)
}
}
}
export async function hasGvSession(): Promise<boolean> {
return !!(await gvTransport().cookie('SAPISID'))
}
// Sign in with Google in a window of our own. Resolves once the sign-in
// cookies exist and Google Voice has loaded; rejects if the window is closed.
export function signInWindow(parent?: BrowserWindow): Promise<void> {
return new Promise((resolve, reject) => {
const win = new BrowserWindow({
parent,
width: 520,
height: 720,
title: 'Sign in to Google Voice',
autoHideMenuBar: true,
webPreferences: { partition: PARTITION, sandbox: true, contextIsolation: true, nodeIntegration: false }
})
let done = false
const check = async (): Promise<void> => {
if (done || win.isDestroyed()) return
const url = win.webContents.getURL()
if (url.startsWith('https://voice.google.com/') && (await hasGvSession())) {
done = true
clearInterval(timer)
resolve()
win.close()
}
}
// Navigation events don't reliably fire as Google's pages hand off, so
// also just look every second.
const timer = setInterval(() => void check(), 1000)
win.webContents.on('did-navigate', () => void check())
win.webContents.on('did-navigate-in-page', () => void check())
// Closing the window by hand once signed in counts as done too.
win.on('closed', () => {
clearInterval(timer)
if (done) return
void hasGvSession().then((ok) => (ok ? resolve() : reject(new Error('Sign-in was cancelled before it finished.'))))
})
void win.loadURL(SIGN_IN_URL, { userAgent: USER_AGENT })
})
}
// Fallback for when Google refuses to sign in inside the app: cookies copied
// from a browser where you're signed in, as a "Copy as cURL" command, a raw
// Cookie header, or a JSON object of name → value.
export function parseCookies(input: string): Record<string, string> {
const text = input.trim()
if (text.startsWith('{')) {
const obj = JSON.parse(text) as Record<string, unknown>
return Object.fromEntries(Object.entries(obj).filter(([, v]) => typeof v === 'string')) as Record<string, string>
}
let header = text
const curl = /(?:-H|--header)\s+(['"])cookie:\s*(.*?)\1/is.exec(text) ?? /(?:-b|--cookie)\s+(['"])(.*?)\1/s.exec(text)
if (curl) header = curl[2]
else header = header.replace(/^cookie:\s*/i, '')
const out: Record<string, string> = {}
for (const part of header.split(';')) {
const eq = part.indexOf('=')
if (eq <= 0) continue
out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim()
}
return out
}
export async function importCookies(cookies: Record<string, string>): Promise<void> {
if (!cookies['SAPISID']) throw new Error("Those cookies don't include SAPISID. Copy a request to voice.google.com while signed in.")
const jar = gvSession().cookies
const expirationDate = Date.now() / 1000 + 365 * 86400
for (const [name, value] of Object.entries(cookies)) {
// OSID belongs to voice.google.com itself; __Host- cookies can't carry a domain.
const hostOnly = name === 'OSID' || name.startsWith('__Host-')
await jar.set({
url: hostOnly ? 'https://voice.google.com' : 'https://google.com',
...(hostOnly ? {} : { domain: '.google.com' }),
path: '/',
name,
value,
secure: true,
sameSite: 'no_restriction',
expirationDate
})
}
await jar.flushStore()
}
// The sign-in cookies, for copying to the Rabbit's app. Domain-wide
// (.google.com) cookies win over same-named host ones.
export async function exportCookies(): Promise<Record<string, string>> {
const jar = await gvSession().cookies.get({ domain: 'google.com' })
const out: Record<string, string> = {}
for (const c of [...jar].sort((a, b) => Number((a.domain ?? '').startsWith('.')) - Number((b.domain ?? '').startsWith('.'))))
out[c.name] = c.value
return out
}
export async function clearGvSession(): Promise<void> {
await gvSession().clearStorageData()
}
+237
View File
@@ -0,0 +1,237 @@
// Google Voice history import + polling, alongside the voip.ms SyncEngine.
// Same events ('messages', 'status'), its own status, its own failures.
import crypto from 'node:crypto'
import { EventEmitter } from 'node:events'
import type { MessageDb, NewMessage } from '../db'
import { groupKey, normalizeNumber } from '@shared/phone'
import type { GvStatus, MediaRef } from '@shared/types'
import { GVoiceError, type GVoice } from './client'
import { AttachmentStatus, MessageType, SizeSpec, type GvMessage, type GvThread } from './schema'
// GV message ids are opaque strings; ours are integers. Map them into a range
// of their own, far above voip.ms's ids and the negative local pending ones.
const GV_ID_BASE = 2 ** 52
export function gvMessageId(id: string): number {
const h = crypto.createHash('sha256').update(id).digest()
return GV_ID_BASE + h.readUIntBE(0, 6)
}
export function isGvMessageId(id: number): boolean {
return id >= GV_ID_BASE
}
// The conversation a thread belongs to: the other person's number, or for a
// group, every member's number (see groupKey).
export function threadContact(thread: Pick<GvThread, 'phoneNumbers'>, self: string): string {
const others = thread.phoneNumbers.map(normalizeNumber).filter((n) => n && n !== self)
return others.length > 1 ? groupKey(others) : (others[0] ?? '')
}
export function toNewMessage(m: GvMessage, did: string, contact: string, group: boolean): NewMessage | undefined {
if (m.type !== MessageType.SMS_IN && m.type !== MessageType.SMS_OUT) return undefined // calls, voicemail
const direction = m.type === MessageType.SMS_OUT ? 'out' : 'in'
const mms = m.mms
const text = mms?.text || m.text
const body = mms?.subject ? `${mms.subject}\n${text}` : text
const media: MediaRef[] = (mms?.attachments ?? [])
.filter((a) => a.id && a.status !== AttachmentStatus.NOT_SUPPORTED)
.map((a) => {
const meta = a.metadata.find((x) => x.size === SizeSpec.ORIGINAL) ?? a.metadata.reduce((best, x) => (x.width > (best?.width ?? 0) ? x : best), a.metadata[0])
return {
url: `gv:${a.id}`,
...(a.mimeType ? { mime: a.mimeType } : {}),
...(meta?.width ? { width: meta.width, height: meta.height } : {})
}
})
const out: NewMessage = { id: gvMessageId(m.id), did, contact, direction, body, ts: m.timestamp }
if (media.length) {
out.kind = 'mms'
out.media = media
}
if (group && direction === 'in') {
const sender = normalizeNumber(mms?.senderPhoneNumber || m.contact?.phoneNumber || '')
if (sender) out.sender = sender
}
return out
}
export interface GvSyncOptions {
did: string // our GV number, normalized
pollSeconds: number
backfillFloor: string // YYYY-MM-DD
}
const MIN_POLL_SECONDS = 20
const PAGE = 100
export class GvSyncEngine extends EventEmitter {
private pollTimer?: NodeJS.Timeout
private burstUntil = 0
private running = false
private backfilling = false
private polling?: Promise<void>
private status: GvStatus
constructor(
private db: MessageDb,
private gv: GVoice,
private opts: GvSyncOptions
) {
super()
this.status = { phase: 'idle', backfillDone: db.get('gv_backfill_done') === '1' }
}
getStatus(): GvStatus {
return this.status
}
private setStatus(patch: Partial<GvStatus>): void {
this.status = { ...this.status, ...patch }
this.emit('status', this.status)
}
private fail(e: unknown): void {
const signedOut = e instanceof GVoiceError && e.signedOut
this.setStatus({ phase: signedOut ? 'signedOut' : 'error', error: (e as Error).message })
}
// Store a thread's messages; returns how many were new.
private storeThread(thread: GvThread, messages = thread.messages): number {
const contact = threadContact(thread, this.opts.did)
if (!contact) return 0
this.db.setGvThread(this.opts.did, contact, thread.id)
const group = contact.includes(',')
const msgs = messages.map((m) => toNewMessage(m, this.opts.did, contact, group)).filter((m): m is NewMessage => !!m)
const added = this.db.upsertMessages(msgs)
this.db.reconcileSent(added)
// Already read on the phone or the web: don't show it as unread here.
if (added.length && thread.read) this.db.markRead(this.opts.did, contact)
if (added.length) this.emit('messages', added)
return added.length
}
// Imports from before read state was carried over left everything unread;
// once, go through the thread list and mark read what GV says is read.
private async syncReadStateOnce(): Promise<void> {
if (this.db.get('gv_read_synced') === '1' || !this.status.backfillDone) return
let token = ''
let changed = false
do {
const page = await this.gv.listThreads(token)
for (const t of page.threads) {
const contact = threadContact(t, this.opts.did)
if (t.read && contact) {
this.db.markRead(this.opts.did, contact)
changed = true
}
}
token = page.paginationToken
} while (token && this.running)
if (!this.running) return
this.db.set('gv_read_synced', '1')
if (changed) this.emit('readChanged')
}
start(): void {
if (this.running) return
this.running = true
void this.poll().finally(() => this.scheduleNextPoll())
if (!this.status.backfillDone) void this.backfill()
}
stop(): void {
this.running = false
clearTimeout(this.pollTimer)
}
burst(): void {
this.burstUntil = Date.now() + 2 * 60_000
clearTimeout(this.pollTimer)
this.scheduleNextPoll(3000)
}
private scheduleNextPoll(delay?: number): void {
if (!this.running) return
const d = delay ?? (Date.now() < this.burstUntil ? 5000 : Math.max(MIN_POLL_SECONDS, this.opts.pollSeconds) * 1000)
this.pollTimer = setTimeout(() => {
void this.poll().finally(() => this.scheduleNextPoll())
}, d)
}
async pollNow(): Promise<void> {
await this.poll()
}
private poll(): Promise<void> {
this.polling ??= this.fetchRecent().finally(() => (this.polling = undefined))
return this.polling
}
// The thread list carries each thread's latest few messages. If none of
// them were known yet and the thread already has history here, more may
// have arrived than the list shows, so fetch the thread itself.
private async fetchRecent(): Promise<void> {
try {
const { threads } = await this.gv.listThreads()
for (const t of threads) {
if (!t.messages.length) continue
const known = t.messages.some((m) => this.db.getMessage(gvMessageId(m.id)))
const contact = threadContact(t, this.opts.did)
const hasHistory = !!contact && this.db.getGvThread(this.opts.did, contact) === t.id
this.storeThread(t)
if (!known && hasHistory && t.paginationToken) this.storeThread(t, (await this.gv.getThread(t.id, PAGE)).messages)
}
this.setStatus({ lastPoll: Date.now(), error: undefined, phase: this.backfilling ? 'backfill' : 'polling' })
await this.syncReadStateOnce()
} catch (e) {
this.fail(e)
}
}
// Walk every text thread (resumable page by page), and each thread's
// messages back to the floor date.
private async backfill(): Promise<void> {
if (this.backfilling) return
this.backfilling = true
this.setStatus({ phase: 'backfill' })
const floor = Date.parse(this.opts.backfillFloor + 'T00:00:00Z')
let token = this.db.get('gv_backfill_token') ?? ''
try {
while (this.running) {
const page = await this.gv.listThreads(token)
for (const t of page.threads) {
let thread = t
let pageToken = ''
// The listing's copy is partial; page the thread from the newest.
for (;;) {
thread = await this.gv.getThread(t.id, PAGE, pageToken)
this.storeThread(thread)
const oldest = thread.messages[thread.messages.length - 1]
if (!thread.paginationToken || !oldest || oldest.timestamp < floor || !this.running) break
pageToken = thread.paginationToken
await new Promise((r) => setTimeout(r, 250))
}
}
token = page.paginationToken
this.db.set('gv_backfill_token', token)
if (!token || !page.threads.length) break
}
if (this.running) {
this.db.set('gv_backfill_done', '1')
this.db.set('gv_read_synced', '1')
this.setStatus({ phase: 'polling', backfillDone: true })
}
} catch (e) {
this.fail(e)
if (!(e instanceof GVoiceError && e.signedOut)) setTimeout(() => this.running && void this.backfill(), 60_000)
} finally {
this.backfilling = false
}
}
resetBackfill(): void {
for (const k of ['gv_backfill_token', 'gv_backfill_done']) this.db.db.prepare('DELETE FROM kv WHERE key = ?').run(k)
this.status.backfillDone = false
if (this.running) void this.backfill()
}
}
+121
View File
@@ -0,0 +1,121 @@
// Message signing ("WAA" / BotGuard). Google Voice's web client attaches a
// signature, computed by an obfuscated script Google serves, to every text it
// sends; sends without one work but get rate-limited sooner. Like
// mautrix-gvoice's electron.mjs, we run Google's script in a hidden window,
// locked down so it can't load anything else, and ask it for signatures.
//
// Everything here is best-effort: on any failure the send goes out unsigned.
import { BrowserWindow, session } from 'electron'
import crypto from 'node:crypto'
import { USER_AGENT, type GVoice } from './client'
const EXPIRY = 60 * 60_000
const TIMEOUT = 10_000
const ABOUT_URLS = new Set(['https://voice.google.com/', 'https://voice.google.com/about', 'https://voice.google.com/u/0/about'])
// Runs inside the hidden page.
const LOAD_SCRIPT = (src: string): Promise<void> =>
new Promise((resolve, reject) => {
const s = document.createElement('script')
s.src = src
s.onload = () => resolve()
s.onerror = () => reject(new Error('script failed to load'))
document.head.appendChild(s)
})
type Payload = { message_ids: string; destinations: string; thread_id: string } | undefined
const RUN_PROGRAM = (globalName: string, program: string, payload: Payload): Promise<string> =>
new Promise((resolve, reject) => {
const vm = (window as unknown as Record<string, { a: (...args: unknown[]) => void }>)[globalName]
if (!vm) return reject(new Error('signer not loaded'))
vm.a(
program,
(fn1: (cb: (r: string) => void, args: unknown[]) => void) => fn1((r) => resolve(r), [payload, undefined, undefined, undefined]),
true,
undefined,
() => undefined
)
})
const b64sha256 = (s: string): string => crypto.createHash('sha256').update(s).digest('base64')
const withTimeout = <T>(p: Promise<T>, ms: number): Promise<T> =>
Promise.race([p, new Promise<T>((_, reject) => setTimeout(() => reject(new Error('timed out')), ms))])
export class WaaSigner {
private win?: BrowserWindow
private ready?: Promise<void>
private initedAt = 0
private program = ''
private globalName = ''
private scriptUrl = ''
constructor(private gv: GVoice) {}
private async open(): Promise<BrowserWindow> {
if (this.win && !this.win.isDestroyed()) return this.win
const ses = session.fromPartition('gvoice-waa') // in-memory, no Google cookies
ses.webRequest.onBeforeRequest((d, cb) => cb({ cancel: !(ABOUT_URLS.has(d.url) || d.url === this.scriptUrl) }))
ses.webRequest.onHeadersReceived((d, cb) => {
const headers = { ...d.responseHeaders }
for (const k of Object.keys(headers)) if (k.toLowerCase() === 'content-security-policy') delete headers[k]
cb({ responseHeaders: headers })
})
const win = new BrowserWindow({
show: false,
webPreferences: { session: ses, sandbox: true, contextIsolation: true, nodeIntegration: false }
})
await win.loadURL('https://voice.google.com/about', { userAgent: USER_AGENT })
this.win = win
return win
}
private init(): Promise<void> {
this.ready = (async () => {
const waa = await this.gv.createWaa()
const win = await this.open()
this.program = waa.program
this.globalName = waa.globalName
const url = waa.interpreterUrl.startsWith('//') ? 'https:' + waa.interpreterUrl : waa.interpreterUrl
if (url !== this.scriptUrl) {
this.scriptUrl = url
await win.webContents.executeJavaScript(`(${LOAD_SCRIPT.toString()})(${JSON.stringify(url)})`)
}
this.initedAt = Date.now()
// The web client checks in once with an empty payload.
void this.run(undefined)
.then((sig) => this.gv.pingWaa(sig))
.catch(() => undefined)
})()
this.ready.catch(() => (this.ready = undefined))
return this.ready
}
private async run(payload: Payload): Promise<string> {
const js = `(${RUN_PROGRAM.toString()})(${JSON.stringify(this.globalName)}, ${JSON.stringify(this.program)}, ${JSON.stringify(payload)})`
return withTimeout(this.win!.webContents.executeJavaScript(js) as Promise<string>, TIMEOUT)
}
// Signature for a send, or undefined if one couldn't be had.
async sign(threadId: string, recipients: string[], transactionId: number): Promise<string | undefined> {
try {
if (!this.ready || Date.now() - this.initedAt > EXPIRY) await this.init()
else await this.ready
const sig = await this.run({
message_ids: b64sha256(String(transactionId)),
destinations: b64sha256(recipients.join('|')),
thread_id: b64sha256(threadId)
})
return sig || undefined
} catch (e) {
console.warn('[gvoice] signing failed, sending unsigned:', (e as Error).message)
return undefined
}
}
close(): void {
if (this.win && !this.win.isDestroyed()) this.win.destroy()
this.win = undefined
this.ready = undefined
}
}
+456 -45
View File
@@ -1,29 +1,52 @@
import { app, BrowserWindow, dialog, ipcMain, net, protocol, safeStorage, shell } from 'electron' // First: in sandbox mode this moves every path the app uses (see sandbox.ts).
import { SANDBOX, seedDemo } from './sandbox'
import { app, BrowserWindow, clipboard, ClipboardItem, dialog, ipcMain, nativeTheme, net, protocol, safeStorage, shell } from 'electron'
import crypto from 'node:crypto' import crypto from 'node:crypto'
import fs from 'node:fs' import fs from 'node:fs'
import path from 'node:path' import path from 'node:path'
import os from 'node:os'
import { pathToFileURL } from 'node:url' import { pathToFileURL } from 'node:url'
import { splitMessage, normalizeNumber } from '@shared/phone' import { charCount, groupMembers, isGroup, normalizeNumber, SMS_TEXT_LIMIT } from '@shared/phone'
import type { Credentials, Did, Message, Settings } from '@shared/types' import type { ChatExport, Credentials, Did, MediaRef, Message, NewContact, OutgoingAttachment, Provider, Settings, SyncStatus, Theme } from '@shared/types'
import type { AppState } from '@shared/api' import type { AppState } from '@shared/api'
import { ContactDirectory } from './contacts' import { addToAddressBook, ContactDirectory, listAddressBooks } from './contacts'
import { localDay, MessageDb, type NewMessage } from './db' import { localDay, MessageDb, type NewMessage } from './db'
import { MediaStore } from './media'
import { exportHtml, exportText, inRange, rangeLabel } from './export'
import { extFor, guessMime } from '@shared/mime'
import { clearCredentials, loadCredentials, saveCredentials } from './secrets' import { clearCredentials, loadCredentials, saveCredentials } from './secrets'
import { getDataDir, loadSettings, saveSettings, setDataDir } from './settings' import { getDataDir, loadSettings, saveSettings, setDataDir } from './settings'
import { SyncEngine } from './sync' import { SyncEngine } from './sync'
import { VoipMs } from './voipms' import { loadZoom, saveZoom } from './uistate'
import { sendWithRetry } from './send'
import { VoipMs, VoipMsError } from './voipms'
import { classifyGvError, gvErrorMessage, GVoice, GVoiceError, toE164, transactionId } from './gvoice/client'
import { SendMediaType } from './gvoice/schema'
import { clearGvSession, exportCookies, gvTransport, hasGvSession, importCookies, parseCookies, signInWindow } from './gvoice/session'
import { gvMessageId, GvSyncEngine } from './gvoice/sync'
import { WaaSigner } from './gvoice/waa'
import { clearNotifications, notifyNew } from './notify'
import * as rabbit from './rabbit'
protocol.registerSchemesAsPrivileged([{ scheme: 'contact-photo', privileges: { standard: true, secure: true, supportFetchAPI: true } }]) protocol.registerSchemesAsPrivileged([
{ scheme: 'contact-photo', privileges: { standard: true, secure: true, supportFetchAPI: true } },
{ scheme: 'mms-media', privileges: { standard: true, secure: true, supportFetchAPI: true, stream: true } }
])
if (!app.requestSingleInstanceLock()) app.quit() if (!app.requestSingleInstanceLock()) app.quit()
let win: BrowserWindow | undefined let win: BrowserWindow | undefined
let db: MessageDb let db: MessageDb
let contacts: ContactDirectory let contacts: ContactDirectory
let media: MediaStore
let settings: Settings let settings: Settings
let api: VoipMs | undefined let api: VoipMs | undefined
let sync: SyncEngine | undefined let sync: SyncEngine | undefined
let dids: Did[] = [] let dids: Did[] = []
// Google Voice: optional, alongside voip.ms. Its number is cached in the DB.
let gv: GVoice | undefined
let gvSync: GvSyncEngine | undefined
let waa: WaaSigner | undefined
const send = (channel: string, ...args: unknown[]): void => { const send = (channel: string, ...args: unknown[]): void => {
if (win && !win.isDestroyed()) win.webContents.send(channel, ...args) if (win && !win.isDestroyed()) win.webContents.send(channel, ...args)
@@ -47,18 +70,115 @@ function startSync(creds: Credentials): void {
sync?.stop() sync?.stop()
api = new VoipMs(creds) api = new VoipMs(creds)
sync = new SyncEngine(db, api, settings) sync = new SyncEngine(db, api, settings)
sync.on('messages', (msgs: NewMessage[]) => { sync.on('messages', onNewMessages)
send('messages', msgs) sync.on('status', () => send('syncStatus', syncStatus()))
send('conversationsChanged')
})
sync.on('status', (s) => send('syncStatus', s))
sync.start() sync.start()
api api
.getDids() .getDids()
.then((d) => (dids = d)) .then(setDids)
.catch(() => undefined) .catch(() => undefined)
} }
// The account's numbers, cached in the DB: voip.ms takes seconds to answer, so
// startup uses the cached list and refreshes it in the background.
function setDids(next: Did[]): void {
const changed = JSON.stringify(next) !== JSON.stringify(dids)
dids = next
db.set('dids', JSON.stringify(next))
if (changed) send('stateChanged')
}
// Fresh messages from either provider.
function onNewMessages(msgs: NewMessage[]): void {
media.prefetch(msgs)
send('messages', msgs)
send('conversationsChanged')
// While the window has focus you're looking at them already.
if (settings.notifications && !win?.isFocused()) notifyNew(msgs, { db, contacts, onClick: openFromNotification })
}
function openFromNotification(key: { did: string; contact: string }): void {
if (!win || win.isDestroyed()) return
if (win.isMinimized()) win.restore()
win.show()
win.focus()
send('openConversation', key)
}
const gvNumber = (): string | undefined => db.get('gv_number') || undefined
// Every number we can text from: voip.ms's DIDs, then Google Voice's.
function allDids(): Did[] {
const n = gvNumber()
return n ? [...dids, { did: n, description: 'Google Voice', smsEnabled: true, provider: 'gvoice' }] : dids
}
const providerOf = (did: string): Provider => (did === gvNumber() ? 'gvoice' : 'voipms')
function syncStatus(): SyncStatus {
const base: SyncStatus = sync?.getStatus() ?? { phase: 'unconfigured', backfillDone: false, total: db.count() }
return { ...base, total: db.count(), ...(gvSync ? { gvoice: gvSync.getStatus() } : {}) }
}
function startGvSync(): void {
const did = gvNumber()
if (!did) return
gvSync?.stop()
waa?.close()
gv = new GVoice(gvTransport())
waa = new WaaSigner(gv)
gvSync = new GvSyncEngine(db, gv, { did, pollSeconds: settings.pollSeconds, backfillFloor: settings.backfillFloor })
gvSync.on('messages', onNewMessages)
gvSync.on('status', () => send('syncStatus', syncStatus()))
gvSync.on('readChanged', () => send('conversationsChanged'))
gvSync.start()
}
// After signing in (either way): learn the number and start syncing.
async function finishGvConnect(): Promise<void> {
const number = normalizeNumber(await new GVoice(gvTransport()).getAccount())
db.set('gv_number', number)
startGvSync()
send('stateChanged')
}
function stopGv(): void {
gvSync?.stop()
waa?.close()
gvSync = undefined
waa = undefined
gv = undefined
}
// ---- the Rabbit (Android app) ----
// In the sandbox this targets the separate dev app with made-up data, so
// trying the installer never puts anything real on the device.
const RABBIT_PKG = SANDBOX ? 'me.teafry.voipmessages.dev' : 'me.teafry.voipmessages'
function rabbitTarget(): rabbit.RabbitTarget {
const apk = SANDBOX ? path.join(app.getAppPath(), 'android/build/dev/DevVoipMessages.apk') : rabbit.bundledApk()?.apk
if (!apk || !fs.existsSync(apk)) throw new Error("This build doesn't include the Android app. Run: python3 android/build.py --ship")
return { pkg: RABBIT_PKG, apk }
}
async function rabbitConfig(): Promise<rabbit.RabbitConfig> {
const chosen = settings.dids
const voipDids = dids.filter((d) => d.smsEnabled && (!chosen.length || chosen.includes(d.did)))
const gv = gvNumber()
const creds = loadCredentials()
return {
...(SANDBOX ? { sandbox: true } : {}),
voipms: SANDBOX ? { username: 'sandbox', password: 'sandbox' } : creds ? { username: creds.username, password: creds.password } : null,
gvoice: gv ? { number: gv, cookies: SANDBOX ? {} : await exportCookies() } : null,
dids: voipDids.map((d) => ({ did: d.did, description: d.description })),
defaultDid: settings.defaultDid ?? voipDids[0]?.did ?? gv
}
}
function rabbitDeps(): Omit<rabbit.InstallDeps, 'mediaDir'> {
return { db, target: rabbitTarget(), config: rabbitConfig, progress: (step) => send('rabbitProgress', step) }
}
// ---- contact photos: contact-photo://n/<number> ---- // ---- contact photos: contact-photo://n/<number> ----
async function servePhoto(req: Request): Promise<Response> { async function servePhoto(req: Request): Promise<Response> {
const number = decodeURIComponent(new URL(req.url).pathname.slice(1)) const number = decodeURIComponent(new URL(req.url).pathname.slice(1))
@@ -86,46 +206,254 @@ async function servePhoto(req: Request): Promise<Response> {
} }
} }
// ---- MMS attachments: mms-media://m/<messageId>/<index> ----
async function serveMedia(req: Request): Promise<Response> {
const [id, index] = new URL(req.url).pathname.slice(1).split('/').map(Number)
const ref = await media.resolve(id, index)
if (!ref?.file) return new Response(null, { status: 404 })
const headers = { 'content-type': ref.mime ?? guessMime(ref.file) ?? 'application/octet-stream' }
return new Response(fs.readFileSync(media.filePath(ref.file)), { headers })
}
async function saveMediaAs(id: number, index: number): Promise<void> {
const m = db.getMessage(id)
const ref = await media.resolve(id, index)
if (!m || !ref?.file) throw new Error('That attachment is no longer available.')
const r = await dialog.showSaveDialog(win!, {
defaultPath: path.join(app.getPath('downloads'), `mms-${localDay(new Date(m.ts))}-${id}-${index + 1}.${extFor(ref.mime)}`)
})
if (!r.canceled && r.filePath) fs.copyFileSync(media.filePath(ref.file), r.filePath)
}
// ---- Export chat ----
async function exportChat(did: string, contact: string, opts: ChatExport): Promise<boolean> {
const msgs = inRange(db.getConversationMessages(did, contact), opts)
if (!msgs.length) throw new Error('There are no messages in those dates.')
const name = `${opts.title} - ${rangeLabel(opts)}`.replace(/[/\\:*?"<>|]/g, '-')
const r = await dialog.showSaveDialog(win!, {
defaultPath: path.join(app.getPath('documents'), `${name}.${opts.format}`),
filters: [opts.format === 'pdf' ? { name: 'PDF', extensions: ['pdf'] } : { name: 'Text', extensions: ['txt'] }]
})
if (r.canceled || !r.filePath) return false
if (opts.format === 'txt') {
fs.writeFileSync(r.filePath, exportText(contact, msgs, opts))
return true
}
// Photos as local files (fetching any not downloaded yet, a few at a time).
const photos = new Map<string, string>()
if (opts.attachments) {
const wanted = msgs.flatMap((m) => (m.media ?? []).flatMap((ref, i) => (ref.mime?.startsWith('image/') ? [[m.id, i] as const] : [])))
for (let k = 0; k < wanted.length; k += 4) {
await Promise.all(
wanted.slice(k, k + 4).map(async ([id, i]) => {
const ref = await media.resolve(id, i).catch(() => undefined)
if (ref?.file) photos.set(`${id}/${i}`, pathToFileURL(media.filePath(ref.file)).href)
})
)
}
}
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bubble-export-'))
const page = new BrowserWindow({ show: false, webPreferences: { javascript: false } })
try {
const html = path.join(dir, 'chat.html')
fs.writeFileSync(html, exportHtml(contact, msgs, opts, (m, i) => photos.get(`${m.id}/${i}`)))
await page.loadFile(html)
fs.writeFileSync(r.filePath, await page.webContents.printToPDF({ pageSize: 'Letter', printBackground: true }))
} finally {
page.destroy()
fs.rmSync(dir, { recursive: true, force: true })
}
return true
}
// For "Copy image": the renderer decodes the bytes (any format Chromium reads)
// and hands back a PNG, the one image format every clipboard consumer takes.
async function readMedia(id: number, index: number): Promise<{ mime: string; data: Uint8Array<ArrayBuffer> }> {
const ref = await media.resolve(id, index)
if (!ref?.file) throw new Error('That attachment is no longer available.')
return { mime: ref.mime ?? guessMime(ref.file) ?? 'application/octet-stream', data: new Uint8Array(fs.readFileSync(media.filePath(ref.file))) }
}
// ---- theme + zoom ----
function applyTheme(): void {
nativeTheme.themeSource = settings.theme
win?.setBackgroundColor(windowBackground())
}
function windowBackground(): string {
return nativeTheme.shouldUseDarkColors ? '#121212' : '#ffffff'
}
const ZOOM_STEP = 0.5
const ZOOM_MIN = -3
const ZOOM_MAX = 4
function setZoom(level: number): void {
if (!win) return
const z = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, level))
win.webContents.setZoomLevel(z)
saveZoom(z)
}
// ---- sending ---- // ---- sending ----
// voip.ms can take half a minute to accept a message, so sends to one
// conversation go out one at a time, in the order they were typed; otherwise a
// quick follow-up overtakes a slow message on the recipient's phone.
const sendQueues = new Map<string, Promise<void>>()
function enqueue<T>(key: string, job: () => Promise<T>): Promise<T> {
const run = (sendQueues.get(key) ?? Promise.resolve()).then(job)
const tail = run.then(
() => undefined,
() => undefined
)
sendQueues.set(key, tail)
void tail.then(() => sendQueues.get(key) === tail && sendQueues.delete(key))
return run
}
// The pending bubble shows up right away; the voip.ms call waits its turn.
// Resolves once the message is sent or marked failed (the failure shows on the
// message, with a Retry button).
async function deliver(m: Omit<NewMessage, 'id'>, attempt: () => Promise<number>): Promise<void> {
const engine = providerOf(m.did) === 'gvoice' ? gvSync : sync
const tempId = db.insertPending(m)
send('conversationsChanged')
try {
await enqueue(`${m.did}:${m.contact}`, () =>
sendWithRetry(tempId, {
db,
attempt,
checkSent: () => engine?.pollNow() ?? Promise.resolve(),
...(engine === gvSync ? { classify: classifyGvError, describe: gvErrorMessage } : {})
})
)
} finally {
send('conversationsChanged')
engine?.burst()
}
}
const voipAttempt = (call: (api: VoipMs) => Promise<number>) => (): Promise<number> => {
if (!api) throw new VoipMsError('not_signed_in')
return call(api)
}
// One Google Voice send: text and at most one photo. Resolves with the id the
// message has in GV's own listing, so the next sync recognises it.
async function gvSend(did: string, contact: string, text: string, ref?: MediaRef): Promise<number> {
if (!gv) throw new GVoiceError('Google Voice is not connected. Connect it in Settings.', 401)
const recipients = groupMembers(contact).map(toE164)
let threadId = db.getGvThread(did, contact) ?? ''
if (!threadId && !isGroup(contact)) {
// A 1:1 thread's id is predictable, but it only exists once either side
// has texted; otherwise start one from the recipient list.
try {
threadId = (await gv.getThread(`t.${recipients[0]}`, 1)).id
} catch (e) {
if (!(e instanceof GVoiceError && e.status === 404)) throw e
}
}
const txn = transactionId()
const trackingData = await waa?.sign(threadId, recipients, txn)
const photo = ref && { mime: ref.mime!, data: new Uint8Array(fs.readFileSync(media.filePath(ref.file!))) }
const r = await gv.sendSms({ threadId, recipients, text, media: photo, transactionId: txn, trackingData })
const thread = r.threadId || threadId
if (thread) db.setGvThread(did, contact, thread)
// Find our message by transaction id: the listing is what later syncs see.
const listed = thread ? (await gv.getThread(thread, 10).catch(() => undefined))?.messages.find((m) => m.transactionId === txn) : undefined
return gvMessageId(listed?.id ?? r.threadItemId)
}
// Anything longer than one SMS goes out as a single text-only MMS (voip.ms;
// Google Voice has no such limit).
async function sendText(did: string, contact: string, text: string): Promise<void> { async function sendText(did: string, contact: string, text: string): Promise<void> {
const from = normalizeNumber(did)
const m: Omit<NewMessage, 'id'> = { did: from, contact, direction: 'out', body: text, ts: Date.now() }
if (providerOf(from) === 'gvoice') return deliver(m, () => gvSend(from, contact, text))
if (charCount(text) > SMS_TEXT_LIMIT) return sendMmsRefs(did, contact, text, [])
if (!api) throw new Error('Not signed in') if (!api) throw new Error('Not signed in')
const dst = normalizeNumber(contact) const dst = normalizeNumber(contact)
await deliver({ ...m, contact: dst }, voipAttempt((api) => api.sendSms(from, dst, text)))
}
// One MMS: text (up to 2048 chars) plus up to three attachments, each already
// small enough for voip.ms (the renderer compresses before handing them over).
async function sendMms(did: string, contact: string, text: string, attachments: OutgoingAttachment[]): Promise<void> {
const refs: MediaRef[] = attachments.map((a) => ({ file: media.save(a.data, a.mime), mime: a.mime, width: a.width, height: a.height }))
await sendMmsRefs(did, contact, text, refs)
}
async function sendMmsRefs(did: string, contact: string, text: string, refs: MediaRef[]): Promise<void> {
const from = normalizeNumber(did) const from = normalizeNumber(did)
let failed: Error | undefined if (providerOf(from) === 'gvoice') {
for (const part of splitMessage(text)) { if (refs.some((r) => !SendMediaType[r.mime ?? ''])) throw new Error('Google Voice can only send photos.')
const tempId = db.insertPending({ did: from, contact: dst, direction: 'out', body: part, ts: Date.now() }) // GV carries one photo per message: the text rides with the first.
send('conversationsChanged') await Promise.all(
try { refs.map((ref, i) => {
const realId = await api.sendSms(from, dst, part) const body = i === 0 ? text : ''
db.confirmPending(tempId, realId) const m: Omit<NewMessage, 'id'> = { did: from, contact, direction: 'out', body, ts: Date.now() + i, kind: 'mms', media: [ref] }
} catch (e) { return deliver(m, () => gvSend(from, contact, body, ref))
db.markFailed(tempId) })
failed = e as Error )
} return
send('conversationsChanged')
if (failed) break
} }
sync?.burst() if (!api) throw new Error('Not signed in')
if (failed) throw failed const dst = normalizeNumber(contact)
await deliver(
{ did: from, contact: dst, direction: 'out', body: text, ts: Date.now(), kind: 'mms', media: refs },
voipAttempt((api) => {
const payload = refs.map((r) => `data:${r.mime};base64,${fs.readFileSync(media.filePath(r.file!)).toString('base64')}`)
return api.sendMms(from, dst, text, payload)
})
)
} }
function registerIpc(): void { function registerIpc(): void {
ipcMain.handle('getState', async (): Promise<AppState> => { ipcMain.handle('getState', (): AppState => {
const creds = loadCredentials() const creds = loadCredentials()
if (api && !dids.length) dids = await api.getDids().catch(() => [])
if (process.env['VOIPMS_DEMO'] && !dids.length) dids = [{ did: '5415550100', description: 'Demo', smsEnabled: true }]
return { return {
// VOIPMS_DEMO: show the main UI without an account (for UI work on seeded data). // Sandbox: show the main UI without an account (made-up data).
configured: !!creds || !!process.env['VOIPMS_DEMO'], configured: !!creds || !!gvNumber() || !!SANDBOX,
username: creds?.username, username: creds?.username,
settings, settings,
dataDir: getDataDir(), dataDir: getDataDir(),
dids, dids: allDids(),
keyringBackend: safeBackend() keyringBackend: safeBackend(),
gvoiceNumber: gvNumber()
} }
}) })
ipcMain.handle('rabbitStatus', async () => {
const bundled = SANDBOX ? undefined : rabbit.bundledApk()
const device = await rabbit.status(RABBIT_PKG)
return { adb: !!rabbit.findAdb(), bundledVersion: bundled?.version, ...(device ? { device } : {}) }
})
ipcMain.handle('rabbitInstall', async (_e, mode: 'full' | 'update' = 'full') => {
const names = await rabbit.install({ ...rabbitDeps(), mediaDir: path.join(getDataDir(), 'media'), mode })
if (names) send('conversationsChanged')
})
ipcMain.handle('rabbitSync', async () => {
const names = await rabbit.sync(rabbitDeps())
if (names) send('conversationsChanged')
})
ipcMain.handle('connectGoogleVoice', async () => {
await signInWindow(win)
await finishGvConnect()
})
ipcMain.handle('connectGoogleVoiceCookies', async (_e, text: string) => {
await importCookies(parseCookies(text))
await finishGvConnect()
})
ipcMain.handle('disconnectGoogleVoice', async () => {
stopGv()
db.db.prepare(`DELETE FROM kv WHERE key = 'gv_number'`).run()
await clearGvSession()
send('stateChanged')
send('syncStatus', syncStatus())
})
ipcMain.handle('testCredentials', async (_e, creds: Credentials) => { ipcMain.handle('testCredentials', async (_e, creds: Credentials) => {
dids = await new VoipMs(creds).getDids() setDids(await new VoipMs(creds).getDids())
return dids return dids
}) })
ipcMain.handle('saveSetup', (_e, creds: Credentials, s: Settings) => { ipcMain.handle('saveSetup', (_e, creds: Credentials, s: Settings) => {
@@ -136,28 +464,72 @@ function registerIpc(): void {
}) })
ipcMain.handle('updateSettings', (_e, s: Settings) => { ipcMain.handle('updateSettings', (_e, s: Settings) => {
const floorChanged = s.backfillFloor !== settings.backfillFloor const floorChanged = s.backfillFloor !== settings.backfillFloor
const syncChanged = floorChanged || s.pollSeconds !== settings.pollSeconds || s.dids.join() !== settings.dids.join()
settings = s settings = s
saveSettings(s) saveSettings(s)
applyTheme()
const creds = loadCredentials() const creds = loadCredentials()
if (creds) startSync(creds) if (creds && syncChanged) startSync(creds)
if (floorChanged) sync?.resetBackfill() if (syncChanged && gvSync) startGvSync()
if (floorChanged) {
sync?.resetBackfill()
gvSync?.resetBackfill()
}
})
// Theme takes effect (and is saved) immediately, without the dialog's Save.
ipcMain.handle('setTheme', (_e, theme: Theme) => {
settings = { ...settings, theme }
saveSettings(settings)
applyTheme()
}) })
ipcMain.handle('signOut', () => { ipcMain.handle('signOut', () => {
sync?.stop() sync?.stop()
sync = undefined sync = undefined
api = undefined api = undefined
clearCredentials() clearCredentials()
setDids([])
send('syncStatus', syncStatus())
}) })
ipcMain.handle('listContacts', () => contacts.list()) ipcMain.handle('listContacts', () => contacts.list())
// The sandbox never touches the real address books: pretend.
ipcMain.handle('listAddressBooks', () =>
SANDBOX ? { books: [{ uid: 'sandbox', name: 'Contacts', account: 'Sandbox' }], default: 'sandbox' } : listAddressBooks()
)
ipcMain.handle('addContact', async (_e, c: NewContact) => {
const book = SANDBOX ? 'Contacts (sandbox)' : await addToAddressBook({ ...c, book: c.book ?? settings.contactBook })
const name = [c.first, c.last].filter(Boolean).join(' ') || c.org
contacts.addLocal({ name, number: normalizeNumber(c.number), label: 'cell', book })
return book
})
ipcMain.handle('listConversations', () => db.listConversations()) ipcMain.handle('listConversations', () => db.listConversations())
ipcMain.handle('getMessages', (_e, did: string, contact: string) => db.getConversationMessages(did, contact)) ipcMain.handle('getMessages', (_e, did: string, contact: string) => db.getConversationMessages(did, contact))
ipcMain.handle('markRead', (_e, did: string, contact: string) => { ipcMain.handle('markRead', (_e, did: string, contact: string) => {
// Clear the unread badge on the phone too.
const thread = providerOf(did) === 'gvoice' && db.hasUnread(did, contact) ? db.getGvThread(did, contact) : undefined
if (thread) gv?.markRead(thread).catch((e: Error) => console.warn('[gvoice] mark read failed:', e.message))
db.markRead(did, contact) db.markRead(did, contact)
clearNotifications(did, contact)
send('conversationsChanged') send('conversationsChanged')
}) })
ipcMain.handle('markUnread', (_e, did: string, contact: string) => {
db.markUnread(did, contact)
send('conversationsChanged')
})
ipcMain.handle('setArchived', (_e, did: string, contact: string, archived: boolean) => {
db.setArchived(did, contact, archived)
send('conversationsChanged')
})
ipcMain.handle('setName', (_e, did: string, contact: string, name: string | null) => {
db.setName(did, contact, name)
send('conversationsChanged')
})
ipcMain.handle('getDrafts', () => db.getDrafts())
ipcMain.handle('setDraft', (_e, contact: string, text: string) => db.setDraft(contact, text))
ipcMain.handle('search', (_e, q: string, scope?: { did: string; contact: string }) => db.search(q, scope)) ipcMain.handle('search', (_e, q: string, scope?: { did: string; contact: string }) => db.search(q, scope))
ipcMain.handle('send', (_e, did: string, contact: string, text: string) => sendText(did, contact, text)) ipcMain.handle('send', (_e, did: string, contact: string, text: string, attachments?: OutgoingAttachment[]) =>
attachments?.length ? sendMms(did, contact, text, attachments) : sendText(did, contact, text)
)
ipcMain.handle('deleteFailed', (_e, id: number) => { ipcMain.handle('deleteFailed', (_e, id: number) => {
db.deleteMessage(id) db.deleteMessage(id)
send('conversationsChanged') send('conversationsChanged')
@@ -166,11 +538,18 @@ function registerIpc(): void {
const m: Message | undefined = db.getMessage(id) const m: Message | undefined = db.getMessage(id)
if (!m || m.status !== 'failed') return if (!m || m.status !== 'failed') return
db.deleteMessage(id) db.deleteMessage(id)
await sendText(m.did, m.contact, m.body) if (m.kind === 'mms' && m.media?.length) await sendMmsRefs(m.did, m.contact, m.body, m.media)
else await sendText(m.did, m.contact, m.body)
}) })
ipcMain.handle('saveMedia', (_e, id: number, index: number) => saveMediaAs(id, index))
ipcMain.handle('exportChat', (_e, did: string, contact: string, opts: ChatExport) => exportChat(did, contact, opts))
ipcMain.handle('readMedia', (_e, id: number, index: number) => readMedia(id, index))
ipcMain.handle('copyImage', (_e, png: Uint8Array<ArrayBuffer>) =>
clipboard.write([new ClipboardItem({ 'image/png': new Blob([png], { type: 'image/png' }) })])
)
ipcMain.handle('syncStatus', () => sync?.getStatus() ?? { phase: 'unconfigured', backfillDone: false, total: db.count() }) ipcMain.handle('syncStatus', () => syncStatus())
ipcMain.handle('pollNow', () => sync?.pollNow()) ipcMain.handle('pollNow', () => Promise.all([sync?.pollNow(), gvSync?.pollNow()]))
ipcMain.handle('openDataFolder', () => shell.openPath(getDataDir())) ipcMain.handle('openDataFolder', () => shell.openPath(getDataDir()))
ipcMain.handle('snapshotNow', () => db.snapshot(snapshotDir())) ipcMain.handle('snapshotNow', () => db.snapshot(snapshotDir()))
ipcMain.handle('chooseDataDir', async () => { ipcMain.handle('chooseDataDir', async () => {
@@ -214,8 +593,8 @@ function createWindow(): void {
height: 800, height: 800,
minWidth: 760, minWidth: 760,
minHeight: 480, minHeight: 480,
title: 'voip.ms Messages', title: SANDBOX ? 'bubble (sandbox)' : 'bubble',
backgroundColor: '#1b1b1d', backgroundColor: windowBackground(),
autoHideMenuBar: true, autoHideMenuBar: true,
icon: path.join(__dirname, '../../resources/icon.png'), icon: path.join(__dirname, '../../resources/icon.png'),
webPreferences: { webPreferences: {
@@ -235,12 +614,32 @@ function createWindow(): void {
if (/^https?:/.test(url)) void shell.openExternal(url) if (/^https?:/.test(url)) void shell.openExternal(url)
} }
}) })
// Ctrl +/-/0 zoom (handled here so Ctrl+= works without Shift, and the
// default menu's accelerators don't double-step).
win.webContents.on('before-input-event', (e, input) => {
if (input.type !== 'keyDown' || !(input.control || input.meta) || input.alt) return
const level = win!.webContents.getZoomLevel()
if (input.key === '=' || input.key === '+' || input.code === 'NumpadAdd') setZoom(level + ZOOM_STEP)
else if (input.key === '-' || input.key === '_' || input.code === 'NumpadSubtract') setZoom(level - ZOOM_STEP)
else if (input.key === '0' || input.code === 'Numpad0') setZoom(0)
else return
e.preventDefault()
})
// Ctrl+scroll wheel / pinch.
win.webContents.on('zoom-changed', (_e, dir) => setZoom(win!.webContents.getZoomLevel() + (dir === 'in' ? ZOOM_STEP : -ZOOM_STEP)))
win.webContents.on('did-finish-load', () => win!.webContents.setZoomLevel(loadZoom()))
// The hidden Google Voice window would otherwise keep 'window-all-closed'
// from firing, leaving a windowless process holding the single-instance lock.
win.on('closed', () => {
win = undefined
app.quit()
})
if (process.env['ELECTRON_RENDERER_URL']) void win.loadURL(process.env['ELECTRON_RENDERER_URL']) if (process.env['ELECTRON_RENDERER_URL']) void win.loadURL(process.env['ELECTRON_RENDERER_URL'])
else void win.loadFile(path.join(__dirname, '../renderer/index.html')) else void win.loadFile(path.join(__dirname, '../renderer/index.html'))
} }
app.on('second-instance', () => { app.on('second-instance', () => {
if (win) { if (win && !win.isDestroyed()) {
if (win.isMinimized()) win.restore() if (win.isMinimized()) win.restore()
win.focus() win.focus()
} }
@@ -249,15 +648,26 @@ app.on('second-instance', () => {
app.whenReady().then(async () => { app.whenReady().then(async () => {
settings = loadSettings() settings = loadSettings()
db = new MessageDb(path.join(getDataDir(), 'messages.db')) db = new MessageDb(path.join(getDataDir(), 'messages.db'))
if (SANDBOX) seedDemo(db)
dids = JSON.parse(db.get('dids') ?? '[]') as Did[]
media = new MediaStore(path.join(getDataDir(), 'media'), db, (url) => {
if (!url.startsWith('gv:')) return net.fetch(url)
if (!gv) return Promise.reject(new Error('Google Voice is not connected'))
return gv.downloadMedia(url.slice(3))
})
applyTheme()
contacts = new ContactDirectory() contacts = new ContactDirectory()
contacts.on('changed', () => send('contactsChanged')) contacts.on('changed', () => send('contactsChanged'))
protocol.handle('contact-photo', servePhoto) protocol.handle('contact-photo', servePhoto)
protocol.handle('mms-media', serveMedia)
registerIpc() registerIpc()
createWindow() createWindow()
void contacts.load() // The sandbox stays away from the real address book.
if (!SANDBOX) void contacts.load()
const creds = loadCredentials() const creds = loadCredentials()
if (creds) startSync(creds) if (creds) startSync(creds)
if (gvNumber() && (await hasGvSession())) startGvSync()
void dailySnapshot() void dailySnapshot()
setInterval(() => void dailySnapshot(), 60 * 60 * 1000) setInterval(() => void dailySnapshot(), 60 * 60 * 1000)
@@ -269,6 +679,7 @@ app.on('before-quit', (e) => {
e.preventDefault() e.preventDefault()
quitting = true quitting = true
sync?.stop() sync?.stop()
stopGv()
contacts?.close() contacts?.close()
db.snapshot(snapshotDir()) db.snapshot(snapshotDir())
.catch((err) => console.error('[snapshot] on quit failed:', err)) .catch((err) => console.error('[snapshot] on quit failed:', err))
+79
View File
@@ -0,0 +1,79 @@
// MMS attachments cached on disk in <dataDir>/media, next to the database, so
// backups include them and they outlive voip.ms's copies. Files are named by
// content hash; messages reference them via MediaRef.file.
import { nativeImage, net } from 'electron'
import crypto from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
import { extFor, guessMime } from '@shared/mime'
import type { MediaRef } from '@shared/types'
import type { MessageDb, NewMessage } from './db'
export class MediaStore {
private inflight = new Map<string, Promise<MediaRef | undefined>>()
constructor(
readonly dir: string,
private db: MessageDb,
// How to fetch a MediaRef.url; Google Voice's gv:<id> refs need its session.
private fetchUrl: (url: string) => Promise<Response> = (url) => net.fetch(url)
) {}
filePath(file: string): string {
return path.join(this.dir, path.basename(file))
}
save(data: Uint8Array, mime: string): string {
const file = `${crypto.createHash('sha1').update(data).digest('hex')}.${extFor(mime)}`
fs.mkdirSync(this.dir, { recursive: true })
const dest = this.filePath(file)
if (!fs.existsSync(dest)) fs.writeFileSync(dest, data)
return file
}
// The local copy of attachment `index` of message `id`, downloading it first
// if we only have the provider's URL. Undefined when it can't be had.
async resolve(id: number, index: number): Promise<MediaRef | undefined> {
const ref = this.db.getMessage(id)?.media?.[index]
if (!ref) return undefined
if (ref.file && fs.existsSync(this.filePath(ref.file))) return ref
if (!ref.url) return undefined
const key = `${id}/${index}`
let p = this.inflight.get(key)
if (!p) {
p = this.download(id, index, ref.url).finally(() => this.inflight.delete(key))
this.inflight.set(key, p)
}
return p
}
private async download(id: number, index: number, url: string): Promise<MediaRef | undefined> {
try {
const res = await this.fetchUrl(url)
const header = res.headers.get('content-type')?.split(';')[0].trim()
// voip.ms answers expired/unknown media with a 200 HTML page.
if (!res.ok || header === 'text/html') return undefined
const mime = header && header !== 'application/octet-stream' ? header : (guessMime(url) ?? 'application/octet-stream')
const data = new Uint8Array(await res.arrayBuffer())
const file = this.save(data, mime)
// Remember the size so the chat can reserve space before the image loads.
const patch: MediaRef = { file, mime }
if (mime.startsWith('image/')) {
const size = nativeImage.createFromBuffer(Buffer.from(data)).getSize()
if (size.width) Object.assign(patch, size)
}
this.db.setMediaFile(id, index, patch)
return { url, ...patch }
} catch {
return undefined
}
}
// Cache attachments of freshly synced messages right away, one at a time.
prefetch(msgs: NewMessage[]): void {
const todo = msgs.flatMap((m) => (m.media ?? []).map((_, i) => [m.id, i] as const))
void (async () => {
for (const [id, i] of todo) await this.resolve(id, i)
})()
}
}
+81
View File
@@ -0,0 +1,81 @@
// New-message notifications. Sent at low urgency, which GNOME files straight
// into the notification list (click the clock) without a pop-up banner.
import { Notification } from 'electron'
import { formatNumber, groupMembers, isGroup } from '@shared/phone'
import type { ContactDirectory } from './contacts'
import type { MessageDb, NewMessage } from './db'
import { reactionPreview } from '@shared/reactions'
// Only messages this recent notify: history imports bring in old ones.
const RECENT = 10 * 60_000
export interface NotifyDeps {
db: MessageDb
contacts: ContactDirectory
onClick: (key: { did: string; contact: string }) => void
}
// Shown notifications by conversation, kept referenced so their click
// handlers survive garbage collection until GNOME dismisses them, and so
// reading the conversation in the app can take them back out of the list.
const live = new Map<string, Set<Notification>>()
const convKey = (did: string, contact: string): string => `${did}\n${contact}`
// The conversation's been read: its notifications are stale.
export function clearNotifications(did: string, contact: string): void {
const shown = live.get(convKey(did, contact))
if (!shown) return
live.delete(convKey(did, contact))
for (const n of shown) n.close()
}
const nameOf = (contacts: ContactDirectory, n: string): string => contacts.lookup(n)?.name ?? formatNumber(n)
export function conversationTitle(db: MessageDb, contacts: ContactDirectory, did: string, contact: string): string {
const own = db.getName(did, contact)
if (own) return own
if (!isGroup(contact)) return nameOf(contacts, contact)
return groupMembers(contact)
.map((n) => contacts.lookup(n)?.name.split(/\s+/)[0] ?? formatNumber(n))
.join(', ')
}
function preview(m: NewMessage): string {
const reaction = reactionPreview(m.body)
if (reaction) return reaction
const body = m.body.replace(/\s+/g, ' ').trim()
if (body) return body
return m.media?.length ? '📷 Photo' : ''
}
// One notification per conversation with new incoming messages.
export function notifyNew(msgs: NewMessage[], { db, contacts, onClick }: NotifyDeps, now = Date.now()): void {
if (!Notification.isSupported()) return
const byConv = new Map<string, NewMessage[]>()
for (const m of msgs) {
if (m.direction !== 'in' || m.ts < now - RECENT) continue
const key = convKey(m.did, m.contact)
byConv.set(key, [...(byConv.get(key) ?? []), m])
}
for (const list of byConv.values()) {
const last = list.reduce((a, b) => (b.ts > a.ts ? b : a))
const { did, contact } = last
const sender = isGroup(contact) && last.sender ? `${nameOf(contacts, last.sender).split(/\s+/)[0]}: ` : ''
const more = list.length > 1 ? ` (+${list.length - 1} more)` : ''
const n = new Notification({
title: conversationTitle(db, contacts, did, contact),
body: sender + preview(last) + more,
urgency: 'low'
})
const key = convKey(did, contact)
const shown = live.get(key) ?? new Set()
live.set(key, shown.add(n))
n.on('click', () => onClick({ did, contact }))
n.on('close', () => {
shown.delete(n)
if (!shown.size && live.get(key) === shown) live.delete(key)
})
n.show()
}
}
+266
View File
@@ -0,0 +1,266 @@
// Installing the Android app on a Rabbit R1 (or any Android device) over adb,
// with the accounts, history and chat names copied into its private storage,
// so it opens signed in and with everything already there.
//
// Files go in through `adb shell -T "run-as <pkg> ..."`: run-as needs the APK
// to be debuggable (android/build.py builds it that way), and shell -T (no
// pty) passes stdin through byte for byte, waits for the command to finish and
// returns its exit code. (exec-in does none of the last two: it ends the
// remote command as soon as stdin runs out.) Nothing secret touches the desktop's disk on
// the way: the accounts JSON is piped straight in.
import Database from 'better-sqlite3'
import { app } from 'electron'
import { spawn } from 'node:child_process'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import type { MessageDb, NameChange, ReadState } from './db'
export interface RabbitConfig {
sandbox?: boolean
voipms: { username: string; password: string } | null
gvoice: { number: string; cookies: Record<string, string> } | null
dids: Array<{ did: string; description: string }>
defaultDid?: string
}
export interface RabbitTarget {
pkg: string
apk: string
}
export interface DeviceInfo {
serial: string
model: string
installedVersion?: string
}
const ADB_DIRS = ['/usr/local/sbin', '/usr/local/bin', '/usr/bin', path.join(os.homedir(), 'Android/Sdk/platform-tools')]
export function findAdb(): string | undefined {
const dirs = [...(process.env['PATH'] ?? '').split(':'), ...ADB_DIRS]
return dirs.map((d) => path.join(d, 'adb')).find((f) => f && fs.existsSync(f))
}
// The APK shipped with the desktop app (android/build.py --ship).
export function bundledApk(): { apk: string; version?: string } | undefined {
const packaged = path.join(process.resourcesPath ?? '', 'android', 'VoipMessages.apk')
const dev = path.join(app.getAppPath(), 'resources', 'android', 'VoipMessages.apk')
const apk = [packaged, dev].find((f) => fs.existsSync(f))
if (!apk) return undefined
try {
const meta = JSON.parse(fs.readFileSync(apk.replace(/\.apk$/, '.json'), 'utf8')) as { version_name: string }
return { apk, version: meta.version_name }
} catch {
return { apk }
}
}
class Adb {
constructor(
readonly adb: string,
readonly serial: string
) {}
// Runs adb; resolves stdout. `input` is piped to stdin (a Buffer or a stream).
run(args: string[], input?: Buffer | NodeJS.ReadableStream, timeoutMs = 120_000): Promise<Buffer> {
return new Promise((resolve, reject) => {
const p = spawn(this.adb, this.serial ? ['-s', this.serial, ...args] : args)
const out: Buffer[] = []
const err: Buffer[] = []
const timer = setTimeout(() => p.kill(), timeoutMs)
p.stdout.on('data', (d: Buffer) => out.push(d))
p.stderr.on('data', (d: Buffer) => err.push(d))
p.on('error', reject)
p.on('close', (code) => {
clearTimeout(timer)
const stderr = Buffer.concat(err).toString().trim()
if (code === 0) resolve(Buffer.concat(out))
else reject(new Error(stderr.split('\n').pop() || `adb ${args[0]} failed (${code})`))
})
if (input instanceof Buffer) p.stdin.end(input)
else if (input) (input as NodeJS.ReadableStream).pipe(p.stdin)
else p.stdin.end()
})
}
async shell(cmd: string, timeoutMs?: number): Promise<string> {
return (await this.run(['shell', cmd], undefined, timeoutMs)).toString()
}
// A command run as the app (in its private data dir), fed `input`.
asApp(pkg: string, cmd: string, input?: Buffer | NodeJS.ReadableStream, timeoutMs?: number): Promise<Buffer> {
return this.run(['shell', '-T', `run-as ${pkg} sh -c ${shq(cmd)}`], input, timeoutMs)
}
readAsApp(pkg: string, file: string): Promise<Buffer> {
return this.run(['exec-out', `run-as ${pkg} sh -c ${shq(`cat ${file} 2>/dev/null || true`)}`])
}
}
const shq = (s: string): string => `'${s.replace(/'/g, `'\\''`)}'`
async function listDevices(adb: string): Promise<Array<{ serial: string; state: string; model: string }>> {
const out = await new Adb(adb, '').run(['devices', '-l']).catch(() => Buffer.from(''))
return out
.toString()
.split('\n')
.slice(1)
.map((l) => l.trim())
.filter(Boolean)
.map((l) => {
const [serial, state] = l.split(/\s+/)
const model = /model:(\S+)/.exec(l)?.[1]?.replace(/_/g, ' ') ?? serial
return { serial, state, model }
})
}
export async function connect(): Promise<Adb> {
const adb = findAdb()
if (!adb) throw new Error("adb isn't installed on this computer.")
const devices = await listDevices(adb)
const ready = devices.find((d) => d.state === 'device')
if (ready) return new Adb(adb, ready.serial)
if (devices.some((d) => d.state === 'unauthorized')) throw new Error('Unlock the Rabbit and allow USB debugging for this computer.')
throw new Error('No Rabbit connected. Plug it in over USB (with USB debugging on).')
}
export async function status(pkg: string): Promise<DeviceInfo | undefined> {
const adb = findAdb()
if (!adb) return undefined
const ready = (await listDevices(adb)).find((d) => d.state === 'device')
if (!ready) return undefined
const a = new Adb(adb, ready.serial)
const info = await a.shell(`dumpsys package ${pkg} | grep -m1 versionName`).catch(() => '')
const version = /versionName=(\S+)/.exec(info)?.[1]
return { serial: ready.serial, model: ready.model, ...(version ? { installedVersion: version } : {}) }
}
// A copy of the history the Android app can open: its SQLite has no FTS5,
// so the search index (and the triggers that feed it) come out.
async function historyCopy(db: MessageDb): Promise<string> {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'voip-rabbit-'))
const file = path.join(dir, 'messages.db')
await db.db.backup(file)
const copy = new Database(file)
copy.exec(`
DROP TRIGGER IF EXISTS messages_ai; DROP TRIGGER IF EXISTS messages_ad; DROP TRIGGER IF EXISTS messages_au;
DROP TABLE IF EXISTS messages_fts;
`)
copy.pragma('journal_mode = DELETE')
copy.exec('VACUUM')
copy.close()
return file
}
// Merge chat names and read/unread/archived state both ways: the Rabbit's
// (files/state.json, which the app keeps current) into the desktop, then the
// combined result back (files/state-in.json, applied by the app on its next
// start or check). Newest change wins on each side. Returns how many
// conversations changed here.
interface SyncState {
names: NameChange[]
read: ReadState[]
}
async function syncState(a: Adb, pkg: string, db: MessageDb): Promise<number> {
const raw = (await a.readAsApp(pkg, 'files/state.json')).toString().trim()
let theirs: SyncState = { names: [], read: [] }
try {
if (raw) theirs = { names: [], read: [], ...(JSON.parse(raw) as Partial<SyncState>) }
} catch {
/* a half-written file: skip this round */
}
const changed = db.namesImport(theirs.names) + db.readStateImport(theirs.read)
const ours: SyncState = { names: db.namesExport(), read: db.readStateExport() }
await a.asApp(pkg, 'umask 077 && cat > files/state-in.json.tmp && mv files/state-in.json.tmp files/state-in.json', Buffer.from(JSON.stringify(ours)))
return changed
}
export type Progress = (step: string) => void
export interface InstallDeps {
db: MessageDb
mediaDir: string
target: RabbitTarget
config: () => Promise<RabbitConfig>
progress: Progress
}
async function pushConfig(a: Adb, pkg: string, cfg: RabbitConfig): Promise<void> {
// Straight from memory into the app's private files: no temp file.
await a.asApp(pkg, 'mkdir -p files && umask 077 && cat > files/config.json.tmp && mv files/config.json.tmp files/config.json', Buffer.from(JSON.stringify(cfg)))
}
async function lockDown(a: Adb, pkg: string): Promise<void> {
await a.asApp(pkg, 'chmod -R go-rwx files')
}
// Fresh install (or reinstall): app, permissions, accounts, history, photos, names.
// Photos the Rabbit doesn't have yet (files are named by content hash, so a
// name it already has is the same file). Returns how many were sent.
async function copyMedia(a: Adb, pkg: string, mediaDir: string, progress: Progress): Promise<number> {
if (!fs.existsSync(mediaDir)) return 0
const have = new Set((await a.asApp(pkg, 'mkdir -p files/media && ls files/media')).toString().split('\n').map((l) => l.trim()))
const missing = fs.readdirSync(mediaDir).filter((f) => !have.has(f) && fs.statSync(path.join(mediaDir, f)).isFile())
if (!missing.length) return 0
progress(`Copying ${missing.length.toLocaleString()} photo${missing.length === 1 ? '' : 's'} and attachments…`)
const tar = spawn('tar', ['-C', mediaDir, '-cf', '-', '-T', '-'])
tar.stdin.end(missing.join('\n') + '\n')
await a.asApp(pkg, 'cd files/media && tar xf -', tar.stdout, 1_800_000)
return missing.length
}
// 'full': the app plus history and photos (first install, or starting over;
// only photos the Rabbit lacks are sent). 'update': just the new app version
// -- Android keeps the app's data across an update -- plus accounts and the
// names / read-status merge.
export async function install({ db, mediaDir, target, config, progress, mode = 'full' }: InstallDeps & { mode?: 'full' | 'update' }): Promise<number> {
const { pkg, apk } = target
progress('Connecting to the Rabbit…')
const a = await connect()
progress('Installing the app…')
await a.run(['install', '-r', '-g', apk], undefined, 300_000)
// Background checks: exempt from Doze and background limits.
await a.shell(`dumpsys deviceidle whitelist +${pkg}`).catch(() => undefined)
await a.shell(`cmd appops set ${pkg} RUN_ANY_IN_BACKGROUND allow`).catch(() => undefined)
await a.shell(`am force-stop ${pkg}`)
progress('Copying your accounts…')
await pushConfig(a, pkg, await config())
if (mode === 'full') {
progress('Copying your message history…')
const history = await historyCopy(db)
try {
await a.asApp(pkg, 'rm -f files/messages.db files/messages.db-wal files/messages.db-shm files/messages.db-journal')
await a.asApp(pkg, 'umask 077 && cat > files/messages.db', fs.createReadStream(history), 600_000)
} finally {
fs.rmSync(path.dirname(history), { recursive: true, force: true })
}
await copyMedia(a, pkg, mediaDir, progress)
}
progress('Syncing chat names and read status…')
const names = await syncState(a, pkg, db)
await lockDown(a, pkg)
progress('Opening it on the Rabbit…')
await a.shell(`am start -n ${pkg}/me.teafry.voipmessages.MainActivity`)
return names
}
// Accounts and chat names again (e.g. after reconnecting Google Voice), without
// touching the app or its history. Returns how many names changed here.
export async function sync({ db, target, config, progress }: Omit<InstallDeps, 'mediaDir'>): Promise<number> {
const { pkg } = target
progress('Connecting to the Rabbit…')
const a = await connect()
const installed = await a.shell(`pm path ${pkg}`).catch(() => '')
if (!installed.trim()) throw new Error("The app isn't on the Rabbit yet. Use Install to Rabbit first.")
progress('Copying your accounts…')
await pushConfig(a, pkg, await config())
progress('Syncing chat names and read status…')
const names = await syncState(a, pkg, db)
await lockDown(a, pkg)
return names
}
+74
View File
@@ -0,0 +1,74 @@
// Sandbox mode, for trying the app (and UI work) without going anywhere near
// the real account: VOIPMS_SANDBOX=<dir> (or VOIPMS_DEMO=1, which uses a temp
// dir) keeps *everything* under <dir> -- the Electron profile (so no saved
// voip.ms password and no Google sign-in), settings, and the message database
// -- skips the system address book, and fills an empty database with made-up
// conversations. Imported first by index.ts so it applies before anything
// reads a path.
import { app } from 'electron'
import os from 'node:os'
import path from 'node:path'
import type { MessageDb, NewMessage } from './db'
import { gvMessageId } from './gvoice/sync'
export const SANDBOX: string | undefined =
process.env['VOIPMS_SANDBOX'] || (process.env['VOIPMS_DEMO'] ? path.join(os.tmpdir(), 'voipms-sandbox') : undefined)
if (SANDBOX) {
app.setPath('userData', path.join(SANDBOX, 'profile'))
process.env['VOIPMS_DATA_DIR'] = path.join(SANDBOX, 'data')
console.log(`[sandbox] everything lives in ${SANDBOX}`)
} else {
// The app was "voip.ms Messages" before it was bubble, and Electron names
// the profile folder after the app: keep using the old one so the saved
// login, Google sign-in and data-location pointer carry over.
app.setPath('userData', path.join(app.getPath('appData'), 'voip.ms Messages'))
}
// Fictional numbers (555-01xx is reserved for fiction).
export const DEMO_VOIP = '5415550100'
export const DEMO_GV = '5415550177'
export function seedDemo(db: MessageDb): void {
if (db.count() > 0) return
const now = Date.now()
const min = 60_000
const group = '5415550101,5415550102,5415550103'
let id = 1000
const v = (contact: string, direction: 'in' | 'out', body: string, ago: number): NewMessage => ({
id: id++,
did: DEMO_VOIP,
contact,
direction,
body,
ts: now - ago * min
})
const g = (contact: string, direction: 'in' | 'out', body: string, ago: number, sender?: string): NewMessage => ({
id: gvMessageId(`demo-${id++}`),
did: DEMO_GV,
contact,
direction,
body,
ts: now - ago * min,
...(sender ? { sender } : {})
})
db.upsertMessages([
v('5415550110', 'in', 'Are we still on for Saturday?', 300),
v('5415550110', 'out', 'Yep! 10am at the market', 290),
v('5415550111', 'in', 'Your table is ready', 2000),
g('5415550120', 'in', 'Package left at the front door', 90),
g('5415550120', 'out', 'Thanks!', 85),
g(group, 'in', 'Who is bringing snacks to the hike?', 40, '5415550101'),
g(group, 'in', 'I can do chips', 38, '5415550102'),
g(group, 'in', 'and salsa', 37, '5415550102'),
g(group, 'out', 'I’ll bring cookies 🍪', 30),
g(group, 'in', 'Loved “I’ll bring cookies 🍪”', 29, '5415550101'),
g(group, 'in', 'Laughed at “I’ll bring cookies 🍪”', 28, '5415550103'),
g(group, 'in', 'Perfect, see everyone at 9', 5, '5415550103'),
g(group, 'in', 'Emphasized “Perfect, see everyone at 9”', 4, '5415550102')
])
db.setGvThread(DEMO_GV, group, 'g.demo')
db.set('unread_floor', '0')
db.set('gv_number', DEMO_GV)
db.set('dids', JSON.stringify([{ did: DEMO_VOIP, description: 'Demo', smsEnabled: true }]))
}
+57
View File
@@ -0,0 +1,57 @@
// Sending one message, retrying when it's safe to.
import type { MessageDb } from './db'
import { classifySendError, sendErrorMessage, type SendFailure } from './voipms'
const MAX_ATTEMPTS = 3
// Pause before sending again after an attempt that certainly didn't go out.
const RETRY_DELAYS = [3000, 10_000]
// After an attempt that may have gone out (no reply), look for it in the
// listing at these points before sending again.
const CHECK_DELAYS = [5000, 15_000]
export interface SendDeps {
db: Pick<MessageDb, 'getMessage' | 'confirmPending' | 'markFailed'>
// One attempt; resolves with the id voip.ms assigned.
attempt: () => Promise<number>
// Fetch recent messages, which replaces the local copy of anything that
// turns out to have been sent (MessageDb.reconcileSent).
checkSent: () => Promise<void>
sleep?: (ms: number) => Promise<void>
// How to read the provider's errors (default: voip.ms's).
classify?: (e: unknown) => SendFailure
describe?: (e: unknown) => string
}
const wait = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
// Delivers pending message `tempId`; never throws. On giving up the message
// is marked failed with the reason.
export async function sendWithRetry(
tempId: number,
{ db, attempt, checkSent, sleep = wait, classify = classifySendError, describe = sendErrorMessage }: SendDeps
): Promise<void> {
// A poll found the message already sent and replaced our local copy.
const sent = (): boolean => !db.getMessage(tempId)
for (let n = 1; ; n++) {
try {
db.confirmPending(tempId, await attempt())
return
} catch (e) {
if (sent()) return
const kind = classify(e)
if (kind === 'unknown') {
for (const ms of CHECK_DELAYS) {
await sleep(ms)
await checkSent().catch(() => undefined)
if (sent()) return
}
}
if (kind === 'fatal' || n >= MAX_ATTEMPTS) {
db.markFailed(tempId, describe(e))
return
}
if (kind === 'safe') await sleep(RETRY_DELAYS[n - 1] ?? RETRY_DELAYS.at(-1)!)
if (sent()) return
}
}
}
+3 -1
View File
@@ -11,7 +11,9 @@ import type { Settings } from '@shared/types'
const DEFAULTS: Settings = { const DEFAULTS: Settings = {
pollSeconds: 30, pollSeconds: 30,
dids: [], dids: [],
backfillFloor: '2010-01-01' backfillFloor: '2010-01-01',
theme: 'system',
notifications: true
} }
const pointerFile = (): string => path.join(app.getPath('userData'), 'data-location.json') const pointerFile = (): string => path.join(app.getPath('userData'), 'data-location.json')
+26 -11
View File
@@ -2,7 +2,7 @@
import { EventEmitter } from 'node:events' import { EventEmitter } from 'node:events'
import type { MessageDb, NewMessage } from './db' import type { MessageDb, NewMessage } from './db'
import { parseVoipDate, type RawSms, type VoipMs } from './voipms' import { parseVoipDate, type RawSms, type VoipMs } from './voipms'
import { normalizeNumber } from '@shared/phone' import { charCount, normalizeNumber, SMS_TEXT_LIMIT } from '@shared/phone'
import type { SyncStatus } from '@shared/types' import type { SyncStatus } from '@shared/types'
const WINDOW_DAYS = 90 const WINDOW_DAYS = 90
@@ -19,7 +19,7 @@ function parseYmd(s: string): number {
} }
export function toNewMessage(r: RawSms): NewMessage { export function toNewMessage(r: RawSms): NewMessage {
return { const m: NewMessage = {
id: Number(r.id), id: Number(r.id),
did: normalizeNumber(r.did), did: normalizeNumber(r.did),
contact: normalizeNumber(r.contact), contact: normalizeNumber(r.contact),
@@ -27,12 +27,23 @@ export function toNewMessage(r: RawSms): NewMessage {
body: r.message ?? '', body: r.message ?? '',
ts: parseVoipDate(r.date) ts: parseVoipDate(r.date)
} }
// With all_messages=1 every row carries the media columns, SMS included, so
// only rows that actually have media count as MMS -- or text too long for
// one SMS, which voip.ms carries as a text-only MMS.
const urls = (r.media?.length ? r.media : [r.col_media1, r.col_media2, r.col_media3]).filter((u): u is string => !!u)
if (urls.length) {
m.kind = 'mms'
m.media = urls.map((url) => ({ url }))
} else if (charCount(m.body) > SMS_TEXT_LIMIT) {
m.kind = 'mms'
}
return m
} }
// Fetch every message in [from, to] (inclusive days), halving the range if a // Fetch every message in [from, to] (inclusive days), halving the range if a
// single call comes back full so nothing gets truncated. // single call comes back full so nothing gets truncated.
export async function fetchRange(api: Pick<VoipMs, 'getSms'>, from: number, to: number, limit = PAGE_LIMIT): Promise<RawSms[]> { export async function fetchRange(api: Pick<VoipMs, 'getMessages'>, from: number, to: number, limit = PAGE_LIMIT): Promise<RawSms[]> {
const rows = await api.getSms({ from: ymd(from), to: ymd(to), limit }) const rows = await api.getMessages({ from: ymd(from), to: ymd(to), limit })
if (rows.length < limit || to - from < DAY) return rows if (rows.length < limit || to - from < DAY) return rows
const mid = from + Math.floor((to - from) / DAY / 2) * DAY const mid = from + Math.floor((to - from) / DAY / 2) * DAY
const a = await fetchRange(api, from, mid, limit) const a = await fetchRange(api, from, mid, limit)
@@ -51,7 +62,7 @@ export class SyncEngine extends EventEmitter {
private burstUntil = 0 private burstUntil = 0
private running = false private running = false
private backfilling = false private backfilling = false
private polling = false private polling?: Promise<void>
private status: SyncStatus private status: SyncStatus
constructor( constructor(
@@ -81,6 +92,7 @@ export class SyncEngine extends EventEmitter {
const wanted = new Set(this.opts.dids.map(normalizeNumber)) const wanted = new Set(this.opts.dids.map(normalizeNumber))
const msgs = raw.map(toNewMessage).filter((m) => wanted.size === 0 || wanted.has(m.did)) const msgs = raw.map(toNewMessage).filter((m) => wanted.size === 0 || wanted.has(m.did))
const added = this.db.upsertMessages(msgs) const added = this.db.upsertMessages(msgs)
this.db.reconcileSent(added)
if (added.length) this.emit('messages', added) if (added.length) this.emit('messages', added)
} }
@@ -112,22 +124,25 @@ export class SyncEngine extends EventEmitter {
}, d) }, d)
} }
// Manual refresh. Joins a check that's already under way rather than
// returning early, so the caller knows when fresh results are in.
async pollNow(): Promise<void> { async pollNow(): Promise<void> {
await this.poll() await this.poll()
} }
private async poll(): Promise<void> { private poll(): Promise<void> {
if (this.polling) return this.polling ??= this.fetchRecent().finally(() => (this.polling = undefined))
this.polling = true return this.polling
}
private async fetchRecent(): Promise<void> {
try { try {
const now = Date.now() const now = Date.now()
const rows = await this.api.getSms({ from: ymd(now - DAY), to: ymd(now + DAY), limit: PAGE_LIMIT }) const rows = await this.api.getMessages({ from: ymd(now - DAY), to: ymd(now + DAY), limit: PAGE_LIMIT })
this.store(rows) this.store(rows)
this.setStatus({ lastPoll: Date.now(), error: undefined, phase: this.backfilling ? 'backfill' : 'polling' }) this.setStatus({ lastPoll: Date.now(), error: undefined, phase: this.backfilling ? 'backfill' : 'polling' })
} catch (e) { } catch (e) {
this.setStatus({ phase: 'error', error: (e as Error).message }) this.setStatus({ phase: 'error', error: (e as Error).message })
} finally {
this.polling = false
} }
} }
+27
View File
@@ -0,0 +1,27 @@
// Per-machine window state (not a synced preference, so kept out of settings.json).
import { app } from 'electron'
import fs from 'node:fs'
import path from 'node:path'
interface UiState {
zoom?: number
}
const file = (): string => path.join(app.getPath('userData'), 'ui-state.json')
function load(): UiState {
try {
return JSON.parse(fs.readFileSync(file(), 'utf8')) as UiState
} catch {
return {}
}
}
export function loadZoom(): number {
return load().zoom ?? 0
}
export function saveZoom(zoom: number): void {
fs.mkdirSync(path.dirname(file()), { recursive: true })
fs.writeFileSync(file(), JSON.stringify({ ...load(), zoom }, null, 2))
}
+91 -14
View File
@@ -10,6 +10,11 @@ export interface RawSms {
did: string did: string
contact: string contact: string
message: string message: string
// getMMS only: up to three media URLs ("" when unused).
media?: string[]
col_media1?: string
col_media2?: string
col_media3?: string
} }
const FRIENDLY_ERRORS: Record<string, string> = { const FRIENDLY_ERRORS: Record<string, string> = {
@@ -20,7 +25,12 @@ const FRIENDLY_ERRORS: Record<string, string> = {
sms_toolong: 'Message is too long.', sms_toolong: 'Message is too long.',
invalid_dst: 'Invalid destination number.', invalid_dst: 'Invalid destination number.',
invalid_did: 'That DID is not valid on your account.', invalid_did: 'That DID is not valid on your account.',
sms_failed: 'voip.ms failed to send the message.' sms_failed: 'voip.ms failed to send the message.',
mms_failed: 'voip.ms failed to send the MMS.',
mms_toolong: 'Message is too long for an MMS (2048 characters max).',
invalid_media: 'voip.ms rejected the attachment (unsupported type or too large).',
media_toolarge: 'The attachment is too large for voip.ms MMS.',
not_signed_in: 'Not signed in.'
} }
export class VoipMsError extends Error { export class VoipMsError extends Error {
@@ -29,18 +39,29 @@ export class VoipMsError extends Error {
} }
} }
function toFormData(params: URLSearchParams): FormData {
const fd = new FormData()
for (const [k, v] of params) fd.set(k, v)
return fd
}
export class VoipMs { export class VoipMs {
constructor(private creds: Credentials) {} constructor(private creds: Credentials) {}
private async call<T>(method: string, params: Record<string, string | number | undefined> = {}): Promise<T> { // POST sends params as a multipart form body: needed for base64 media, which
const url = new URL(ENDPOINT) // is far too big for a query string. (voip.ms routes urlencoded POSTs to its
url.searchParams.set('api_username', this.creds.username) // SOAP endpoint, which answers with a 500 fault — multipart is required.)
url.searchParams.set('api_password', this.creds.password) private async call<T>(method: string, params: Record<string, string | number | undefined> = {}, post = false): Promise<T> {
url.searchParams.set('method', method) const form = new URLSearchParams()
form.set('api_username', this.creds.username)
form.set('api_password', this.creds.password)
form.set('method', method)
for (const [k, v] of Object.entries(params)) { for (const [k, v] of Object.entries(params)) {
if (v !== undefined && v !== '') url.searchParams.set(k, String(v)) if (v !== undefined && v !== '') form.set(k, String(v))
} }
const res = await fetch(url, { signal: AbortSignal.timeout(60_000) }) const res = post
? await fetch(ENDPOINT, { method: 'POST', body: toFormData(form), signal: AbortSignal.timeout(120_000) })
: await fetch(`${ENDPOINT}?${form}`, { signal: AbortSignal.timeout(method.startsWith('send') ? 120_000 : 60_000) })
if (!res.ok) throw new Error(`voip.ms HTTP ${res.status}`) if (!res.ok) throw new Error(`voip.ms HTTP ${res.status}`)
const json = (await res.json()) as { status: string } & T const json = (await res.json()) as { status: string } & T
if (json.status !== 'success') throw new VoipMsError(json.status) if (json.status !== 'success') throw new VoipMsError(json.status)
@@ -56,30 +77,86 @@ export class VoipMs {
})) }))
} }
// getMMS with all_messages=1 returns SMS *and* MMS in one listing, with
// absolute media URLs (getSMS only gives relative ones). SMS and MMS ids come
// from separate sequences but live in disjoint ranges (~1e8 vs ~1e7).
// Returns [] when voip.ms reports no messages for the range. // Returns [] when voip.ms reports no messages for the range.
async getSms(opts: { from: string; to: string; did?: string; limit?: number }): Promise<RawSms[]> { async getMessages(opts: { from: string; to: string; did?: string; limit?: number }): Promise<RawSms[]> {
try { try {
const r = await this.call<{ sms: RawSms[] }>('getSMS', { const r = await this.call<{ sms: RawSms[] }>('getMMS', {
from: opts.from, from: opts.from,
to: opts.to, to: opts.to,
did: opts.did, did: opts.did,
limit: opts.limit ?? 10000, limit: opts.limit ?? 10000,
timezone: 0 timezone: 0,
all_messages: 1
}) })
return r.sms ?? [] return r.sms ?? []
} catch (e) { } catch (e) {
if (e instanceof VoipMsError && e.status === 'no_sms') return [] if (e instanceof VoipMsError && (e.status === 'no_sms' || e.status === 'no_mms')) return []
throw e throw e
} }
} }
// media: data URLs ("data:image/jpeg;base64,...") or public URLs, max 3.
async sendMms(did: string, dst: string, message: string, media: string[]): Promise<number> {
const params: Record<string, string> = { did, dst, message }
media.slice(0, 3).forEach((m, i) => (params[`media${i + 1}`] = m))
const r = await this.call<{ mms: number | string }>('sendMMS', params, true)
return Number(r.mms)
}
async sendSms(did: string, dst: string, message: string): Promise<number> { async sendSms(did: string, dst: string, message: string): Promise<number> {
const r = await this.call<{ sms: number | string }>('sendSMS', { did, dst, message }) const r = await this.call<{ sms: number | string }>('sendSMS', { did, dst, message })
return Number(r.sms) return Number(r.sms)
} }
} }
// "2024-01-02 03:04:05" (UTC) -> epoch ms // How a failed send should be handled:
// fatal - voip.ms rejected it; sending again won't help.
// safe - it definitely didn't go out; send again.
// unknown - it may have gone out (e.g. we gave up waiting for the reply);
// check the listing before sending again, or it arrives twice.
export type SendFailure = 'fatal' | 'safe' | 'unknown'
// Network errors raised before the request reached voip.ms.
const NOT_SENT_CODES = new Set(['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH'])
export function classifySendError(e: unknown): SendFailure {
if (e instanceof VoipMsError) return e.status === 'sms_failed' || e.status === 'mms_failed' ? 'safe' : 'fatal'
const code = ((e as { cause?: { code?: string } })?.cause?.code) ?? (e as { code?: string })?.code
if (code && NOT_SENT_CODES.has(code)) return 'safe'
return 'unknown'
}
// A short explanation to show on a message that couldn't be sent.
export function sendErrorMessage(e: unknown): string {
const err = e as Error
if (err?.name === 'TimeoutError' || err?.name === 'AbortError') return "voip.ms didn't respond in time."
if (err instanceof VoipMsError) return err.message
const code = (err as { cause?: { code?: string } })?.cause?.code
if (code && NOT_SENT_CODES.has(code)) return "Couldn't reach voip.ms. Check your internet connection."
if (err?.message === 'fetch failed') return 'The connection to voip.ms was interrupted.'
return err?.message || String(e)
}
// voip.ms's `timezone` parameter adds its own daylight-saving hour: asking for
// timezone=0 returns UTC+1 for any message dated inside *US* daylight time
// (verified against messages with known send times; winter dates are exact).
// Undo that hour so stored times are true UTC.
const HOUR = 3_600_000
const easternOffset = new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', timeZoneName: 'shortOffset' })
function isUsDst(ms: number): boolean {
return easternOffset.formatToParts(ms).find((p) => p.type === 'timeZoneName')?.value === 'GMT-4'
}
// A time voip.ms reported for timezone=0 (as epoch ms) -> the real instant.
export function fixVoipDst(ms: number): number {
return isUsDst(ms - HOUR) ? ms - HOUR : ms
}
// "2024-01-02 03:04:05" (fetched with timezone=0) -> epoch ms UTC
export function parseVoipDate(s: string): number { export function parseVoipDate(s: string): number {
return Date.parse(s.replace(' ', 'T') + 'Z') return fixVoipDst(Date.parse(s.replace(' ', 'T') + 'Z'))
} }
+23 -2
View File
@@ -12,16 +12,35 @@ const api: Api = {
testCredentials: (creds) => ipcRenderer.invoke('testCredentials', creds), testCredentials: (creds) => ipcRenderer.invoke('testCredentials', creds),
saveSetup: (creds, settings) => ipcRenderer.invoke('saveSetup', creds, settings), saveSetup: (creds, settings) => ipcRenderer.invoke('saveSetup', creds, settings),
updateSettings: (settings) => ipcRenderer.invoke('updateSettings', settings), updateSettings: (settings) => ipcRenderer.invoke('updateSettings', settings),
setTheme: (theme) => ipcRenderer.invoke('setTheme', theme),
signOut: () => ipcRenderer.invoke('signOut'), signOut: () => ipcRenderer.invoke('signOut'),
connectGoogleVoice: () => ipcRenderer.invoke('connectGoogleVoice'),
connectGoogleVoiceCookies: (text) => ipcRenderer.invoke('connectGoogleVoiceCookies', text),
disconnectGoogleVoice: () => ipcRenderer.invoke('disconnectGoogleVoice'),
rabbitStatus: () => ipcRenderer.invoke('rabbitStatus'),
rabbitInstall: (mode) => ipcRenderer.invoke('rabbitInstall', mode),
rabbitSync: () => ipcRenderer.invoke('rabbitSync'),
onRabbitProgress: (cb) => on('rabbitProgress', cb),
listContacts: () => ipcRenderer.invoke('listContacts'), listContacts: () => ipcRenderer.invoke('listContacts'),
listAddressBooks: () => ipcRenderer.invoke('listAddressBooks'),
addContact: (c) => ipcRenderer.invoke('addContact', c),
listConversations: () => ipcRenderer.invoke('listConversations'), listConversations: () => ipcRenderer.invoke('listConversations'),
getMessages: (did, contact) => ipcRenderer.invoke('getMessages', did, contact), getMessages: (did, contact) => ipcRenderer.invoke('getMessages', did, contact),
markRead: (did, contact) => ipcRenderer.invoke('markRead', did, contact), markRead: (did, contact) => ipcRenderer.invoke('markRead', did, contact),
markUnread: (did, contact) => ipcRenderer.invoke('markUnread', did, contact),
setArchived: (did, contact, archived) => ipcRenderer.invoke('setArchived', did, contact, archived),
setName: (did, contact, name) => ipcRenderer.invoke('setName', did, contact, name),
getDrafts: () => ipcRenderer.invoke('getDrafts'),
setDraft: (contact, text) => ipcRenderer.invoke('setDraft', contact, text),
search: (query, scope) => ipcRenderer.invoke('search', query, scope), search: (query, scope) => ipcRenderer.invoke('search', query, scope),
send: (did, contact, text) => ipcRenderer.invoke('send', did, contact, text), send: (did, contact, text, attachments) => ipcRenderer.invoke('send', did, contact, text, attachments),
deleteFailed: (id) => ipcRenderer.invoke('deleteFailed', id), deleteFailed: (id) => ipcRenderer.invoke('deleteFailed', id),
retryFailed: (id) => ipcRenderer.invoke('retryFailed', id), retryFailed: (id) => ipcRenderer.invoke('retryFailed', id),
saveMedia: (id, index) => ipcRenderer.invoke('saveMedia', id, index),
exportChat: (did, contact, opts) => ipcRenderer.invoke('exportChat', did, contact, opts),
readMedia: (id, index) => ipcRenderer.invoke('readMedia', id, index),
copyImage: (png) => ipcRenderer.invoke('copyImage', png),
syncStatus: () => ipcRenderer.invoke('syncStatus'), syncStatus: () => ipcRenderer.invoke('syncStatus'),
pollNow: () => ipcRenderer.invoke('pollNow'), pollNow: () => ipcRenderer.invoke('pollNow'),
@@ -32,7 +51,9 @@ const api: Api = {
onMessages: (cb) => on('messages', cb), onMessages: (cb) => on('messages', cb),
onConversationsChanged: (cb) => on('conversationsChanged', cb), onConversationsChanged: (cb) => on('conversationsChanged', cb),
onSyncStatus: (cb) => on('syncStatus', cb), onSyncStatus: (cb) => on('syncStatus', cb),
onContactsChanged: (cb) => on('contactsChanged', cb) onContactsChanged: (cb) => on('contactsChanged', cb),
onStateChanged: (cb) => on('stateChanged', cb),
onOpenConversation: (cb) => on('openConversation', cb)
} }
contextBridge.exposeInMainWorld('api', api) contextBridge.exposeInMainWorld('api', api)
+2 -2
View File
@@ -2,10 +2,10 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<title>voip.ms Messages</title> <title>bubble</title>
<meta <meta
http-equiv="Content-Security-Policy" http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: contact-photo:; connect-src 'self' ws://localhost:*" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: contact-photo: mms-media:; media-src 'self' blob: mms-media:; connect-src 'self' ws://localhost:*"
/> />
</head> </head>
<body> <body>
+51 -9
View File
@@ -5,6 +5,9 @@ import { Sidebar, type SidebarMode } from './components/Sidebar'
import { ChatView } from './components/ChatView' import { ChatView } from './components/ChatView'
import { Setup } from './components/Setup' import { Setup } from './components/Setup'
import { SettingsDialog } from './components/SettingsDialog' import { SettingsDialog } from './components/SettingsDialog'
import { ConversationInfo } from './components/ConversationInfo'
import { AddContact, AddContactContext } from './components/AddContact'
import { ExportChat } from './components/ExportChat'
export interface ConvKey { export interface ConvKey {
did: string did: string
@@ -30,6 +33,10 @@ 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 [archiveView, setArchiveView] = useState(false)
const [info, setInfo] = useState<ConvKey | null>(null)
const [exporting, setExporting] = useState<ConvKey | null>(null)
const [adding, setAdding] = useState<string | null>(null)
const refreshState = useCallback(() => void window.api.getState().then(setState), []) const refreshState = useCallback(() => void window.api.getState().then(setState), [])
const refreshConversations = useCallback(() => { const refreshConversations = useCallback(() => {
@@ -46,17 +53,26 @@ export function App() {
const offs = [ const offs = [
window.api.onConversationsChanged(refreshConversations), window.api.onConversationsChanged(refreshConversations),
window.api.onContactsChanged(refreshContacts), window.api.onContactsChanged(refreshContacts),
window.api.onSyncStatus(setSync) window.api.onStateChanged(refreshState),
window.api.onSyncStatus(setSync),
// Clicked in the notification list.
window.api.onOpenConversation((key) => {
setMode('chats')
setSelected(key)
setJump(undefined)
})
] ]
return () => offs.forEach((off) => off()) return () => offs.forEach((off) => off())
}, [refreshState, refreshConversations, refreshContacts]) }, [refreshState, refreshConversations, refreshContacts])
const contactMap = useMemo(() => new Map(contacts.map((c) => [c.number, c])), [contacts]) const contactMap = useMemo(() => new Map(contacts.map((c) => [c.number, c])), [contacts])
const named = (key: ConvKey | null): string | undefined => conversations.find((c) => sameConv(c, key))?.name
const smsDids = useMemo(() => { const smsDids = useMemo(() => {
const all = state?.dids.filter((d) => d.smsEnabled) ?? [] const all = state?.dids.filter((d) => d.smsEnabled) ?? []
const chosen = state?.settings.dids ?? [] const chosen = state?.settings.dids ?? []
return chosen.length ? all.filter((d) => chosen.includes(d.did)) : all // The sync list is voip.ms's; Google Voice is on whenever it's connected.
return chosen.length ? all.filter((d) => d.provider === 'gvoice' || chosen.includes(d.did)) : all
}, [state]) }, [state])
const open = useCallback((key: ConvKey, jumpTo?: number) => { const open = useCallback((key: ConvKey, jumpTo?: number) => {
@@ -64,6 +80,12 @@ export function App() {
setJump(jumpTo !== undefined ? { id: jumpTo, nonce: Date.now() } : undefined) setJump(jumpTo !== undefined ? { id: jumpTo, nonce: Date.now() } : undefined)
}, []) }, [])
// An open chat would immediately mark itself read again, so close it.
const onMarkUnread = useCallback((key: ConvKey) => setSelected((cur) => (sameConv(cur, key) ? null : cur)), [])
// The list currently shown in the sidebar (for Alt+↑/↓).
const listed = useMemo(() => conversations.filter((c) => c.archived === archiveView), [conversations, archiveView])
// Keyboard shortcuts (Signal-like). // Keyboard shortcuts (Signal-like).
useEffect(() => { useEffect(() => {
const onKey = (e: KeyboardEvent): void => { const onKey = (e: KeyboardEvent): void => {
@@ -75,21 +97,22 @@ export function App() {
} else if (mod && e.key.toLowerCase() === 'n') { } else if (mod && e.key.toLowerCase() === 'n') {
e.preventDefault() e.preventDefault()
setMode('compose') setMode('compose')
} else if (e.altKey && (e.key === 'ArrowDown' || e.key === 'ArrowUp') && conversations.length) { } else if (e.altKey && (e.key === 'ArrowDown' || e.key === 'ArrowUp') && listed.length) {
e.preventDefault() e.preventDefault()
const i = conversations.findIndex((c) => sameConv(c, selected)) const i = listed.findIndex((c) => sameConv(c, selected))
const next = e.key === 'ArrowDown' ? Math.min(conversations.length - 1, i + 1) : Math.max(0, i - 1) const next = e.key === 'ArrowDown' ? Math.min(listed.length - 1, i + 1) : Math.max(0, i - 1)
open(conversations[i < 0 ? 0 : next]) open(listed[i < 0 ? 0 : next])
} }
} }
window.addEventListener('keydown', onKey) window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey) return () => window.removeEventListener('keydown', onKey)
}, [conversations, selected, open]) }, [listed, selected, open])
if (!state) return <div className="app loading" /> if (!state) return <div className="app loading" />
if (!state.configured) return <Setup initial={state} onDone={refreshState} /> if (!state.configured) return <Setup initial={state} onDone={refreshState} />
return ( return (
<AddContactContext.Provider value={setAdding}>
<div className="app"> <div className="app">
<Sidebar <Sidebar
mode={mode} mode={mode}
@@ -103,14 +126,28 @@ export function App() {
onOpen={open} onOpen={open}
sync={sync} sync={sync}
multiDid={smsDids.length > 1} multiDid={smsDids.length > 1}
smsDids={smsDids}
gvNumber={state.gvoiceNumber}
defaultDid={state.settings.defaultDid ?? smsDids[0]?.did} defaultDid={state.settings.defaultDid ?? smsDids[0]?.did}
onSettings={() => setSettingsOpen(true)} onSettings={() => setSettingsOpen(true)}
archiveView={archiveView}
setArchiveView={setArchiveView}
onMarkUnread={onMarkUnread}
onInfo={setInfo}
onExport={setExporting}
/> />
{selected ? ( {selected ? (
<ChatView <ChatView
key={`${selected.did}:${selected.contact}`} key={`${selected.did}:${selected.contact}`}
conv={selected} conv={selected}
contact={contactMap.get(selected.contact)} contact={contactMap.get(selected.contact)}
contactMap={contactMap}
conversations={conversations}
onOpen={open}
name={named(selected)}
onInfo={() => setInfo(selected)}
onExport={() => setExporting(selected)}
gvNumber={state.gvoiceNumber}
jump={jump} jump={jump}
highlight={mode === 'search' ? query : ''} highlight={mode === 'search' ? query : ''}
version={msgVersion} version={msgVersion}
@@ -120,11 +157,14 @@ export function App() {
) : ( ) : (
<main className="chat empty"> <main className="chat empty">
<div className="empty-hint"> <div className="empty-hint">
<div className="empty-title">voip.ms Messages</div> <div className="empty-title">bubble</div>
<div>Pick a conversation, or press Ctrl+N to start a new one.</div>
</div> </div>
</main> </main>
)} )}
{info && (
<ConversationInfo conv={info} name={named(info)} contactMap={contactMap} gvNumber={state.gvoiceNumber} onClose={() => setInfo(null)} />
)}
{exporting && <ExportChat conv={exporting} name={named(exporting)} contactMap={contactMap} onClose={() => setExporting(null)} />}
{settingsOpen && ( {settingsOpen && (
<SettingsDialog <SettingsDialog
state={state} state={state}
@@ -133,6 +173,8 @@ export function App() {
onChanged={refreshState} onChanged={refreshState}
/> />
)} )}
{adding && <AddContact number={adding} defaultBook={state.settings.contactBook} onClose={() => setAdding(null)} />}
</div> </div>
</AddContactContext.Provider>
) )
} }
+105
View File
@@ -0,0 +1,105 @@
import { createContext, useContext, useEffect, useState } from 'react'
import { formatNumber } from '@shared/phone'
import type { AddressBook } from '@shared/types'
import { CloseIcon } from './Icons'
// Anywhere a number shows, "Add to contacts…" calls this (provided by App).
export const AddContactContext = createContext<(number: string) => void>(() => undefined)
export const useAddContact = (): ((number: string) => void) => useContext(AddContactContext)
const cleanError = (e: Error): string => e.message.replace(/^Error invoking remote method '\w+': (Error: )?/, '')
const e164 = (n: string): string => (n.length === 10 ? `+1${n}` : `+${n}`)
interface Props {
number: string
defaultBook?: string // from Settings; else GNOME Contacts' default
onClose: () => void
}
export function AddContact({ number, defaultBook, onClose }: Props) {
const [first, setFirst] = useState('')
const [last, setLast] = useState('')
const [org, setOrg] = useState('')
const [books, setBooks] = useState<AddressBook[]>()
const [book, setBook] = useState<string>()
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string>()
useEffect(() => {
window.api
.listAddressBooks()
.then((r) => {
setBooks(r.books)
setBook(r.books.some((b) => b.uid === defaultBook) ? defaultBook : (r.default ?? r.books[0]?.uid))
})
.catch((e: Error) => setError(cleanError(e)))
}, [defaultBook])
useEffect(() => {
const onKey = (e: KeyboardEvent): void => {
if (e.key === 'Escape') onClose()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const canSave = !!(first.trim() || last.trim() || org.trim()) && !!book && !busy
const save = (): void => {
if (!canSave) return
setBusy(true)
setError(undefined)
window.api
.addContact({ first: first.trim(), last: last.trim(), org: org.trim(), number: e164(number), book })
.then(onClose)
.catch((e: Error) => {
setError(cleanError(e))
setBusy(false)
})
}
const onEnter = (e: React.KeyboardEvent): void => {
if (e.key === 'Enter') save()
}
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal add-contact" role="dialog" aria-label="Add to contacts">
<header>
<h2>Add to contacts</h2>
<button className="icon-btn" onClick={onClose} title="Close">
<CloseIcon />
</button>
</header>
<section>
<div className="kv">
<span>Mobile</span>
<span>{formatNumber(number)}</span>
</div>
<input className="text-input" placeholder="First name" value={first} autoFocus onChange={(e) => setFirst(e.target.value)} onKeyDown={onEnter} />
<input className="text-input" placeholder="Last name" value={last} onChange={(e) => setLast(e.target.value)} onKeyDown={onEnter} />
<input className="text-input" placeholder="Organization" value={org} onChange={(e) => setOrg(e.target.value)} onKeyDown={onEnter} />
{books && books.length > 1 && (
<label className="field">
Address book
<select value={book} onChange={(e) => setBook(e.target.value)}>
{books.map((b) => (
<option key={b.uid} value={b.uid}>
{b.name}
{b.account ? ` (${b.account})` : ''}
</option>
))}
</select>
</label>
)}
{error && <p className="form-error">{error}</p>}
</section>
<footer>
<button onClick={onClose}>Cancel</button>
<button className="primary" disabled={!canSave} onClick={save}>
{busy ? 'Adding…' : 'Add'}
</button>
</footer>
</div>
</div>
)
}
+14 -2
View File
@@ -1,11 +1,14 @@
import { useState } from 'react' import { useState } from 'react'
import { isGroup } from '@shared/phone'
import type { ContactInfo } from '@shared/types' import type { ContactInfo } from '@shared/types'
import { avatarColors, initials } from '../format' import { avatarColors, initials } from '../format'
export function Avatar({ number, contact, size = 40 }: { number: string; contact?: ContactInfo; size?: number }) { export function Avatar({ number, contact, size = 40 }: { number: string; contact?: ContactInfo; size?: number }) {
const [broken, setBroken] = useState<string>() const [broken, setBroken] = useState<string>()
const { bg, fg } = avatarColors(contact?.name ?? number) const { bg, fg } = avatarColors(contact?.name ?? number)
const style = { width: size, height: size, fontSize: size * 0.4, background: bg, color: fg } // Scales with --s, which the sidebar lowers when it's resized narrow.
const px = (n: number): string => `calc(${n}px * var(--s, 1))`
const style = { width: px(size), height: px(size), fontSize: px(size * 0.4), background: bg, color: fg }
if (contact?.photo && broken !== contact.photo) { if (contact?.photo && broken !== contact.photo) {
return ( return (
<div className="avatar" style={style}> <div className="avatar" style={style}>
@@ -14,10 +17,19 @@ export function Avatar({ number, contact, size = 40 }: { number: string; contact
) )
} }
const text = contact ? initials(contact.name) : '' const text = contact ? initials(contact.name) : ''
if (isGroup(number)) {
return (
<div className="avatar" style={style}>
<svg viewBox="0 0 24 24" style={{ width: px(size * 0.6), height: px(size * 0.6) }} fill="currentColor" aria-hidden>
<path d="M9 11a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7Zm7.5 0a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM9 12.5c-3.3 0-6.5 1.7-6.5 4.2V19h13v-2.3c0-2.5-3.2-4.2-6.5-4.2Zm7.5.3c-.6 0-1.2.1-1.8.2 1.3.9 2.3 2.2 2.3 3.7V19h4.5v-2c0-2.3-2.4-4.2-5-4.2Z" />
</svg>
</div>
)
}
return ( return (
<div className="avatar" style={style}> <div className="avatar" style={style}>
{text || ( {text || (
<svg viewBox="0 0 24 24" width={size * 0.55} height={size * 0.55} fill="currentColor" aria-hidden> <svg viewBox="0 0 24 24" style={{ width: px(size * 0.55), height: px(size * 0.55) }} fill="currentColor" aria-hidden>
<path d="M12 12a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9Zm0 2c-4.4 0-8 2.2-8 5v1.5h16V19c0-2.8-3.6-5-8-5Z" /> <path d="M12 12a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9Zm0 2c-4.4 0-8 2.2-8 5v1.5h16V19c0-2.8-3.6-5-8-5Z" />
</svg> </svg>
)} )}
+169 -19
View File
@@ -1,18 +1,27 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Virtuoso, type VirtuosoHandle } from 'react-virtuoso' import { Virtuoso, type VirtuosoHandle } from 'react-virtuoso'
import { formatNumber } from '@shared/phone' import { formatNumber, groupMembers, isGroup } from '@shared/phone'
import type { ContactInfo, Did, Message, SearchHit } from '@shared/types' import type { ContactInfo, Conversation, Did, Message, SearchHit } from '@shared/types'
import type { ConvKey, Jump } from '../App' import type { ConvKey, Jump } from '../App'
import { dayLabel, displayName, sameDay } from '../format' import { chatsWith, convName, dayLabel, sameDay, senderName, senderShortName } from '../format'
import { Avatar } from './Avatar' import { Avatar } from './Avatar'
import { Composer } from './Composer' import { Composer, type ComposerHandle } from './Composer'
import { CloseIcon, DownIcon, SearchIcon, UpIcon } from './Icons' import { CloseIcon, DownIcon, SearchIcon, UpIcon } from './Icons'
import { Lightbox } from './Lightbox'
import { MessageBubble } from './MessageBubble' import { MessageBubble } from './MessageBubble'
import { foldReactions, type Reaction } from '@shared/reactions'
import { Via } from './Via'
import { useAddContact } from './AddContact'
import { ContextMenu, type MenuItem } from './ContextMenu'
import { imageMenuItems } from './Lightbox'
type Row = { kind: 'day'; key: string; ts: number } | { kind: 'msg'; key: string; m: Message; groupStart: boolean; groupEnd: boolean } type Row = { kind: 'day'; key: string; ts: number } | { kind: 'msg'; key: string; m: Message; groupStart: boolean; groupEnd: boolean }
const GROUP_GAP = 5 * 60_000 const GROUP_GAP = 5 * 60_000
// Breathing room between the newest message and the composer.
const ListFooter = () => <div className="list-footer" />
function buildRows(msgs: Message[]): Row[] { function buildRows(msgs: Message[]): Row[] {
const rows: Row[] = [] const rows: Row[] = []
msgs.forEach((m, i) => { msgs.forEach((m, i) => {
@@ -20,8 +29,9 @@ function buildRows(msgs: Message[]): Row[] {
const next = msgs[i + 1] const next = msgs[i + 1]
const newDay = !prev || !sameDay(prev.ts, m.ts) const newDay = !prev || !sameDay(prev.ts, m.ts)
if (newDay) rows.push({ kind: 'day', key: `d${m.ts}`, ts: m.ts }) if (newDay) rows.push({ kind: 'day', key: `d${m.ts}`, ts: m.ts })
const groupStart = newDay || prev.direction !== m.direction || m.ts - prev.ts > GROUP_GAP const groupStart = newDay || prev.direction !== m.direction || prev.sender !== m.sender || m.ts - prev.ts > GROUP_GAP
const groupEnd = !next || !sameDay(m.ts, next.ts) || next.direction !== m.direction || next.ts - m.ts > GROUP_GAP const groupEnd =
!next || !sameDay(m.ts, next.ts) || next.direction !== m.direction || next.sender !== m.sender || next.ts - m.ts > GROUP_GAP
rows.push({ kind: 'msg', key: String(m.id), m, groupStart, groupEnd }) rows.push({ kind: 'msg', key: String(m.id), m, groupStart, groupEnd })
}) })
return rows return rows
@@ -30,6 +40,13 @@ function buildRows(msgs: Message[]): Row[] {
interface Props { interface Props {
conv: ConvKey conv: ConvKey
contact?: ContactInfo contact?: ContactInfo
contactMap: Map<string, ContactInfo>
conversations: Conversation[]
onOpen: (key: ConvKey) => void
name?: string // a name you gave the conversation
onInfo: () => void
onExport: () => void
gvNumber?: string
jump?: Jump jump?: Jump
highlight: string highlight: string
version: number version: number
@@ -37,15 +54,48 @@ interface Props {
onChangeDid: (did: string) => void onChangeDid: (did: string) => void
} }
export function ChatView({ conv, contact, jump, highlight, version, smsDids, onChangeDid }: Props) { export function ChatView({ conv, contact, contactMap, conversations, onOpen, name: ownName, onInfo, onExport, gvNumber, jump, highlight, version, smsDids, onChangeDid }: Props) {
const name = convName(conv.contact, contactMap, ownName)
const addContact = useAddContact()
const [menu, setMenu] = useState<{ number: string; x: number; y: number }>()
const [headerMenu, setHeaderMenu] = useState<{ x: number; y: number }>()
// "Other chats with …": the groups (and other-number 1:1s) someone's in.
const [others, setOthers] = useState<{ number: string; x: number; y: number }>()
const othersItem = (number: string, x: number, y: number, label: string): MenuItem => ({
label,
onSelect: () => setOthers({ number, x, y })
})
const otherChatItems = (number: string): MenuItem[] => {
const chats = chatsWith(number, conversations, conv)
if (!chats.length) return [{ label: `No other chats with ${senderShortName(number, contactMap)}`, onSelect: () => undefined, disabled: true }]
return chats.map((c) => ({
label:
(isGroup(c.contact) ? convName(c.contact, contactMap, c.name) : `${senderName(c.contact, contactMap)} (just you two, from ${formatNumber(c.did)})`) +
(c.archived ? ' — archived' : ''),
onSelect: () => onOpen({ did: c.did, contact: c.contact })
}))
}
// Right-click a group member's name: other chats with them, and "Add to
// contacts…" if they aren't in your contacts.
const numberMenu = (number?: string) => (e: React.MouseEvent) => {
if (!number) return
e.preventDefault()
setMenu({ number, x: e.clientX, y: e.clientY })
}
const group = isGroup(conv.contact)
const members = group ? groupMembers(conv.contact).map((n) => senderName(n, contactMap)) : []
const [messages, setMessages] = useState<Message[]>() const [messages, setMessages] = useState<Message[]>()
const [flashId, setFlashId] = useState<number>() const [flashId, setFlashId] = useState<number>()
const [searchOpen, setSearchOpen] = useState(false) const [searchOpen, setSearchOpen] = useState(false)
const [q, setQ] = useState('') const [q, setQ] = useState('')
const [hits, setHits] = useState<SearchHit[]>([]) const [hits, setHits] = useState<SearchHit[]>([])
const [hitIdx, setHitIdx] = useState(0) const [hitIdx, setHitIdx] = useState(0)
const [lightbox, setLightbox] = useState<{ id: number; index: number }>()
const [dragging, setDragging] = useState(false)
const virtuoso = useRef<VirtuosoHandle>(null) const virtuoso = useRef<VirtuosoHandle>(null)
const searchInput = useRef<HTMLInputElement>(null) const searchInput = useRef<HTMLInputElement>(null)
const composer = useRef<ComposerHandle>(null)
const atBottom = useRef(true)
// Load (and reload on any change) the whole conversation. // Load (and reload on any change) the whole conversation.
useEffect(() => { useEffect(() => {
@@ -66,7 +116,11 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
return () => window.removeEventListener('focus', onFocus) return () => window.removeEventListener('focus', onFocus)
}, [conv.did, conv.contact]) }, [conv.did, conv.contact])
const rows = useMemo(() => buildRows(messages ?? []), [messages]) // iPhone tapbacks ("Loved “…”") become reactions on the message they quote.
const folded = useMemo(() => foldReactions(messages ?? []), [messages])
const rows = useMemo(() => buildRows(folded.shown), [folded])
const [reactionList, setReactionList] = useState<{ reactions: Reaction[]; x: number; y: number }>()
const showReactions = useCallback((reactions: Reaction[], x: number, y: number) => setReactionList({ reactions, x, y }), [])
const indexOf = useCallback((id: number) => rows.findIndex((r) => r.kind === 'msg' && r.m.id === id), [rows]) const 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) => {
@@ -142,21 +196,58 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
return () => window.removeEventListener('keydown', onKey) return () => window.removeEventListener('keydown', onKey)
}, []) }, [])
const openMedia = useCallback((id: number, index: number) => setLightbox({ id, index }), [])
const [mediaMenu, setMediaMenu] = useState<{ id: number; index: number; x: number; y: number }>()
const showMediaMenu = useCallback((id: number, index: number, e: React.MouseEvent) => {
e.preventDefault()
setMediaMenu({ id, index, x: e.clientX, y: e.clientY })
}, [])
// Images that arrive after layout grow the list; stay pinned to the newest.
const onMediaLoad = useCallback(() => {
if (atBottom.current) virtuoso.current?.scrollToIndex({ index: 'LAST', align: 'end' })
}, [])
const mark = searchOpen && q.trim() ? q : highlight const mark = searchOpen && q.trim() ? q : highlight
const isNew = messages !== undefined && messages.length === 0 const isNew = messages !== undefined && messages.length === 0
const initialIndex = jump && messages ? Math.max(0, indexOf(jump.id)) : rows.length - 1 const initialIndex = jump && messages ? Math.max(0, indexOf(jump.id)) : rows.length - 1
return ( return (
<main className="chat"> <main
<header className="chat-header"> className={`chat${dragging ? ' dragging' : ''}`}
onDragOver={(e) => {
if (!e.dataTransfer.types.includes('Files')) return
e.preventDefault()
setDragging(true)
}}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node)) setDragging(false)
}}
onDrop={(e) => {
e.preventDefault()
setDragging(false)
composer.current?.addFiles([...e.dataTransfer.files])
}}
>
<header
className="chat-header"
onContextMenu={(e) => {
e.preventDefault()
setHeaderMenu({ x: e.clientX, y: e.clientY })
}}
>
<Avatar number={conv.contact} contact={contact} size={36} /> <Avatar number={conv.contact} contact={contact} size={36} />
<div className="chat-title"> <div
<div className="chat-name">{displayName(conv.contact, contact)}</div> className={`chat-title${group ? ' clickable' : ''}`}
onClick={group ? onInfo : undefined}
title={group ? 'Get info' : undefined}
>
<div className="chat-name">{name}</div>
<div className="chat-sub"> <div className="chat-sub">
{contact ? formatNumber(conv.contact) : ''} {group ? `${members.length} people` : contact ? formatNumber(conv.contact) : ''}
{smsDids.length > 1 && ( {smsDids.length > 1 && (
<span className="chat-via"> <span className="chat-via">
{contact ? ' · ' : ''}via {formatNumber(conv.did)} {contact || group ? ' · ' : ''}
<Via did={conv.did} gvNumber={gvNumber} />
</span> </span>
)} )}
</div> </div>
@@ -172,7 +263,7 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
<input <input
ref={searchInput} ref={searchInput}
value={q} value={q}
placeholder={`Search in ${displayName(conv.contact, contact)}`} placeholder={`Search in ${name}`}
onChange={(e) => setQ(e.target.value)} onChange={(e) => setQ(e.target.value)}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === 'Enter') stepHit(e.shiftKey ? -1 : 1) if (e.key === 'Enter') stepHit(e.shiftKey ? -1 : 1)
@@ -206,8 +297,8 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
{messages === undefined ? null : isNew ? ( {messages === undefined ? null : isNew ? (
<div className="new-conv"> <div className="new-conv">
<Avatar number={conv.contact} contact={contact} size={80} /> <Avatar number={conv.contact} contact={contact} size={80} />
<div className="new-conv-name">{displayName(conv.contact, contact)}</div> <div className="new-conv-name">{name}</div>
{contact && <div className="new-conv-sub">{formatNumber(conv.contact)}</div>} {group ? <div className="new-conv-sub">{members.join(', ')}</div> : contact && <div className="new-conv-sub">{formatNumber(conv.contact)}</div>}
</div> </div>
) : ( ) : (
<Virtuoso <Virtuoso
@@ -216,9 +307,12 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
className="message-scroller" className="message-scroller"
computeItemKey={(_, r) => r.key} computeItemKey={(_, r) => r.key}
initialTopMostItemIndex={{ index: initialIndex, align: jump ? 'center' : 'end' }} initialTopMostItemIndex={{ index: initialIndex, align: jump ? 'center' : 'end' }}
followOutput={(atBottom) => (atBottom ? 'smooth' : false)} followOutput={(bottom) => (bottom ? 'smooth' : false)}
atBottomStateChange={(bottom) => (atBottom.current = bottom)}
atBottomThreshold={80}
alignToBottom alignToBottom
increaseViewportBy={{ top: 800, bottom: 800 }} increaseViewportBy={{ top: 800, bottom: 800 }}
components={{ Footer: ListFooter }}
itemContent={(_, r) => itemContent={(_, r) =>
r.kind === 'day' ? ( r.kind === 'day' ? (
<div className="day-sep"> <div className="day-sep">
@@ -227,10 +321,17 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
) : ( ) : (
<MessageBubble <MessageBubble
m={r.m} m={r.m}
sender={group && r.m.sender && r.groupStart ? senderName(r.m.sender, contactMap) : undefined}
onSenderMenu={numberMenu(r.m.sender)}
groupStart={r.groupStart} groupStart={r.groupStart}
groupEnd={r.groupEnd} groupEnd={r.groupEnd}
flash={flashId === r.m.id} flash={flashId === r.m.id}
highlight={mark} highlight={mark}
onOpenMedia={openMedia}
onMediaMenu={showMediaMenu}
onMediaLoad={onMediaLoad}
reactions={folded.reactions.get(r.m.id)}
onShowReactions={showReactions}
/> />
) )
} }
@@ -238,7 +339,56 @@ export function ChatView({ conv, contact, jump, highlight, version, smsDids, onC
)} )}
</div> </div>
<Composer conv={conv} isNew={isNew} smsDids={smsDids} onChangeDid={onChangeDid} /> <Composer ref={composer} conv={conv} isNew={isNew} smsDids={smsDids} gvNumber={gvNumber} onChangeDid={onChangeDid} />
{dragging && <div className="drop-hint">Drop to attach</div>}
{lightbox && <Lightbox {...lightbox} onClose={() => setLightbox(undefined)} />}
{reactionList && (
<ContextMenu
x={reactionList.x}
y={reactionList.y}
items={reactionList.reactions.map((r) => ({
label: `${r.emoji} ${r.from === 'me' ? 'You' : senderName(r.from, contactMap)}`,
onSelect: () => undefined
}))}
onClose={() => setReactionList(undefined)}
/>
)}
{mediaMenu && (
<ContextMenu
x={mediaMenu.x}
y={mediaMenu.y}
items={imageMenuItems(mediaMenu.id, mediaMenu.index)}
onClose={() => setMediaMenu(undefined)}
/>
)}
{headerMenu && (
<ContextMenu
x={headerMenu.x}
y={headerMenu.y}
items={[
...(group
? groupMembers(conv.contact).map((n) =>
othersItem(n, headerMenu.x, headerMenu.y, `Other chats with ${senderShortName(n, contactMap)}`)
)
: [othersItem(conv.contact, headerMenu.x, headerMenu.y, 'Other chats with this person')]),
...(!group && !contact ? [{ label: 'Add to contacts…', onSelect: () => addContact(conv.contact), separator: true }] : []),
{ label: 'Export chat…', onSelect: onExport, separator: group || !!contact }
]}
onClose={() => setHeaderMenu(undefined)}
/>
)}
{menu && (
<ContextMenu
x={menu.x}
y={menu.y}
items={[
othersItem(menu.number, menu.x, menu.y, `Other chats with ${senderShortName(menu.number, contactMap)}`),
...(contactMap.get(menu.number) ? [] : [{ label: 'Add to contacts…', onSelect: () => addContact(menu.number) }])
]}
onClose={() => setMenu(undefined)}
/>
)}
{others && <ContextMenu x={others.x} y={others.y} items={otherChatItems(others.number)} onClose={() => setOthers(undefined)} />}
</main> </main>
) )
} }
+234 -27
View File
@@ -1,48 +1,178 @@
import { useEffect, useRef, useState } from 'react' import { useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type ChangeEvent, type Ref } from 'react'
import { formatNumber, splitMessage } from '@shared/phone' import { charCount, formatNumber, isGroup, SMS_TEXT_LIMIT } from '@shared/phone'
import type { Did } from '@shared/types' import type { Did } from '@shared/types'
import type { ConvKey } from '../App' import type { ConvKey } from '../App'
import { SendIcon } from './Icons' import { emojiQuery, exactEmoji, searchEmoji } from '../emoji'
import { formatBytes, MAX_ATTACHMENTS, MMS_TEXT_LIMIT, prepareAttachment, type Attachment } from '../media'
import { EmojiSuggest } from './EmojiSuggest'
import { AttachIcon, CloseIcon, SendIcon } from './Icons'
// Drafts survive switching conversations (not app restarts). // Unsent text survives switching conversations and app restarts (it's kept in
// the database until sent or cleared); attachments only the former.
const drafts = new Map<string, string>() const drafts = new Map<string, string>()
const draftsLoaded = window.api.getDrafts().then((saved) => {
for (const [contact, text] of Object.entries(saved)) if (!drafts.get(contact)) drafts.set(contact, text)
})
const attachmentDrafts = new Map<string, Attachment[]>()
export interface ComposerHandle {
addFiles: (files: File[]) => void
}
interface Props { interface Props {
conv: ConvKey conv: ConvKey
isNew: boolean isNew: boolean
smsDids: Did[] smsDids: Did[]
gvNumber?: string
onChangeDid: (did: string) => void onChangeDid: (did: string) => void
ref?: Ref<ComposerHandle>
} }
export function Composer({ conv, isNew, smsDids, onChangeDid }: Props) { const cleanError = (e: Error): string => e.message.replace(/^Error invoking remote method '\w+': (Error: )?/, '')
// A complete `:shortname:` just typed at the caret, e.g. "hi :joy:".
const CLOSED_SHORTNAME = /(?:^|[\s([]):([a-z0-9_+-]+):$/i
export function Composer({ conv, isNew, smsDids, gvNumber, onChangeDid, ref }: Props) {
const key = conv.contact const key = conv.contact
// Google Voice: no SMS/MMS split to count toward, and photos only.
const gv = conv.did === gvNumber
// A group thread lives on Google Voice; it can't switch numbers.
const fromDids = isGroup(conv.contact) ? smsDids.filter((d) => d.did === gvNumber) : smsDids
const [text, setText] = useState(() => drafts.get(key) ?? '') const [text, setText] = useState(() => drafts.get(key) ?? '')
const [attachments, setAttachments] = useState<Attachment[]>(() => attachmentDrafts.get(key) ?? [])
const [preparing, setPreparing] = useState(0)
const [error, setError] = useState<string>() const [error, setError] = useState<string>()
const ref = useRef<HTMLTextAreaElement>(null) const textarea = useRef<HTMLTextAreaElement>(null)
const fileInput = useRef<HTMLInputElement>(null)
const [caret, setCaret] = useState(text.length)
const [focused, setFocused] = useState(false)
const [activeEmoji, setActiveEmoji] = useState(0)
// Where the `:` sat when Escape closed the emoji list, so it stays closed
// while that shortname is being typed.
const [dismissedAt, setDismissedAt] = useState<number>()
const pendingCaret = useRef<number>(undefined)
useEffect(() => { useEffect(() => {
ref.current?.focus() textarea.current?.focus()
}, []) }, [])
// A chat opened before the saved drafts arrived picks its draft up now.
useEffect(() => { useEffect(() => {
drafts.set(key, text) let live = true
const el = ref.current void draftsLoaded.then(() => {
const saved = drafts.get(key)
if (live && saved) {
setText((cur) => cur || saved)
setCaret(saved.length)
}
})
return () => {
live = false
}
}, [key])
useEffect(() => {
if ((drafts.get(key) ?? '') !== text) {
drafts.set(key, text)
void window.api.setDraft(key, text)
}
const el = textarea.current
if (el) { if (el) {
el.style.height = 'auto' el.style.height = 'auto'
el.style.height = `${Math.min(el.scrollHeight, 200)}px` el.style.height = `${Math.min(el.scrollHeight, 200)}px`
} }
}, [text, key]) }, [text, key])
const submit = (): void => { // Put the caret after an emoji we swapped in (setting the value moves it to the end).
const body = text.trim() useLayoutEffect(() => {
if (!body) return if (pendingCaret.current === undefined) return
setText('') textarea.current?.setSelectionRange(pendingCaret.current, pendingCaret.current)
pendingCaret.current = undefined
}, [text])
useEffect(() => {
attachmentDrafts.set(key, attachments)
}, [attachments, key])
const addFiles = (files: File[]): void => {
if (!files.length) return
setError(undefined) setError(undefined)
window.api.send(conv.did, conv.contact, body).catch((e: Error) => setError(e.message.replace(/^Error invoking remote method '\w+': (Error: )?/, ''))) const room = MAX_ATTACHMENTS - attachments.length - preparing
if (room <= 0) {
setError(`An MMS can carry at most ${MAX_ATTACHMENTS} attachments.`)
return
}
if (files.length > room) setError(`Only the first ${room} added — an MMS can carry at most ${MAX_ATTACHMENTS} attachments.`)
if (gv && files.some((f) => !f.type.startsWith('image/'))) {
setError('Google Voice can only send photos.')
files = files.filter((f) => f.type.startsWith('image/'))
}
for (const file of files.slice(0, room)) {
setPreparing((n) => n + 1)
prepareAttachment(file)
.then((a) => setAttachments((cur) => [...cur, a]))
.catch((e: Error) => setError(e.message))
.finally(() => setPreparing((n) => n - 1))
}
textarea.current?.focus()
} }
const len = [...text.trim()].length useImperativeHandle(ref, () => ({ addFiles }))
const parts = len ? splitMessage(text).length : 0
const remove = (a: Attachment): void => {
URL.revokeObjectURL(a.previewUrl)
setAttachments((cur) => cur.filter((x) => x !== a))
}
// Text too long for one SMS goes out as a single text-only MMS.
const len = charCount(text.trim())
const isMms = attachments.length > 0 || len > SMS_TEXT_LIMIT
const tooLong = !gv && len > MMS_TEXT_LIMIT
const canSend = (len > 0 || attachments.length > 0) && !preparing && !tooLong
const submit = (): void => {
if (!canSend) return
const body = text.trim()
const outgoing = attachments.map(({ name, mime, data, width, height }) => ({ name, mime, data, width, height }))
attachments.forEach((a) => URL.revokeObjectURL(a.previewUrl))
setText('')
setCaret(0)
setAttachments([])
setError(undefined)
window.api.send(conv.did, conv.contact, body, outgoing.length ? outgoing : undefined).catch((e: Error) => setError(cleanError(e)))
}
const emojiMatch = focused ? emojiQuery(text, caret) : null
const suggestions = emojiMatch && emojiMatch.start !== dismissedAt ? searchEmoji(emojiMatch.query) : []
const active = Math.min(activeEmoji, suggestions.length - 1)
const replaceAt = (from: number, to: number, emoji: string): void => {
pendingCaret.current = from + emoji.length
setText(text.slice(0, from) + emoji + text.slice(to))
setCaret(pendingCaret.current)
}
const pickEmoji = (i: number): void => {
if (emojiMatch && suggestions[i]) replaceAt(emojiMatch.start, caret, suggestions[i].char)
}
const onChange = (e: ChangeEvent<HTMLTextAreaElement>): void => {
const { value, selectionStart: pos } = e.target
setActiveEmoji(0)
const closed = CLOSED_SHORTNAME.exec(value.slice(0, pos))
const emoji = closed && exactEmoji(closed[1])
if (emoji) {
const from = pos - closed![1].length - 2
pendingCaret.current = from + emoji.length
setText(value.slice(0, from) + emoji + value.slice(pos))
setCaret(pendingCaret.current)
return
}
if (!emojiQuery(value, pos)) setDismissedAt(undefined)
setText(value)
setCaret(pos)
}
return ( return (
<footer className="composer"> <footer className="composer">
@@ -51,39 +181,116 @@ export function Composer({ conv, isNew, smsDids, onChangeDid }: Props) {
{error} {error}
</div> </div>
)} )}
{isNew && smsDids.length > 1 && ( {isNew && fromDids.length > 1 && (
<label className="from-picker"> <label className="from-picker">
From From
<select value={conv.did} onChange={(e) => onChangeDid(e.target.value)}> <select value={conv.did} onChange={(e) => onChangeDid(e.target.value)}>
{smsDids.map((d) => ( {fromDids.map((d) => (
<option key={d.did} value={d.did}> <option key={d.did} value={d.did}>
{formatNumber(d.did)} {formatNumber(d.did)}
{d.description ? ` — ${d.description}` : ''} {d.provider === 'gvoice' ? ' — Google Voice' : d.description ? ` — ${d.description}` : ''}
</option> </option>
))} ))}
</select> </select>
</label> </label>
)} )}
{(attachments.length > 0 || preparing > 0) && (
<div className="attach-tray">
{attachments.map((a) => (
<div key={a.previewUrl} className="attach-item" title={a.note ?? a.name}>
{a.mime.startsWith('image/') ? (
<img src={a.previewUrl} alt="" draggable={false} />
) : (
<div className="attach-file">{a.mime.split('/')[0]}</div>
)}
<span className={`attach-size${a.note ? ' shrunk' : ''}`}>{formatBytes(a.data.byteLength)}</span>
<button className="attach-remove" title="Remove" onClick={() => remove(a)}>
<CloseIcon size={14} />
</button>
</div>
))}
{Array.from({ length: preparing }, (_, i) => (
<div key={`p${i}`} className="attach-item preparing" title="Compressing…">
<span className="spinner" />
</div>
))}
</div>
)}
<div className="composer-row"> <div className="composer-row">
{suggestions.length > 0 && <EmojiSuggest items={suggestions} active={active} onPick={pickEmoji} onHover={setActiveEmoji} />}
<button
className="icon-btn attach-btn"
title={gv ? 'Attach photos' : 'Attach photo, video or audio'}
disabled={attachments.length + preparing >= MAX_ATTACHMENTS}
onClick={() => fileInput.current?.click()}
>
<AttachIcon />
</button>
<input
ref={fileInput}
type="file"
accept={gv ? 'image/*' : 'image/*,video/*,audio/*'}
multiple
hidden
onChange={(e) => {
addFiles([...(e.target.files ?? [])])
e.target.value = ''
}}
/>
<textarea <textarea
ref={ref} ref={textarea}
rows={1} rows={1}
value={text} value={text}
placeholder="Message" placeholder="Message"
onChange={(e) => setText(e.target.value)} onChange={onChange}
onSelect={(e) => setCaret(e.currentTarget.selectionStart)}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
onPaste={(e) => {
const files = [...e.clipboardData.files]
if (files.length) {
e.preventDefault()
addFiles(files)
}
}}
onKeyDown={(e) => { onKeyDown={(e) => {
if (suggestions.length && !e.nativeEvent.isComposing) {
const n = suggestions.length
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault()
setActiveEmoji((active + (e.key === 'ArrowDown' ? 1 : n - 1)) % n)
return
}
if (e.key === 'Tab' || (e.key === 'Enter' && !e.shiftKey)) {
e.preventDefault()
pickEmoji(active)
return
}
if (e.key === 'Escape') {
e.preventDefault()
e.stopPropagation()
setDismissedAt(emojiMatch!.start)
return
}
}
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) { if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault() e.preventDefault()
submit() submit()
} }
}} }}
/> />
{len > 0 && ( {len > 0 &&
<span className={`counter${parts > 1 ? ' multi' : ''}`} title="voip.ms sends up to 160 characters per message"> !gv &&
{parts > 1 ? `${parts} msgs` : `${len}/160`} (isMms ? (
</span> <span className={`counter multi${tooLong ? ' over' : ''}`} title="Sends as one MMS (up to 2048 characters)">
)} MMS · {len}/{MMS_TEXT_LIMIT}
<button className="send-btn" title="Send (Enter)" disabled={!len} onClick={submit}> </span>
) : (
<span className="counter" title="An SMS carries up to 160 characters; longer texts send as one MMS">
{len}/{SMS_TEXT_LIMIT}
</span>
))}
<button className="send-btn" title="Send (Enter)" disabled={!canSend} onClick={submit}>
<SendIcon /> <SendIcon />
</button> </button>
</div> </div>
@@ -0,0 +1,60 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
export interface MenuItem {
label: string
onSelect: () => void
disabled?: boolean
separator?: boolean // draw a line above this item
}
// A small right-click menu at (x, y), kept inside the window. Closes on any
// outside click, Escape, scroll, resize or the window losing focus.
export function ContextMenu({ x, y, items, onClose }: { x: number; y: number; items: MenuItem[]; onClose: () => void }) {
const ref = useRef<HTMLDivElement>(null)
const [pos, setPos] = useState({ left: x, top: y })
useLayoutEffect(() => {
const r = ref.current!.getBoundingClientRect()
setPos({ left: Math.min(x, window.innerWidth - r.width - 4), top: Math.min(y, window.innerHeight - r.height - 4) })
}, [x, y])
useEffect(() => {
const onDown = (e: MouseEvent): void => {
if (!ref.current?.contains(e.target as Node)) onClose()
}
const onKey = (e: KeyboardEvent): void => {
if (e.key === 'Escape') onClose()
}
window.addEventListener('mousedown', onDown, true)
window.addEventListener('keydown', onKey)
window.addEventListener('wheel', onClose, { passive: true })
window.addEventListener('resize', onClose)
window.addEventListener('blur', onClose)
return () => {
window.removeEventListener('mousedown', onDown, true)
window.removeEventListener('keydown', onKey)
window.removeEventListener('wheel', onClose)
window.removeEventListener('resize', onClose)
window.removeEventListener('blur', onClose)
}
}, [onClose])
return (
<div ref={ref} className="context-menu" role="menu" style={pos} onContextMenu={(e) => e.preventDefault()}>
{items.map((it, i) => [
it.separator && <div key={`sep${i}`} className="menu-sep" />,
<button
key={i}
role="menuitem"
disabled={it.disabled}
onClick={() => {
onClose()
it.onSelect()
}}
>
{it.label}
</button>
])}
</div>
)
}
@@ -0,0 +1,106 @@
import { useEffect, useState } from 'react'
import { formatNumber, groupMembers } from '@shared/phone'
import type { ContactInfo } from '@shared/types'
import type { ConvKey } from '../App'
import { convName, displayName } from '../format'
import { Avatar } from './Avatar'
import { CloseIcon } from './Icons'
import { Via } from './Via'
import { useAddContact } from './AddContact'
interface Props {
conv: ConvKey
name?: string // the name you gave it, if any
contactMap: Map<string, ContactInfo>
gvNumber?: string
onClose: () => void
}
// "Get info" for a group chat: who's in it, and a name of your own for it
// (kept on this computer only).
export function ConversationInfo({ conv, name, contactMap, gvNumber, onClose }: Props) {
const [draft, setDraft] = useState(name ?? '')
const members = groupMembers(conv.contact)
const membersName = convName(conv.contact, contactMap)
const dirty = draft.trim() !== (name ?? '')
const addContact = useAddContact()
useEffect(() => {
const onKey = (e: KeyboardEvent): void => {
if (e.key === 'Escape') onClose()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const save = (): void => {
void window.api.setName(conv.did, conv.contact, draft.trim() || null).then(onClose)
}
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal conv-info" role="dialog" aria-label="Chat info">
<header>
<h2>Chat info</h2>
<button className="icon-btn" onClick={onClose} title="Close">
<CloseIcon />
</button>
</header>
<section className="conv-info-top">
<Avatar number={conv.contact} size={72} />
<div className="conv-info-title">{convName(conv.contact, contactMap, name)}</div>
<div className="muted small">
{members.length} people · <Via did={conv.did} gvNumber={gvNumber} />
</div>
</section>
<section>
<h3>Name</h3>
<input
className="conv-name-input"
value={draft}
placeholder={membersName}
autoFocus
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && dirty && save()}
/>
<p className="muted small">Only you see this name; it stays on this computer. Leave it empty to show the members' names.</p>
</section>
<section>
<h3>Members</h3>
{members.map((n) => {
const c = contactMap.get(n)
return (
<div key={n} className="member">
<Avatar number={n} contact={c} size={36} />
<div className="member-main">
<div>{displayName(n, c)}</div>
{c && (
<div className="muted small">
{formatNumber(n)}
{c.label ? ` · ${c.label}` : ''}
</div>
)}
</div>
{!c && (
<button className="member-add" onClick={() => addContact(n)}>
Add to contacts…
</button>
)}
</div>
)
})}
</section>
<footer>
<button onClick={onClose}>{dirty ? 'Cancel' : 'Close'}</button>
<button className="primary" disabled={!dirty} onClick={save}>
Save
</button>
</footer>
</div>
</div>
)
}
@@ -1,20 +1,32 @@
import { memo, useEffect, useState } from 'react' import { memo, useCallback, useContext, useEffect, useState } from 'react'
import { Virtuoso } from 'react-virtuoso' import { Virtuoso } from 'react-virtuoso'
import { formatNumber } from '@shared/phone' import { isGroup } from '@shared/phone'
import type { ContactInfo, Conversation } from '@shared/types' import type { ContactInfo, Conversation } from '@shared/types'
import { sameConv, type ConvKey } from '../App' import { sameConv, type ConvKey } from '../App'
import { displayName, shortTime } from '../format' import { convName, previewText, senderShortName, shortTime } from '../format'
import { Avatar } from './Avatar' import { Avatar } from './Avatar'
import { AddContactContext } from './AddContact'
import { ContextMenu } from './ContextMenu'
import { Via } from './Via'
interface Props { interface Props {
conversations: Conversation[] conversations: Conversation[]
contactMap: Map<string, ContactInfo> contactMap: Map<string, ContactInfo>
selected: ConvKey | null selected: ConvKey | null
multiDid: boolean multiDid: boolean
gvNumber?: string
emptyText: string
onOpen: (key: ConvKey) => void onOpen: (key: ConvKey) => void
onMarkUnread: (key: ConvKey) => void
onInfo: (key: ConvKey) => void
onExport: (key: ConvKey) => void
} }
export function ConversationList({ conversations, contactMap, selected, multiDid, onOpen }: Props) { export function ConversationList({ conversations, contactMap, selected, multiDid, gvNumber, emptyText, onOpen, onMarkUnread, onInfo, onExport }: Props) {
const [menu, setMenu] = useState<{ conv: Conversation; x: number; y: number }>()
const addContact = useContext(AddContactContext)
const closeMenu = useCallback(() => setMenu(undefined), [])
const openMenu = useCallback((conv: Conversation, x: number, y: number) => setMenu({ conv, x, y }), [])
// Re-render every minute so relative times ("5m") stay fresh. // Re-render every minute so relative times ("5m") stay fresh.
const [, tick] = useState(0) const [, tick] = useState(0)
useEffect(() => { useEffect(() => {
@@ -22,53 +34,101 @@ export function ConversationList({ conversations, contactMap, selected, multiDid
return () => clearInterval(t) return () => clearInterval(t)
}, []) }, [])
if (!conversations.length) return <div className="list-empty">No conversations yet.</div> if (!conversations.length) return <div className="list-empty">{emptyText}</div>
const menuItems = (c: Conversation) => [
...(isGroup(c.contact) ? [{ label: 'Get info…', onSelect: () => onInfo(c) }] : []),
...(!isGroup(c.contact) && !contactMap.get(c.contact) ? [{ label: 'Add to contacts…', onSelect: () => addContact(c.contact) }] : []),
c.archived
? { label: 'Unarchive', onSelect: () => void window.api.setArchived(c.did, c.contact, false) }
: { label: 'Archive', onSelect: () => void window.api.setArchived(c.did, c.contact, true) },
c.unread > 0 || c.markedUnread
? { label: 'Mark as read', onSelect: () => void window.api.markRead(c.did, c.contact) }
: {
label: 'Mark as unread',
onSelect: () => {
onMarkUnread(c)
void window.api.markUnread(c.did, c.contact)
}
},
{ label: 'Export chat…', onSelect: () => onExport(c) }
]
return ( return (
<Virtuoso <>
className="conv-list" <Virtuoso
data={conversations} className="conv-list"
computeItemKey={(_, c) => `${c.did}:${c.contact}`} data={conversations}
itemContent={(_, c) => ( computeItemKey={(_, c) => `${c.did}:${c.contact}`}
<ConversationRow itemContent={(_, c) => (
conv={c} <ConversationRow
contact={contactMap.get(c.contact)} conv={c}
active={sameConv(c, selected)} contact={contactMap.get(c.contact)}
multiDid={multiDid} name={convName(c.contact, contactMap, c.name)}
onOpen={onOpen} sender={c.lastSender && c.lastDirection === 'in' ? senderShortName(c.lastSender, contactMap) : undefined}
/> active={sameConv(c, selected)}
)} multiDid={multiDid}
/> gvNumber={gvNumber}
onOpen={onOpen}
onMenu={openMenu}
/>
)}
/>
{menu && <ContextMenu x={menu.x} y={menu.y} items={menuItems(menu.conv)} onClose={closeMenu} />}
</>
) )
} }
const ConversationRow = memo(function ConversationRow({ const ConversationRow = memo(function ConversationRow({
conv, conv,
contact, contact,
name,
sender,
active, active,
multiDid, multiDid,
onOpen gvNumber,
onOpen,
onMenu
}: { }: {
conv: Conversation conv: Conversation
contact?: ContactInfo contact?: ContactInfo
name: string
sender?: string // group chats: who sent the last message
active: boolean active: boolean
multiDid: boolean multiDid: boolean
gvNumber?: string
onOpen: (key: ConvKey) => void onOpen: (key: ConvKey) => void
onMenu: (conv: Conversation, x: number, y: number) => void
}) { }) {
const preview = (conv.lastDirection === 'out' ? 'You: ' : '') + conv.lastBody.replace(/\s+/g, ' ') const preview = (conv.lastDirection === 'out' ? 'You: ' : sender ? `${sender}: ` : '') + previewText(conv)
return ( return (
<button className={`row${active ? ' active' : ''}${conv.unread ? ' unread' : ''}`} onClick={() => onOpen(conv)}> <button
className={`row${active ? ' active' : ''}${conv.unread || conv.markedUnread ? ' unread' : ''}`}
onClick={() => onOpen(conv)}
onContextMenu={(e) => {
e.preventDefault()
onMenu(conv, e.clientX, e.clientY)
}}
>
<Avatar number={conv.contact} contact={contact} size={48} /> <Avatar number={conv.contact} contact={contact} size={48} />
<div className="row-main"> <div className="row-main">
<div className="row-top"> <div className="row-top">
<span className="row-name">{displayName(conv.contact, contact)}</span> <span className="row-name">{name}</span>
<span className="row-time">{shortTime(conv.lastTs)}</span> <span className="row-time">{shortTime(conv.lastTs)}</span>
</div> </div>
<div className="row-bottom"> <div className="row-bottom">
<span className="row-preview">{preview}</span> <span className="row-preview">{preview}</span>
{conv.unread > 0 && <span className="badge">{conv.unread > 99 ? '99+' : conv.unread}</span>} {conv.unread > 0 ? (
<span className="badge">{conv.unread > 99 ? '99+' : conv.unread}</span>
) : (
conv.markedUnread && <span className="badge dot" title="Marked as unread" />
)}
</div> </div>
{multiDid && <div className="row-via">via {formatNumber(conv.did)}</div>} {multiDid && (
<div className="row-via">
<Via did={conv.did} gvNumber={gvNumber} />
</div>
)}
</div> </div>
</button> </button>
) )
@@ -0,0 +1,37 @@
import { useEffect, useRef } from 'react'
import type { EmojiMatch } from '../emoji'
interface Props {
items: EmojiMatch[]
active: number
onPick: (i: number) => void
onHover: (i: number) => void
}
// The `:shortname` completion list above the composer. It never takes focus:
// the textarea keeps handling keys, and clicks are caught on mousedown.
export function EmojiSuggest({ items, active, onPick, onHover }: Props) {
const list = useRef<HTMLDivElement>(null)
useEffect(() => {
list.current?.children[active]?.scrollIntoView({ block: 'nearest' })
}, [active])
return (
<div ref={list} className="emoji-suggest" role="listbox" onMouseDown={(e) => e.preventDefault()}>
{items.map((it, i) => (
<div
key={it.char}
role="option"
aria-selected={i === active}
className={i === active ? 'active' : undefined}
onMouseEnter={() => onHover(i)}
onClick={() => onPick(i)}
>
<span className="emoji-glyph">{it.char}</span>
<span className="emoji-name">:{it.name}:</span>
</div>
))}
</div>
)
}
+119
View File
@@ -0,0 +1,119 @@
import { useEffect, useState } from 'react'
import { groupMembers, isGroup } from '@shared/phone'
import type { ContactInfo } from '@shared/types'
import type { ConvKey } from '../App'
import { convName, senderName } from '../format'
import { CloseIcon } from './Icons'
interface Props {
conv: ConvKey
name?: string // the name you gave it, if any
contactMap: Map<string, ContactInfo>
onClose: () => void
}
const cleanError = (e: Error): string => e.message.replace(/^Error invoking remote method '\w+': (Error: )?/, '')
const day = (d: Date): string => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
// "Export chat…": all of it or the days between two dates, as a PDF (with or
// without its photos) or a .txt; then the usual save dialog picks where.
export function ExportChat({ conv, name, contactMap, onClose }: Props) {
const today = day(new Date())
const [allTime, setAllTime] = useState(true)
const [from, setFrom] = useState(day(new Date(Date.now() - 30 * 86_400_000)))
const [to, setTo] = useState(today)
const [format, setFormat] = useState<'pdf' | 'txt'>('pdf')
const [attachments, setAttachments] = useState(true)
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string>()
useEffect(() => {
const onKey = (e: KeyboardEvent): void => {
if (e.key === 'Escape' && !busy) onClose()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose, busy])
const badDates = !allTime && (!from || !to || from > to)
const go = (): void => {
if (badDates || busy) return
setBusy(true)
setError(undefined)
const names = Object.fromEntries((isGroup(conv.contact) ? groupMembers(conv.contact) : []).map((n) => [n, senderName(n, contactMap)]))
window.api
.exportChat(conv.did, conv.contact, {
...(allTime ? {} : { from, to }),
format,
attachments: format === 'pdf' && attachments,
title: convName(conv.contact, contactMap, name),
names
})
.then((saved) => (saved ? onClose() : setBusy(false)))
.catch((e: Error) => {
setError(cleanError(e))
setBusy(false)
})
}
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && !busy && onClose()}>
<div className="modal export-chat" role="dialog" aria-label="Export chat">
<header>
<h2>Export chat</h2>
<button className="icon-btn" onClick={onClose} disabled={busy} title="Close">
<CloseIcon />
</button>
</header>
<section>
<h3>Messages</h3>
<label className="field">
All time
<input type="checkbox" checked={allTime} onChange={(e) => setAllTime(e.target.checked)} />
</label>
<div className={`export-dates${allTime ? ' disabled' : ''}`}>
<label className="field">
From
<input type="date" value={from} max={today} disabled={allTime} onChange={(e) => setFrom(e.target.value)} />
</label>
<label className="field">
To
<input type="date" value={to} max={today} disabled={allTime} onChange={(e) => setTo(e.target.value)} />
</label>
</div>
{badDates && <p className="form-error">The start date needs to be on or before the end date.</p>}
</section>
<section>
<h3>Format</h3>
<div className="field">
Save as
<div className="segmented" role="radiogroup" aria-label="Format">
{(['pdf', 'txt'] as const).map((f) => (
<button key={f} role="radio" aria-checked={format === f} className={format === f ? 'on' : ''} onClick={() => setFormat(f)}>
{f === 'pdf' ? 'PDF' : 'Text (.txt)'}
</button>
))}
</div>
</div>
<label className={`field${format === 'txt' ? ' disabled' : ''}`}>
Include attachments
<input type="checkbox" checked={format === 'pdf' && attachments} disabled={format === 'txt'} onChange={(e) => setAttachments(e.target.checked)} />
</label>
{format === 'txt' && <p className="muted small">A text file lists attachments as [Photo], [Audio] and so on.</p>}
{error && <p className="form-error">{error}</p>}
</section>
<footer>
<button onClick={onClose} disabled={busy}>
Cancel
</button>
<button className="primary" disabled={badDates || busy} onClick={go}>
{busy ? 'Exporting…' : 'Export…'}
</button>
</footer>
</div>
</div>
)
}
+32
View File
@@ -56,3 +56,35 @@ export const AlertIcon = () => (
<path d="M12 8v5M12 16h.01" /> <path d="M12 8v5M12 16h.01" />
</svg> </svg>
) )
export const AttachIcon = () => (
<svg {...base}>
<path d="m21 11.5-8.6 8.6a5.5 5.5 0 0 1-7.8-7.8l8.6-8.6a3.7 3.7 0 0 1 5.2 5.2l-8.6 8.6a1.8 1.8 0 0 1-2.6-2.6l8-8" />
</svg>
)
export const DownloadIcon = () => (
<svg {...base}>
<path d="M12 3v12m-5-5 5 5 5-5M4 20h16" />
</svg>
)
export const RefreshIcon = () => (
<svg {...base}>
<path d="M20 11a8 8 0 0 0-14.3-4.9L4 8" />
<path d="M4 3v5h5" />
<path d="M4 13a8 8 0 0 0 14.3 4.9L20 16" />
<path d="M20 21v-5h-5" />
</svg>
)
export const ArchiveIcon = () => (
<svg {...base}>
<rect x="3" y="4" width="18" height="5" rx="1" />
<path d="M5 9v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9M10 13h4" />
</svg>
)
export const GroupIcon = () => (
<svg {...base}>
<circle cx="9" cy="8" r="3.5" />
<path d="M2.5 20a6.5 6.5 0 0 1 13 0" />
<path d="M16 4.6a3.5 3.5 0 0 1 0 6.8" />
<path d="M18.5 14.2a6.5 6.5 0 0 1 3 5.8" />
</svg>
)
+59
View File
@@ -0,0 +1,59 @@
import { useEffect, useState } from 'react'
import { ContextMenu, type MenuItem } from './ContextMenu'
import { CloseIcon, DownloadIcon } from './Icons'
import { mediaSrc } from './MessageBubble'
// Copy an attachment to the clipboard as a PNG (so GIF/WebP/HEIC work too).
async function copyImage(id: number, index: number): Promise<void> {
const { mime, data } = await window.api.readMedia(id, index)
const bitmap = await createImageBitmap(new Blob([data], { type: mime }))
try {
const canvas = new OffscreenCanvas(bitmap.width, bitmap.height)
canvas.getContext('2d')!.drawImage(bitmap, 0, 0)
const png = await canvas.convertToBlob({ type: 'image/png' })
await window.api.copyImage(new Uint8Array(await png.arrayBuffer()))
} finally {
bitmap.close()
}
}
// Right-click on an image, in the chat or the lightbox.
export const imageMenuItems = (id: number, index: number): MenuItem[] => [
{ label: 'Copy image', onSelect: () => void copyImage(id, index).catch(() => undefined) },
{ label: 'Save image…', onSelect: () => void window.api.saveMedia(id, index).catch(() => undefined) }
]
export function Lightbox({ id, index, onClose }: { id: number; index: number; onClose: () => void }) {
const [menu, setMenu] = useState<{ x: number; y: number }>()
useEffect(() => {
const onKey = (e: KeyboardEvent): void => {
if (e.key === 'Escape' && !menu) onClose()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose, menu])
return (
<div className="lightbox" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="lightbox-bar">
<button className="icon-btn" title="Save…" onClick={() => void window.api.saveMedia(id, index)}>
<DownloadIcon />
</button>
<button className="icon-btn" title="Close (Esc)" onClick={onClose}>
<CloseIcon size={20} />
</button>
</div>
<img
src={mediaSrc(id, index)}
alt=""
draggable={false}
onContextMenu={(e) => {
e.preventDefault()
setMenu({ x: e.clientX, y: e.clientY })
}}
/>
{menu && <ContextMenu x={menu.x} y={menu.y} items={imageMenuItems(id, index)} onClose={() => setMenu(undefined)} />}
</div>
)
}
+84 -6
View File
@@ -1,5 +1,7 @@
import { memo, type ReactNode } from 'react' import { memo, useState, type ReactNode } from 'react'
import type { Message } from '@shared/types' import { mediaKind } from '@shared/mime'
import type { MediaRef, Message } from '@shared/types'
import type { Reaction } from '@shared/reactions'
import { highlightChunks, timeOfDay } from '../format' import { highlightChunks, timeOfDay } from '../format'
import { AlertIcon, ClockIcon } from './Icons' import { AlertIcon, ClockIcon } from './Icons'
@@ -26,15 +28,61 @@ function renderText(text: string, highlight: string): ReactNode[] {
return out return out
} }
export const mediaSrc = (id: number, index: number): string => `mms-media://m/${id}/${index}`
// Display box for an image: fit within 300×360, keeping the aspect ratio when
// we know it (so the list doesn't jump when the image arrives).
function imageBox(ref: MediaRef): { width: number; height: number } | undefined {
if (!ref.width || !ref.height) return undefined
const scale = Math.min(1, 300 / ref.width, 360 / ref.height)
return { width: Math.round(ref.width * scale), height: Math.round(ref.height * scale) }
}
function Attachment({ id, index, media, onOpen, onMenu, onLoad }: { id: number; index: number; media: MediaRef; onOpen: () => void; onMenu: (e: React.MouseEvent) => void; onLoad: () => void }) {
const [broken, setBroken] = useState(false)
const src = mediaSrc(id, index)
const kind = mediaKind(media)
if (broken) return <div className="media-missing">Media unavailable</div>
if (kind === 'image')
return (
<img
className="media-img"
src={src}
alt=""
draggable={false}
style={imageBox(media) ?? { minHeight: 120, minWidth: 120 }}
onClick={onOpen}
onContextMenu={onMenu}
onLoad={onLoad}
onError={() => setBroken(true)}
/>
)
if (kind === 'video') return <video className="media-video" src={src} controls preload="metadata" onLoadedMetadata={onLoad} onError={() => setBroken(true)} />
if (kind === 'audio') return <audio className="media-audio" src={src} controls preload="metadata" onError={() => setBroken(true)} />
return (
<button className="media-file" onClick={() => void window.api.saveMedia(id, index).catch(() => setBroken(true))}>
Attachment · Save…
</button>
)
}
interface Props { interface Props {
m: Message m: Message
sender?: string // group chats: name shown above the first bubble of a run
onSenderMenu?: (e: React.MouseEvent) => void
reactions?: Reaction[]
onShowReactions?: (reactions: Reaction[], x: number, y: number) => void
groupStart: boolean groupStart: boolean
groupEnd: boolean groupEnd: boolean
flash: boolean flash: boolean
highlight: string highlight: string
onOpenMedia: (id: number, index: number) => void
onMediaMenu: (id: number, index: number, e: React.MouseEvent) => void
onMediaLoad: () => void
} }
export const MessageBubble = memo(function MessageBubble({ m, groupStart, groupEnd, flash, highlight }: Props) { export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMenu, reactions, onShowReactions, groupStart, groupEnd, flash, highlight, onOpenMedia, onMediaMenu, onMediaLoad }: Props) {
const media = m.media ?? []
const cls = [ const cls = [
'msg', 'msg',
m.direction, m.direction,
@@ -47,9 +95,29 @@ export const MessageBubble = memo(function MessageBubble({ m, groupStart, groupE
.join(' ') .join(' ')
return ( return (
<div className={cls} data-id={m.id}> <div className={cls} data-id={m.id}>
<div className="bubble" title={new Date(m.ts).toLocaleString()}> {sender && (
<span className="text">{renderText(m.body, highlight)}</span> <div className="msg-sender" onContextMenu={onSenderMenu}>
{sender}
</div>
)}
<div
className={`bubble${media.length ? ' has-media' : ''}${media.length && !m.body ? ' media-only' : ''}`}
title={new Date(m.ts).toLocaleString()}
>
{media.length > 0 && (
<div className="media">
{media.map((ref, i) => (
<Attachment key={i} id={m.id} index={i} media={ref} onOpen={() => onOpenMedia(m.id, i)} onMenu={(e) => onMediaMenu(m.id, i, e)} onLoad={onMediaLoad} />
))}
</div>
)}
{m.body && <span className="text">{renderText(m.body, highlight)}</span>}
<span className="meta"> <span className="meta">
{m.kind === 'mms' && !media.length && (
<span className="kind-tag" title="Sent as one MMS, so it arrives as a single message">
MMS
</span>
)}
{timeOfDay(m.ts)} {timeOfDay(m.ts)}
{m.status === 'pending' && ( {m.status === 'pending' && (
<span className="status" title="Sending…"> <span className="status" title="Sending…">
@@ -58,9 +126,19 @@ export const MessageBubble = memo(function MessageBubble({ m, groupStart, groupE
)} )}
</span> </span>
</div> </div>
{reactions && reactions.length > 0 && (
<button
className="reactions"
title="See who reacted"
onClick={(e) => onShowReactions?.(reactions, e.clientX, e.clientY)}
>
{[...new Set(reactions.map((r) => r.emoji))].join('')}
{reactions.length > 1 && <span className="reaction-count">{reactions.length}</span>}
</button>
)}
{m.status === 'failed' && ( {m.status === 'failed' && (
<div className="failed-row"> <div className="failed-row">
<AlertIcon /> Not sent · <AlertIcon /> Not sent{m.error ? `: ${m.error}` : ''} ·
<button onClick={() => void window.api.retryFailed(m.id).catch(() => undefined)}>Retry</button>· <button onClick={() => void window.api.retryFailed(m.id).catch(() => undefined)}>Retry</button>·
<button onClick={() => void window.api.deleteFailed(m.id)}>Delete</button> <button onClick={() => void window.api.deleteFailed(m.id)}>Delete</button>
</div> </div>
+127 -27
View File
@@ -1,24 +1,32 @@
import { useEffect, useMemo, useRef, useState } from 'react' import { useEffect, useMemo, useRef, useState } from 'react'
import { formatNumber, normalizeNumber } from '@shared/phone' import { formatNumber, groupKey, normalizeNumber } from '@shared/phone'
import type { ContactInfo, Conversation } from '@shared/types' import type { ContactInfo, Conversation, Did } from '@shared/types'
import type { ConvKey } from '../App' import type { ConvKey } from '../App'
import { Avatar } from './Avatar' import { Avatar } from './Avatar'
import { BackIcon } from './Icons' import { BackIcon, CloseIcon, GroupIcon } from './Icons'
import { matchesContact } from './SearchResults' import { matchesContact } from './SearchResults'
interface Props { interface Props {
contacts: ContactInfo[] contacts: ContactInfo[]
conversations: Conversation[] conversations: Conversation[]
smsDids: Did[]
gvNumber?: string
defaultDid?: string defaultDid?: string
onPick: (key: ConvKey) => void onPick: (key: ConvKey) => void
onCancel: () => void onCancel: () => void
} }
export function NewChat({ contacts, conversations, defaultDid, onPick, onCancel }: Props) { export function NewChat({ contacts, conversations, smsDids, gvNumber, defaultDid, onPick, onCancel }: Props) {
const [q, setQ] = useState('') const [q, setQ] = useState('')
const [cursor, setCursor] = useState(0) const [cursor, setCursor] = useState(0)
const [from, setFrom] = useState(defaultDid)
const [fromChosen, setFromChosen] = useState(false)
// Building a group (Google Voice only): picking people adds them to it.
const [grouping, setGrouping] = useState(false)
const [members, setMembers] = useState<string[]>([])
const inputRef = useRef<HTMLInputElement>(null) const inputRef = useRef<HTMLInputElement>(null)
const listRef = useRef<HTMLDivElement>(null) const listRef = useRef<HTMLDivElement>(null)
const canGroup = !!from && from === gvNumber
useEffect(() => inputRef.current?.focus(), []) useEffect(() => inputRef.current?.focus(), [])
@@ -31,45 +39,116 @@ export function NewChat({ contacts, conversations, defaultDid, onPick, onCancel
const matches = useMemo(() => { const matches = useMemo(() => {
const list = q.trim() ? contacts.filter((c) => matchesContact(q, c.name, c.number)) : contacts const list = q.trim() ? contacts.filter((c) => matchesContact(q, c.name, c.number)) : contacts
return [...list].sort((a, b) => (recency.get(b.number) ?? 0) - (recency.get(a.number) ?? 0) || a.name.localeCompare(b.name)).slice(0, 100) return [...list]
}, [q, contacts, recency]) .filter((c) => !members.includes(c.number))
.sort((a, b) => (recency.get(b.number) ?? 0) - (recency.get(a.number) ?? 0) || a.name.localeCompare(b.name))
.slice(0, 100)
}, [q, contacts, recency, members])
const typed = normalizeNumber(q) const typed = normalizeNumber(q)
const typedIsNumber = /^[\d\s()+.-]+$/.test(q.trim()) && (typed.length === 10 || (typed.length >= 3 && typed.length <= 6)) const typedIsNumber = /^[\d\s()+.-]+$/.test(q.trim()) && (typed.length === 10 || (typed.length >= 3 && typed.length <= 6))
const options: Array<{ number: string; contact?: ContactInfo }> = [ const options: Array<{ number: string; contact?: ContactInfo }> = [
...(typedIsNumber && !matches.some((m) => m.number === typed) ? [{ number: typed }] : []), ...(typedIsNumber && !matches.some((m) => m.number === typed) && !members.includes(typed) ? [{ number: typed }] : []),
...matches.map((c) => ({ number: c.number, contact: c })) ...matches.map((c) => ({ number: c.number, contact: c }))
] ]
const nameOf = (n: string): string => contacts.find((c) => c.number === n)?.name ?? formatNumber(n)
useEffect(() => setCursor(0), [q]) useEffect(() => setCursor(0), [q])
useEffect(() => { useEffect(() => {
listRef.current?.querySelector<HTMLElement>(`[data-i="${cursor}"]`)?.scrollIntoView({ block: 'nearest' }) listRef.current?.querySelector<HTMLElement>(`[data-i="${cursor}"]`)?.scrollIntoView({ block: 'nearest' })
}, [cursor]) }, [cursor])
const pick = (number: string): void => { const open = (contact: string): void => {
if (!defaultDid) return if (!from) return
// Reuse an existing conversation with this person if there is one. // Reuse an existing conversation with this person (or group) if there is
const existing = conversations.find((c) => c.contact === number) // one -- from the chosen number, or any number if none was chosen.
onPick({ did: existing?.did ?? defaultDid, contact: number }) const existing = conversations.find((c) => c.contact === contact && (c.did === from || !fromChosen))
onPick({ did: existing?.did ?? from, contact })
} }
// Groups only exist on Google Voice, so starting one sends from there.
const startGroup = (): void => {
if (!gvNumber) return
setFrom(gvNumber)
setFromChosen(true)
setGrouping(true)
setQ('')
inputRef.current?.focus()
}
const addMember = (number: string): void => {
if (!grouping) startGroup()
setMembers((m) => [...m, number])
setQ('')
inputRef.current?.focus()
}
// Opens the chat with exactly these people -- the existing one if there is.
const done = (): void => {
if (members.length) open(members.length > 1 ? groupKey(members) : members[0])
}
const pick = (number: string): void => (grouping ? addMember(number) : open(number))
return ( return (
<> <>
<header className="sidebar-header compose"> <header className="sidebar-header compose">
<button className="icon-btn" title="Back" onClick={onCancel}> <button className="icon-btn" title="Back" onClick={onCancel}>
<BackIcon /> <BackIcon />
</button> </button>
<span className="compose-title">New chat</span> <span className="compose-title">{grouping ? 'New group' : 'New chat'}</span>
{grouping && (
<button className="primary small start-group" disabled={!members.length} onClick={done}>
Done
</button>
)}
</header> </header>
{smsDids.length > 1 && (
<label className="from-picker compose-from">
From
<select
value={from}
onChange={(e) => {
setFrom(e.target.value)
setFromChosen(true)
if (e.target.value !== gvNumber) {
setMembers([])
setGrouping(false)
}
}}
>
{smsDids.map((d) => (
<option key={d.did} value={d.did}>
{formatNumber(d.did)}
{d.provider === 'gvoice' ? ' — Google Voice' : d.description ? ` — ${d.description}` : ''}
</option>
))}
</select>
</label>
)}
{members.length > 0 && (
<div className="chips">
{members.map((n) => (
<span key={n} className="chip">
{nameOf(n)}
<button title="Remove" onClick={() => setMembers((m) => m.filter((x) => x !== n))}>
<CloseIcon size={12} />
</button>
</span>
))}
</div>
)}
<div className="to-field"> <div className="to-field">
<span>To:</span> <span>{grouping ? 'Add:' : 'To:'}</span>
<input <input
ref={inputRef} ref={inputRef}
value={q} value={q}
placeholder="Name or number" placeholder={grouping && !members.length ? 'Add people to the group' : 'Name or number'}
onChange={(e) => setQ(e.target.value)} onChange={(e) => setQ(e.target.value)}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === 'Escape') onCancel() if (e.key === 'Escape') onCancel()
else if (e.key === 'Enter' && grouping && !q.trim() && members.length) done()
else if (e.key === 'Backspace' && !q && members.length) setMembers((m) => m.slice(0, -1))
else if (e.key === 'ArrowDown') { else if (e.key === 'ArrowDown') {
e.preventDefault() e.preventDefault()
setCursor((c) => Math.min(options.length - 1, c + 1)) setCursor((c) => Math.min(options.length - 1, c + 1))
@@ -80,28 +159,49 @@ export function NewChat({ contacts, conversations, defaultDid, onPick, onCancel
}} }}
/> />
</div> </div>
{!defaultDid && <div className="list-empty">No SMS-enabled number to send from. Check Settings.</div>} {!from && <div className="list-empty">No SMS-enabled number to send from. Check Settings.</div>}
<div className="sidebar-body search-results" ref={listRef}> <div className="sidebar-body search-results" ref={listRef}>
{options.map((o, i) => ( {!grouping && !q.trim() && (
<button <button
key={o.number + (o.contact ? '' : ':typed')} className="row group-row"
data-i={i} disabled={!gvNumber}
className={`row${i === cursor ? ' active' : ''}`} title={gvNumber ? undefined : 'Group chats need Google Voice — connect it in Settings.'}
onMouseEnter={() => setCursor(i)} onClick={startGroup}
onClick={() => pick(o.number)}
> >
<Avatar number={o.number} contact={o.contact} size={40} /> <span className="group-row-icon">
<GroupIcon />
</span>
<div className="row-main"> <div className="row-main">
<div className="row-top"> <div className="row-top">
<span className="row-name">{o.contact?.name ?? formatNumber(o.number)}</span> <span className="row-name">Group chat</span>
</div> </div>
<div className="row-bottom"> <div className="row-bottom">
<span className="row-preview"> <span className="row-preview">{gvNumber ? 'Pick several people, then Done' : 'Needs Google Voice (Settings)'}</span>
{o.contact ? formatNumber(o.number) + (o.contact.label ? ` · ${o.contact.label}` : '') : 'Send to this number'}
</span>
</div> </div>
</div> </div>
</button> </button>
)}
{options.map((o, i) => (
<div key={o.number + (o.contact ? '' : ':typed')} className="row-wrap">
<button data-i={i} className={`row${i === cursor ? ' active' : ''}`} onMouseEnter={() => setCursor(i)} onClick={() => pick(o.number)}>
<Avatar number={o.number} contact={o.contact} size={40} />
<div className="row-main">
<div className="row-top">
<span className="row-name">{o.contact?.name ?? formatNumber(o.number)}</span>
</div>
<div className="row-bottom">
<span className="row-preview">
{o.contact ? formatNumber(o.number) + (o.contact.label ? ` · ${o.contact.label}` : '') : 'Send to this number'}
</span>
</div>
</div>
</button>
{canGroup && !grouping && (
<button className="add-member" title="Start a group with this person" onClick={() => addMember(o.number)}>
+ Group
</button>
)}
</div>
))} ))}
{q && !options.length && <div className="list-empty">No matching contacts. Type a 10-digit number.</div>} {q && !options.length && <div className="list-empty">No matching contacts. Type a 10-digit number.</div>}
</div> </div>
+18 -9
View File
@@ -1,8 +1,8 @@
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { formatNumber } from '@shared/phone' import { formatNumber, groupMembers, isGroup } from '@shared/phone'
import { SNIPPET_END, SNIPPET_START, type ContactInfo, type Conversation, type SearchHit } from '@shared/types' import { SNIPPET_END, SNIPPET_START, type ContactInfo, type Conversation, type SearchHit } from '@shared/types'
import type { ConvKey } from '../App' import type { ConvKey } from '../App'
import { displayName, shortTime } from '../format' import { convName, senderName, shortTime } from '../format'
import { Avatar } from './Avatar' import { Avatar } from './Avatar'
interface Props { interface Props {
@@ -38,10 +38,19 @@ export function SearchResults({ query, conversations, contacts, contactMap, defa
} }
}, [query]) }, [query])
const chats = useMemo( const chats = useMemo(() => {
() => conversations.filter((c) => matchesContact(query, contactMap.get(c.contact)?.name ?? '', c.contact)).slice(0, 8), // Chats whose own title matches come first, so a group you named isn't
[query, conversations, contactMap] // crowded out by every other chat that merely includes a matching member.
) const byName: Conversation[] = []
const byMember: Conversation[] = []
for (const c of conversations) {
if (matchesContact(query, convName(c.contact, contactMap, c.name), c.contact)) byName.push(c)
// A group turns up under any of its members, whatever it's called.
else if (isGroup(c.contact) && groupMembers(c.contact).some((n) => matchesContact(query, senderName(n, contactMap), n)))
byMember.push(c)
}
return [...byName, ...byMember].slice(0, 8)
}, [query, conversations, contactMap])
const otherContacts = useMemo(() => { const otherContacts = useMemo(() => {
const inChats = new Set(conversations.map((c) => c.contact)) const inChats = new Set(conversations.map((c) => c.contact))
return contacts.filter((c) => !inChats.has(c.number) && matchesContact(query, c.name, c.number)).slice(0, 8) return contacts.filter((c) => !inChats.has(c.number) && matchesContact(query, c.name, c.number)).slice(0, 8)
@@ -61,10 +70,10 @@ export function SearchResults({ query, conversations, contacts, contactMap, defa
<Avatar number={c.contact} contact={contact} size={40} /> <Avatar number={c.contact} contact={contact} size={40} />
<div className="row-main"> <div className="row-main">
<div className="row-top"> <div className="row-top">
<span className="row-name">{displayName(c.contact, contact)}</span> <span className="row-name">{convName(c.contact, contactMap, c.name)}</span>
</div> </div>
<div className="row-bottom"> <div className="row-bottom">
<span className="row-preview">{formatNumber(c.contact)}</span> <span className="row-preview">{isGroup(c.contact) ? 'Group' : formatNumber(c.contact)}</span>
</div> </div>
</div> </div>
</button> </button>
@@ -113,7 +122,7 @@ export function SearchResults({ query, conversations, contacts, contactMap, defa
<Avatar number={h.contact} contact={contact} size={40} /> <Avatar number={h.contact} contact={contact} size={40} />
<div className="row-main"> <div className="row-main">
<div className="row-top"> <div className="row-top">
<span className="row-name">{displayName(h.contact, contact)}</span> <span className="row-name">{convName(h.contact, contactMap, conversations.find((c) => c.did === h.did && c.contact === h.contact)?.name)}</span>
<span className="row-time">{shortTime(h.ts)}</span> <span className="row-time">{shortTime(h.ts)}</span>
</div> </div>
<div className="row-snippet"> <div className="row-snippet">
+256 -8
View File
@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import type { AppState } from '@shared/api' import type { AppState, RabbitStatus } from '@shared/api'
import { formatNumber } from '@shared/phone' import { formatNumber } from '@shared/phone'
import type { Settings, SyncStatus } from '@shared/types' import type { AddressBook, GvStatus, Settings, SyncStatus, Theme } from '@shared/types'
import { CloseIcon } from './Icons' import { CloseIcon } from './Icons'
interface Props { interface Props {
@@ -14,8 +14,10 @@ interface Props {
export function SettingsDialog({ state, sync, onClose, onChanged }: Props) { export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
const [s, setS] = useState<Settings>(state.settings) const [s, setS] = useState<Settings>(state.settings)
const [note, setNote] = useState<string>() const [note, setNote] = useState<string>()
const smsDids = state.dids.filter((d) => d.smsEnabled) // voip.ms numbers; Google Voice has its own section.
const dirty = JSON.stringify(s) !== JSON.stringify(state.settings) const smsDids = state.dids.filter((d) => d.smsEnabled && d.provider !== 'gvoice')
// Theme is saved on click, so it never makes the dialog dirty.
const dirty = JSON.stringify({ ...s, theme: undefined }) !== JSON.stringify({ ...state.settings, theme: undefined })
useEffect(() => { useEffect(() => {
const onKey = (e: KeyboardEvent): void => { const onKey = (e: KeyboardEvent): void => {
@@ -32,6 +34,7 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
} }
const synced = s.dids.length ? s.dids : smsDids.map((d) => d.did) const synced = s.dids.length ? s.dids : smsDids.map((d) => d.did)
const sendFrom = state.gvoiceNumber ? [...synced, state.gvoiceNumber] : synced
return ( return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}> <div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
@@ -43,6 +46,36 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
</button> </button>
</header> </header>
<section>
<h3>Appearance</h3>
<div className="field">
Theme
<div className="segmented" role="radiogroup" aria-label="Theme">
{(['system', 'light', 'dark'] as Theme[]).map((t) => (
<button
key={t}
role="radio"
aria-checked={s.theme === t}
className={s.theme === t ? 'on' : ''}
onClick={() => {
setS({ ...s, theme: t })
void window.api.setTheme(t).then(onChanged)
}}
>
{t[0].toUpperCase() + t.slice(1)}
</button>
))}
</div>
</div>
<label className="field">
Show new messages in the notification list
<input type="checkbox" checked={s.notifications} onChange={(e) => setS({ ...s, notifications: e.target.checked })} />
</label>
<p className="muted small">
Zoom with <kbd>Ctrl</kbd> <kbd>+</kbd> / <kbd>Ctrl</kbd> <kbd>−</kbd>, and <kbd>Ctrl</kbd> <kbd>0</kbd> to reset.
</p>
</section>
<section> <section>
<h3>Account</h3> <h3>Account</h3>
<div className="kv"> <div className="kv">
@@ -71,6 +104,12 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
</button> </button>
</section> </section>
<GoogleVoiceSection number={state.gvoiceNumber} status={sync?.gvoice} onChanged={onChanged} />
<ContactsSection value={s.contactBook} onChange={(contactBook) => setS({ ...s, contactBook })} />
<RabbitSection onChanged={onChanged} />
{smsDids.length > 0 && ( {smsDids.length > 0 && (
<section> <section>
<h3>Numbers</h3> <h3>Numbers</h3>
@@ -88,13 +127,14 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
<span className="muted">{d.description}</span> <span className="muted">{d.description}</span>
</label> </label>
))} ))}
{smsDids.length > 1 && ( {sendFrom.length > 1 && (
<label className="field"> <label className="field">
Send new chats from Send new chats from
<select value={s.defaultDid ?? synced[0]} onChange={(e) => setS({ ...s, defaultDid: e.target.value })}> <select value={s.defaultDid ?? sendFrom[0]} onChange={(e) => setS({ ...s, defaultDid: e.target.value })}>
{synced.map((d) => ( {sendFrom.map((d) => (
<option key={d} value={d}> <option key={d} value={d}>
{formatNumber(d)} {formatNumber(d)}
{d === state.gvoiceNumber ? ' — Google Voice' : ''}
</option> </option>
))} ))}
</select> </select>
@@ -137,7 +177,7 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
</section> </section>
<footer> <footer>
<button onClick={onClose}>Cancel</button> <button onClick={onClose}>{dirty ? 'Cancel' : 'Close'}</button>
<button className="primary" disabled={!dirty} onClick={() => void save()}> <button className="primary" disabled={!dirty} onClick={() => void save()}>
Save Save
</button> </button>
@@ -146,3 +186,211 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
</div> </div>
) )
} }
const cleanError = (e: Error): string => e.message.replace(/^Error invoking remote method '\w+': (Error: )?/, '')
function gvStatusText(st?: GvStatus): string {
if (!st) return 'Starting…'
if (st.phase === 'signedOut') return 'Signed out'
if (st.phase === 'error') return `Error: ${st.error ?? 'unknown'}`
if (!st.backfillDone) return 'Importing history…'
return st.lastPoll ? `Up to date (checked ${new Date(st.lastPoll).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })})` : 'Connected'
}
function GoogleVoiceSection({ number, status, onChanged }: { number?: string; status?: GvStatus; onChanged: () => void }) {
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string>()
const [cookies, setCookies] = useState('')
const signedOut = status?.phase === 'signedOut'
const run = (p: Promise<void>): void => {
setBusy(true)
setError(undefined)
p.then(onChanged)
.catch((e: Error) => setError(cleanError(e)))
.finally(() => setBusy(false))
}
const fallback = (
<details className="gv-fallback">
<summary>Sign-in window not working?</summary>
<p className="muted small">
Google sometimes refuses sign-ins inside apps. Instead, sign in at voice.google.com in Firefox, open the developer tools
(F12) → Network, reload, right-click any request to <code>clients6.google.com</code> → Copy → Copy as cURL, and paste it here.
It holds your Google sign-in, so only paste it here.
</p>
<textarea value={cookies} onChange={(e) => setCookies(e.target.value)} placeholder="curl 'https://clients6.google.com/…' -H 'Cookie: …'" rows={4} />
<button disabled={busy || !cookies.trim()} onClick={() => run(window.api.connectGoogleVoiceCookies(cookies).then(() => setCookies('')))}>
Connect with these cookies
</button>
</details>
)
return (
<section>
<h3>Google Voice</h3>
{number ? (
<>
<div className="kv">
<span>Number</span>
<span>{formatNumber(number)}</span>
</div>
<div className="kv">
<span>Status</span>
<span>{gvStatusText(status)}</span>
</div>
<div className="btn-row">
{signedOut && (
<button className="primary" disabled={busy} onClick={() => run(window.api.connectGoogleVoice())}>
Reconnect…
</button>
)}
<button className="danger" disabled={busy} onClick={() => run(window.api.disconnectGoogleVoice())}>
Disconnect
</button>
</div>
{signedOut && fallback}
</>
) : (
<>
<p className="muted small">
Text from your Google Voice number here too. This uses the private API behind voice.google.com (Google has no public one),
so a change on Google's side can break it until the app is updated. voip.ms keeps working either way.
</p>
<button className="primary" disabled={busy} onClick={() => run(window.api.connectGoogleVoice())}>
{busy ? 'Waiting for sign-in…' : 'Connect Google Voice…'}
</button>
{fallback}
</>
)}
{error && <p className="form-error">{error}</p>}
</section>
)
}
// Where "Add to contacts" puts new contacts.
function ContactsSection({ value, onChange }: { value?: string; onChange: (uid?: string) => void }) {
const [books, setBooks] = useState<AddressBook[]>()
const [fallback, setFallback] = useState<string>()
const [error, setError] = useState<string>()
useEffect(() => {
window.api
.listAddressBooks()
.then((r) => {
setBooks(r.books)
setFallback(r.books.find((b) => b.uid === r.default)?.name)
})
.catch((e: Error) => setError(cleanError(e)))
}, [])
return (
<section>
<h3>Contacts</h3>
<label className="field">
Add new contacts to
<select value={value ?? ''} disabled={!books} onChange={(e) => onChange(e.target.value || undefined)}>
<option value="">Same as GNOME Contacts{fallback ? ` (${fallback})` : ''}</option>
{books?.map((b) => (
<option key={b.uid} value={b.uid}>
{b.name}
{b.account ? ` (${b.account})` : ''}
</option>
))}
</select>
</label>
<p className="muted small">Right-click a number that isn't in your contacts to add it.</p>
{error && <p className="form-error">{error}</p>}
</section>
)
}
// The Android app on a Rabbit R1, installed and kept in step over USB.
function RabbitSection({ onChanged }: { onChanged: () => void }) {
const [st, setSt] = useState<RabbitStatus>()
const [busy, setBusy] = useState(false)
const [step, setStep] = useState<string>()
const [error, setError] = useState<string>()
const [done, setDone] = useState<string>()
const refresh = (): void => void window.api.rabbitStatus().then(setSt)
useEffect(() => {
refresh()
const t = setInterval(refresh, 4000) // notice it being plugged in
const off = window.api.onRabbitProgress(setStep)
return () => {
clearInterval(t)
off()
}
}, [])
const run = (what: 'install' | 'update' | 'sync'): void => {
setBusy(true)
setError(undefined)
setDone(undefined)
;(what === 'sync' ? window.api.rabbitSync() : window.api.rabbitInstall(what === 'update' ? 'update' : 'full'))
.then(() => {
setDone(
what === 'install'
? 'Installed. It\'s open on the Rabbit now.'
: what === 'update'
? 'Updated. It\'s open on the Rabbit now.'
: 'Synced accounts, chat names and read status.'
)
onChanged()
})
.catch((e: Error) => setError(cleanError(e)))
.finally(() => {
setBusy(false)
setStep(undefined)
refresh()
})
}
const device = st?.device
const installed = device?.installedVersion
return (
<section>
<h3>Rabbit</h3>
<div className="kv">
<span>Device</span>
<span>{!st ? '…' : !st.adb ? 'adb not installed' : device ? device.model : 'Not connected'}</span>
</div>
{device && (
<div className="kv">
<span>bubble on it</span>
<span>
{installed ? `Version ${installed}` : 'Not installed'}
{installed && st?.bundledVersion && installed !== st.bundledVersion ? ` (update to ${st.bundledVersion} available)` : ''}
</span>
</div>
)}
<p className="muted small">
Install puts the app on the Rabbit along with your voip.ms and Google Voice sign-ins, your message history and photos, and
your chat names. Update installs a new version of the app and keeps everything already on the Rabbit. Sync sends the
sign-ins again (say, after reconnecting Google Voice here) and merges chat names and read/unread/archived both ways, newest
change winning. Recopy replaces the Rabbit's history with this computer's, sending only photos it doesn't have.
</p>
<div className="btn-row">
{installed ? (
<button className="primary" disabled={busy} onClick={() => run('update')}>
Update app
</button>
) : (
<button className="primary" disabled={busy || !device} onClick={() => run('install')}>
Install to Rabbit
</button>
)}
<button disabled={busy || !installed} onClick={() => run('sync')}>
Sync to Rabbit
</button>
{installed && (
<button disabled={busy} onClick={() => run('install')}>
Recopy history &amp; photos
</button>
)}
</div>
{busy && step && <p className="muted small">{step}</p>}
{done && <p className="muted small">{done}</p>}
{error && <p className="form-error">{error}</p>}
</section>
)
}
+1 -1
View File
@@ -48,7 +48,7 @@ export function Setup({ initial, onDone }: { initial: AppState; onDone: () => vo
return ( return (
<div className="setup"> <div className="setup">
<div className="setup-card"> <div className="setup-card">
<h1>voip.ms Messages</h1> <h1>bubble</h1>
{!dids ? ( {!dids ? (
<> <>
<p className="muted"> <p className="muted">
+155 -11
View File
@@ -1,13 +1,89 @@
import { useEffect, useRef } from 'react' import { useEffect, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react'
import type { ContactInfo, Conversation, SyncStatus } from '@shared/types' import type { ContactInfo, Conversation, Did, SyncStatus } from '@shared/types'
import type { ConvKey } 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 { BackIcon, CloseIcon, ComposeIcon, GearIcon, 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'
// Dragging below the default width shrinks the sidebar's contents
// proportionally (via --s) rather than dropping parts of each row.
const DEFAULT_WIDTH = 340
const MIN_WIDTH = 170
const MAX_WIDTH = 640
const MIN_CHAT_WIDTH = 320
const WIDTH_KEY = 'sidebarWidth'
function clampWidth(w: number): number {
return Math.round(Math.max(MIN_WIDTH, Math.min(w, MAX_WIDTH, window.innerWidth - MIN_CHAT_WIDTH)))
}
function loadWidth(): number {
try {
const w = Number(localStorage.getItem(WIDTH_KEY))
if (w) return clampWidth(w)
} catch {
// storage unavailable: fall back to the default
}
return DEFAULT_WIDTH
}
function useSidebarWidth() {
const [width, setWidth] = useState(loadWidth)
const [dragging, setDragging] = useState(false)
// Re-clamp when the window shrinks so the chat pane keeps some room.
useEffect(() => {
const onResize = (): void => setWidth((w) => Math.max(MIN_WIDTH, Math.min(w, window.innerWidth - MIN_CHAT_WIDTH)))
window.addEventListener('resize', onResize)
return () => window.removeEventListener('resize', onResize)
}, [])
const save = (w: number): void => {
try {
localStorage.setItem(WIDTH_KEY, String(w))
} catch {
// not fatal; the width just won't persist
}
}
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>): void => {
if (e.button !== 0) return
e.preventDefault()
const handle = e.currentTarget
handle.setPointerCapture(e.pointerId)
const startX = e.clientX
const startW = width
let latest = startW
setDragging(true)
const onMove = (ev: PointerEvent): void => {
latest = clampWidth(startW + ev.clientX - startX)
setWidth(latest)
}
const onUp = (): void => {
handle.removeEventListener('pointermove', onMove)
handle.removeEventListener('pointerup', onUp)
handle.removeEventListener('pointercancel', onUp)
setDragging(false)
save(latest)
}
handle.addEventListener('pointermove', onMove)
handle.addEventListener('pointerup', onUp)
handle.addEventListener('pointercancel', onUp)
}
const reset = (): void => {
const w = clampWidth(DEFAULT_WIDTH)
setWidth(w)
save(w)
}
const scale = Math.min(1, width / DEFAULT_WIDTH)
return { width, scale, dragging, onPointerDown, reset }
}
interface Props { interface Props {
mode: SidebarMode mode: SidebarMode
setMode: (m: SidebarMode) => void setMode: (m: SidebarMode) => void
@@ -20,12 +96,20 @@ interface Props {
onOpen: (key: ConvKey, jumpTo?: number) => void onOpen: (key: ConvKey, jumpTo?: number) => void
sync?: SyncStatus sync?: SyncStatus
multiDid: boolean multiDid: boolean
smsDids: Did[]
gvNumber?: string
defaultDid?: string defaultDid?: string
onSettings: () => void onSettings: () => void
archiveView: boolean
setArchiveView: (on: boolean) => void
onMarkUnread: (key: ConvKey) => void
onInfo: (key: ConvKey) => void
onExport: (key: ConvKey) => void
} }
export function Sidebar(p: Props) { export function Sidebar(p: Props) {
const searchRef = useRef<HTMLInputElement>(null) const searchRef = useRef<HTMLInputElement>(null)
const size = useSidebarWidth()
useEffect(() => { useEffect(() => {
if (p.mode === 'search') searchRef.current?.focus() if (p.mode === 'search') searchRef.current?.focus()
@@ -37,11 +121,13 @@ export function Sidebar(p: Props) {
} }
return ( return (
<aside className="sidebar"> <aside className="sidebar" style={{ width: size.width, '--s': size.scale } as CSSProperties}>
{p.mode === 'compose' ? ( {p.mode === 'compose' ? (
<NewChat <NewChat
contacts={p.contacts} contacts={p.contacts}
conversations={p.conversations} conversations={p.conversations}
smsDids={p.smsDids}
gvNumber={p.gvNumber}
defaultDid={p.defaultDid} defaultDid={p.defaultDid}
onCancel={() => p.setMode('chats')} onCancel={() => p.setMode('chats')}
onPick={(key) => { onPick={(key) => {
@@ -88,6 +174,18 @@ export function Sidebar(p: Props) {
<button className="icon-btn" title="New chat (Ctrl+N)" onClick={() => p.setMode('compose')}> <button className="icon-btn" title="New chat (Ctrl+N)" onClick={() => p.setMode('compose')}>
<ComposeIcon /> <ComposeIcon />
</button> </button>
<RefreshButton />
<button
className={`icon-btn${p.archiveView ? ' on' : ''}`}
title={p.archiveView ? 'Back to chats' : 'Archived chats'}
aria-pressed={p.archiveView}
onClick={() => {
p.setArchiveView(!p.archiveView)
if (p.mode === 'search') clearSearch()
}}
>
<ArchiveIcon />
</button>
<button className="icon-btn" title="Settings" onClick={p.onSettings}> <button className="icon-btn" title="Settings" onClick={p.onSettings}>
<GearIcon /> <GearIcon />
</button> </button>
@@ -103,18 +201,39 @@ export function Sidebar(p: Props) {
onOpen={p.onOpen} onOpen={p.onOpen}
/> />
) : ( ) : (
<ConversationList <>
conversations={p.conversations} {p.archiveView && (
contactMap={p.contactMap} <div className="archive-header">
selected={p.selected} <button className="icon-btn inline" title="Back to chats" onClick={() => p.setArchiveView(false)}>
multiDid={p.multiDid} <BackIcon />
onOpen={p.onOpen} </button>
/> Archived chats
</div>
)}
<ConversationList
conversations={p.conversations.filter((c) => c.archived === p.archiveView)}
contactMap={p.contactMap}
selected={p.selected}
multiDid={p.multiDid}
gvNumber={p.gvNumber}
emptyText={p.archiveView ? 'No archived chats. Right-click a chat to archive it.' : 'No conversations yet.'}
onOpen={p.onOpen}
onMarkUnread={p.onMarkUnread}
onInfo={p.onInfo}
onExport={p.onExport}
/>
</>
)} )}
</div> </div>
</> </>
)} )}
<SyncFooter sync={p.sync} /> <SyncFooter sync={p.sync} />
<div
className={`sidebar-resizer${size.dragging ? ' dragging' : ''}`}
title="Drag to resize · double-click to reset"
onPointerDown={size.onPointerDown}
onDoubleClick={size.reset}
/>
</aside> </aside>
) )
} }
@@ -123,14 +242,23 @@ function SyncFooter({ sync }: { sync?: SyncStatus }) {
if (!sync) return null if (!sync) return null
let text = '' let text = ''
let cls = 'sync-footer' let cls = 'sync-footer'
const gv = sync.gvoice
if (sync.phase === 'error') { if (sync.phase === 'error') {
text = `⚠ ${sync.error ?? 'Sync error'}` text = `⚠ ${sync.error ?? 'Sync error'}`
cls += ' error' cls += ' error'
} else if (gv?.phase === 'signedOut') {
text = '⚠ Google Voice signed out. Reconnect it in Settings.'
cls += ' error'
} else if (gv?.phase === 'error') {
text = `⚠ Google Voice: ${gv.error ?? 'sync error'}`
cls += ' error'
} else if (!sync.backfillDone && sync.backfillCursor) { } else if (!sync.backfillDone && sync.backfillCursor) {
const d = new Date(sync.backfillCursor + 'T12:00:00Z') const d = new Date(sync.backfillCursor + 'T12:00:00Z')
text = `Importing history… back to ${d.toLocaleDateString([], { month: 'short', year: 'numeric' })} · ${sync.total.toLocaleString()} messages` text = `Importing history… back to ${d.toLocaleDateString([], { month: 'short', year: 'numeric' })} · ${sync.total.toLocaleString()} messages`
} else if (!sync.backfillDone && sync.phase === 'backfill') { } else if (!sync.backfillDone && sync.phase === 'backfill') {
text = 'Importing history…' text = 'Importing history…'
} else if (gv && !gv.backfillDone && gv.phase === 'backfill') {
text = `Importing Google Voice history… · ${sync.total.toLocaleString()} messages`
} else { } else {
return null return null
} }
@@ -140,3 +268,19 @@ function SyncFooter({ sync }: { sync?: SyncStatus }) {
</div> </div>
) )
} }
function RefreshButton() {
const [busy, setBusy] = useState(false)
const refresh = (): void => {
if (busy) return
setBusy(true)
// Keep the spin visible briefly even when voip.ms answers instantly.
const minSpin = new Promise((r) => setTimeout(r, 600))
void Promise.allSettled([window.api.pollNow(), minSpin]).then(() => setBusy(false))
}
return (
<button className={`icon-btn${busy ? ' spinning' : ''}`} title="Check for new messages" onClick={refresh}>
<RefreshIcon />
</button>
)
}
+11
View File
@@ -0,0 +1,11 @@
import { formatNumber } from '@shared/phone'
// "via <number>", with a GV tag when it's the Google Voice number.
export function Via({ did, gvNumber }: { did: string; gvNumber?: string }) {
return (
<>
via {did === gvNumber && <span className="gv-tag">GV</span>}
{formatNumber(did)}
</>
)
}
File diff suppressed because one or more lines are too long
+45
View File
@@ -0,0 +1,45 @@
import data from './emoji-data.json'
// [emoji, shortnames] in picker order; generated by scripts/gen-emoji.mjs.
const EMOJI = data as [string, string[]][]
const BY_NAME = new Map(EMOJI.flatMap(([char, names]) => names.map((n) => [n, char] as const)))
export interface EmojiMatch {
char: string
name: string
}
const NAME_CHAR = /[a-z0-9_+-]/i
const MIN_QUERY = 2
// The `:shortname` being typed at the caret, if any. The colon has to start a
// word so times ("10:30") and URLs ("http://") don't open the picker.
export function emojiQuery(text: string, caret: number): { start: number; query: string } | null {
let i = caret
while (i > 0 && NAME_CHAR.test(text[i - 1])) i--
const start = i - 1
if (start < 0 || text[start] !== ':') return null
if (start > 0 && !/[\s([]/.test(text[start - 1])) return null
const query = text.slice(i, caret)
return query.length >= MIN_QUERY ? { start, query } : null
}
// An exact name first, then prefix matches, then matches at a word start
// ("_heart"), then any substring; ties keep picker order. One entry per emoji.
export function searchEmoji(query: string, limit = 8): EmojiMatch[] {
const q = query.toLowerCase()
const tiers: EmojiMatch[][] = [[], [], [], []]
for (const [char, names] of EMOJI) {
let best: { tier: number; name: string } | undefined
for (const name of names) {
const at = name.indexOf(q)
if (at < 0) continue
const tier = name === q ? 0 : at === 0 ? 1 : name[at - 1] === '_' ? 2 : 3
if (!best || tier < best.tier) best = { tier, name }
}
if (best) tiers[best.tier].push({ char, name: best.name })
}
return tiers.flat().slice(0, limit)
}
export const exactEmoji = (name: string): string | undefined => BY_NAME.get(name.toLowerCase())
+45 -2
View File
@@ -1,5 +1,7 @@
import { formatNumber } from '@shared/phone' import { mediaKind } from '@shared/mime'
import type { ContactInfo } from '@shared/types' import { formatNumber, groupMembers, isGroup } from '@shared/phone'
import { reactionPreview } from '@shared/reactions'
import type { ContactInfo, Conversation } from '@shared/types'
const DAY = 86_400_000 const DAY = 86_400_000
@@ -44,10 +46,51 @@ export function sameDay(a: number, b: number): boolean {
return startOfDay(a) === startOfDay(b) return startOfDay(a) === startOfDay(b)
} }
const MEDIA_LABELS = { image: '📷 Photo', video: '🎥 Video', audio: '🎤 Audio', file: '📎 Attachment' }
// Sidebar preview line for a conversation's last message.
export function previewText(c: Pick<Conversation, 'lastBody' | 'lastMedia'>): string {
const reaction = reactionPreview(c.lastBody)
if (reaction) return reaction
const body = c.lastBody.replace(/\s+/g, ' ').trim()
if (!c.lastMedia) return body
const label = MEDIA_LABELS[mediaKind(c.lastMedia)]
return body ? `${label.split(' ')[0]} ${body}` : label
}
export function displayName(number: string, contact?: ContactInfo): string { export function displayName(number: string, contact?: ContactInfo): string {
return contact?.name ?? formatNumber(number) return contact?.name ?? formatNumber(number)
} }
const firstName = (number: string, contactMap: Map<string, ContactInfo>): string =>
contactMap.get(number)?.name.split(/\s+/)[0] ?? formatNumber(number)
// A conversation's title: the name you gave it, the person, or a group's
// members ("Sam, Alex +2").
export function convName(contact: string, contactMap: Map<string, ContactInfo>, name?: string): string {
if (name) return name
if (!isGroup(contact)) return displayName(contact, contactMap.get(contact))
const names = groupMembers(contact).map((n) => firstName(n, contactMap))
return names.length > 3 ? `${names.slice(0, 3).join(', ')} +${names.length - 3}` : names.join(', ')
}
// Every other chat this number is in -- groups, and 1:1s from your other
// numbers -- newest first.
export function chatsWith(number: string, conversations: Conversation[], except: { did: string; contact: string }): Conversation[] {
return conversations
.filter((c) => groupMembers(c.contact).includes(number) && !(c.did === except.did && c.contact === except.contact))
.sort((a, b) => b.lastTs - a.lastTs)
}
// Who sent a group message, as shown above their bubbles and in previews.
export function senderName(number: string, contactMap: Map<string, ContactInfo>): string {
return displayName(number, contactMap.get(number))
}
export function senderShortName(number: string, contactMap: Map<string, ContactInfo>): string {
return firstName(number, contactMap)
}
const AVATAR_COLORS = ['#e3b5a4', '#a4c9e3', '#b5e3a4', '#e3a4d6', '#e3d6a4', '#a4e3d4', '#c2a4e3', '#e3a4a4', '#a4b0e3', '#d4e3a4'] const AVATAR_COLORS = ['#e3b5a4', '#a4c9e3', '#b5e3a4', '#e3a4d6', '#e3d6a4', '#a4e3d4', '#c2a4e3', '#e3a4a4', '#a4b0e3', '#d4e3a4']
const AVATAR_INK = ['#5c2a17', '#16405c', '#2a5c17', '#5c1750', '#5c4a17', '#175c4c', '#3c175c', '#5c1717', '#17245c', '#4a5c17'] const AVATAR_INK = ['#5c2a17', '#16405c', '#2a5c17', '#5c1750', '#5c4a17', '#175c4c', '#3c175c', '#5c1717', '#17245c', '#4a5c17']
+88
View File
@@ -0,0 +1,88 @@
// Preparing attachments for MMS: voip.ms accepts ~1.2 MB per file and carriers
// are often stricter, so anything bigger gets downscaled / re-encoded as JPEG.
import type { OutgoingAttachment } from '@shared/types'
export const MMS_BUDGET = 900 * 1024
export const MAX_ATTACHMENTS = 3
export const MMS_TEXT_LIMIT = 2048
// Formats every phone can show; anything else is re-encoded as JPEG.
const PASSTHROUGH_IMAGES = new Set(['image/jpeg', 'image/png', 'image/gif'])
const EDGES = [2048, 1600, 1280, 1024, 800, 640]
const QUALITIES = [0.85, 0.72, 0.6]
export interface Attachment extends OutgoingAttachment {
previewUrl: string // blob: URL for the composer tray
originalBytes: number
note?: string // e.g. "Resized from 6.2 MB"
}
// Scale/quality attempts in order, from gentlest to harshest. The first one
// is always full size so small-but-exotic images (WebP, HEIC…) just convert.
export function compressionSteps(width: number, height: number): Array<{ scale: number; quality: number }> {
const long = Math.max(width, height)
const scales = [...new Set([1, ...EDGES.map((e) => Math.min(1, e / long))])].sort((a, b) => b - a)
return scales.flatMap((scale) => QUALITIES.map((quality) => ({ scale, quality })))
}
export function formatBytes(n: number): string {
if (n < 1024) return `${n} B`
if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`
return `${(n / 1024 / 1024).toFixed(1)} MB`
}
async function withPreview(blob: Blob, name: string, extra: Partial<Attachment> & { originalBytes: number }): Promise<Attachment> {
return {
name,
mime: blob.type,
data: new Uint8Array(await blob.arrayBuffer()),
previewUrl: URL.createObjectURL(blob),
...extra
}
}
export async function prepareAttachment(file: File): Promise<Attachment> {
const kind = file.type.split('/')[0]
if (kind === 'video' || kind === 'audio') {
if (file.size > MMS_BUDGET)
throw new Error(
`${kind === 'video' ? 'Video' : 'Audio'} is ${formatBytes(file.size)} — MMS attachments must be under ${formatBytes(MMS_BUDGET)}.`
)
return withPreview(file, file.name, { originalBytes: file.size })
}
if (kind !== 'image') throw new Error(`Can't send ${file.name || 'that file'}: only photos, video and audio can go by MMS.`)
let bitmap: ImageBitmap
try {
bitmap = await createImageBitmap(file)
} catch {
throw new Error(`Can't read ${file.name || 'that image'} (unsupported format). Try saving it as JPEG or PNG.`)
}
const { width, height } = bitmap
try {
if (file.size <= MMS_BUDGET && PASSTHROUGH_IMAGES.has(file.type)) {
return withPreview(file, file.name, { originalBytes: file.size, width, height })
}
for (const { scale, quality } of compressionSteps(width, height)) {
const w = Math.max(1, Math.round(width * scale))
const h = Math.max(1, Math.round(height * scale))
const canvas = new OffscreenCanvas(w, h)
const ctx = canvas.getContext('2d')!
ctx.fillStyle = '#fff' // JPEG has no alpha: flatten transparency onto white
ctx.fillRect(0, 0, w, h)
ctx.imageSmoothingQuality = 'high'
ctx.drawImage(bitmap, 0, 0, w, h)
const blob = await canvas.convertToBlob({ type: 'image/jpeg', quality })
if (blob.size <= MMS_BUDGET) {
const name = file.name.replace(/\.[^.]*$/, '') + '.jpg'
const shrunk = file.size > MMS_BUDGET
const note =
file.type === 'image/gif' ? 'Too big to animate — sending a still' : shrunk ? `Shrunk from ${formatBytes(file.size)}` : undefined
return withPreview(blob, name, { originalBytes: file.size, width: w, height: h, note })
}
}
throw new Error(`Couldn't shrink ${file.name || 'that image'} below ${formatBytes(MMS_BUDGET)}.`)
} finally {
bitmap.close()
}
}
+604 -51
View File
@@ -1,10 +1,11 @@
/* Signal Desktop–inspired theme. Light + dark follow the system setting. */ /* Signal Desktop–inspired theme. Light + dark follow prefers-color-scheme, which the main process points at the system or the Settings choice (nativeTheme.themeSource). */
:root { :root {
--accent: #2c6bed; --accent: #2c6bed;
--accent-hover: #1f5ad6; --accent-hover: #1f5ad6;
--bg: #ffffff; --bg: #ffffff;
--sidebar: #ffffff; --sidebar: #ffffff;
--panel: #f6f6f6; --panel: #f6f6f6;
--menu-bg: #ffffff;
--border: #e9e9e9; --border: #e9e9e9;
--text: #1b1b1b; --text: #1b1b1b;
--muted: #6b6b6b; --muted: #6b6b6b;
@@ -28,6 +29,7 @@
--bg: #121212; --bg: #121212;
--sidebar: #1b1b1d; --sidebar: #1b1b1d;
--panel: #242426; --panel: #242426;
--menu-bg: #2a2a2d;
--border: #2e2e30; --border: #2e2e30;
--text: #e9e9e9; --text: #e9e9e9;
--muted: #a3a3a3; --muted: #a3a3a3;
@@ -55,7 +57,7 @@ body,
margin: 0; margin: 0;
} }
body { body {
font-family: Inter, 'Cantarell', system-ui, -apple-system, 'Segoe UI', sans-serif; font-family: Inter, 'Cantarell', system-ui, -apple-system, 'Segoe UI', 'Apple Color Emoji', 'Noto Color Emoji', sans-serif;
font-size: 14px; font-size: 14px;
background: var(--bg); background: var(--bg);
color: var(--text); color: var(--text);
@@ -100,41 +102,65 @@ mark {
} }
/* ---------- sidebar ---------- */ /* ---------- sidebar ---------- */
/* Width is set inline (user-resizable). Below the default width --s drops
under 1 and everything sized with var(--s) shrinks with it. */
.sidebar { .sidebar {
width: 340px; position: relative;
min-width: 280px; flex: none;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
font-size: calc(14px * var(--s, 1));
background: var(--sidebar); background: var(--sidebar);
border-right: 1px solid var(--border); border-right: 1px solid var(--border);
} }
.sidebar svg[width='20'] {
width: calc(20px * var(--s, 1));
height: calc(20px * var(--s, 1));
}
.sidebar svg[width='16'] {
width: calc(16px * var(--s, 1));
height: calc(16px * var(--s, 1));
}
.sidebar-resizer {
position: absolute;
top: 0;
right: -4px;
bottom: 0;
width: 8px;
z-index: 5;
cursor: col-resize;
}
.sidebar-resizer:hover,
.sidebar-resizer.dragging {
background: linear-gradient(to right, transparent 3px, var(--accent) 3px, var(--accent) 5px, transparent 5px);
}
.sidebar-header { .sidebar-header {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 4px; gap: calc(4px * var(--s, 1));
padding: 12px 10px 8px 12px; padding: calc(12px * var(--s, 1)) calc(10px * var(--s, 1)) calc(8px * var(--s, 1)) calc(12px * var(--s, 1));
} }
.sidebar-header.compose { .sidebar-header.compose {
gap: 8px; gap: calc(8px * var(--s, 1));
} }
.compose-title { .compose-title {
font-weight: 600; font-weight: 600;
font-size: 15px; font-size: calc(15px * var(--s, 1));
} }
.search-box { .search-box {
flex: 1; flex: 1;
display: flex; display: flex;
align-items: center; align-items: center;
background: var(--input-bg); background: var(--input-bg);
border-radius: 8px; border-radius: calc(8px * var(--s, 1));
height: 32px; height: calc(32px * var(--s, 1));
padding: 0 4px 0 8px; padding: 0 calc(4px * var(--s, 1)) 0 calc(8px * var(--s, 1));
min-width: 0; min-width: 0;
} }
.search-glyph { .search-glyph {
color: var(--faint); color: var(--faint);
display: flex; display: flex;
padding-right: 6px; padding-right: calc(6px * var(--s, 1));
} }
.search-box input { .search-box input {
flex: 1; flex: 1;
@@ -147,8 +173,8 @@ mark {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 32px; width: calc(32px * var(--s, 1));
height: 32px; height: calc(32px * var(--s, 1));
border: 0; border: 0;
background: transparent; background: transparent;
border-radius: 50%; border-radius: 50%;
@@ -164,14 +190,14 @@ mark {
cursor: default; cursor: default;
} }
.icon-btn.inline { .icon-btn.inline {
width: 24px; width: calc(24px * var(--s, 1));
height: 24px; height: calc(24px * var(--s, 1));
margin-left: -4px; margin-left: -4px;
margin-right: 2px; margin-right: calc(2px * var(--s, 1));
} }
.icon-btn.small { .icon-btn.small {
width: 28px; width: calc(28px * var(--s, 1));
height: 28px; height: calc(28px * var(--s, 1));
} }
.sidebar-body { .sidebar-body {
flex: 1; flex: 1;
@@ -182,31 +208,31 @@ mark {
height: 100%; height: 100%;
} }
.list-empty { .list-empty {
padding: 24px 16px; padding: calc(24px * var(--s, 1)) calc(16px * var(--s, 1));
color: var(--muted); color: var(--muted);
text-align: center; text-align: center;
} }
.section-label { .section-label {
padding: 14px 16px 6px; padding: calc(14px * var(--s, 1)) calc(16px * var(--s, 1)) calc(6px * var(--s, 1));
font-weight: 600; font-weight: 600;
font-size: 13px; font-size: calc(13px * var(--s, 1));
color: var(--text); color: var(--text);
} }
.section-label .count { .section-label .count {
color: var(--faint); color: var(--faint);
font-weight: 400; font-weight: 400;
margin-left: 4px; margin-left: calc(4px * var(--s, 1));
} }
.row { .row {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 12px; gap: calc(12px * var(--s, 1));
width: calc(100% - 16px); width: calc(100% - calc(16px * var(--s, 1)));
margin: 0 8px; margin: 0 calc(8px * var(--s, 1));
padding: 10px 8px; padding: calc(10px * var(--s, 1)) calc(8px * var(--s, 1));
border: 0; border: 0;
border-radius: 10px; border-radius: calc(10px * var(--s, 1));
background: transparent; background: transparent;
text-align: left; text-align: left;
} }
@@ -227,29 +253,29 @@ mark {
.row-bottom { .row-bottom {
display: flex; display: flex;
align-items: baseline; align-items: baseline;
gap: 8px; gap: calc(8px * var(--s, 1));
} }
.row-name { .row-name {
flex: 1; flex: 1;
font-weight: 600; font-weight: 600;
font-size: 14px; font-size: calc(14px * var(--s, 1));
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
} }
.row-time { .row-time {
font-size: 12px; font-size: calc(12px * var(--s, 1));
color: var(--faint); color: var(--faint);
flex: none; flex: none;
} }
.row-preview { .row-preview {
flex: 1; flex: 1;
color: var(--muted); color: var(--muted);
font-size: 13px; font-size: calc(13px * var(--s, 1));
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
margin-top: 2px; margin-top: calc(2px * var(--s, 1));
} }
.row.unread .row-preview { .row.unread .row-preview {
color: var(--text); color: var(--text);
@@ -259,14 +285,14 @@ mark {
font-weight: 600; font-weight: 600;
} }
.row-via { .row-via {
font-size: 11px; font-size: calc(11px * var(--s, 1));
color: var(--faint); color: var(--faint);
margin-top: 2px; margin-top: calc(2px * var(--s, 1));
} }
.row-snippet { .row-snippet {
color: var(--muted); color: var(--muted);
font-size: 13px; font-size: calc(13px * var(--s, 1));
margin-top: 2px; margin-top: calc(2px * var(--s, 1));
display: -webkit-box; display: -webkit-box;
-webkit-line-clamp: 2; -webkit-line-clamp: 2;
-webkit-box-orient: vertical; -webkit-box-orient: vertical;
@@ -279,28 +305,28 @@ mark {
.badge { .badge {
background: var(--accent); background: var(--accent);
color: #fff; color: #fff;
border-radius: 10px; border-radius: calc(10px * var(--s, 1));
font-size: 11px; font-size: calc(11px * var(--s, 1));
font-weight: 600; font-weight: 600;
min-width: 20px; min-width: calc(20px * var(--s, 1));
height: 20px; height: calc(20px * var(--s, 1));
line-height: 20px; line-height: calc(20px * var(--s, 1));
padding: 0 6px; padding: 0 calc(6px * var(--s, 1));
text-align: center; text-align: center;
flex: none; flex: none;
} }
.search-results { .search-results {
padding-bottom: 12px; padding-bottom: calc(12px * var(--s, 1));
} }
.to-field { .to-field {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: calc(8px * var(--s, 1));
margin: 0 12px 8px; margin: 0 calc(12px * var(--s, 1)) calc(8px * var(--s, 1));
padding: 0 10px; padding: 0 calc(10px * var(--s, 1));
height: 36px; height: calc(36px * var(--s, 1));
background: var(--input-bg); background: var(--input-bg);
border-radius: 8px; border-radius: calc(8px * var(--s, 1));
} }
.to-field span { .to-field span {
color: var(--muted); color: var(--muted);
@@ -312,9 +338,9 @@ mark {
background: transparent; background: transparent;
} }
.sync-footer { .sync-footer {
font-size: 12px; font-size: calc(12px * var(--s, 1));
color: var(--muted); color: var(--muted);
padding: 8px 14px; padding: calc(8px * var(--s, 1)) calc(14px * var(--s, 1));
border-top: 1px solid var(--border); border-top: 1px solid var(--border);
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;
@@ -380,6 +406,7 @@ mark {
.chat-name { .chat-name {
font-weight: 600; font-weight: 600;
font-size: 15px; font-size: 15px;
user-select: text;
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
@@ -519,6 +546,7 @@ mark {
.failed-row { .failed-row {
display: flex; display: flex;
align-items: center; align-items: center;
flex-wrap: wrap;
gap: 4px; gap: 4px;
font-size: 12px; font-size: 12px;
color: var(--danger); color: var(--danger);
@@ -539,6 +567,7 @@ mark {
border-top: 1px solid var(--border); border-top: 1px solid var(--border);
} }
.composer-row { .composer-row {
position: relative;
display: flex; display: flex;
align-items: flex-end; align-items: flex-end;
gap: 8px; gap: 8px;
@@ -555,6 +584,41 @@ mark {
max-height: 200px; max-height: 200px;
user-select: text; user-select: text;
} }
.emoji-suggest {
position: absolute;
bottom: calc(100% + 6px);
left: 44px;
z-index: 20;
min-width: 240px;
max-height: 290px;
overflow-y: auto;
padding: 4px;
background: var(--menu-bg);
border: 1px solid var(--border);
border-radius: 8px;
box-shadow: var(--shadow);
}
.emoji-suggest [role='option'] {
display: flex;
align-items: center;
gap: 10px;
padding: 5px 10px;
border-radius: 5px;
cursor: pointer;
}
.emoji-suggest .active {
background: var(--row-hover);
}
.emoji-glyph {
font-size: 22px;
line-height: 1;
width: 26px;
text-align: center;
}
.emoji-name {
color: var(--muted);
font-size: 13px;
}
.counter { .counter {
font-size: 11px; font-size: 11px;
color: var(--faint); color: var(--faint);
@@ -564,6 +628,15 @@ mark {
.counter.multi { .counter.multi {
color: var(--accent); color: var(--accent);
} }
.kind-tag {
font-size: 9px;
font-weight: 600;
letter-spacing: 0.04em;
padding: 0 4px;
border: 1px solid currentColor;
border-radius: 4px;
line-height: 13px;
}
.send-btn { .send-btn {
width: 36px; width: 36px;
height: 36px; height: 36px;
@@ -691,6 +764,10 @@ label.did {
label.did.disabled { label.did.disabled {
opacity: 0.5; opacity: 0.5;
} }
.export-chat .field.disabled,
.export-dates.disabled {
opacity: 0.5;
}
.modal-backdrop { .modal-backdrop {
position: fixed; position: fixed;
@@ -775,3 +852,479 @@ label.did.disabled {
gap: 8px; gap: 8px;
margin-top: 10px; margin-top: 10px;
} }
/* ---------- MMS ---------- */
.bubble.has-media {
padding: 4px 4px 6px;
}
.bubble.has-media .text {
display: block;
padding: 4px 8px 0;
}
.bubble.has-media .meta {
margin-right: 8px;
}
.bubble.media-only {
padding: 0;
background: transparent !important;
position: relative;
}
.bubble.media-only .meta {
position: absolute;
right: 8px;
bottom: 8px;
margin: 0;
padding: 1px 7px;
border-radius: 10px;
background: rgba(0, 0, 0, 0.5);
color: #fff;
opacity: 1;
}
.media {
display: flex;
flex-direction: column;
gap: 4px;
}
.media-img {
display: block;
max-width: min(300px, 100%);
max-height: 360px;
object-fit: cover;
border-radius: 14px;
background: var(--input-bg);
cursor: zoom-in;
}
.media-video {
display: block;
max-width: min(300px, 100%);
max-height: 360px;
border-radius: 14px;
background: #000;
}
.media-audio {
display: block;
width: 260px;
max-width: 100%;
}
.media-missing,
.media-file {
padding: 18px 20px;
border-radius: 14px;
background: color-mix(in srgb, currentColor 12%, transparent);
font-size: 13px;
opacity: 0.8;
border: 0;
}
.bubble.media-only .media-missing,
.bubble.media-only .media-file {
color: var(--muted);
background: var(--input-bg);
padding-right: 84px; /* room for the time pill */
}
.attach-tray {
display: flex;
gap: 8px;
margin: 0 0 8px 40px;
}
.attach-item {
position: relative;
width: 76px;
height: 76px;
border-radius: 10px;
overflow: hidden;
background: var(--input-bg);
flex: none;
display: flex;
align-items: center;
justify-content: center;
}
.attach-item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.attach-file {
font-size: 12px;
color: var(--muted);
text-transform: capitalize;
}
.attach-size {
position: absolute;
left: 4px;
bottom: 4px;
font-size: 10px;
padding: 0 5px;
border-radius: 6px;
background: rgba(0, 0, 0, 0.55);
color: #fff;
}
.attach-size.shrunk::before {
content: '↓ ';
}
.attach-remove {
position: absolute;
top: 3px;
right: 3px;
width: 20px;
height: 20px;
border-radius: 50%;
border: 0;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.55);
color: #fff;
}
.spinner {
width: 20px;
height: 20px;
border-radius: 50%;
border: 2px solid var(--faint);
border-top-color: transparent;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
.attach-btn {
margin-bottom: 2px;
}
.counter.over {
color: var(--danger);
}
.chat {
position: relative;
}
.drop-hint {
position: absolute;
inset: 8px;
border: 2px dashed var(--accent);
border-radius: 14px;
background: color-mix(in srgb, var(--bg) 85%, transparent);
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
font-weight: 600;
color: var(--accent);
pointer-events: none;
z-index: 5;
}
.lightbox {
position: fixed;
inset: 0;
z-index: 20;
background: rgba(0, 0, 0, 0.88);
display: flex;
align-items: center;
justify-content: center;
padding: 56px 32px 32px;
}
.lightbox img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
border-radius: 4px;
}
.lightbox-bar {
position: absolute;
top: 10px;
right: 12px;
display: flex;
gap: 4px;
}
.lightbox .icon-btn {
color: #ddd;
}
.lightbox .icon-btn:hover {
background: rgba(255, 255, 255, 0.12);
color: #fff;
}
/* ---------- settings: appearance ---------- */
.segmented {
display: inline-flex;
background: var(--input-bg);
border: 1px solid var(--border);
border-radius: 8px;
padding: 2px;
}
.modal .segmented button:not(.icon-btn):not(.primary) {
border: 0;
background: transparent;
border-radius: 6px;
padding: 4px 12px;
color: var(--muted);
}
.modal .segmented button.on:not(.icon-btn):not(.primary) {
background: var(--bg);
color: var(--text);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
}
kbd {
font-family: inherit;
font-size: 11px;
padding: 1px 5px;
border: 1px solid var(--border);
border-bottom-width: 2px;
border-radius: 4px;
background: var(--input-bg);
}
.icon-btn.spinning svg {
animation: spin 0.8s linear infinite;
}
.list-footer {
height: 14px;
}
/* ---------- archive + unread ---------- */
.icon-btn.on {
background: var(--row-active);
color: var(--text);
}
.archive-header {
display: flex;
align-items: center;
gap: calc(6px * var(--s, 1));
padding: calc(4px * var(--s, 1)) calc(16px * var(--s, 1)) calc(8px * var(--s, 1));
font-weight: 600;
font-size: calc(13px * var(--s, 1));
}
.badge.dot {
min-width: calc(12px * var(--s, 1));
width: calc(12px * var(--s, 1));
height: calc(12px * var(--s, 1));
padding: 0;
align-self: center;
}
.context-menu {
position: fixed;
z-index: 30;
min-width: 170px;
padding: 4px;
background: var(--menu-bg);
border: 1px solid var(--border);
border-radius: 8px;
box-shadow: var(--shadow);
display: flex;
flex-direction: column;
}
.context-menu button {
border: 0;
background: transparent;
text-align: left;
padding: 7px 12px;
border-radius: 5px;
}
.context-menu button:hover,
.context-menu button:focus-visible {
background: var(--row-hover);
outline: none;
}
/* ---------- Google Voice + group chats ---------- */
.gv-tag {
font-size: 9px;
font-weight: 700;
letter-spacing: 0.04em;
padding: 0 3px;
margin-right: 4px;
border: 1px solid currentColor;
border-radius: 4px;
line-height: 12px;
display: inline-block;
}
.msg-sender {
font-size: 12px;
color: var(--muted);
margin: 0 0 2px 10px;
}
.compose-from {
margin: 0 calc(12px * var(--s, 1)) calc(8px * var(--s, 1));
}
.start-group {
margin-left: auto;
padding: 4px 12px;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin: 0 calc(12px * var(--s, 1)) calc(8px * var(--s, 1));
}
.chip {
display: inline-flex;
align-items: center;
gap: 2px;
padding: 2px 4px 2px 10px;
border-radius: 999px;
background: var(--input-bg);
font-size: 13px;
}
.chip button {
border: 0;
background: none;
color: var(--muted);
display: flex;
padding: 2px;
border-radius: 50%;
}
.chip button:hover {
background: var(--row-active);
}
.row-wrap {
position: relative;
}
.add-member {
position: absolute;
right: 12px;
top: 50%;
transform: translateY(-50%);
font-size: 12px;
border: 1px solid var(--border);
background: var(--sidebar);
color: var(--muted);
border-radius: 999px;
padding: 2px 8px;
opacity: 0;
}
.row-wrap:hover .add-member,
.add-member:focus-visible {
opacity: 1;
}
.add-member:hover {
color: var(--text);
}
.gv-fallback {
margin-top: 10px;
}
.gv-fallback summary {
cursor: pointer;
font-size: 13px;
color: var(--muted);
}
.gv-fallback textarea {
width: 100%;
box-sizing: border-box;
font: 12px ui-monospace, monospace;
margin: 6px 0;
padding: 6px 8px;
background: var(--input-bg);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text);
}
/* ---------- chat info ---------- */
.chat-title.clickable {
cursor: pointer;
}
.chat-title.clickable:hover .chat-name {
text-decoration: underline;
}
.conv-info-top {
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
text-align: center;
}
.conv-info-title {
font-size: 18px;
font-weight: 600;
}
.conv-name-input {
width: 100%;
box-sizing: border-box;
padding: 8px 10px;
background: var(--input-bg);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
font-size: 15px;
}
.member {
display: flex;
align-items: center;
gap: 12px;
padding: 6px 0;
}
.member-main {
min-width: 0;
}
/* ---------- add contact ---------- */
.text-input {
display: block;
width: 100%;
box-sizing: border-box;
margin-top: 10px;
padding: 8px 10px;
background: var(--input-bg);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
font-size: 15px;
}
.add-contact .field {
margin-top: 12px;
}
.member-add {
margin-left: auto;
font-size: 12px;
}
/* ---------- reactions (iPhone tapbacks) ---------- */
.reactions {
display: inline-flex;
align-items: center;
gap: 4px;
margin-top: -6px;
margin-bottom: 2px;
padding: 1px 7px;
font-size: 14px;
line-height: 20px;
border-radius: 999px;
border: 2px solid var(--bg);
background: var(--bubble-in);
color: var(--text);
cursor: pointer;
position: relative;
z-index: 1;
}
.msg.in .reactions {
margin-left: 10px;
}
.msg.out .reactions {
margin-right: 10px;
}
.reaction-count {
font-size: 11px;
color: var(--muted);
}
.group-row-icon {
flex: none;
width: calc(40px * var(--s, 1));
height: calc(40px * var(--s, 1));
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
background: var(--input-bg);
color: var(--muted);
}
.context-menu button:disabled {
color: var(--muted);
background: transparent;
}
.context-menu .menu-sep {
height: 1px;
margin: 4px 6px;
background: var(--border);
}
+32 -2
View File
@@ -1,5 +1,5 @@
// The typed bridge exposed to the renderer as window.api. // The typed bridge exposed to the renderer as window.api.
import type { ContactInfo, Conversation, Credentials, Did, Message, SearchHit, Settings, SyncStatus } from './types' import type { AddressBook, ChatExport, ContactInfo, NewContact, Conversation, Credentials, Did, Message, OutgoingAttachment, SearchHit, Settings, SyncStatus, Theme } from './types'
export interface AppState { export interface AppState {
configured: boolean configured: boolean
@@ -8,6 +8,13 @@ export interface AppState {
dataDir: string dataDir: string
dids: Did[] dids: Did[]
keyringBackend: string keyringBackend: string
gvoiceNumber?: string // set when Google Voice is connected
}
export interface RabbitStatus {
adb: boolean // adb is installed
bundledVersion?: string // the Android app this build carries
device?: { serial: string; model: string; installedVersion?: string }
} }
export interface Api { export interface Api {
@@ -15,16 +22,37 @@ export interface Api {
testCredentials(creds: Credentials): Promise<Did[]> testCredentials(creds: Credentials): Promise<Did[]>
saveSetup(creds: Credentials, settings: Settings): Promise<void> saveSetup(creds: Credentials, settings: Settings): Promise<void>
updateSettings(settings: Settings): Promise<void> updateSettings(settings: Settings): Promise<void>
setTheme(theme: Theme): Promise<void>
signOut(): Promise<void> signOut(): Promise<void>
connectGoogleVoice(): Promise<void>
connectGoogleVoiceCookies(text: string): Promise<void>
disconnectGoogleVoice(): Promise<void>
rabbitStatus(): Promise<RabbitStatus>
rabbitInstall(mode?: 'full' | 'update'): Promise<void> // update: app only, keeps its data
rabbitSync(): Promise<void>
onRabbitProgress(cb: (step: string) => void): () => void
listContacts(): Promise<ContactInfo[]> listContacts(): Promise<ContactInfo[]>
listAddressBooks(): Promise<{ books: AddressBook[]; default?: string }>
addContact(c: NewContact): Promise<string> // resolves with the book's name
listConversations(): Promise<Conversation[]> listConversations(): Promise<Conversation[]>
getMessages(did: string, contact: string): Promise<Message[]> getMessages(did: string, contact: string): Promise<Message[]>
markRead(did: string, contact: string): Promise<void> markRead(did: string, contact: string): Promise<void>
markUnread(did: string, contact: string): Promise<void>
setArchived(did: string, contact: string, archived: boolean): Promise<void>
setName(did: string, contact: string, name: string | null): Promise<void>
// Unsent composer text, by contact; kept until sent or cleared.
getDrafts(): Promise<Record<string, string>>
setDraft(contact: string, text: string): Promise<void>
search(query: string, scope?: { did: string; contact: string }): Promise<SearchHit[]> search(query: string, scope?: { did: string; contact: string }): Promise<SearchHit[]>
send(did: string, contact: string, text: string): Promise<void> send(did: string, contact: string, text: string, attachments?: OutgoingAttachment[]): Promise<void>
deleteFailed(id: number): Promise<void> deleteFailed(id: number): Promise<void>
retryFailed(id: number): Promise<void> retryFailed(id: number): Promise<void>
saveMedia(id: number, index: number): Promise<void>
exportChat(did: string, contact: string, opts: ChatExport): Promise<boolean> // false: no file chosen
readMedia(id: number, index: number): Promise<{ mime: string; data: Uint8Array<ArrayBuffer> }>
copyImage(png: Uint8Array): Promise<void> // onto the system clipboard
syncStatus(): Promise<SyncStatus> syncStatus(): Promise<SyncStatus>
pollNow(): Promise<void> pollNow(): Promise<void>
@@ -36,4 +64,6 @@ export interface Api {
onConversationsChanged(cb: () => void): () => void onConversationsChanged(cb: () => void): () => void
onSyncStatus(cb: (s: SyncStatus) => void): () => void onSyncStatus(cb: (s: SyncStatus) => void): () => void
onContactsChanged(cb: () => void): () => void onContactsChanged(cb: () => void): () => void
onStateChanged(cb: () => void): () => void
onOpenConversation(cb: (key: { did: string; contact: string }) => void): () => void
} }
+41
View File
@@ -0,0 +1,41 @@
// Attachment type helpers shared by main (file names) and renderer (display).
import type { MediaRef } from './types'
const EXT_BY_MIME: Record<string, string> = {
'image/jpeg': 'jpg',
'image/png': 'png',
'image/gif': 'gif',
'image/webp': 'webp',
'image/bmp': 'bmp',
'video/mp4': 'mp4',
'video/3gpp': '3gp',
'video/quicktime': 'mov',
'audio/mpeg': 'mp3',
'audio/mp4': 'm4a',
'audio/amr': 'amr',
'audio/ogg': 'ogg',
'text/vcard': 'vcf',
'text/x-vcard': 'vcf',
'text/plain': 'txt'
}
const MIME_BY_EXT: Record<string, string> = {
...Object.fromEntries(Object.entries(EXT_BY_MIME).map(([m, e]) => [e, m])),
jpeg: 'image/jpeg'
}
export function guessMime(nameOrUrl: string): string | undefined {
const ext = /\.([a-z0-9]+)(?:[?#].*)?$/i.exec(nameOrUrl)?.[1]?.toLowerCase()
return ext ? MIME_BY_EXT[ext] : undefined
}
export function extFor(mime: string | undefined): string {
return (mime && EXT_BY_MIME[mime.split(';')[0].trim()]) || 'bin'
}
export type MediaKind = 'image' | 'video' | 'audio' | 'file'
export function mediaKind(ref: MediaRef): MediaKind {
const mime = ref.mime ?? guessMime(ref.file ?? ref.url ?? '') ?? ''
const top = mime.split('/')[0]
return top === 'image' || top === 'video' || top === 'audio' ? top : 'file'
}
+21 -19
View File
@@ -14,23 +14,25 @@ export function formatNumber(n: string): string {
return n return n
} }
// Split text into voip.ms-sized parts (160 chars max per sendSMS call), // Group chats (Google Voice only) are keyed by their members' numbers, sorted
// preferring to break on whitespace. // and comma-joined, in the place a 1:1 chat keeps its one number.
export function splitMessage(text: string, max = 160): string[] { export function groupKey(numbers: string[]): string {
const parts: string[] = [] return [...new Set(numbers.map(normalizeNumber).filter(Boolean))].sort().join(',')
let rest = text.trim() }
while ([...rest].length > max) {
const chars = [...rest] export function isGroup(contact: string): boolean {
let cut = max return contact.includes(',')
for (let i = max; i > max * 0.6; i--) { }
if (/\s/.test(chars[i])) {
cut = i export function groupMembers(contact: string): string[] {
break return contact.split(',')
} }
}
parts.push(chars.slice(0, cut).join('').trimEnd()) // voip.ms's sendSMS takes at most 160 characters. Longer texts go out as one
rest = chars.slice(cut).join('').trimStart() // text-only MMS, which the recipient sees as a single message (split SMS arrive
} // as separate fragments, often out of order).
if (rest) parts.push(rest) export const SMS_TEXT_LIMIT = 160
return parts
export function charCount(text: string): number {
return [...text].length
} }

Some files were not shown because too many files have changed in this diff Show More