v0.5.0: bubble for Android 0.5.0 — text from the Rabbit's SIM on the desktop, and chat names and read status sync, through jai
A relay on jai (server/bubble_relay.py, stdlib + SQLite, tailscale address only, bearer token) carries sealed blobs between the desktop and the Rabbit: AES-256-GCM with a key the desktop makes and hands over USB (Sync to Rabbit), so jai can neither read nor forge anything. It deletes what's been picked up, and anything after 14 days. - Desktop (src/main/relay.ts): "Rabbit SIM" is a number to text from, groups included; the SIM's history and new texts arrive; older photos are fetched when shown; names and read/unread/archived go both ways. Settings → Rabbit relay connects it. - Rabbit (Relay.java, RelayJob): no timer of its own for the battery; it rides along with the background checks, plus one network job after a text, a send or a swipe. Each send from the desktop goes out at most once and not after a day. Plain http only to jai and localhost (network_security_config). - scripts/deploy-jai.sh; tests: server unit tests, an end-to-end relay test, and DEVICE=1 relay.device.test.ts against the dev app.
This commit is contained in:
@@ -29,7 +29,7 @@
|
||||
android:icon="@drawable/ic_launcher"
|
||||
android:theme="@android:style/Theme.DeviceDefault.NoActionBar"
|
||||
android:allowBackup="false"
|
||||
android:usesCleartextTraffic="false">
|
||||
android:networkSecurityConfig="@xml/network_security_config">
|
||||
|
||||
<activity
|
||||
android:name="me.teafry.voipmessages.MainActivity"
|
||||
@@ -118,6 +118,9 @@
|
||||
<service android:name="me.teafry.voipmessages.PollJob"
|
||||
android:permission="android.permission.BIND_JOB_SERVICE"
|
||||
android:exported="false" />
|
||||
<service android:name="me.teafry.voipmessages.RelayJob"
|
||||
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" />
|
||||
|
||||
@@ -53,6 +53,9 @@ final class Config {
|
||||
final List<Did> dids = new CopyOnWriteArrayList<>();
|
||||
private boolean hasSim;
|
||||
String defaultDid;
|
||||
/** The relay through jai (Relay.java): address, bearer token, and the 32-byte key that seals everything. */
|
||||
String relayUrl, relayToken;
|
||||
byte[] relayKey;
|
||||
/** Made-up data for testing (android/tools/push_sandbox.py): never goes online. */
|
||||
boolean sandbox;
|
||||
private final File file;
|
||||
@@ -120,6 +123,17 @@ final class Config {
|
||||
}
|
||||
if (cfg.gvNumber != null && !cfg.gvNumber.isEmpty()) cfg.dids.add(new Did(cfg.gvNumber, "Google Voice", true));
|
||||
cfg.defaultDid = o.optString("defaultDid", null);
|
||||
JSONObject r = o.optJSONObject("relay");
|
||||
if (r != null) {
|
||||
String url = r.optString("url", ""), token = r.optString("token", "");
|
||||
byte[] key = android.util.Base64.decode(r.optString("key", ""), android.util.Base64.DEFAULT);
|
||||
// Only the addresses network_security_config lets through, and a real key.
|
||||
if (url.matches("http://(100\\.\\d+\\.\\d+\\.\\d+|127\\.0\\.0\\.1)(:\\d+)?|https://[^/]+") && !token.isEmpty() && key.length == 32) {
|
||||
cfg.relayUrl = url;
|
||||
cfg.relayToken = token;
|
||||
cfg.relayKey = key;
|
||||
}
|
||||
}
|
||||
cfg.sandbox = o.optBoolean("sandbox", false);
|
||||
} catch (IOException | JSONException e) {
|
||||
cfg.raw = new JSONObject();
|
||||
|
||||
@@ -148,6 +148,8 @@ public final class MainActivity extends BaseActivity {
|
||||
refresh();
|
||||
}
|
||||
|
||||
private static long lastRelay;
|
||||
|
||||
private void refresh() {
|
||||
bg.execute(() -> {
|
||||
Sync.poll(this);
|
||||
@@ -269,6 +271,10 @@ public final class MainActivity extends BaseActivity {
|
||||
bg.execute(() -> {
|
||||
StateSync.importPending(this);
|
||||
Sim.syncSoon(this);
|
||||
if (System.currentTimeMillis() - lastRelay > 60_000) {
|
||||
lastRelay = System.currentTimeMillis();
|
||||
Relay.soon(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(() -> {
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
package me.teafry.voipmessages;
|
||||
|
||||
import android.app.job.JobInfo;
|
||||
import android.app.job.JobScheduler;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.database.Cursor;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.util.Base64;
|
||||
import android.util.Log;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
/**
|
||||
* The relay through jai (the desktop's src/main/relay.ts; server in
|
||||
* server/bubble_relay.py): the SIM's texts go to the desktop, texts typed
|
||||
* there go out over the SIM here, and chat names and read/unread/archived
|
||||
* stay in step without a cable.
|
||||
*
|
||||
* Everything is AES-256-GCM sealed with the key the desktop handed over USB
|
||||
* (config.json "relay"); jai only passes blobs on. It runs with the checks
|
||||
* the Rabbit already makes (PollJob) plus one network job after something
|
||||
* happens here (a text, a send, a swipe), never on a timer of its own: the
|
||||
* battery pays for nothing new while nothing's going on.
|
||||
*/
|
||||
final class Relay {
|
||||
private Relay() {}
|
||||
|
||||
private static final String TAG = "Relay";
|
||||
private static final int JOB_ID = 2;
|
||||
private static final Object LOCK = new Object();
|
||||
private static final SecureRandom random = new SecureRandom();
|
||||
|
||||
/** A send from the desktop that waited longer than this isn't sent any more. */
|
||||
private static final long MAX_SEND_AGE = 24 * 3600_000L;
|
||||
private static final int MSG_CHUNK = 300;
|
||||
private static final int MAX_PUSH = 7 * 1024 * 1024;
|
||||
/** New messages carry their photos; older ones (the first copy of the history) send them when asked. */
|
||||
private static final long INLINE_RECENT = 2 * 86_400_000L;
|
||||
|
||||
static boolean configured(Config cfg) {
|
||||
return cfg.relayUrl != null && cfg.relayToken != null && cfg.relayKey != null;
|
||||
}
|
||||
|
||||
private static SharedPreferences prefs(Context c) {
|
||||
return c.getSharedPreferences("relay", Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
// ---- sealing (relay.ts seal/unseal) ----
|
||||
static String seal(byte[] key, String author, JSONObject payload) throws Exception {
|
||||
byte[] nonce = new byte[12];
|
||||
random.nextBytes(nonce);
|
||||
Cipher ci = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
ci.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, nonce));
|
||||
ci.updateAAD(("bubble-relay/1/" + author).getBytes(StandardCharsets.UTF_8));
|
||||
byte[] ct = ci.doFinal(payload.toString().getBytes(StandardCharsets.UTF_8));
|
||||
byte[] out = new byte[1 + 12 + ct.length];
|
||||
out[0] = 1;
|
||||
System.arraycopy(nonce, 0, out, 1, 12);
|
||||
System.arraycopy(ct, 0, out, 13, ct.length);
|
||||
return Base64.encodeToString(out, Base64.NO_WRAP);
|
||||
}
|
||||
|
||||
/** Null for anything not sealed with our key by `author`. */
|
||||
static JSONObject unseal(byte[] key, String author, String blob) {
|
||||
try {
|
||||
byte[] b = Base64.decode(blob, Base64.DEFAULT);
|
||||
if (b.length < 1 + 12 + 16 || b[0] != 1) return null;
|
||||
Cipher ci = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
ci.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, b, 1, 12));
|
||||
ci.updateAAD(("bubble-relay/1/" + author).getBytes(StandardCharsets.UTF_8));
|
||||
return new JSONObject(new String(ci.doFinal(b, 13, b.length - 13), StandardCharsets.UTF_8));
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- what's waiting to go ----
|
||||
|
||||
/** Names or read/unread/archived changed here (StateSync): tell the desktop soon. */
|
||||
static void stateChanged(Context c) {
|
||||
if (!configured(Config.get(c))) return;
|
||||
prefs(c).edit().putBoolean("stateDirty", true).apply();
|
||||
soon(c);
|
||||
}
|
||||
|
||||
/** Something to tell the desktop: one network job, a few seconds out so a burst shares it. */
|
||||
static void soon(Context c) {
|
||||
if (!configured(Config.get(c))) return;
|
||||
JobInfo job = new JobInfo.Builder(JOB_ID, new ComponentName(c, RelayJob.class))
|
||||
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
|
||||
.setMinimumLatency(5000)
|
||||
.build();
|
||||
c.getSystemService(JobScheduler.class).schedule(job);
|
||||
}
|
||||
|
||||
private static synchronized void addToList(Context c, String key, JSONObject item) {
|
||||
try {
|
||||
JSONArray a = new JSONArray(prefs(c).getString(key, "[]"));
|
||||
a.put(item);
|
||||
prefs(c).edit().putString(key, a.toString()).commit();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private static synchronized JSONArray takeList(Context c, String key, int count) {
|
||||
try {
|
||||
JSONArray a = new JSONArray(prefs(c).getString(key, "[]"));
|
||||
JSONArray rest = new JSONArray();
|
||||
for (int i = count; i < a.length(); i++) rest.put(a.get(i));
|
||||
prefs(c).edit().putString(key, rest.toString()).commit();
|
||||
return a;
|
||||
} catch (Exception e) {
|
||||
return new JSONArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static JSONArray peekList(Context c, String key) {
|
||||
try {
|
||||
return new JSONArray(prefs(c).getString(key, "[]"));
|
||||
} catch (Exception e) {
|
||||
return new JSONArray();
|
||||
}
|
||||
}
|
||||
|
||||
// ---- one sync ----
|
||||
|
||||
/** One round with jai (more while there's more). Off the main thread; quiet when jai's unreachable. */
|
||||
static void sync(Context c) {
|
||||
Config cfg = Config.get(c);
|
||||
if (!configured(cfg)) return;
|
||||
synchronized (LOCK) {
|
||||
try {
|
||||
for (int round = 0; round < 20; round++)
|
||||
if (!syncOnce(c, cfg)) break;
|
||||
prefs(c).edit().putLong("lastSync", System.currentTimeMillis()).remove("error").apply();
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "relay sync failed: " + e.getMessage());
|
||||
prefs(c).edit().putString("error", e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()).apply();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String status(Context c) {
|
||||
SharedPreferences p = prefs(c);
|
||||
String err = p.getString("error", null);
|
||||
long last = p.getLong("lastSync", 0);
|
||||
if (err != null) return "⚠ " + err;
|
||||
return last == 0 ? "Not yet" : "Last check " + Ui.shortTime(c, last).toLowerCase();
|
||||
}
|
||||
|
||||
/** Returns true if there's more to do right away. */
|
||||
private static boolean syncOnce(Context c, Config cfg) throws Exception {
|
||||
SharedPreferences p = prefs(c);
|
||||
Store store = Store.get(c);
|
||||
List<String> push = new ArrayList<>();
|
||||
int size = 0;
|
||||
|
||||
// 1. How the desktop's sends went.
|
||||
JSONArray results = peekList(c, "results");
|
||||
for (int i = 0; i < results.length(); i++) {
|
||||
String b = seal(cfg.relayKey, "rabbit", results.getJSONObject(i));
|
||||
push.add(b);
|
||||
size += b.length();
|
||||
}
|
||||
int resultsPushed = results.length();
|
||||
|
||||
// 2. The SIM's messages we haven't passed on (both id ranges: SMS, MMS).
|
||||
long smsLast = p.getLong("smsLast", Sim.SMS_BASE), mmsLast = p.getLong("mmsLast", Sim.MMS_BASE);
|
||||
long[] newSms = {smsLast}, newMms = {mmsLast};
|
||||
boolean moreMsgs = false;
|
||||
long now = System.currentTimeMillis();
|
||||
int[] inlineBudget = {3 * 1024 * 1024};
|
||||
for (int range = 0; range < 2; range++) {
|
||||
long from = range == 0 ? smsLast : mmsLast, to = range == 0 ? Sim.MMS_BASE : Sim.FALLBACK_BASE;
|
||||
JSONArray msgs = new JSONArray();
|
||||
long max = from;
|
||||
int n = 0;
|
||||
try (Cursor cur = store.db.rawQuery("SELECT id FROM messages WHERE did = ? AND id > ? AND id < ? ORDER BY id LIMIT " + MSG_CHUNK,
|
||||
new String[] {Sim.DID, String.valueOf(from), String.valueOf(to)})) {
|
||||
while (cur.moveToNext()) {
|
||||
Store.Msg m = store.getMessage(cur.getLong(0));
|
||||
n++;
|
||||
if (m == null) continue;
|
||||
max = Math.max(max, m.id);
|
||||
msgs.put(toJson(c, m, now - m.ts < INLINE_RECENT, inlineBudget));
|
||||
}
|
||||
}
|
||||
if (n == MSG_CHUNK) moreMsgs = true;
|
||||
if (msgs.length() > 0) {
|
||||
String b = seal(cfg.relayKey, "rabbit", new JSONObject().put("t", "msgs").put("msgs", msgs));
|
||||
push.add(b);
|
||||
size += b.length();
|
||||
}
|
||||
if (range == 0) newSms[0] = max;
|
||||
else newMms[0] = max;
|
||||
}
|
||||
|
||||
// 3. Names and read status, if they changed here.
|
||||
boolean stateDirty = p.getBoolean("stateDirty", false);
|
||||
if (stateDirty) {
|
||||
String b = seal(cfg.relayKey, "rabbit", new JSONObject().put("t", "state")
|
||||
.put("names", store.namesExport()).put("read", store.readStateExport()));
|
||||
push.add(b);
|
||||
size += b.length();
|
||||
}
|
||||
|
||||
// 4. Photos the desktop asked for (a few MB per round).
|
||||
JSONArray wants = peekList(c, "wants");
|
||||
int wantsDone = 0;
|
||||
for (int i = 0; i < wants.length() && size < MAX_PUSH; i++) {
|
||||
JSONObject w = wants.getJSONObject(i);
|
||||
String b = seal(cfg.relayKey, "rabbit", mediaReply(c, w.optLong("id"), w.optInt("index")));
|
||||
push.add(b);
|
||||
size += b.length();
|
||||
wantsDone++;
|
||||
}
|
||||
|
||||
// Out, and in.
|
||||
long since = p.getLong("cursor", 0);
|
||||
JSONArray arr = new JSONArray();
|
||||
for (String b : push) arr.put(b);
|
||||
byte[] body = new JSONObject().put("device", "rabbit").put("since", since).put("push", arr).toString().getBytes(StandardCharsets.UTF_8);
|
||||
Map<String, String> h = new HashMap<>();
|
||||
h.put("Authorization", "Bearer " + cfg.relayToken);
|
||||
h.put("Content-Type", "application/json");
|
||||
Http.Response r = Http.request("POST", cfg.relayUrl + "/sync", h, body, 120_000);
|
||||
if (r.status == 401) throw new Exception("jai turned down the token (Sync to Rabbit from the desktop again)");
|
||||
if (r.status != 200) throw new Exception("jai answered " + r.status);
|
||||
JSONObject res = new JSONObject(new String(r.body, StandardCharsets.UTF_8));
|
||||
|
||||
// jai has them now.
|
||||
if (resultsPushed > 0) takeList(c, "results", resultsPushed);
|
||||
if (wantsDone > 0) takeList(c, "wants", wantsDone);
|
||||
SharedPreferences.Editor ed = p.edit().putLong("smsLast", newSms[0]).putLong("mmsLast", newMms[0]);
|
||||
if (stateDirty) ed.putBoolean("stateDirty", false);
|
||||
ed.commit();
|
||||
|
||||
JSONArray events = res.getJSONArray("events");
|
||||
for (int i = 0; i < events.length(); i++) handle(c, unseal(cfg.relayKey, "desktop", events.getString(i)));
|
||||
p.edit().putLong("cursor", res.getLong("cursor")).commit();
|
||||
return res.optBoolean("more") || moreMsgs || peekList(c, "wants").length() > 0 && wantsDone > 0;
|
||||
}
|
||||
|
||||
private static JSONObject toJson(Context c, Store.Msg m, boolean inline, int[] budget) throws Exception {
|
||||
JSONObject o = new JSONObject().put("id", m.id).put("did", m.did).put("contact", m.contact).put("direction", m.direction)
|
||||
.put("body", m.body == null ? "" : m.body).put("ts", m.ts).put("kind", m.kind);
|
||||
if (m.sender != null) o.put("sender", m.sender);
|
||||
List<JSONObject> refs = m.media();
|
||||
if (!refs.isEmpty()) {
|
||||
JSONArray media = new JSONArray();
|
||||
for (int i = 0; i < refs.size(); i++) {
|
||||
JSONObject ref = refs.get(i);
|
||||
JSONObject out = new JSONObject().put("mime", ref.optString("mime", "application/octet-stream"));
|
||||
String url = ref.optString("url", "");
|
||||
File f = null;
|
||||
if (inline || !url.startsWith("mmspart:")) f = Media.resolve(c, m.id, i);
|
||||
if (f != null && (f.length() <= budget[0] || !url.startsWith("mmspart:"))) {
|
||||
budget[0] -= (int) f.length();
|
||||
out.put("data", Base64.encodeToString(Media.read(f), Base64.NO_WRAP));
|
||||
if (ref.optInt("width") > 0) out.put("width", ref.optInt("width")).put("height", ref.optInt("height"));
|
||||
} else if (url.startsWith("mmspart:")) {
|
||||
out.put("url", url);
|
||||
} else continue;
|
||||
media.put(out);
|
||||
}
|
||||
if (media.length() > 0) o.put("media", media);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
private static JSONObject mediaReply(Context c, long id, int index) throws Exception {
|
||||
JSONObject out = new JSONObject().put("t", "media").put("id", id).put("index", index);
|
||||
Store.Msg m = Store.get(c).getMessage(id);
|
||||
// Only the SIM's own attachments go this way.
|
||||
File f = m != null && Sim.isSim(m.did) ? Media.resolve(c, id, index) : null;
|
||||
if (f == null) return out.put("missing", true);
|
||||
JSONObject ref = m.media().get(index);
|
||||
out.put("mime", ref.optString("mime", "application/octet-stream")).put("data", Base64.encodeToString(Media.read(f), Base64.NO_WRAP));
|
||||
if (ref.optInt("width") > 0) out.put("width", ref.optInt("width")).put("height", ref.optInt("height"));
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- what the desktop sent ----
|
||||
|
||||
private static void handle(Context c, JSONObject p) {
|
||||
if (p == null) return;
|
||||
try {
|
||||
switch (p.optString("t")) {
|
||||
case "send": onSend(c, p); break;
|
||||
case "state": onState(c, p); break;
|
||||
case "want": {
|
||||
JSONArray items = p.optJSONArray("items");
|
||||
for (int i = 0; items != null && i < items.length(); i++) addToList(c, "wants", items.getJSONObject(i));
|
||||
break;
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "skipped a message from the desktop: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void onState(Context c, JSONObject p) throws Exception {
|
||||
Store store = Store.get(c);
|
||||
JSONArray names = p.optJSONArray("names"), read = p.optJSONArray("read");
|
||||
if (names != null) store.namesImport(names);
|
||||
if (read != null) store.readStateImport(read);
|
||||
StateSync.export(c);
|
||||
Notifier.sweep(c);
|
||||
Sync.changed();
|
||||
}
|
||||
|
||||
/** Each send from the desktop goes out at most once, ever: remembered before it's tried. */
|
||||
private static synchronized boolean firstTime(Context c, String id) {
|
||||
SharedPreferences p = prefs(c);
|
||||
Set<String> done = new HashSet<>(p.getStringSet("sent", new HashSet<>()));
|
||||
long now = System.currentTimeMillis();
|
||||
for (String e : done) if (e.startsWith(id + "\t")) return false;
|
||||
// Forget ones old enough to be refused by age anyway.
|
||||
done.removeIf(e -> {
|
||||
try {
|
||||
return now - Long.parseLong(e.substring(e.indexOf('\t') + 1)) > 2 * MAX_SEND_AGE;
|
||||
} catch (Exception x) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
done.add(id + "\t" + now);
|
||||
return p.edit().putStringSet("sent", done).commit();
|
||||
}
|
||||
|
||||
private static void result(Context c, String id, long msgId, String error) {
|
||||
try {
|
||||
JSONObject o = new JSONObject().put("t", "sent").put("id", id);
|
||||
o.put("msgId", msgId != 0 ? msgId : JSONObject.NULL);
|
||||
o.put("error", error != null ? error : JSONObject.NULL);
|
||||
addToList(c, "results", o);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
soon(c);
|
||||
}
|
||||
|
||||
private static void onSend(Context c, JSONObject p) throws Exception {
|
||||
String id = p.getString("id");
|
||||
if (!id.matches("[0-9a-fA-F-]{36}") || !firstTime(c, id)) return;
|
||||
String contact = p.optString("contact", "");
|
||||
String text = p.optString("text", "");
|
||||
if (contact.isEmpty() || !contact.matches("[0-9,]+|[^,]+")) {
|
||||
result(c, id, 0, "No one to send it to.");
|
||||
return;
|
||||
}
|
||||
if (System.currentTimeMillis() - p.optLong("ts") > MAX_SEND_AGE) {
|
||||
result(c, id, 0, "Waited over a day for the Rabbit, so it wasn't sent. Send it again?");
|
||||
return;
|
||||
}
|
||||
if (!Sim.isDefault(c)) {
|
||||
result(c, id, 0, "bubble isn't the Rabbit's texting app, so it can't use the SIM.");
|
||||
return;
|
||||
}
|
||||
List<Sender.Photo> photos = new ArrayList<>();
|
||||
JSONArray media = p.optJSONArray("media");
|
||||
for (int i = 0; media != null && i < media.length(); i++) {
|
||||
JSONObject a = media.getJSONObject(i);
|
||||
byte[] data = Base64.decode(a.getString("data"), Base64.DEFAULT);
|
||||
String mime = a.optString("mime", "application/octet-stream");
|
||||
String file = Media.save(c, data, mime);
|
||||
int w = a.optInt("width"), hgt = a.optInt("height");
|
||||
if (w == 0 && mime.startsWith("image/")) {
|
||||
BitmapFactory.Options o = new BitmapFactory.Options();
|
||||
o.inJustDecodeBounds = true;
|
||||
BitmapFactory.decodeByteArray(data, 0, data.length, o);
|
||||
w = o.outWidth;
|
||||
hgt = o.outHeight;
|
||||
}
|
||||
photos.add(new Sender.Photo(file, mime, Math.max(0, w), Math.max(0, hgt)));
|
||||
}
|
||||
if (text.isEmpty() && photos.isEmpty()) {
|
||||
result(c, id, 0, "It was empty.");
|
||||
return;
|
||||
}
|
||||
Sender.send(c, Sim.DID, contact, text, photos, (msgId, error) -> result(c, id, msgId, error));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package me.teafry.voipmessages;
|
||||
|
||||
import android.app.job.JobParameters;
|
||||
import android.app.job.JobService;
|
||||
|
||||
/** One round with the relay, after something happened here (Relay.soon). */
|
||||
public final class RelayJob extends JobService {
|
||||
@Override
|
||||
public boolean onStartJob(JobParameters params) {
|
||||
new Thread(() -> {
|
||||
Relay.sync(this);
|
||||
jobFinished(params, false);
|
||||
}, "relay").start();
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onStopJob(JobParameters params) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -55,7 +55,16 @@ final class Sender {
|
||||
long run() throws Exception;
|
||||
}
|
||||
|
||||
/** How a send ended: the message's id, or 0 and why not (Relay reports it to the desktop). */
|
||||
interface Done {
|
||||
void done(long msgId, String error);
|
||||
}
|
||||
|
||||
static void send(Context ctx, String did, String contact, String text, List<Photo> photos) {
|
||||
send(ctx, did, contact, text, photos, null);
|
||||
}
|
||||
|
||||
static void send(Context ctx, String did, String contact, String text, List<Photo> photos, Done done) {
|
||||
Context c = ctx.getApplicationContext();
|
||||
Config cfg = Config.get(c);
|
||||
if (cfg.sandbox) {
|
||||
@@ -63,13 +72,15 @@ final class Sender {
|
||||
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));
|
||||
long real = 9_000_000_000L + (System.currentTimeMillis() % 1_000_000_000L);
|
||||
store.confirmPending(id, real);
|
||||
Sync.changed();
|
||||
if (done != null) done.done(real, null);
|
||||
return;
|
||||
}
|
||||
if (cfg.isGv(did)) {
|
||||
if (photos.isEmpty()) {
|
||||
enqueue(c, pending(did, contact, text, null), () -> gvSend(c, did, contact, text, null), true);
|
||||
enqueue(c, pending(did, contact, text, null), () -> gvSend(c, did, contact, text, null), true, done);
|
||||
} else {
|
||||
// Google Voice carries one photo per message: the text rides with the first.
|
||||
for (int i = 0; i < photos.size(); i++) {
|
||||
@@ -79,7 +90,7 @@ final class Sender {
|
||||
one.add(p);
|
||||
Store.Msg m = pending(did, contact, body, one);
|
||||
m.ts += i;
|
||||
enqueue(c, m, () -> gvSend(c, did, contact, body, p), true);
|
||||
enqueue(c, m, () -> gvSend(c, did, contact, body, p), true, i == 0 ? done : null);
|
||||
}
|
||||
}
|
||||
return;
|
||||
@@ -89,7 +100,10 @@ final class Sender {
|
||||
boolean mms = !photos.isEmpty() || Phone.isGroup(contact);
|
||||
Store.Msg m = pending(did, contact, text, photos);
|
||||
if (mms) m.kind = "mms";
|
||||
enqueue(c, m, () -> mms ? Sim.sendMms(c, contact, text, photos) : Sim.sendSms(c, contact, text), false);
|
||||
enqueue(c, m, () -> mms ? Sim.sendMms(c, contact, text, photos) : Sim.sendSms(c, contact, text), false, (id, err) -> {
|
||||
if (done != null) done.done(id, err);
|
||||
Relay.soon(c); // the desktop hears about it on the next round
|
||||
});
|
||||
return;
|
||||
}
|
||||
boolean mms = !photos.isEmpty() || Phone.charCount(text) > Phone.SMS_TEXT_LIMIT;
|
||||
@@ -102,7 +116,7 @@ final class Sender {
|
||||
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);
|
||||
}, false, done);
|
||||
}
|
||||
|
||||
private static Store.Msg pending(String did, String contact, String text, List<Photo> photos) {
|
||||
@@ -121,34 +135,38 @@ final class Sender {
|
||||
return m;
|
||||
}
|
||||
|
||||
private static void enqueue(Context c, Store.Msg m, Attempt attempt, boolean gv) {
|
||||
private static void enqueue(Context c, Store.Msg m, Attempt attempt, boolean gv, Done done) {
|
||||
Store store = Store.get(c);
|
||||
long tempId = store.insertPending(m);
|
||||
Sync.changed();
|
||||
queue.execute(() -> {
|
||||
deliver(c, store, tempId, attempt, gv);
|
||||
long[] id = {0};
|
||||
String error = deliver(c, store, tempId, attempt, gv, id);
|
||||
Sync.changed();
|
||||
if (done != null) done.done(id[0], error);
|
||||
});
|
||||
}
|
||||
|
||||
private static void deliver(Context c, Store store, long tempId, Attempt attempt, boolean gv) {
|
||||
/** Null when it went out (its id in id[0]), else why not. */
|
||||
private static String deliver(Context c, Store store, long tempId, Attempt attempt, boolean gv, long[] id) {
|
||||
for (int n = 1; ; n++) {
|
||||
try {
|
||||
store.confirmPending(tempId, attempt.run());
|
||||
return;
|
||||
id[0] = attempt.run();
|
||||
store.confirmPending(tempId, id[0]);
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
if (store.getMessage(tempId) == null) return; // a check found it already sent
|
||||
if (store.getMessage(tempId) == null) return null; // 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 (store.getMessage(tempId) == null) return null;
|
||||
}
|
||||
}
|
||||
if (kind.equals("fatal") || n >= MAX_ATTEMPTS) {
|
||||
store.markFailed(tempId, e.getMessage());
|
||||
return;
|
||||
return e.getMessage() == null ? "It didn't go out." : e.getMessage();
|
||||
}
|
||||
if (kind.equals("safe")) sleep(RETRY_DELAYS[Math.min(n - 1, RETRY_DELAYS.length - 1)]);
|
||||
}
|
||||
|
||||
@@ -122,6 +122,13 @@ public final class SettingsActivity extends BaseActivity {
|
||||
+ " the texts already on the phone come over too.");
|
||||
}
|
||||
|
||||
if (Relay.configured(cfg)) {
|
||||
section("Relay (jai)");
|
||||
kv("Desktop link", Relay.status(c));
|
||||
note("Texts typed on the desktop for \"via SIM\" go out at this Rabbit's background check, and chat names and read status"
|
||||
+ " go both ways. Sealed with a key only the desktop and this Rabbit have.");
|
||||
}
|
||||
|
||||
section("About");
|
||||
String version = "?";
|
||||
try {
|
||||
|
||||
@@ -389,6 +389,7 @@ final class Sim {
|
||||
List<Store.Msg> added = sync(c);
|
||||
Sync.changed();
|
||||
Notifier.notifyNew(c, added);
|
||||
if (!added.isEmpty()) Relay.soon(c);
|
||||
}
|
||||
|
||||
/** A carrier's "you have an MMS" (MmsReceiver): fetch it. */
|
||||
|
||||
@@ -54,6 +54,7 @@ final class StateSync {
|
||||
static void rename(Context c, String did, String contact, String name) {
|
||||
Store.get(c).setName(did, contact, name, System.currentTimeMillis());
|
||||
export(c);
|
||||
Relay.stateChanged(c);
|
||||
Sync.changed();
|
||||
}
|
||||
|
||||
@@ -61,16 +62,19 @@ final class StateSync {
|
||||
Store.get(c).markRead(did, contact);
|
||||
if (Sim.isSim(did)) Sim.markRead(c, contact);
|
||||
export(c);
|
||||
Relay.stateChanged(c);
|
||||
Notifier.sweep(c);
|
||||
}
|
||||
|
||||
static void markUnread(Context c, String did, String contact) {
|
||||
Store.get(c).markUnread(did, contact);
|
||||
export(c);
|
||||
Relay.stateChanged(c);
|
||||
}
|
||||
|
||||
static void setArchived(Context c, String did, String contact, boolean archived) {
|
||||
Store.get(c).setArchived(did, contact, archived);
|
||||
export(c);
|
||||
Relay.stateChanged(c);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,6 +93,8 @@ final class Sync {
|
||||
}
|
||||
}
|
||||
store.set("last_poll", String.valueOf(System.currentTimeMillis()));
|
||||
// The relay rides along with this check: no wakeups of its own.
|
||||
Relay.sync(c);
|
||||
if (!added.isEmpty()) StateSync.export(c);
|
||||
// Threads read on the phone or the web came back read (see storeThread).
|
||||
Notifier.sweep(c);
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Everything is https, except the relay on jai over tailscale (WireGuard
|
||||
already encrypts that hop, and what it carries is sealed: Relay.java) and
|
||||
localhost for testing it with adb reverse. -->
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="false" />
|
||||
<domain-config cleartextTrafficPermitted="true">
|
||||
<domain includeSubdomains="false">100.69.139.40</domain>
|
||||
<domain includeSubdomains="false">127.0.0.1</domain>
|
||||
</domain-config>
|
||||
</network-security-config>
|
||||
Reference in New Issue
Block a user