diff --git a/android/app/src/main/java/me/teafry/voipmessages/ChatActivity.java b/android/app/src/main/java/me/teafry/voipmessages/ChatActivity.java index d7d080e..399daf8 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/ChatActivity.java +++ b/android/app/src/main/java/me/teafry/voipmessages/ChatActivity.java @@ -46,6 +46,7 @@ public final class ChatActivity extends BaseActivity { private ListView list; private TextView titleView, subView, counter, attach, send; private EditText input; + private TextView unsentBanner; 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). @@ -106,6 +107,21 @@ public final class ChatActivity extends BaseActivity { list.setAdapter(adapter); root.addView(list, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1)); + // Texts here that didn't go out: never just a quiet line on a bubble. + unsentBanner = Ui.bold(Ui.text(this, "", Ui.T_SMALL, 0xFFFFFFFF)); + unsentBanner.setBackgroundColor(Ui.DANGER); + unsentBanner.setPadding(Ui.dp(this, 32), Ui.dp(this, 16), Ui.dp(this, 32), Ui.dp(this, 16)); + unsentBanner.setVisibility(View.GONE); + unsentBanner.setOnClickListener(v -> { + for (int i = 0; i < rows.size(); i++) + if (rows.get(i) instanceof Store.Msg && "failed".equals(((Store.Msg) rows.get(i)).status)) { + list.setSelection(i); + failedMenu((Store.Msg) rows.get(i)); + return; + } + }); + root.addView(unsentBanner); + root.addView(composer()); setContentView(root); root.getViewTreeObserver().addOnGlobalLayoutListener(() -> { @@ -246,6 +262,7 @@ public final class ChatActivity extends BaseActivity { protected void onResume() { super.onResume(); Notifier.clear(this, did, contact); + Notifier.clearUnsent(this, did, contact); } @Override @@ -310,6 +327,11 @@ public final class ChatActivity extends BaseActivity { View firstView = list.getChildAt(0); Object anchor = !atBottom && firstPos < rows.size() ? rows.get(firstPos) : null; int anchorTop = firstView == null ? 0 : firstView.getTop(); + int unsent = 0; + for (Store.Msg m : msgs) if ("failed".equals(m.status)) unsent++; + unsentBanner.setVisibility(unsent > 0 ? View.VISIBLE : View.GONE); + unsentBanner.setText("⚠ " + (unsent > 1 ? unsent + " of your texts weren't sent." : "Your text wasn't sent.") + + " Tap to retry, edit or delete."); rows.clear(); for (int i = 0; i < msgs.size(); i++) { Store.Msg m = msgs.get(i); @@ -644,7 +666,8 @@ public final class ChatActivity extends BaseActivity { bubble.addView(media); bubble.addView(body); bubble.addView(meta); - failed = Ui.text(c, "", Ui.T_TINY, Ui.DANGER); + failed = Ui.bold(Ui.text(c, "", Ui.T_SMALL, Ui.DANGER)); + failed.setPadding(Ui.dp(c, 14), Ui.dp(c, 6), Ui.dp(c, 14), Ui.dp(c, 6)); 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)); @@ -680,7 +703,11 @@ public final class ChatActivity extends BaseActivity { 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); + if ("failed".equals(msg.status)) { + android.graphics.drawable.GradientDrawable g = Ui.round(Ui.ACCENT, Ui.dp(c, 30)); + g.setStroke(Ui.dp(c, 4), Ui.DANGER); + bubble.setBackground(g); + } bubble.setMinimumWidth(0); // Keep bubbles to ~80% of the width. body.setMaxWidth(Math.round(getResources().getDisplayMetrics().widthPixels * 0.72f)); @@ -693,7 +720,8 @@ public final class ChatActivity extends BaseActivity { meta.setTextColor(out ? 0xB3FFFFFF : Ui.MUTED); Ui.glyph(meta, "pending".equals(msg.status) ? Glyph.Kind.CLOCK : null, true); failed.setVisibility("failed".equals(msg.status) ? VISIBLE : GONE); - failed.setText("⚠ Not sent" + (msg.error != null ? ": " + msg.error : "") + " · tap to retry"); + failed.setText("⚠ Not sent. " + (msg.error != null ? msg.error + " " : "") + "Tap to retry, edit or delete."); + failed.setGravity(out ? Gravity.END : Gravity.START); List rs = reactions.get(msg.id); reacts.setVisibility(rs == null ? GONE : VISIBLE); if (rs != null) { @@ -861,7 +889,33 @@ public final class ChatActivity extends BaseActivity { Store.get(this).deleteMessage(m.id); changed(); }) - .setNeutralButton("Cancel", null) + .setNeutralButton("Edit", (d, w) -> editFailed(m)) .show(); } + + /** + * Back into the box to change before sending again: its words (and + * photos) go into the composer and the failed copy goes. A voice note + * can't be edited, so it just goes back to Retry. + */ + private void editFailed(Store.Msg m) { + List back = new ArrayList<>(); + for (JSONObject ref : m.media()) { + String mime = ref.optString("mime"); + if (!mime.startsWith("image/")) { + Toast.makeText(this, "A voice note can't be edited: retry or delete it.", Toast.LENGTH_LONG).show(); + return; + } + back.add(new Sender.Photo(ref.optString("file"), mime, ref.optInt("width"), ref.optInt("height"))); + } + String cur = input.getText().toString(); + input.setText(cur.trim().isEmpty() ? m.body : m.body + "\n" + cur); + input.setSelection(input.getText().length()); + for (Sender.Photo p : back) addToTray(p); + input.requestFocus(); + MainActivity.bg.execute(() -> { + Store.get(this).deleteMessage(m.id); + changed(); + }); + } } diff --git a/android/app/src/main/java/me/teafry/voipmessages/MainActivity.java b/android/app/src/main/java/me/teafry/voipmessages/MainActivity.java index 7bdaa9d..de295a6 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/MainActivity.java +++ b/android/app/src/main/java/me/teafry/voipmessages/MainActivity.java @@ -430,11 +430,21 @@ public final class MainActivity extends BaseActivity { 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) : "•"); + if (c.failed > 0) { + // A text here didn't go out: red, ahead of everything else. + preview.setText("Not sent · " + who + body); + preview.setTextColor(Ui.DANGER); + badge.setVisibility(VISIBLE); + badge.setText("!"); + badge.setBackground(Ui.round(Ui.DANGER, Ui.dp(ctx, 20))); + } else { + preview.setText(who + body); + 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) : "•"); + badge.setBackground(Ui.round(Ui.ACCENT, Ui.dp(ctx, 20))); + } via.setText(Config.get(ctx).dids.size() > 1 ? Ui.via(ctx, c.did) : ""); via.setVisibility(Config.get(ctx).dids.size() > 1 ? VISIBLE : GONE); } diff --git a/android/app/src/main/java/me/teafry/voipmessages/Notifier.java b/android/app/src/main/java/me/teafry/voipmessages/Notifier.java index 84b1de0..115b08d 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/Notifier.java +++ b/android/app/src/main/java/me/teafry/voipmessages/Notifier.java @@ -19,6 +19,7 @@ final class Notifier { private Notifier() {} private static final String CHANNEL = "messages"; + private static final String UNSENT = "unsent"; // Only messages this recent notify (not a big catch-up after being offline). private static final long RECENT = 6 * 60 * 60_000L; @@ -65,6 +66,44 @@ final class Notifier { c.getSystemService(NotificationManager.class).cancel((did + contact).hashCode()); } + /** + * Your text didn't go out. Its own channel, whatever the notification + * setting and even with a screen in front: a send that fails quietly is + * the worst thing a phone can do. Do Not Disturb still applies. + */ + static void notifyUnsent(Context c, List msgs) { + NotificationManager nm = c.getSystemService(NotificationManager.class); + nm.createNotificationChannel(new NotificationChannel(UNSENT, "Texts that didn't send", NotificationManager.IMPORTANCE_HIGH)); + Map> byConv = new LinkedHashMap<>(); + for (Store.Msg m : msgs) byConv.computeIfAbsent(m.did + "\n" + m.contact, k -> new ArrayList<>()).add(m); + Store store = Store.get(c); + for (List list : byConv.values()) { + Store.Msg first = list.get(0); + String who = Contacts.title(c, first.contact, store.getName(first.did, first.contact)); + String title = list.size() > 1 ? list.size() + " texts to " + who + " weren't sent" : "Text to " + who + " wasn't sent"; + String preview = first.body.trim().isEmpty() ? "Your message" : "“" + first.body.trim() + "”"; + String body = list.size() > 1 ? "Open the chat to retry, edit or delete them." + : preview + " · " + (first.error != null ? first.error : "Open the chat to retry it."); + int id = ("unsent" + first.did + first.contact).hashCode(); + PendingIntent pi = PendingIntent.getActivity(c, id, ChatActivity.intent(c, first.did, first.contact), + PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); + nm.notify(id, new Notification.Builder(c, UNSENT) + .setSmallIcon(R.drawable.ic_launcher) + .setContentTitle(title) + .setContentText(body) + .setStyle(new Notification.BigTextStyle().bigText(body)) + .setShowWhen(true) + .setAutoCancel(true) + .setContentIntent(pi) + .build()); + } + } + + /** The chat's open, and its banner says the same. */ + static void clearUnsent(Context c, String did, String contact) { + c.getSystemService(NotificationManager.class).cancel(("unsent" + did + contact).hashCode()); + } + private static Bundle conversation(String did, String contact) { Bundle b = new Bundle(); b.putString("did", did); diff --git a/android/app/src/main/java/me/teafry/voipmessages/Relay.java b/android/app/src/main/java/me/teafry/voipmessages/Relay.java index 9fcd5d0..178c2f7 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/Relay.java +++ b/android/app/src/main/java/me/teafry/voipmessages/Relay.java @@ -346,6 +346,7 @@ final class Relay { } private static void result(Context c, String id, long msgId, String error) { + inflight(c, id, 0); try { JSONObject o = new JSONObject().put("t", "sent").put("id", id); o.put("msgId", msgId != 0 ? msgId : JSONObject.NULL); @@ -394,6 +395,44 @@ final class Relay { result(c, id, 0, "It was empty."); return; } - Sender.send(c, Sim.DID, contact, text, photos, (msgId, error) -> result(c, id, msgId, error)); + long temp = Sender.send(c, Sim.DID, contact, text, photos, (msgId, error) -> result(c, id, msgId, error)); + // Until its result is posted: if this process dies first, the next one + // still answers the desktop (orphaned), so it never waits forever. + if (temp < 0) inflight(c, id, temp); + } + + /** Remember (tempId < 0) or forget (0) the local message a desktop send became. */ + private static synchronized void inflight(Context c, String id, long tempId) { + SharedPreferences p = prefs(c); + Set s = new HashSet<>(p.getStringSet("inflight", new HashSet<>())); + s.removeIf(e -> e.startsWith(id + "\t")); + if (tempId < 0) s.add(id + "\t" + tempId); + p.edit().putStringSet("inflight", s).commit(); + } + + /** + * Sends an earlier process left unfinished: those the desktop asked for are + * reported back to it as failed (it alerts there). Returns the others. + */ + static List orphaned(Context c, List orphans) { + Map byTemp = new HashMap<>(); + synchronized (Relay.class) { + for (String e : prefs(c).getStringSet("inflight", new HashSet<>())) { + int tab = e.indexOf('\t'); + try { + byTemp.put(Long.parseLong(e.substring(tab + 1)), e.substring(0, tab)); + } catch (Exception ignored) { + } + } + // Whatever isn't an orphan finished (or will be answered by this process). + prefs(c).edit().remove("inflight").commit(); + } + List mine = new ArrayList<>(); + for (Store.Msg m : orphans) { + String id = byTemp.get(m.id); + if (id == null) mine.add(m); + else result(c, id, 0, m.error); + } + return mine; } } diff --git a/android/app/src/main/java/me/teafry/voipmessages/Sender.java b/android/app/src/main/java/me/teafry/voipmessages/Sender.java index ffacaa3..700832c 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/Sender.java +++ b/android/app/src/main/java/me/teafry/voipmessages/Sender.java @@ -69,7 +69,12 @@ final class Sender { send(ctx, did, contact, text, photos, null); } - static void send(Context ctx, String did, String contact, String text, List photos, Done done) { + /** + * Returns the local id of the (first) pending message. With `done` (the + * desktop's sends over the relay) the outcome goes back to whoever asked, + * who alerts on failure; without, a failure notifies here. + */ + static long send(Context ctx, String did, String contact, String text, List photos, Done done) { Context c = ctx.getApplicationContext(); Config cfg = Config.get(c); if (cfg.sandbox) { @@ -81,12 +86,13 @@ final class Sender { store.confirmPending(id, real); Sync.changed(); if (done != null) done.done(real, null); - return; + return real; } if (cfg.isGv(did)) { if (photos.isEmpty()) { - enqueue(c, pending(did, contact, text, null), () -> gvSend(c, did, contact, text, null), true, done); + return enqueue(c, pending(did, contact, text, null), () -> gvSend(c, did, contact, text, null), true, done); } else { + long first = 0; // 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 : ""; @@ -95,26 +101,27 @@ final class Sender { one.add(p); Store.Msg m = pending(did, contact, body, one); m.ts += i; - enqueue(c, m, () -> gvSend(c, did, contact, body, p), true, i == 0 ? done : null); + long id = enqueue(c, m, () -> gvSend(c, did, contact, body, p), true, i == 0 ? done : null); + if (i == 0) first = id; } + return first; } - return; } if (Sim.isSim(did)) { // A long text goes as several SMS parts; photos, voice notes and groups as one MMS. boolean mms = !photos.isEmpty() || Phone.isGroup(contact); Store.Msg m = pending(did, contact, text, photos); if (mms) m.kind = "mms"; - enqueue(c, m, () -> mms ? Sim.sendMms(c, contact, text, photos) : Sim.sendSms(c, contact, text), false, (id, err) -> { + Done told = (id, err) -> { if (done != null) done.done(id, err); Relay.soon(c); // the desktop hears about it on the next round - }); - return; + }; + return enqueue(c, m, () -> mms ? Sim.sendMms(c, contact, text, photos) : Sim.sendSms(c, contact, text), false, told, done == null); } 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, () -> { + return enqueue(c, m, () -> { VoipMs api = new VoipMs(cfg.voipUser, cfg.voipPass); if (!mms) return api.sendSms(did, contact, text); List media = new ArrayList<>(); @@ -140,7 +147,11 @@ final class Sender { return m; } - private static void enqueue(Context c, Store.Msg m, Attempt attempt, boolean gv, Done done) { + private static long enqueue(Context c, Store.Msg m, Attempt attempt, boolean gv, Done done) { + return enqueue(c, m, attempt, gv, done, done == null); + } + + private static long enqueue(Context c, Store.Msg m, Attempt attempt, boolean gv, Done done, boolean alert) { Store store = Store.get(c); long tempId = store.insertPending(m); Sync.changed(); @@ -149,7 +160,28 @@ final class Sender { String error = deliver(c, store, tempId, attempt, gv, id); Sync.changed(); if (done != null) done.done(id[0], error); + Store.Msg after = store.getMessage(tempId); + if (alert && after != null && "failed".equals(after.status)) { + List one = new ArrayList<>(); + one.add(after); + Notifier.notifyUnsent(c, one); + } }); + return tempId; + } + + /** + * At startup, the sends an earlier process left unfinished (already marked + * failed): the desktop's go back to it as failed, the rest notify here. + */ + static void recover(Context c, List orphans) { + if (orphans.isEmpty()) return; + // Now, before this process's own sends add to the relay's in-flight list. + List mine = Relay.orphaned(c, orphans); + new Thread(() -> { + if (!mine.isEmpty()) Notifier.notifyUnsent(c, mine); + Sync.changed(); + }, "recover-sends").start(); } /** Null when it went out (its id in id[0]), else why not. */ diff --git a/android/app/src/main/java/me/teafry/voipmessages/Store.java b/android/app/src/main/java/me/teafry/voipmessages/Store.java index 5888692..f205cee 100644 --- a/android/app/src/main/java/me/teafry/voipmessages/Store.java +++ b/android/app/src/main/java/me/teafry/voipmessages/Store.java @@ -29,7 +29,11 @@ final class Store { private static final long MATCH_AFTER = 15 * 60_000L; static synchronized Store get(Context c) { - if (instance == null) instance = new Store(c.getApplicationContext()); + if (instance == null) { + instance = new Store(c.getApplicationContext()); + // A new process: any send still 'pending' belonged to one that died. + Sender.recover(c.getApplicationContext(), instance.failOrphanedSends()); + } return instance; } @@ -222,6 +226,32 @@ final class Store { db.execSQL("UPDATE messages SET status = 'failed', error = ? WHERE id = ?", new Object[] {error, tempId}); } + /** + * Sends left 'pending' by an earlier process (Android killed it, or it + * crashed, mid-send): their send loop died with it, so nothing will ever + * finish them. They become failed, shown as Not sent with Retry, never + * resent on their own (by now they may be stale). If one did go out, the + * next check still replaces it (reconcileSent matches failed rows too). + */ + List failOrphanedSends() { + List ids = new ArrayList<>(); + try (Cursor c = db.rawQuery("SELECT id FROM messages WHERE id < 0 AND status = 'pending' AND direction = 'out'", null)) { + while (c.moveToNext()) ids.add(c.getLong(0)); + } + List out = new ArrayList<>(); + for (long id : ids) { + Msg m = getMessage(id); + if (m == null) continue; + // A SIM text may already be with the radio, which sends it whether or not we're alive. + markFailed(id, Sim.isSim(m.did) ? ORPHAN_SIM : ORPHAN); + out.add(getMessage(id)); + } + return out; + } + + static final String ORPHAN = "bubble stopped before this finished sending, so it most likely didn't go out."; + static final String ORPHAN_SIM = "bubble stopped before the SIM said whether this went out. Check before retrying."; + /** Sent messages that turned up in a poll replace our pending/failed copies. */ void reconcileSent(List added) { List sorted = new ArrayList<>(added); @@ -308,6 +338,7 @@ final class Store { String did, contact, lastBody, lastDirection, lastSender, lastMediaJson, name; long lastTs; int unread; + int failed; // your texts here that didn't send boolean archived, markedUnread; } @@ -319,7 +350,8 @@ final class Store { + " 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" + + " r.archived_at IS NOT NULL, COALESCE(r.marked_unread, 0), r.name," + + " (SELECT COUNT(*) FROM messages m WHERE m.did = l.did AND m.contact = l.contact AND m.id < 0 AND m.status = 'failed')" + " 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" @@ -338,6 +370,7 @@ final class Store { v.archived = c.getInt(8) != 0; v.markedUnread = c.getInt(9) != 0; v.name = c.getString(10); + v.failed = c.getInt(11); if (archived == null || v.archived == archived) out.add(v); } } diff --git a/android/build.py b/android/build.py index f9007b7..94e9d84 100644 --- a/android/build.py +++ b/android/build.py @@ -26,8 +26,8 @@ import sys import zipfile from pathlib import Path -VERSION_NAME = "0.7.8" -VERSION_CODE = 16 +VERSION_NAME = "0.7.9" +VERSION_CODE = 17 PACKAGE = "me.teafry.voipmessages" DEV_PACKAGE = PACKAGE + ".dev" diff --git a/package.json b/package.json index 39087e3..3210cc5 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "voipms-desktop", "productName": "bubble", - "version": "0.9.8", + "version": "0.9.9", "description": "Signal-style desktop SMS client for voip.ms", "author": "trav ", "private": true, diff --git a/resources/android/VoipMessages.apk b/resources/android/VoipMessages.apk index 09165f4..835c6f7 100644 Binary files a/resources/android/VoipMessages.apk and b/resources/android/VoipMessages.apk differ diff --git a/resources/android/VoipMessages.json b/resources/android/VoipMessages.json index 982d971..f930396 100644 --- a/resources/android/VoipMessages.json +++ b/resources/android/VoipMessages.json @@ -1 +1 @@ -{"version_name": "0.7.8", "version_code": 16, "package": "me.teafry.voipmessages"} +{"version_name": "0.7.9", "version_code": 17, "package": "me.teafry.voipmessages"} diff --git a/src/main/notify.ts b/src/main/notify.ts index bd8ba73..0613e0b 100644 --- a/src/main/notify.ts +++ b/src/main/notify.ts @@ -105,9 +105,9 @@ export function notifyNew(msgs: NewMessage[], { db, contacts, onClick }: NotifyD } } -// Your text didn't go out. Unlike new messages this pops up (normal urgency) -// and stays until clicked or dismissed: a send that fails quietly is the -// worst thing a phone can do. +// Your text didn't go out. Normal urgency (new messages are low): it pops up +// unless Do Not Disturb is on, and stays in the list either way. Never +// critical, which would break through Do Not Disturb. export function notifyUnsent(msgs: Message[], { db, contacts, onClick }: NotifyDeps): void { if (!Notification.isSupported()) return const byConv = new Map() @@ -118,7 +118,7 @@ export function notifyUnsent(msgs: Message[], { db, contacts, onClick }: NotifyD const n = new Notification({ title: list.length > 1 ? `${list.length} texts to ${who} weren't sent` : `Text to ${who} wasn't sent`, body: list.length > 1 ? 'Open the chat to retry or delete them.' : `“${preview(list[0]) || 'Your message'}” · ${list[0].error ?? 'Open the chat to retry it.'}`, - urgency: 'critical' + urgency: 'normal' }) // Kept referenced like the others so the click survives; not filed under // `live`, so reading the chat doesn't take it back down. diff --git a/src/renderer/src/components/ChatView.tsx b/src/renderer/src/components/ChatView.tsx index 066ff67..8f90036 100644 --- a/src/renderer/src/components/ChatView.tsx +++ b/src/renderer/src/components/ChatView.tsx @@ -168,6 +168,20 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam const unsent = useMemo(() => (messages ?? []).filter((m) => m.status === 'failed'), [messages]) + // Edit on a text that wasn't sent: its words (and pictures) go back into the + // box, and the failed copy goes, so what's sent next is the edited one. + const editFailed = useCallback(async (m: Message) => { + const files = await Promise.all( + (m.media ?? []).map(async (ref, i) => { + const { mime, data } = await window.api.readMedia(m.id, i) + return new File([data], ref.file ?? `photo-${i + 1}`, { type: mime }) + }) + ).catch(() => undefined) + if (!files) return // keep it rather than lose its pictures + composer.current?.edit(m.body, files) + await window.api.deleteFailed(m.id) + }, []) + const indexOf = useCallback((id: number) => rows.findIndex((r) => r.kind === 'msg' && r.m.id === id), [rows]) const flash = useCallback((id: number) => { @@ -395,6 +409,7 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam reactions={folded.reactions.get(r.m.id)} onShowReactions={showReactions} onMenu={showMsgMenu} + onEditFailed={editFailed} versions={folded.versions.get(r.m.id)} onShowEdits={showEdits} /> diff --git a/src/renderer/src/components/Composer.tsx b/src/renderer/src/components/Composer.tsx index 7b1aaf2..691cb3b 100644 --- a/src/renderer/src/components/Composer.tsx +++ b/src/renderer/src/components/Composer.tsx @@ -17,6 +17,8 @@ const attachmentDrafts = new Map() export interface ComposerHandle { addFiles: (files: File[]) => void + // Back into the box to change before sending again (a text that wasn't sent). + edit: (text: string, files: File[]) => void } interface Props { @@ -118,7 +120,14 @@ export function Composer({ conv, isNew, smsDids, gvNumber, onChangeDid, ref }: P textarea.current?.focus() } - useImperativeHandle(ref, () => ({ addFiles })) + const edit = (body: string, files: File[]): void => { + // Anything already being typed stays, after it. + setText((cur) => (cur.trim() ? `${body}\n${cur}` : body)) + if (files.length) addFiles(files) + textarea.current?.focus() + } + + useImperativeHandle(ref, () => ({ addFiles, edit })) const remove = (a: Attachment): void => { URL.revokeObjectURL(a.previewUrl) diff --git a/src/renderer/src/components/MessageBubble.tsx b/src/renderer/src/components/MessageBubble.tsx index a710f38..dfd3e72 100644 --- a/src/renderer/src/components/MessageBubble.tsx +++ b/src/renderer/src/components/MessageBubble.tsx @@ -88,12 +88,13 @@ interface Props { onOpenMedia: (id: number, index: number) => void onMediaMenu: (id: number, index: number, e: React.MouseEvent) => void onMediaLoad: () => void + onEditFailed?: (m: Message) => void } // A send still going after this long gets a visible "Still sending…". const SLOW_SEND_MS = 15_000 -export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMenu, reactions, onShowReactions, onMenu, versions, onShowEdits, groupStart, groupEnd, flash, highlight, onOpenMedia, onMediaMenu, onMediaLoad }: Props) { +export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMenu, reactions, onShowReactions, onMenu, versions, onShowEdits, groupStart, groupEnd, flash, highlight, onOpenMedia, onMediaMenu, onMediaLoad, onEditFailed }: Props) { const media = m.media ?? [] const cls = [ 'msg', @@ -168,6 +169,7 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe + {onEditFailed && }