diff --git a/android/README.md b/android/README.md index 9ff98d8..d50738c 100644 --- a/android/README.md +++ b/android/README.md @@ -74,5 +74,18 @@ Install/Sync buttons then target the dev app with the sandbox's made-up data. 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. +- SIM card (`Sim`, `Pdu`): the third source, while bubble is Android's default + texting app (Settings → SIM card asks for that). Chats are did `sim` ("via + SIM"). Android's shared message store (`content://sms`, `content://mms`) stays + the record, as a default SMS app must keep it: `SmsReceiver`/`MmsReceiver` + write incoming messages there and sends are written there too, then `Sim.sync` + copies whatever is new into `Store` (ids `2^51 + _id` for SMS, `2^51 + 2^49 + + _id` for MMS). The phone's existing texts come over the first time, and an + Install to Rabbit that replaces messages.db just copies them in again. MMS + photos are read from the store when first shown (`mmspart:` refs). `Pdu` + reads/writes the MMS wire format (no libraries); `SmsManager` does the carrier + side, through `MmsFiles`. Long texts go as multipart SMS; photos, voice notes + and group chats as MMS (needs mobile data on). The dev app's sandbox never + uses the SIM. - The scroll wheel is left alone: it stays the volume control (and volume down + the side button still takes a screenshot). diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index a4ff2aa..bb57e42 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -13,6 +13,16 @@ Doze) hands off to a job, and boot puts the alarm back. --> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/me/teafry/voipmessages/ChatActivity.java b/android/app/src/main/java/me/teafry/voipmessages/ChatActivity.java index e6f6d08..1c26d45 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/ChatActivity.java +++ b/android/app/src/main/java/me/teafry/voipmessages/ChatActivity.java @@ -234,7 +234,7 @@ public final class ChatActivity extends BaseActivity { private void updateCounter() { int len = Phone.charCount(input.getText().toString().trim()); boolean gv = Config.get(this).isGv(did); - boolean show = !gv && len > 0; + boolean show = !gv && !Sim.isSim(did) && 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"); } @@ -325,12 +325,12 @@ public final class ChatActivity extends BaseActivity { // A conversation with nothing in it yet can still pick its number. Config cfg = Config.get(this); List choices = new ArrayList<>(); - for (Config.Did d : cfg.dids) if (!group || d.gv) choices.add(d); + for (Config.Did d : cfg.dids) if (!group || d.gv || d.sim) choices.add(d); if (msgs.isEmpty() && choices.size() > 1 && fromRow.getVisibility() != View.VISIBLE) { List 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" : "")); + labels.add(Ui.didLabel(this, choices.get(i))); if (choices.get(i).did.equals(did)) sel = i; } ArrayAdapter a = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, labels); @@ -353,7 +353,7 @@ public final class ChatActivity extends BaseActivity { 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) { + if (!Config.get(this).isGv(did) && !Sim.isSim(did) && Phone.charCount(text) > 2048) { Toast.makeText(this, "Too long for an MMS (2048 characters max).", Toast.LENGTH_SHORT).show(); return; } diff --git a/android/app/src/main/java/me/teafry/voipmessages/Config.java b/android/app/src/main/java/me/teafry/voipmessages/Config.java index 785229b..b9d0ed6 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/Config.java +++ b/android/app/src/main/java/me/teafry/voipmessages/Config.java @@ -17,6 +17,7 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; /** * Accounts, copied over by the desktop's "Install to Rabbit" into the app's @@ -31,19 +32,26 @@ import java.util.Map; final class Config { static final class Did { final String did, description; - final boolean gv; + final boolean gv, sim; Did(String did, String description, boolean gv) { + this(did, description, gv, false); + } + + Did(String did, String description, boolean gv, boolean sim) { this.did = did; this.description = description; this.gv = gv; + this.sim = sim; } } String voipUser, voipPass; String gvNumber; final Map gvCookies = new LinkedHashMap<>(); - final List dids = new ArrayList<>(); + // Changes while screens read it: the SIM comes and goes with the default-SMS-app role. + final List dids = new CopyOnWriteArrayList<>(); + private boolean hasSim; String defaultDid; /** Made-up data for testing (android/tools/push_sandbox.py): never goes online. */ boolean sandbox; @@ -59,9 +67,24 @@ final class Config { static synchronized Config get(Context c) { File f = new File(c.getFilesDir(), "config.json"); if (cached == null || cached.stale()) cached = load(f); + cached.applySim(c); return cached; } + /** The SIM is a number to text from while bubble is the default SMS app (never in the sandbox). */ + private void applySim(Context c) { + boolean sim = !sandbox && Sim.isDefault(c); + if (sim == hasSim) return; + hasSim = sim; + if (sim) { + dids.add(new Did(Sim.DID, "SIM card", false, true)); + if (defaultDid == null) defaultDid = Sim.DID; + } else { + dids.removeIf(d -> d.sim); + if (Sim.DID.equals(defaultDid)) defaultDid = dids.isEmpty() ? null : dids.get(0).did; + } + } + private long loadedAt; private boolean stale() { @@ -106,7 +129,12 @@ final class Config { } boolean configured() { - return voipUser != null || gvNumber != null; + return voipUser != null || gvNumber != null || hasSim; + } + + /** Group chats: Google Voice and the SIM (as MMS); voip.ms numbers can't. */ + boolean canGroup(String did) { + return isGv(did) || Sim.isSim(did) && hasSim; } boolean isGv(String did) { diff --git a/android/app/src/main/java/me/teafry/voipmessages/MainActivity.java b/android/app/src/main/java/me/teafry/voipmessages/MainActivity.java index eb4d9a6..a88fd9c 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/MainActivity.java +++ b/android/app/src/main/java/me/teafry/voipmessages/MainActivity.java @@ -132,8 +132,10 @@ public final class MainActivity extends BaseActivity { 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.") + .setMessage("Install from the desktop app (Settings → Rabbit → Install to Rabbit) to copy your accounts and history here." + + " Or text from the Rabbit's own SIM card by making bubble its texting app.") .setPositiveButton("OK", null) + .setNeutralButton("Use the SIM", (d, w) -> startActivity(new Intent(this, SettingsActivity.class))) .show(); } } @@ -266,6 +268,7 @@ public final class MainActivity extends BaseActivity { if (list == null) return; bg.execute(() -> { StateSync.importPending(this); + Sim.syncSoon(this); List fresh = Store.get(this).conversations(null); Contacts.all(this); // load names here, not on the main thread while drawing rows runOnUiThread(() -> { diff --git a/android/app/src/main/java/me/teafry/voipmessages/Media.java b/android/app/src/main/java/me/teafry/voipmessages/Media.java index f772968..d214b9d 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/Media.java +++ b/android/app/src/main/java/me/teafry/voipmessages/Media.java @@ -105,7 +105,14 @@ final class Media { try { byte[] data; String mime; - if (url.startsWith("gv:")) { + if (url.startsWith("mmspart:")) { + // A SIM MMS: in Android's message store (Sim.readMms). + try (InputStream in = c.getContentResolver().openInputStream(Uri.parse("content://mms/part/" + url.substring(8)))) { + if (in == null) return null; + data = Http.readAll(in); + } + mime = ref.optString("mime", "application/octet-stream"); + } else if (url.startsWith("gv:")) { Object[] r = new GVoice(Config.get(c)).download(url.substring(3)); data = (byte[]) r[0]; mime = (String) r[1]; diff --git a/android/app/src/main/java/me/teafry/voipmessages/MmsDownloaded.java b/android/app/src/main/java/me/teafry/voipmessages/MmsDownloaded.java new file mode 100644 index 0000000..039a40b --- /dev/null +++ b/android/app/src/main/java/me/teafry/voipmessages/MmsDownloaded.java @@ -0,0 +1,26 @@ +package me.teafry.voipmessages; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +/** + * SmsManager saying an MMS download finished. Apart from MmsReceiver because + * that one only takes broadcasts from holders of BROADCAST_WAP_PUSH, and this + * one comes from our own PendingIntent. + */ +public final class MmsDownloaded extends BroadcastReceiver { + @Override + public void onReceive(Context c, Intent intent) { + Context app = c.getApplicationContext(); + int result = getResultCode(); + PendingResult done = goAsync(); + new Thread(() -> { + try { + Sim.downloaded(app, intent, result); + } finally { + done.finish(); + } + }, "mms-in").start(); + } +} diff --git a/android/app/src/main/java/me/teafry/voipmessages/MmsFiles.java b/android/app/src/main/java/me/teafry/voipmessages/MmsFiles.java new file mode 100644 index 0000000..358173d --- /dev/null +++ b/android/app/src/main/java/me/teafry/voipmessages/MmsFiles.java @@ -0,0 +1,70 @@ +package me.teafry.voipmessages; + +import android.content.ContentProvider; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.os.ParcelFileDescriptor; + +import java.io.File; +import java.io.FileNotFoundException; + +/** + * Where the phone's MMS service reads a message we're sending and writes one + * it fetched for us. Not exported: SmsManager grants it access per file. + */ +public final class MmsFiles extends ContentProvider { + static String authority(Context c) { + return c.getPackageName() + ".mmsfiles"; + } + + static File file(Context c, String name) { + File d = new File(c.getCacheDir(), "mms"); + d.mkdirs(); + return new File(d, new File(name).getName()); + } + + static Uri uri(Context c, String name) { + return new Uri.Builder().scheme("content").authority(authority(c)).appendPath(name).build(); + } + + @Override + public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { + File f = file(getContext(), uri.getLastPathSegment()); + int m = mode.contains("w") + ? ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE + : ParcelFileDescriptor.MODE_READ_ONLY; + return ParcelFileDescriptor.open(f, m); + } + + @Override + public boolean onCreate() { + return true; + } + + @Override + public Cursor query(Uri u, String[] p, String s, String[] a, String o) { + return null; + } + + @Override + public String getType(Uri u) { + return "application/vnd.wap.mms-message"; + } + + @Override + public Uri insert(Uri u, ContentValues v) { + return null; + } + + @Override + public int delete(Uri u, String s, String[] a) { + return 0; + } + + @Override + public int update(Uri u, ContentValues v, String s, String[] a) { + return 0; + } +} diff --git a/android/app/src/main/java/me/teafry/voipmessages/MmsReceiver.java b/android/app/src/main/java/me/teafry/voipmessages/MmsReceiver.java new file mode 100644 index 0000000..dc28016 --- /dev/null +++ b/android/app/src/main/java/me/teafry/voipmessages/MmsReceiver.java @@ -0,0 +1,25 @@ +package me.teafry.voipmessages; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.provider.Telephony; + +/** The carrier's push saying an MMS is waiting (WAP_PUSH_DELIVER, default SMS app only). */ +public final class MmsReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context c, Intent intent) { + if (!Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION.equals(intent.getAction())) return; + byte[] data = intent.getByteArrayExtra("data"); + if (data == null) return; + Context app = c.getApplicationContext(); + PendingResult done = goAsync(); + new Thread(() -> { + try { + Sim.notified(app, data); + } finally { + done.finish(); + } + }, "mms-push").start(); + } +} diff --git a/android/app/src/main/java/me/teafry/voipmessages/NewChatActivity.java b/android/app/src/main/java/me/teafry/voipmessages/NewChatActivity.java index 2d30322..97187fc 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/NewChatActivity.java +++ b/android/app/src/main/java/me/teafry/voipmessages/NewChatActivity.java @@ -64,7 +64,7 @@ public final class NewChatActivity extends BaseActivity { 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" : "")); + labels.add(Ui.didLabel(this, d)); if (d.did.equals(from)) sel = i; } sp.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, labels)); @@ -73,7 +73,7 @@ public final class NewChatActivity extends BaseActivity { 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)) { + if (!cfg.canGroup(from)) { members.clear(); renderChips(); } @@ -237,7 +237,7 @@ public final class NewChatActivity extends BaseActivity { 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()) { + if (Config.get(c).canGroup(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)); diff --git a/android/app/src/main/java/me/teafry/voipmessages/Pdu.java b/android/app/src/main/java/me/teafry/voipmessages/Pdu.java new file mode 100644 index 0000000..c6d5e11 --- /dev/null +++ b/android/app/src/main/java/me/teafry/voipmessages/Pdu.java @@ -0,0 +1,464 @@ +package me.teafry.voipmessages; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +/** + * Just enough of the MMS wire format (OMA MMS encapsulation over WAP WSP) to + * be a default SMS app: read the notification a carrier pushes and the + * message it then hands over, and write a message to send plus the + * acknowledgement. Every WSP header value says how long it is, so headers we + * don't care about are skipped without knowing what they are. + */ +final class Pdu { + private Pdu() {} + + // X-Mms-Message-Type values + static final int SEND_REQ = 0x80, NOTIFICATION_IND = 0x82, RETRIEVE_CONF = 0x84, ACKNOWLEDGE_IND = 0x85; + + // Header fields (without the high bit) + private static final int H_CC = 0x02, H_CONTENT_LOCATION = 0x03, H_CONTENT_TYPE = 0x04, H_DATE = 0x05, + H_FROM = 0x09, H_MESSAGE_TYPE = 0x0C, H_SUBJECT = 0x16, H_TO = 0x17, H_TRANSACTION_ID = 0x18; + + /** WSP's well-known content types (the ones messages actually use). */ + private static final String[] TYPES = new String[0x34]; + + static { + TYPES[0x00] = "*/*"; + TYPES[0x01] = "text/*"; + TYPES[0x02] = "text/html"; + TYPES[0x03] = "text/plain"; + TYPES[0x06] = "text/x-vcalendar"; + TYPES[0x07] = "text/x-vcard"; + TYPES[0x1C] = "image/*"; + TYPES[0x1D] = "image/gif"; + TYPES[0x1E] = "image/jpeg"; + TYPES[0x1F] = "image/tiff"; + TYPES[0x20] = "image/png"; + TYPES[0x21] = "image/vnd.wap.wbmp"; + TYPES[0x22] = "application/vnd.wap.multipart.*"; + TYPES[0x23] = "application/vnd.wap.multipart.mixed"; + TYPES[0x26] = "application/vnd.wap.multipart.alternative"; + TYPES[0x33] = "application/vnd.wap.multipart.related"; + } + + static final class Part { + String type = "application/octet-stream", name, charset; + byte[] data; + + String text() { + Charset cs = StandardCharsets.UTF_8; + try { + if (charset != null) cs = Charset.forName(charset); + } catch (Exception ignored) { + } + return new String(data, cs); + } + } + + static final class Message { + int type = -1; + String transactionId, contentLocation, from, subject; + final List to = new ArrayList<>(), cc = new ArrayList<>(); + long date; // seconds + final List parts = new ArrayList<>(); + } + + // ---------------------------------------------------------------- reading + + private static final class In { + final byte[] b; + int p; + + In(byte[] b) { + this.b = b; + } + + boolean more() { + return p < b.length; + } + + int u8() { + if (p >= b.length) throw new IllegalArgumentException("truncated PDU"); + return b[p++] & 0xff; + } + + int peek() { + return p < b.length ? b[p] & 0xff : -1; + } + + long uintvar() { + long v = 0; + for (int i = 0; i < 5; i++) { + int x = u8(); + v = (v << 7) | (x & 0x7f); + if ((x & 0x80) == 0) return v; + } + throw new IllegalArgumentException("bad uintvar"); + } + + /** Value-length: a short length octet, or 31 then a uintvar. */ + int valueLength() { + int x = u8(); + if (x < 31) return x; + if (x == 31) return (int) uintvar(); + throw new IllegalArgumentException("not a value-length"); + } + + byte[] cstring() { + if (peek() == 0x7F || peek() == 0x22) p++; // Quote / quoted-string marker + int start = p; + while (p < b.length && b[p] != 0) p++; + byte[] out = java.util.Arrays.copyOfRange(b, start, p); + if (p < b.length) p++; + return out; + } + + String text() { + return new String(cstring(), StandardCharsets.UTF_8); + } + + long longInt() { + int n = u8(); + long v = 0; + for (int i = 0; i < n; i++) v = (v << 8) | u8(); + return v; + } + + long integer() { + int x = peek(); + if (x >= 0x80) return u8() & 0x7f; + return longInt(); + } + + /** Skips any WSP value: they all carry their own length. */ + void skipValue() { + int x = peek(); + if (x < 0) return; + if (x < 31) p += 1 + x; + else if (x == 31) { + p++; + int n = (int) uintvar(); + p += n; + } else if (x < 0x80) cstring(); + else p++; + } + + /** Encoded-string-value: plain text, or a length, a charset and the text. */ + String encodedString() { + int x = peek(); + if (x >= 32 || x == 0) return text(); + int len = valueLength(); + int end = p + len; + long charset = integer(); + byte[] raw = cstring(); + p = end; + return new String(raw, charsetFor(charset)); + } + } + + static Charset charsetFor(long mib) { + if (mib == 4) return StandardCharsets.ISO_8859_1; + if (mib == 3) return StandardCharsets.US_ASCII; + if (mib == 1000 || mib == 1015) return StandardCharsets.UTF_16BE; + if (mib == 1013) return StandardCharsets.UTF_16BE; + if (mib == 1014) return StandardCharsets.UTF_16LE; + return StandardCharsets.UTF_8; + } + + /** "+15415550100/TYPE=PLMN" -> "+15415550100" */ + static String address(String a) { + int slash = a.indexOf('/'); + return (slash >= 0 ? a.substring(0, slash) : a).trim(); + } + + static Message parse(byte[] pdu) { + In in = new In(pdu); + Message m = new Message(); + while (in.more()) { + int h = in.u8(); + if (h < 0x80) { + // An application header: name and value as text. + in.p--; + in.cstring(); + in.cstring(); + continue; + } + switch (h & 0x7f) { + case H_MESSAGE_TYPE: m.type = in.u8(); break; + case H_TRANSACTION_ID: m.transactionId = in.text(); break; + case H_CONTENT_LOCATION: m.contentLocation = in.text(); break; + case H_DATE: m.date = in.longInt(); break; + case H_SUBJECT: m.subject = in.encodedString(); break; + case H_TO: m.to.add(address(in.encodedString())); break; + case H_CC: m.cc.add(address(in.encodedString())); break; + case H_FROM: { + int len = in.valueLength(); + int end = in.p + len; + if (in.u8() == 0x80) m.from = address(in.encodedString()); + in.p = end; + break; + } + case H_CONTENT_TYPE: { + // Always the last header: the body follows. + String type = contentType(in, null); + if (type.startsWith("application/vnd.wap.multipart")) multipart(in, m.parts); + else { + Part one = new Part(); + one.type = type; + one.data = java.util.Arrays.copyOfRange(pdu, in.p, pdu.length); + m.parts.add(one); + } + return m; + } + default: in.skipValue(); + } + } + return m; + } + + /** Reads a Content-type value; fills `part`'s charset and name if given. */ + private static String contentType(In in, Part part) { + int x = in.peek(); + if (x >= 0x80) return wellKnown(in.u8() & 0x7f); + if (x >= 32) return in.text().toLowerCase(); + int len = in.valueLength(); + int end = in.p + len; + String type; + if (in.peek() >= 0x80) type = wellKnown(in.u8() & 0x7f); + else if (in.peek() >= 32) type = in.text().toLowerCase(); + else type = wellKnown((int) in.longInt()); + while (in.p < end) { + int param = in.u8(); + switch (param & 0x7f) { + case 0x01: { // Charset + long cs = in.peek() >= 32 && in.peek() < 0x80 ? -1 : in.integer(); + if (cs == -1) in.cstring(); + else if (part != null) part.charset = charsetFor(cs).name(); + break; + } + case 0x05: case 0x17: // Name + case 0x06: case 0x18: { // Filename + String v = in.text(); + if (part != null && part.name == null) part.name = v; + break; + } + default: + if (param < 0x80) { + in.p--; + in.cstring(); // untyped parameter name + } + in.skipValue(); + } + } + in.p = end; + return type; + } + + private static String wellKnown(int code) { + String t = code < TYPES.length ? TYPES[code] : null; + return t == null ? "application/octet-stream" : t; + } + + private static void multipart(In in, List out) { + long count = in.uintvar(); + for (long i = 0; i < count && in.more(); i++) { + int headersLen = (int) in.uintvar(); + int dataLen = (int) in.uintvar(); + int headersEnd = in.p + headersLen; + Part part = new Part(); + part.type = contentType(in, part); + while (in.p < headersEnd) { + int h = in.u8(); + if (h == 0x8E && part.name == null) part.name = in.text(); // Content-Location + else if (h < 0x80) { + in.p--; + in.cstring(); + in.cstring(); + } else in.skipValue(); + } + in.p = headersEnd; + part.data = java.util.Arrays.copyOfRange(in.b, in.p, Math.min(in.b.length, in.p + dataLen)); + in.p += dataLen; + if (part.type.startsWith("application/vnd.wap.multipart")) { + // A nested multipart (rare): flatten it. + List inner = new ArrayList<>(); + try { + multipart(new In(part.data), inner); + } catch (Exception ignored) { + } + out.addAll(inner); + } else out.add(part); + } + } + + // ---------------------------------------------------------------- writing + + private static final class Out extends ByteArrayOutputStream { + void u8(int v) { + write(v & 0xff); + } + + void uintvar(long v) { + int n = 1; + while ((v >> (7 * n)) != 0) n++; + for (int i = n - 1; i >= 0; i--) u8((int) ((v >> (7 * i)) & 0x7f) | (i > 0 ? 0x80 : 0)); + } + + void valueLength(int len) { + if (len < 31) u8(len); + else { + u8(31); + uintvar(len); + } + } + + void text(String s) { + byte[] b = s.getBytes(StandardCharsets.UTF_8); + if (b.length > 0 && (b[0] & 0xff) >= 0x80) u8(0x7F); + write(b, 0, b.length); + u8(0); + } + + void bytes(byte[] b) { + write(b, 0, b.length); + } + + void longInt(long v) { + int n = 1; + while (n < 8 && (v >> (8 * n)) != 0) n++; + u8(n); + for (int i = n - 1; i >= 0; i--) u8((int) (v >> (8 * i))); + } + } + + private static int wellKnownCode(String type) { + for (int i = 0; i < TYPES.length; i++) if (type.equals(TYPES[i])) return i; + return -1; + } + + /** One thing to attach to a message being sent. */ + static final class Attachment { + final byte[] data; + final String type, name; + + Attachment(byte[] data, String type, String name) { + this.data = data; + this.type = type; + this.name = name; + } + } + + /** An m-send-req to `to` (phone numbers) with text and attachments, SMIL first. */ + static byte[] sendReq(List to, String subject, String text, List media) { + Out o = new Out(); + o.u8(0x80 | H_MESSAGE_TYPE); + o.u8(SEND_REQ); + o.u8(0x80 | H_TRANSACTION_ID); + o.text("T" + Long.toHexString(System.currentTimeMillis()) + Long.toHexString((long) (Math.random() * 0xffffff))); + o.u8(0x8D); // MMS version 1.2 + o.u8(0x92); + o.u8(0x80 | H_DATE); + o.longInt(System.currentTimeMillis() / 1000); + o.u8(0x80 | H_FROM); + o.u8(1); + o.u8(0x81); // insert-address-token: the carrier fills in our number + for (String n : to) { + o.u8(0x80 | H_TO); + o.text(n + "/TYPE=PLMN"); + } + if (subject != null && !subject.isEmpty()) { + o.u8(0x80 | H_SUBJECT); + o.text(subject); + } + o.u8(0x8A); // Message class: personal + o.u8(0x80); + o.u8(0x86); // Delivery report: no + o.u8(0x81); + o.u8(0x90); // Read report: no + o.u8(0x81); + + // Content-Type: multipart/related; start=; type=application/smil + Out ct = new Out(); + ct.u8(0x80 | 0x33); + ct.u8(0x8A); + ct.text(""); + ct.u8(0x89); + ct.text("application/smil"); + o.u8(0x80 | H_CONTENT_TYPE); + o.valueLength(ct.size()); + o.bytes(ct.toByteArray()); + + List parts = new ArrayList<>(); // {headers, data} + StringBuilder smil = new StringBuilder("" + + "" + + ""); + for (Attachment a : media) { + String tag = a.type.startsWith("image/") ? "img" : a.type.startsWith("video/") ? "video" : a.type.startsWith("audio/") ? "audio" : "ref"; + smil.append("<").append(tag).append(" src=\"").append(a.name).append('"') + .append(tag.equals("img") || tag.equals("video") ? " region=\"Image\"" : "").append("/>"); + } + if (text != null && !text.isEmpty()) + smil.append(""); + smil.append(""); + + parts.add(new byte[][] {partHeaders("application/smil", null, false, "smil", "smil.xml"), smil.toString().getBytes(StandardCharsets.UTF_8)}); + for (int i = 0; i < media.size(); i++) { + Attachment a = media.get(i); + parts.add(new byte[][] {partHeaders(a.type, a.name, false, "part" + i, a.name), a.data}); + } + if (text != null && !text.isEmpty()) + parts.add(new byte[][] {partHeaders("text/plain", null, true, "text0", "text0.txt"), text.getBytes(StandardCharsets.UTF_8)}); + + o.uintvar(parts.size()); + for (byte[][] p : parts) { + o.uintvar(p[0].length); + o.uintvar(p[1].length); + o.bytes(p[0]); + o.bytes(p[1]); + } + return o.toByteArray(); + } + + private static byte[] partHeaders(String type, String name, boolean utf8, String cid, String location) { + Out ct = new Out(); + int code = wellKnownCode(type); + if (code >= 0) ct.u8(0x80 | code); + else ct.text(type); + if (utf8) { + ct.u8(0x81); // charset + ct.u8(0x80 | 106); + } + if (name != null) { + ct.u8(0x85); // name + ct.text(name); + } + Out h = new Out(); + h.valueLength(ct.size()); + h.bytes(ct.toByteArray()); + h.u8(0xC0); // Content-ID: "" + h.u8(0x22); + h.bytes(("<" + cid + ">").getBytes(StandardCharsets.UTF_8)); + h.u8(0); + h.u8(0x8E); // Content-Location + h.text(location); + return h.toByteArray(); + } + + /** m-acknowledge-ind: tells the carrier a retrieved message arrived. */ + static byte[] acknowledgeInd(String transactionId) { + Out o = new Out(); + o.u8(0x80 | H_MESSAGE_TYPE); + o.u8(ACKNOWLEDGE_IND); + o.u8(0x80 | H_TRANSACTION_ID); + o.text(transactionId); + o.u8(0x8D); + o.u8(0x92); + o.u8(0x91); // Report allowed: no + o.u8(0x81); + return o.toByteArray(); + } +} diff --git a/android/app/src/main/java/me/teafry/voipmessages/RespondService.java b/android/app/src/main/java/me/teafry/voipmessages/RespondService.java new file mode 100644 index 0000000..124ec6b --- /dev/null +++ b/android/app/src/main/java/me/teafry/voipmessages/RespondService.java @@ -0,0 +1,27 @@ +package me.teafry.voipmessages; + +import android.app.Service; +import android.content.Intent; +import android.os.IBinder; + +import java.util.ArrayList; + +/** "Reply with a message" from an incoming call screen; required of a default SMS app. */ +public final class RespondService extends Service { + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + if (intent != null && intent.getData() != null) { + String text = intent.getStringExtra(Intent.EXTRA_TEXT); + String contact = SendToActivity.contact(intent.getData()); + if (text != null && !text.trim().isEmpty() && !contact.isEmpty()) + Sender.send(this, Sim.DID, contact, text.trim(), new ArrayList<>()); + } + stopSelf(startId); + return START_NOT_STICKY; + } + + @Override + public IBinder onBind(Intent intent) { + return null; + } +} diff --git a/android/app/src/main/java/me/teafry/voipmessages/SendToActivity.java b/android/app/src/main/java/me/teafry/voipmessages/SendToActivity.java new file mode 100644 index 0000000..941cad8 --- /dev/null +++ b/android/app/src/main/java/me/teafry/voipmessages/SendToActivity.java @@ -0,0 +1,63 @@ +package me.teafry.voipmessages; + +import android.app.Activity; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; + +import java.util.ArrayList; +import java.util.List; + +/** + * sms:/smsto:/mms:/mmsto: links from other apps ("Message" on a contact, a + * number on a web page): opens that chat, with any text they passed as the draft. + */ +public final class SendToActivity extends Activity { + /** The conversation key for an sms: link's recipients ("" if none). */ + static String contact(Uri uri) { + String ssp = uri.getSchemeSpecificPart(); + if (ssp == null) return ""; + int q = ssp.indexOf('?'); + if (q >= 0) ssp = ssp.substring(0, q); + List nums = new ArrayList<>(); + for (String s : ssp.split("[,;]")) { + String n = Sim.contactFor(s); + if (!n.isEmpty()) nums.add(n); + } + if (nums.isEmpty()) return ""; + return nums.size() == 1 ? nums.get(0) : Phone.groupKey(nums); + } + + @Override + protected void onCreate(Bundle b) { + super.onCreate(b); + Intent in = getIntent(); + Uri data = in.getData(); + String contact = data == null ? "" : contact(data); + String body = in.getStringExtra("sms_body"); + if (body == null) body = in.getStringExtra(Intent.EXTRA_TEXT); + if (body == null && data != null && data.isHierarchical()) body = data.getQueryParameter("body"); + if (body == null && data != null) { + String ssp = data.getSchemeSpecificPart(); + int q = ssp == null ? -1 : ssp.indexOf("body="); + if (q >= 0) body = Uri.decode(ssp.substring(q + 5)); + } + if (contact.isEmpty()) { + startActivity(new Intent(this, NewChatActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + finish(); + return; + } + if (body != null && !body.trim().isEmpty()) + getSharedPreferences("drafts", MODE_PRIVATE).edit().putString(contact, body).apply(); + startActivity(ChatActivity.intent(this, didFor(contact), contact)); + finish(); + } + + /** An existing chat with them from any number; otherwise the SIM. */ + private String didFor(String contact) { + for (Store.Conv c : Store.get(this).conversations(null)) if (c.contact.equals(contact)) return c.did; + Config cfg = Config.get(this); + for (Config.Did d : cfg.dids) if (d.sim) return d.did; + return cfg.defaultDid != null ? cfg.defaultDid : Sim.DID; + } +} diff --git a/android/app/src/main/java/me/teafry/voipmessages/Sender.java b/android/app/src/main/java/me/teafry/voipmessages/Sender.java index e126c48..0866e73 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/Sender.java +++ b/android/app/src/main/java/me/teafry/voipmessages/Sender.java @@ -84,6 +84,14 @@ final class Sender { } return; } + if (Sim.isSim(did)) { + // A long text goes as several SMS parts; photos, voice notes and groups as one MMS. + 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); + 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"; @@ -148,6 +156,8 @@ final class Sender { } private static String classify(Exception e, boolean gv) { + // The SIM answers for certain, and a fresh check can't see our own sends. + if (e instanceof Sim.Failure) return ((Sim.Failure) e).safe ? "safe" : "fatal"; 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"; diff --git a/android/app/src/main/java/me/teafry/voipmessages/SettingsActivity.java b/android/app/src/main/java/me/teafry/voipmessages/SettingsActivity.java index f0ecf56..7ccba0f 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/SettingsActivity.java +++ b/android/app/src/main/java/me/teafry/voipmessages/SettingsActivity.java @@ -15,6 +15,7 @@ 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 static final int ROLE = 1; private LinearLayout box; @Override @@ -28,6 +29,16 @@ public final class SettingsActivity extends BaseActivity { setContentView(scroll); } + @Override + protected void onActivityResult(int req, int res, android.content.Intent data) { + super.onActivityResult(req, res, data); + if (req != ROLE) return; + Sim.recheck(); + // Bring over the texts already on the phone. + Sim.syncSoon(this); + changed(); + } + private static String intervalLabel(int m) { if (m == 0) return "Never (pull to refresh)"; if (m < 60) return "Every " + m + " minutes"; @@ -78,6 +89,27 @@ public final class SettingsActivity extends BaseActivity { : 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("SIM card"); + Sim.recheck(); + if (Sim.isDefault(c)) { + String carrier = Sim.carrier(c); + kv("Texting from the SIM", carrier.isEmpty() ? "On" : carrier); + note(cfg.sandbox ? "Not in the dev app's made-up data: the sandbox never texts for real." + : "bubble is the Rabbit's texting app: texts and MMS to the SIM come here, and chats can be sent \"via SIM\"." + + " To stop, choose another app under Android Settings → Apps → Default apps → SMS app."); + } else { + row("Text from the SIM card", "Make bubble the texting app", v -> { + try { + startActivityForResult(Sim.roleRequest(c), ROLE); + } catch (Exception e) { + note("This Android won't let bubble become its texting app."); + } + }); + note("Sends and receives texts and MMS over the Rabbit's own SIM, as a third number next to voip.ms and Google Voice." + + " Android lets only its default texting app do that, so it takes over from the one you use now;" + + " the texts already on the phone come over too."); + } + section("About"); String version = "?"; try { diff --git a/android/app/src/main/java/me/teafry/voipmessages/Sim.java b/android/app/src/main/java/me/teafry/voipmessages/Sim.java new file mode 100644 index 0000000..4845386 --- /dev/null +++ b/android/app/src/main/java/me/teafry/voipmessages/Sim.java @@ -0,0 +1,732 @@ +package me.teafry.voipmessages; + +import android.app.Activity; +import android.app.PendingIntent; +import android.app.role.RoleManager; +import android.content.BroadcastReceiver; +import android.content.ContentResolver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.net.Uri; +import android.os.Build; +import android.provider.Telephony; +import android.telephony.SmsManager; +import android.telephony.SmsMessage; +import android.telephony.SubscriptionInfo; +import android.telephony.SubscriptionManager; +import android.telephony.TelephonyManager; +import android.util.Log; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * The Rabbit's own SIM card, the third source next to voip.ms and Google + * Voice. It only works while bubble is the default SMS app, which is also + * what makes Android hand incoming texts to us and nobody else. + * + * Android's shared message store (content://sms, content://mms) stays the + * record: incoming and sent messages are written there, as a default SMS app + * must, and copied into our Store from there (ids SMS_BASE/MMS_BASE + the + * provider's _id), so the history the phone already had shows up too, and + * an "Install to Rabbit" that replaces messages.db just copies it in again. + * Conversations use did "sim". + */ +final class Sim { + private Sim() {} + + private static final String TAG = "Sim"; + static final String DID = "sim"; + // Below 2^53 (the desktop is JavaScript) and clear of Google Voice's 2^52 range. + static final long SMS_BASE = 1L << 51, MMS_BASE = (1L << 51) + (1L << 49), FALLBACK_BASE = (1L << 51) + (1L << 50); + + private static final String SMS_SENT = "me.teafry.voipmessages.SMS_SENT"; + private static final String MMS_SENT = "me.teafry.voipmessages.MMS_SENT"; + + static boolean isSim(String did) { + return DID.equals(did); + } + + // ---- being the default SMS app ---- + // Read from the main thread on every Config.get, so no lock: a long import + // holding one froze the screens. + private static volatile long checkedAt; + private static volatile boolean isDefault; + + static boolean isDefault(Context c) { + long now = System.currentTimeMillis(); + if (now - checkedAt > 3000) { + isDefault = c.getPackageName().equals(Telephony.Sms.getDefaultSmsPackage(c)); + checkedAt = now; + } + return isDefault; + } + + static void recheck() { + checkedAt = 0; + } + + /** The system's "make this your SMS app?" prompt. */ + static Intent roleRequest(Context c) { + if (Build.VERSION.SDK_INT >= 29) { + RoleManager rm = c.getSystemService(RoleManager.class); + if (rm != null && rm.isRoleAvailable(RoleManager.ROLE_SMS)) return rm.createRequestRoleIntent(RoleManager.ROLE_SMS); + } + return new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT) + .putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, c.getPackageName()); + } + + static String carrier(Context c) { + try { + String n = c.getSystemService(TelephonyManager.class).getSimOperatorName(); + return n == null ? "" : n; + } catch (Exception e) { + return ""; + } + } + + private static SharedPreferences prefs(Context c) { + return c.getSharedPreferences("sim", Context.MODE_PRIVATE); + } + + /** The SIM's own number (normalized), or "" if the carrier doesn't say. */ + static String self(Context c) { + String n = ""; + try { + n = Phone.normalize(c.getSystemService(TelephonyManager.class).getLine1Number()); + } catch (Exception ignored) { + } + if (n.isEmpty()) { + try { + SubscriptionInfo s = c.getSystemService(SubscriptionManager.class) + .getActiveSubscriptionInfo(SubscriptionManager.getDefaultSmsSubscriptionId()); + if (s != null) n = Phone.normalize(s.getNumber()); + } catch (Exception ignored) { + } + } + if (n.isEmpty()) n = prefs(c).getString("self", ""); + else prefs(c).edit().putString("self", n).apply(); + return n; + } + + /** Who to send to: the carrier wants +1 numbers, but short codes as they are. */ + static String dest(String n) { + String d = Phone.normalize(n); + if (d.isEmpty()) return n; + return d.length() == 10 ? "+1" + d : d; + } + + /** A conversation key for an address: the usual digits, or the sender's name ("T-Mobile"). */ + static String contactFor(String raw) { + if (raw == null) return ""; + String n = Phone.normalize(raw); + return n.isEmpty() ? raw.trim().replace(",", " ") : n; + } + + static SmsManager smsManager(Context c) { + int sub = SubscriptionManager.getDefaultSmsSubscriptionId(); + if (Build.VERSION.SDK_INT >= 31) { + SmsManager m = c.getSystemService(SmsManager.class); + return sub != SubscriptionManager.INVALID_SUBSCRIPTION_ID ? m.createForSubscriptionId(sub) : m; + } + return sub != SubscriptionManager.INVALID_SUBSCRIPTION_ID ? SmsManager.getSmsManagerForSubscriptionId(sub) : SmsManager.getDefault(); + } + + /** A send that didn't go out; `safe` = certainly not sent, so worth retrying. */ + static final class Failure extends Exception { + final boolean safe; + + Failure(String message, boolean safe) { + super(message); + this.safe = safe; + } + } + + // ---- copying from Android's message store ---- + + /** + * Copies messages Android's store has that we don't yet into ours; returns + * the new ones worth notifying about. Cheap when there's nothing new. + */ + private static final Object SYNC = new Object(), PERSIST = new Object(), PENDING = new Object(); + // Per pass: the first copy of a long history goes in chunks, each saved + // (with its high-water mark) before the next, and the list redraws as it goes. + private static final int SMS_CHUNK = 500, MMS_CHUNK = 100; + + static List sync(Context c) { + List out = new ArrayList<>(); + if (!isDefault(c) || Config.get(c).sandbox) return out; + synchronized (SYNC) { + Store store = Store.get(c); + boolean first = store.get("sim_sms_last") == null || store.get("sim_mms_last") == null; + long now = System.currentTimeMillis(); + try { + List added = new ArrayList<>(); + for (boolean more = true; more; ) { + int before = added.size(); + more = readSms(c, store, added); + if (added.size() > before) Sync.changed(); + } + for (boolean more = true; more; ) { + int before = added.size(); + more = readMms(c, store, added); + if (added.size() > before) Sync.changed(); + } + for (Store.Msg m : added) + // The first copy brings in the whole history: only notify about what just came. + if (!first || m.ts > now - 120_000) out.add(m); + } catch (Exception e) { + Log.w(TAG, "copying from the message store failed", e); + } + } + return out; + } + + private static final java.util.concurrent.atomic.AtomicBoolean syncing = new java.util.concurrent.atomic.AtomicBoolean(); + + /** sync() on its own thread (one at a time), for screens: redraws come through Sync.changed. */ + static void syncSoon(Context c) { + if (!isDefault(c) || !syncing.compareAndSet(false, true)) return; + Context app = c.getApplicationContext(); + new Thread(() -> { + try { + Notifier.notifyNew(app, sync(app)); + } finally { + syncing.set(false); + } + }, "sim-sync").start(); + } + + private static long lastId(Store store, String key) { + String v = store.get(key); + return v == null ? 0 : Long.parseLong(v); + } + + /** One chunk of texts into `added`; true if there may be more. */ + private static boolean readSms(Context c, Store store, List added) { + long last = lastId(store, "sim_sms_last"); + long max = last; + int seen = 0; + List rows = new ArrayList<>(); + try (Cursor cur = c.getContentResolver().query(Telephony.Sms.CONTENT_URI, + new String[] {"_id", "address", "body", "date", "type"}, + "_id > ? AND type IN (1, 2)", new String[] {String.valueOf(last)}, "_id LIMIT " + SMS_CHUNK)) { + if (cur == null) return false; + while (cur.moveToNext()) { + seen++; + long id = cur.getLong(0); + max = Math.max(max, id); + String contact = contactFor(cur.getString(1)); + if (contact.isEmpty()) continue; + Store.Msg m = new Store.Msg(); + m.id = SMS_BASE + id; + m.did = DID; + m.contact = contact; + m.body = cur.getString(2) == null ? "" : cur.getString(2); + m.ts = cur.getLong(3); + m.direction = cur.getInt(4) == 1 ? "in" : "out"; + rows.add(m); + } + } + added.addAll(store.upsert(rows)); + store.set("sim_sms_last", String.valueOf(max)); + return seen == SMS_CHUNK; + } + + /** One chunk of MMS into `added`; true if there may be more. */ + private static boolean readMms(Context c, Store store, List added) { + long last = lastId(store, "sim_mms_last"); + long max = last; + int seen = 0; + ContentResolver cr = c.getContentResolver(); + String self = self(c); + List rows = new ArrayList<>(); + try (Cursor cur = cr.query(Telephony.Mms.CONTENT_URI, new String[] {"_id", "date", "msg_box", "sub"}, + "_id > ? AND msg_box IN (1, 2) AND m_type IN (128, 132)", new String[] {String.valueOf(last)}, "_id LIMIT " + MMS_CHUNK)) { + if (cur == null) return false; + while (cur.moveToNext()) { + seen++; + long id = cur.getLong(0); + max = Math.max(max, id); + boolean in = cur.getInt(2) == 1; + String from = null; + Set others = new LinkedHashSet<>(); + try (Cursor a = cr.query(Uri.parse("content://mms/" + id + "/addr"), new String[] {"address", "type"}, null, null, null)) { + while (a != null && a.moveToNext()) { + String addr = a.getString(0); + if (addr == null || addr.equals("insert-address-token")) continue; + String n = contactFor(Pdu.address(addr)); + if (n.isEmpty()) continue; + if (a.getInt(1) == 137) from = n; + else others.add(n); + } + } + // Learn our own number from someone texting just us. + if (self.isEmpty() && in && others.size() == 1) { + self = others.iterator().next(); + prefs(c).edit().putString("self", self).apply(); + } + Set members = new LinkedHashSet<>(); + if (in && from != null) members.add(from); + members.addAll(others); + members.remove(self); + if (members.isEmpty()) continue; + Store.Msg m = new Store.Msg(); + m.id = MMS_BASE + id; + m.did = DID; + m.contact = members.size() == 1 ? members.iterator().next() : Phone.groupKey(new ArrayList<>(members)); + m.direction = in ? "in" : "out"; + m.kind = "mms"; + m.ts = cur.getLong(1) * 1000; + if (in && members.size() > 1) m.sender = from; + StringBuilder body = new StringBuilder(); + String subject = cur.getString(3); + if (subject != null && !subject.trim().isEmpty() && !subject.trim().equalsIgnoreCase("nosubject") + && !subject.trim().equalsIgnoreCase("no subject")) body.append(subject.trim()); + JSONArray media = new JSONArray(); + try (Cursor p = cr.query(Uri.parse("content://mms/part"), new String[] {"_id", "ct", "text"}, + "mid = ?", new String[] {String.valueOf(id)}, "seq, _id")) { + while (p != null && p.moveToNext()) { + String ct = p.getString(1) == null ? "" : p.getString(1).toLowerCase(); + if (ct.equals("application/smil")) continue; + if (ct.equals("text/plain")) { + String t = p.getString(2); + if (t == null) t = readText(cr, p.getLong(0)); + if (t != null && !t.trim().isEmpty()) body.append(body.length() > 0 ? "\n" : "").append(t.trim()); + continue; + } + // Read from the store when first shown (see Media.download), not copied now. + try { + media.put(new JSONObject().put("url", "mmspart:" + p.getLong(0)).put("mime", ct)); + } catch (Exception ignored) { + } + } + } + m.body = body.toString(); + if (media.length() > 0) m.mediaJson = media.toString(); + rows.add(m); + } + } + added.addAll(store.upsert(rows)); + store.set("sim_mms_last", String.valueOf(max)); + return seen == MMS_CHUNK; + } + + private static String readText(ContentResolver cr, long partId) { + try (InputStream in = cr.openInputStream(Uri.parse("content://mms/part/" + partId))) { + return in == null ? null : new String(Http.readAll(in), java.nio.charset.StandardCharsets.UTF_8); + } catch (Exception e) { + return null; + } + } + + /** Read in bubble: read in Android's store too, so another app agrees. */ + static void markRead(Context c, String contact) { + if (!isDefault(c)) return; + new Thread(() -> { + try { + Set addrs = new HashSet<>(); + for (String n : Phone.members(contact)) addrs.add(dest(n)); + long thread = Telephony.Threads.getOrCreateThreadId(c, addrs); + ContentValues v = new ContentValues(); + v.put("read", 1); + v.put("seen", 1); + ContentResolver cr = c.getContentResolver(); + cr.update(Telephony.Sms.CONTENT_URI, v, "thread_id = ? AND read = 0", new String[] {String.valueOf(thread)}); + cr.update(Telephony.Mms.CONTENT_URI, v, "thread_id = ? AND read = 0", new String[] {String.valueOf(thread)}); + } catch (Exception e) { + Log.w(TAG, "marking read in the message store failed", e); + } + }, "sim-read").start(); + } + + // ---- receiving ---- + + /** A text that just came in (SmsReceiver): into Android's store, then ours. */ + static void received(Context c, SmsMessage[] parts, int subId) { + StringBuilder body = new StringBuilder(); + for (SmsMessage p : parts) if (p != null && p.getDisplayMessageBody() != null) body.append(p.getDisplayMessageBody()); + SmsMessage first = parts[0]; + ContentValues v = new ContentValues(); + v.put("address", first.getDisplayOriginatingAddress()); + v.put("body", body.toString()); + v.put("date", System.currentTimeMillis()); + v.put("date_sent", first.getTimestampMillis()); + v.put("read", 0); + v.put("seen", 0); + v.put("type", 1); + v.put("protocol", first.getProtocolIdentifier()); + if (first.getServiceCenterAddress() != null) v.put("service_center", first.getServiceCenterAddress()); + if (subId >= 0) v.put("sub_id", subId); + try { + c.getContentResolver().insert(Telephony.Sms.Inbox.CONTENT_URI, v); + } catch (Exception e) { + Log.w(TAG, "saving an incoming text failed", e); + } + delivered(c); + } + + /** Something new is in Android's store: copy it, tell the screens, notify. */ + private static void delivered(Context c) { + List added = sync(c); + Sync.changed(); + Notifier.notifyNew(c, added); + } + + /** A carrier's "you have an MMS" (MmsReceiver): fetch it. */ + static void notified(Context c, byte[] pushData) { + Pdu.Message n; + try { + n = Pdu.parse(pushData); + } catch (Exception e) { + Log.w(TAG, "unreadable MMS notification", e); + return; + } + if (n.type != Pdu.NOTIFICATION_IND || n.contentLocation == null) return; + Set done = new HashSet<>(prefs(c).getStringSet("fetched", new HashSet<>())); + if (done.contains(n.contentLocation)) return; // the carrier said it again + addPending(c, n.contentLocation, n.transactionId == null ? "" : n.transactionId); + download(c, n.contentLocation, n.transactionId == null ? "" : n.transactionId); + } + + static final String DOWNLOADED = "me.teafry.voipmessages.MMS_DOWNLOADED"; + + private static void download(Context c, String location, String txn) { + String name = "dl-" + UUID.randomUUID() + ".pdu"; + Intent done = new Intent(c, MmsDownloaded.class).setAction(DOWNLOADED) + .putExtra("file", name).putExtra("location", location).putExtra("txn", txn); + PendingIntent pi = PendingIntent.getBroadcast(c, name.hashCode(), done, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_ONE_SHOT); + try { + smsManager(c).downloadMultimediaMessage(c, location, MmsFiles.uri(c, name), null, pi); + } catch (Exception e) { + Log.w(TAG, "couldn't start an MMS download", e); + } + } + + /** An MMS download finished (MmsReceiver). */ + static void downloaded(Context c, Intent intent, int result) { + File f = MmsFiles.file(c, intent.getStringExtra("file")); + String location = intent.getStringExtra("location"), txn = intent.getStringExtra("txn"); + try { + if (result != Activity.RESULT_OK || !f.exists() || f.length() == 0) { + Log.w(TAG, "MMS download failed: " + result); + return; // stays pending: tried again on the next check + } + Pdu.Message m = Pdu.parse(Media.read(f)); + List parts = new ArrayList<>(); + for (Pdu.Part p : m.parts) if (!p.type.equals("application/smil")) parts.add(p); + List to = new ArrayList<>(m.to); + to.addAll(m.cc); + persist(c, 1, m.from, to, m.subject, parts, txn); + removePending(c, location, true); + if (txn != null && !txn.isEmpty()) acknowledge(c, txn); + delivered(c); + } catch (Exception e) { + Log.w(TAG, "couldn't read a downloaded MMS", e); + } finally { + f.delete(); + } + } + + private static void acknowledge(Context c, String txn) { + try { + String name = "ack-" + UUID.randomUUID() + ".pdu"; + try (FileOutputStream out = new FileOutputStream(MmsFiles.file(c, name))) { + out.write(Pdu.acknowledgeInd(txn)); + } + smsManager(c).sendMultimediaMessage(c, MmsFiles.uri(c, name), null, null, null); + } catch (Exception e) { + Log.w(TAG, "MMS acknowledgement failed", e); + } + } + + // Downloads that haven't worked yet: "location\ttxn\tattempts" + private static void addPending(Context c, String location, String txn) { + synchronized (PENDING) { + addPendingLocked(c, location, txn); + } + } + + private static void addPendingLocked(Context c, String location, String txn) { + Set s = new HashSet<>(prefs(c).getStringSet("pending", new HashSet<>())); + for (String e : s) if (e.startsWith(location + "\t")) return; + s.add(location + "\t" + txn + "\t0"); + prefs(c).edit().putStringSet("pending", s).apply(); + } + + private static void removePending(Context c, String location, boolean fetched) { + synchronized (PENDING) { + removePendingLocked(c, location, fetched); + } + } + + private static void removePendingLocked(Context c, String location, boolean fetched) { + SharedPreferences p = prefs(c); + Set s = new HashSet<>(p.getStringSet("pending", new HashSet<>())); + s.removeIf(e -> e.startsWith(location + "\t")); + SharedPreferences.Editor ed = p.edit().putStringSet("pending", s); + if (fetched) { + Set done = new HashSet<>(p.getStringSet("fetched", new HashSet<>())); + if (done.size() > 100) done.clear(); + done.add(location); + ed.putStringSet("fetched", done); + } + ed.apply(); + } + + /** Try again the MMS downloads that failed (no data, flaky signal); give up after 6 tries. */ + static void retryDownloads(Context c) { + synchronized (PENDING) { + retryDownloadsLocked(c); + } + } + + private static void retryDownloadsLocked(Context c) { + if (!isDefault(c)) return; + Set s = new HashSet<>(prefs(c).getStringSet("pending", new HashSet<>())); + if (s.isEmpty()) return; + Set next = new HashSet<>(); + for (String e : s) { + String[] f = e.split("\t", -1); + if (f.length < 3) continue; + int n = Integer.parseInt(f[2]) + 1; + if (n > 6) continue; + next.add(f[0] + "\t" + f[1] + "\t" + n); + download(c, f[0], f[1]); + } + prefs(c).edit().putStringSet("pending", next).apply(); + } + + // ---- sending ---- + + private static void requireDefault(Context c) throws Failure { + recheck(); + if (!isDefault(c)) throw new Failure("bubble isn't the default texting app any more (Settings → SIM card).", false); + } + + /** One text over the SIM; waits for the radio's answer and returns its message id. */ + static long sendSms(Context c, String contact, String text) throws Exception { + requireDefault(c); + SmsManager sm = smsManager(c); + String to = dest(contact); + ArrayList parts = sm.divideMessage(text); + String token = UUID.randomUUID().toString(); + CountDownLatch latch = new CountDownLatch(parts.size()); + int[] error = {0}; + BroadcastReceiver r = new BroadcastReceiver() { + @Override + public void onReceive(Context x, Intent i) { + if (!token.equals(i.getStringExtra("token"))) return; + if (getResultCode() != Activity.RESULT_OK && error[0] == 0) error[0] = getResultCode() == 0 ? -1 : getResultCode(); + latch.countDown(); + } + }; + register(c, r, SMS_SENT); + try { + ArrayList sent = new ArrayList<>(); + for (int i = 0; i < parts.size(); i++) { + Intent i2 = new Intent(SMS_SENT).setPackage(c.getPackageName()).putExtra("token", token); + sent.add(PendingIntent.getBroadcast(c, (token + i).hashCode(), i2, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_ONE_SHOT)); + } + if (parts.size() == 1) sm.sendTextMessage(to, null, text, sent.get(0), null); + else sm.sendMultipartTextMessage(to, null, parts, sent, null); + if (!latch.await(3, TimeUnit.MINUTES)) throw new Failure("The SIM never said whether it went out.", false); + } finally { + c.unregisterReceiver(r); + } + if (error[0] != 0) throw smsFailure(error[0]); + ContentValues v = new ContentValues(); + v.put("address", to); + v.put("body", text); + v.put("date", System.currentTimeMillis()); + v.put("read", 1); + v.put("seen", 1); + v.put("type", 2); + int sub = SubscriptionManager.getDefaultSmsSubscriptionId(); + if (sub >= 0) v.put("sub_id", sub); + try { + Uri u = c.getContentResolver().insert(Telephony.Sms.Sent.CONTENT_URI, v); + if (u != null) return SMS_BASE + ContentUris.parseId(u); + } catch (Exception e) { + Log.w(TAG, "saving a sent text failed", e); + } + return FALLBACK_BASE + System.currentTimeMillis(); + } + + private static Failure smsFailure(int code) { + switch (code) { + case SmsManager.RESULT_ERROR_RADIO_OFF: return new Failure("The radio is off (airplane mode?).", true); + case SmsManager.RESULT_ERROR_NO_SERVICE: return new Failure("No signal.", true); + case SmsManager.RESULT_ERROR_GENERIC_FAILURE: return new Failure("The carrier didn't take it.", true); + case SmsManager.RESULT_ERROR_LIMIT_EXCEEDED: return new Failure("Too many texts at once; try again in a bit.", false); + case SmsManager.RESULT_ERROR_SHORT_CODE_NOT_ALLOWED: + case SmsManager.RESULT_ERROR_SHORT_CODE_NEVER_ALLOWED: return new Failure("Android blocked texting this short code.", false); + default: return new Failure("The SIM couldn't send it (error " + code + ").", code == -1 || (code >= 100 && code < 200)); + } + } + + /** An MMS over the SIM (photos, voice notes, group chats): waits for the carrier. */ + static long sendMms(Context c, String contact, String text, List photos) throws Exception { + requireDefault(c); + List to = new ArrayList<>(); + for (String n : Phone.members(contact)) to.add(dest(n)); + List media = new ArrayList<>(); + for (int i = 0; i < photos.size(); i++) { + Sender.Photo p = photos.get(i); + String kind = p.mime.startsWith("audio/") ? "audio" : p.mime.startsWith("video/") ? "video" : "image"; + media.add(new Pdu.Attachment(Media.read(new File(Media.dir(c), p.file)), p.mime, kind + i + "." + Media.ext(p.mime))); + } + String name = "send-" + UUID.randomUUID() + ".pdu"; + File f = MmsFiles.file(c, name); + try (FileOutputStream out = new FileOutputStream(f)) { + out.write(Pdu.sendReq(to, null, text, media)); + } + String token = UUID.randomUUID().toString(); + CountDownLatch latch = new CountDownLatch(1); + int[] result = {Activity.RESULT_OK}; + BroadcastReceiver r = new BroadcastReceiver() { + @Override + public void onReceive(Context x, Intent i) { + if (!token.equals(i.getStringExtra("token"))) return; + result[0] = getResultCode(); + latch.countDown(); + } + }; + register(c, r, MMS_SENT); + try { + Intent i = new Intent(MMS_SENT).setPackage(c.getPackageName()).putExtra("token", token); + PendingIntent pi = PendingIntent.getBroadcast(c, token.hashCode(), i, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_ONE_SHOT); + smsManager(c).sendMultimediaMessage(c, MmsFiles.uri(c, name), null, null, pi); + if (!latch.await(5, TimeUnit.MINUTES)) throw new Failure("The carrier never said whether it went out.", false); + } finally { + c.unregisterReceiver(r); + f.delete(); + } + if (result[0] != Activity.RESULT_OK) { + int code = result[0]; + // 1 unspecified, 2 invalid APN, 3 unable to connect, 4 HTTP failure, 5 IO, 6 retry, 8 no data network + boolean safe = code == 2 || code == 3 || code == 5 || code == 6 || code == 8; + throw new Failure(code == 8 ? "MMS needs mobile data, and it's off." : "The carrier didn't take the MMS (error " + code + ").", safe); + } + List parts = new ArrayList<>(); + if (text != null && !text.isEmpty()) { + Pdu.Part t = new Pdu.Part(); + t.type = "text/plain"; + t.data = text.getBytes(java.nio.charset.StandardCharsets.UTF_8); + parts.add(t); + } + for (Pdu.Attachment a : media) { + Pdu.Part p = new Pdu.Part(); + p.type = a.type; + p.name = a.name; + p.data = a.data; + parts.add(p); + } + long id = persist(c, 2, null, to, null, parts, null); + return id > 0 ? MMS_BASE + id : FALLBACK_BASE + System.currentTimeMillis(); + } + + private static void register(Context c, BroadcastReceiver r, String action) { + IntentFilter f = new IntentFilter(action); + if (Build.VERSION.SDK_INT >= 33) c.registerReceiver(r, f, Context.RECEIVER_NOT_EXPORTED); + else c.registerReceiver(r, f); + } + + /** + * Writes an MMS into Android's store: box 1 = received (from `from` to + * `to`), 2 = sent (from us to `to`). Returns its _id, or -1. + */ + private static long persist(Context c, int box, String from, List to, String subject, List parts, String txn) { + synchronized (PERSIST) { + return persistLocked(c, box, from, to, subject, parts, txn); + } + } + + private static long persistLocked(Context c, int box, String from, List to, String subject, List parts, String txn) { + ContentResolver cr = c.getContentResolver(); + try { + Set everyone = new HashSet<>(to); + if (from != null) everyone.add(from); + String self = self(c); + if (!self.isEmpty()) everyone.removeIf(a -> Phone.normalize(a).equals(self)); + if (everyone.isEmpty() && from != null) everyone.add(from); + ContentValues v = new ContentValues(); + v.put("thread_id", Telephony.Threads.getOrCreateThreadId(c, everyone)); + v.put("date", System.currentTimeMillis() / 1000); + v.put("msg_box", box); + v.put("read", box == 2 ? 1 : 0); + v.put("seen", box == 2 ? 1 : 0); + v.put("m_type", box == 2 ? 128 : 132); + v.put("v", 18); + v.put("ct_t", "application/vnd.wap.multipart.related"); + v.put("m_cls", "personal"); + if (subject != null && !subject.isEmpty()) { + v.put("sub", subject); + v.put("sub_cs", 106); + } + if (txn != null && !txn.isEmpty()) v.put("tr_id", txn); + int sub = SubscriptionManager.getDefaultSmsSubscriptionId(); + if (sub >= 0) v.put("sub_id", sub); + Uri msg = cr.insert(Telephony.Mms.CONTENT_URI, v); + if (msg == null) return -1; + long id = ContentUris.parseId(msg); + Uri addrs = Uri.parse("content://mms/" + id + "/addr"); + addAddr(cr, addrs, id, box == 2 ? "insert-address-token" : from == null ? "" : from, 137); + for (String a : to) addAddr(cr, addrs, id, a, 151); + Uri partsUri = Uri.parse("content://mms/" + id + "/part"); + int seq = 0; + for (Pdu.Part p : parts) { + ContentValues pv = new ContentValues(); + pv.put("mid", id); + pv.put("seq", seq); + pv.put("ct", p.type); + String loc = p.name != null ? p.name : (p.type.equals("text/plain") ? "text" : "part") + seq; + pv.put("cl", loc); + pv.put("cid", "<" + loc + ">"); + if (p.name != null) pv.put("name", p.name); + if (p.type.equals("text/plain")) { + pv.put("chset", 106); + pv.put("text", p.text()); + cr.insert(partsUri, pv); + } else { + Uri pu = cr.insert(partsUri, pv); + if (pu != null) try (OutputStream out = cr.openOutputStream(pu)) { + if (out != null) out.write(p.data); + } + } + seq++; + } + return id; + } catch (Exception e) { + Log.w(TAG, "saving an MMS failed", e); + return -1; + } + } + + private static void addAddr(ContentResolver cr, Uri uri, long id, String address, int type) { + ContentValues v = new ContentValues(); + v.put("msg_id", id); + v.put("address", address); + v.put("type", type); + v.put("charset", 106); + cr.insert(uri, v); + } +} diff --git a/android/app/src/main/java/me/teafry/voipmessages/SmsReceiver.java b/android/app/src/main/java/me/teafry/voipmessages/SmsReceiver.java new file mode 100644 index 0000000..cf7b8a7 --- /dev/null +++ b/android/app/src/main/java/me/teafry/voipmessages/SmsReceiver.java @@ -0,0 +1,27 @@ +package me.teafry.voipmessages; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.provider.Telephony; +import android.telephony.SmsMessage; + +/** Texts to the SIM: Android hands them to the default SMS app alone (SMS_DELIVER). */ +public final class SmsReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context c, Intent intent) { + if (!Telephony.Sms.Intents.SMS_DELIVER_ACTION.equals(intent.getAction())) return; + SmsMessage[] parts = Telephony.Sms.Intents.getMessagesFromIntent(intent); + if (parts == null || parts.length == 0 || parts[0] == null) return; + int sub = intent.getIntExtra("subscription", -1); + Context app = c.getApplicationContext(); + PendingResult done = goAsync(); + new Thread(() -> { + try { + Sim.received(app, parts, sub); + } finally { + done.finish(); + } + }, "sms-in").start(); + } +} diff --git a/android/app/src/main/java/me/teafry/voipmessages/StateSync.java b/android/app/src/main/java/me/teafry/voipmessages/StateSync.java index 74f2795..653aa97 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/StateSync.java +++ b/android/app/src/main/java/me/teafry/voipmessages/StateSync.java @@ -59,6 +59,7 @@ final class StateSync { static void markRead(Context c, String did, String contact) { Store.get(c).markRead(did, contact); + if (Sim.isSim(did)) Sim.markRead(c, contact); export(c); Notifier.sweep(c); } diff --git a/android/app/src/main/java/me/teafry/voipmessages/Sync.java b/android/app/src/main/java/me/teafry/voipmessages/Sync.java index 8b1f330..f5cfda3 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/Sync.java +++ b/android/app/src/main/java/me/teafry/voipmessages/Sync.java @@ -52,6 +52,10 @@ final class Sync { Store store = Store.get(c); StateSync.importPending(c); List added = new ArrayList<>(); + // The SIM's messages arrive on their own (SmsReceiver/MmsReceiver); this + // catches up on anything missed and retries MMS that didn't download. + added.addAll(Sim.sync(c)); + Sim.retryDownloads(c); if (cfg.sandbox) { store.set("last_poll", String.valueOf(System.currentTimeMillis())); changed(); diff --git a/android/app/src/main/java/me/teafry/voipmessages/Ui.java b/android/app/src/main/java/me/teafry/voipmessages/Ui.java index 1e97149..6548501 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/Ui.java +++ b/android/app/src/main/java/me/teafry/voipmessages/Ui.java @@ -192,6 +192,16 @@ final class Ui { /** "via (541) 555-0100" / "via GV (484) …" */ static String via(Context c, String did) { + if (Sim.isSim(did)) return "via SIM"; return "via " + (Config.get(c).isGv(did) ? "GV " : "") + Phone.format(did); } + + /** A number to send from, as the From pickers list it. */ + static String didLabel(Context c, Config.Did d) { + if (d.sim) { + String carrier = Sim.carrier(c); + return "SIM card" + (carrier.isEmpty() ? "" : " — " + carrier); + } + return Phone.format(d.did) + (d.gv ? " — Google Voice" : ""); + } } diff --git a/android/build.py b/android/build.py index 74bfdaa..01ab184 100644 --- a/android/build.py +++ b/android/build.py @@ -26,8 +26,8 @@ import sys import zipfile from pathlib import Path -VERSION_NAME = "0.2.0" -VERSION_CODE = 2 +VERSION_NAME = "0.3.0" +VERSION_CODE = 3 PACKAGE = "me.teafry.voipmessages" DEV_PACKAGE = PACKAGE + ".dev" @@ -83,10 +83,16 @@ def build(dev: bool) -> Path: for d in (gen, classes, dex): d.mkdir(parents=True) + # aapt2 has no manifest placeholders: fill in ${applicationId} (the MMS + # file provider's authority must differ between the real and dev apps). + manifest = out / "AndroidManifest.xml" + manifest.write_text((SRC / "AndroidManifest.xml").read_text() + .replace("${applicationId}", DEV_PACKAGE if dev else PACKAGE)) + 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", + "-I", android_jar, "--manifest", manifest, "--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, diff --git a/package.json b/package.json index 3629b63..bc6d8dd 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "voipms-desktop", "productName": "bubble", - "version": "0.2.0", + "version": "0.3.0", "description": "Signal-style desktop SMS client for voip.ms", "author": "trav ", "private": true, diff --git a/resources/android/VoipMessages.apk b/resources/android/VoipMessages.apk index 19abadd..0ee290f 100644 Binary files a/resources/android/VoipMessages.apk and b/resources/android/VoipMessages.apk differ diff --git a/resources/android/VoipMessages.json b/resources/android/VoipMessages.json index 7d0252f..c30ad4c 100644 --- a/resources/android/VoipMessages.json +++ b/resources/android/VoipMessages.json @@ -1 +1 @@ -{"version_name": "0.2.0", "version_code": 2, "package": "me.teafry.voipmessages"} +{"version_name": "0.3.0", "version_code": 3, "package": "me.teafry.voipmessages"}