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

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

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

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

After

Width:  |  Height:  |  Size: 60 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">bubble</string>
</resources>