Archive and mark read from the notification itself
Both happen in the background. The phone stays where it is. This was twice described as impossible, here and in FEATURES.md: the service worker was said to have no session, so anything touching mail had to open the app. That is wrong, and checking it rather than repeating it is the whole of this change. ihasmail's session is an httpOnly cookie against its own origin and the only other thing the API asks for is a fixed `x-requested-with` header, which is not a secret and is not held anywhere. A same-origin fetch from the worker carries the cookie like any other. Confirmed against the mock: logging in with curl and then issuing `Email/set` with nothing but that cookie and the static headers marked a message read and moved it to Archive, HTTP 200. Nothing the tab holds in memory is involved, because the API asks for none of it. Two actions, because `maxActions` is two on Android and anything past it is dropped without a word. Archive and Mark as read are the two worth having: they are what somebody does to a notification they have already read the whole of. Reply is not among them -- it would have to open the app, which is what tapping the notification does already. The worker still cannot reach a catalogue. It is plain JavaScript copied into the build, outside the bundle, with no i18n and no idea which mailbox is the archive. So the app writes both down in the same cache it already uses for handoffs, and rewrites them whenever the language, the account or the folder list changes. Where there is no such note -- between installing this worker and next opening ihasmail -- the notification appears with no buttons at all, rather than English ones over a mailbox guessed by name. That also fixes two strings the worker had always shown in English regardless: "New mail" and "(no subject)". A session can be gone by the time a button is pressed. That comes back as a refusal and the notification says so, rather than vanishing as though it had worked. It does not open the app to recover: being interrupted is what the button existed to avoid. The two claims that were wrong are corrected rather than quietly deleted, including the one about push renewal -- which still needs a tab, but for a different reason than the one given. The reason is when the worker runs, not what it may do: it wakes only for a push, and the push stops when the subscription lapses. Two new strings, in all nine catalogues.
This commit is contained in:
+149
-13
@@ -130,14 +130,23 @@ self.addEventListener("fetch", (event) => {
|
||||
|
||||
/*
|
||||
* Stalwart signs with VAPID and pushes straight to the browser's push service;
|
||||
* nothing here talks to ihasmail's server. The payload is an EmailPush object
|
||||
* (draft-ietf-jmap-emailpush) carrying enough of the message to show a useful
|
||||
* notification without a round-trip — which matters, because when this fires
|
||||
* there may be no session to make one with.
|
||||
* nothing here talks to ihasmail's server on the way in. The payload is an
|
||||
* EmailPush object (draft-ietf-jmap-emailpush) carrying enough of the message
|
||||
* to show a useful notification without a round-trip, which is what lets a
|
||||
* notification appear immediately rather than after a request.
|
||||
*
|
||||
* This file used to say that a round-trip was impossible here, and it was
|
||||
* wrong: see the note on `jmap()`. What it can do is ask; what it cannot do is
|
||||
* be sure of an answer, since the session may be gone by the time it does. So
|
||||
* the payload still carries the message and the request is only made when
|
||||
* somebody presses something.
|
||||
*
|
||||
* A JMAP subscription also delivers a PushVerification first, and stays silent
|
||||
* until the client echoes its code back. That cannot be done from here (no
|
||||
* credentials), so it is stashed for a tab to collect and confirm.
|
||||
* until the client echoes its code back. It is stashed for a tab to confirm
|
||||
* rather than answered here — on the same reasoning, and because a
|
||||
* verification that failed silently would leave push looking broken with
|
||||
* nothing to show for it. Answering it directly is now possible and is worth
|
||||
* revisiting.
|
||||
*/
|
||||
|
||||
/*
|
||||
@@ -153,13 +162,90 @@ self.addEventListener("fetch", (event) => {
|
||||
*/
|
||||
const VERIFY_KEY = `${BASE}/ihasmail-push-verification`;
|
||||
|
||||
function textOf(email) {
|
||||
/*
|
||||
* What a tab wrote down for this worker: the account, which mailbox is the
|
||||
* archive, and the worker's own text in the reader's language. See
|
||||
* `lib/swFacts.ts` for why any of that has to be handed over rather than
|
||||
* worked out here.
|
||||
*
|
||||
* Everything that depends on it is skipped when it is missing, which is the
|
||||
* state between installing this worker and next opening the app. An action
|
||||
* button with no label, or one that files mail into a mailbox guessed by name,
|
||||
* is worse than the notification that was here before.
|
||||
*/
|
||||
const FACTS_KEY = `${BASE}/ihasmail-worker-facts`;
|
||||
|
||||
async function readFacts() {
|
||||
try {
|
||||
const hit = await (await caches.open(VERSION)).match(FACTS_KEY);
|
||||
return hit ? await hit.json() : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* A JMAP call, made as the reader.
|
||||
*
|
||||
* This worker was written believing it could not do this -- that acting on
|
||||
* mail needed a session it had no way to hold. It does not: ihasmail's session
|
||||
* is an httpOnly cookie against its own origin, and the only other thing the
|
||||
* API asks for is a fixed `x-requested-with` header that is not a secret and
|
||||
* is not held anywhere. A same-origin fetch from here carries the cookie like
|
||||
* any other, so `Email/set` from a notification is an ordinary request.
|
||||
*
|
||||
* What is genuinely not available is anything the *tab* holds in memory, and
|
||||
* the answer is that the API asks for none of it.
|
||||
*
|
||||
* The session can still be gone -- expired, signed out, or a cookie that did
|
||||
* not survive the browser closing -- which arrives as a 401 and is reported
|
||||
* rather than swallowed. A tap that silently does nothing is the failure worth
|
||||
* avoiding here: the reader has already put the phone down.
|
||||
*/
|
||||
async function jmap(methodCalls) {
|
||||
const res = await fetch(`${BASE}/api/jmap`, {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "content-type": "application/json", accept: "application/json", "x-requested-with": "ihasmail" },
|
||||
body: JSON.stringify({ using: ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"], methodCalls }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const body = await res.json();
|
||||
// A JMAP method can fail inside a 200. Treat that as a failure too, rather
|
||||
// than reporting success because the transport was fine.
|
||||
const first = body?.methodResponses?.[0];
|
||||
if (!first || first[0] === "error") throw new Error(first?.[1]?.type || "error");
|
||||
const notUpdated = first[1]?.notUpdated;
|
||||
if (notUpdated && Object.keys(notUpdated).length) throw new Error("notUpdated");
|
||||
return body;
|
||||
}
|
||||
|
||||
function textOf(email, strings) {
|
||||
const from = email?.from?.[0];
|
||||
const who = from?.name || from?.email || "New message";
|
||||
const what = email?.subject || "(no subject)";
|
||||
const who = from?.name || from?.email || strings.newMessage;
|
||||
const what = email?.subject || strings.noSubject;
|
||||
return { title: who, body: what, preview: email?.preview || "" };
|
||||
}
|
||||
|
||||
/*
|
||||
* Two, because that is what a phone shows. `Notification.maxActions` is 2 on
|
||||
* Android Chrome, and anything past it is dropped silently -- so these are the
|
||||
* two worth having rather than the two that happened to come first. Both are
|
||||
* triage: they are what somebody does to a notification they have read the
|
||||
* whole of on the lock screen and does not need to open.
|
||||
*
|
||||
* Reply is deliberately not among them. It cannot be done from here, so it
|
||||
* would have to open the app -- and an action that opens the app is what
|
||||
* tapping the notification already does.
|
||||
*/
|
||||
function actionsFor(facts) {
|
||||
if (!facts) return [];
|
||||
const actions = [];
|
||||
if (facts.archiveId) actions.push({ action: "archive", title: facts.strings.archive });
|
||||
actions.push({ action: "read", title: facts.strings.markRead });
|
||||
return actions;
|
||||
}
|
||||
|
||||
self.addEventListener("push", (event) => {
|
||||
let data = null;
|
||||
try {
|
||||
@@ -186,6 +272,8 @@ self.addEventListener("push", (event) => {
|
||||
|
||||
const emails = (data && data["@type"] === "EmailPush" && Array.isArray(data.emails)) ? data.emails : [];
|
||||
event.waitUntil((async () => {
|
||||
const facts = await readFacts();
|
||||
const strings = facts?.strings ?? { newMail: "New mail", newMessage: "New message", noSubject: "(no subject)" };
|
||||
/*
|
||||
* Mark the app icon, without claiming a number.
|
||||
*
|
||||
@@ -201,7 +289,7 @@ self.addEventListener("push", (event) => {
|
||||
if (!emails.length) {
|
||||
// A StateChange, or a payload too large to carry the message. Say
|
||||
// something true rather than inventing a sender.
|
||||
await self.registration.showNotification("New mail", {
|
||||
await self.registration.showNotification(strings.newMail, {
|
||||
icon: `${BASE}/img/icon-192.png`, badge: `${BASE}/img/favicon-64.png`, tag: "ihasmail-mail", data: { url: `${BASE}/mail` },
|
||||
});
|
||||
return;
|
||||
@@ -209,21 +297,69 @@ self.addEventListener("push", (event) => {
|
||||
// One notification per message, collapsing repeats of the same message by
|
||||
// tag so a re-push does not stack.
|
||||
for (const email of emails.slice(0, 5)) {
|
||||
const { title, body, preview } = textOf(email);
|
||||
const { title, body, preview } = textOf(email, strings);
|
||||
await self.registration.showNotification(title, {
|
||||
body: preview ? `${body}\n${preview}` : body,
|
||||
icon: `${BASE}/img/icon-192.png`,
|
||||
badge: `${BASE}/img/favicon-64.png`,
|
||||
tag: `ihasmail-${email.id || body}`,
|
||||
data: { url: email.id ? `${BASE}/mail/inbox/${email.id}` : `${BASE}/mail` },
|
||||
// Only where there is a message to act on: a payload without an id can
|
||||
// be shown but not archived, and a button that cannot work should not
|
||||
// be drawn.
|
||||
actions: email.id ? actionsFor(facts) : [],
|
||||
data: {
|
||||
url: email.id ? `${BASE}/mail/inbox/${email.id}` : `${BASE}/mail`,
|
||||
id: email.id || null,
|
||||
title,
|
||||
accountId: facts?.accountId ?? null,
|
||||
archiveId: facts?.archiveId ?? null,
|
||||
failed: strings.failed ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
})());
|
||||
});
|
||||
|
||||
/*
|
||||
* Do what the button said, without opening anything.
|
||||
*
|
||||
* The whole point of an action is that the phone goes back in the pocket, so
|
||||
* this must not fall back to opening the app when the call fails -- that is
|
||||
* the same interruption the action existed to avoid. It re-notifies instead,
|
||||
* saying it did not happen, and leaves opening ihasmail to the reader.
|
||||
*
|
||||
* Archiving replaces the mailbox set rather than adding to it, which is what
|
||||
* archiving is: the message leaves the inbox. Marking read is a keyword and
|
||||
* touches nothing else.
|
||||
*/
|
||||
async function runAction(action, data) {
|
||||
const { id, accountId, archiveId } = data;
|
||||
if (!id || !accountId) return;
|
||||
const patch = action === "archive"
|
||||
? { mailboxIds: { [archiveId]: true } }
|
||||
: { "keywords/$seen": true };
|
||||
try {
|
||||
if (action === "archive" && !archiveId) throw new Error("no archive mailbox");
|
||||
await jmap([["Email/set", { accountId, update: { [id]: patch } }, "0"]]);
|
||||
} catch {
|
||||
await self.registration.showNotification(data.title || "ihasmail", {
|
||||
body: data.failed || "Could not do that — open ihasmail and try again",
|
||||
icon: `${BASE}/img/icon-192.png`,
|
||||
badge: `${BASE}/img/favicon-64.png`,
|
||||
tag: `ihasmail-failed-${id}`,
|
||||
data: { url: data.url },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
self.addEventListener("notificationclick", (event) => {
|
||||
event.notification.close();
|
||||
const url = event.notification.data?.url || `${BASE}/mail`;
|
||||
const data = event.notification.data || {};
|
||||
if (event.action === "archive" || event.action === "read") {
|
||||
event.waitUntil(runAction(event.action, data));
|
||||
return;
|
||||
}
|
||||
const url = data.url || `${BASE}/mail`;
|
||||
event.waitUntil((async () => {
|
||||
const clients = await self.clients.matchAll({ includeUncontrolled: true, type: "window" });
|
||||
// Reuse a tab if one is open rather than piling up windows. Same origin is
|
||||
|
||||
Reference in New Issue
Block a user