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
@@ -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;
}
}