Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Restore web push quick reply for chat messages (#39614)

Rafael dos Santos Silvab0873d3ecd16
diff --git a/app/services/push_notification_pusher.rb b/app/services/push_notification_pusher.rb
index d10d5054f23..791147b5057 100644
--- a/app/services/push_notification_pusher.rb
+++ b/app/services/push_notification_pusher.rb
@@ -29,6 +29,9 @@ class PushNotificationPusher
url: payload[:post_url]&.sub(/\A#{Discourse.base_path}/, ""),
}
+ message[:actions] = payload[:actions] if payload[:actions].present?
+ message[:action_data] = payload[:action_data] if payload[:action_data].present?
+
subscriptions(user).each { |subscription| send_notification(user, subscription, message) }
end
diff --git a/app/views/static/service-worker.js.erb b/app/views/static/service-worker.js.erb
index a1868b739ea..e982ae788b5 100644
--- a/app/views/static/service-worker.js.erb
+++ b/app/views/static/service-worker.js.erb
@@ -1,35 +1,78 @@
'use strict';
-var chatRegex = /\/chat\/channel\/(\d+)\//;
-var inlineReplyIcon = "<%= ::UrlHelper.absolute("/images/push-notifications/inline_reply.png") %>";
-
-function showNotification(title, body, icon, badge, tag, baseUrl, url) {
- var notificationOptions = {
- body: body,
- icon: icon,
- badge: badge,
- data: { url: url, baseUrl: baseUrl },
- tag: tag
+// Plugins (and core features) can register handlers for notification action
+// buttons by calling self.registerNotificationActionHandler(action, handler).
+//
+// The push payload may include:
+// actions: a Web Notifications API "actions" array, attached to the
+// notification verbatim (each entry: { action, title, type,
+// placeholder, icon }).
+// action_data: an arbitrary object made available to the handler at
+// event.notification.data.actionData when the user activates
+// an action button.
+//
+// When the user activates an action, the handler registered for that
+// action name is invoked with the original notificationclick event.
+self.notificationActionHandlers = {};
+
+self.registerNotificationActionHandler = function (action, handler) {
+ self.notificationActionHandlers[action] = handler;
+};
+
+function buildNotificationOptions(payload) {
+ var options = {
+ body: payload.body,
+ icon: payload.icon,
+ badge: payload.badge,
+ data: {
+ url: payload.url,
+ baseUrl: payload.base_url,
+ actionData: payload.action_data || {},
+ },
+ tag: payload.tag,
+ };
+
+ if (Array.isArray(payload.actions) && payload.actions.length > 0) {
+ options.actions = payload.actions;
}
- if (chatRegex.test(url)) {
- notificationOptions['actions'] = [{
- action: "reply",
- title: "Reply",
- placeholder: "reply",
- type: "text",
- icon: inlineReplyIcon
- }];
- }
+ return options;
+}
+
+function focusOrOpenWindow(event) {
+ var url = event.notification.data.url;
+ var baseUrl = event.notification.data.baseUrl;
- return self.registration.showNotification(title, notificationOptions);
+ return clients.matchAll({ type: "window" }).then(function (clientList) {
+ // Skip nested frames (e.g. full-app embed iframes) — we want to
+ // focus/open a standalone Discourse window, not navigate an embed.
+ var topLevelClients = clientList.filter(function (client) {
+ return client.frameType !== "nested";
+ });
+
+ var reusedClientWindow = topLevelClients.some(function (client) {
+ if (client.url === baseUrl + url && "focus" in client) {
+ client.focus();
+ return true;
+ }
+
+ if ("postMessage" in client && "focus" in client) {
+ client.focus();
+ client.postMessage({ url: url });
+ return true;
+ }
+ return false;
+ });
+
+ if (!reusedClientWindow && clients.openWindow)
+ return clients.openWindow(baseUrl + url);
+ });
}
self.addEventListener('push', function(event) {
var payload = event.data.json();
-
event.waitUntil(
- showNotification(payload.title, payload.body, payload.icon, payload.badge, payload.tag, payload.base_url, payload.url)
+ self.registration.showNotification(payload.title, buildNotificationOptions(payload))
);
});
@@ -37,72 +80,23 @@ self.addEventListener('notificationclick', function(event) {
// Android doesn't close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();
- var url = event.notification.data.url;
- var baseUrl = event.notification.data.baseUrl;
- if (event.action === "reply") {
- let csrf;
- fetch("/session/csrf", {
- credentials: "include",
- headers: {
- Accept: "application/json",
- },
- })
- .then((response) => {
- if (!response.ok) {
- throw new Error("Network response was not OK");
- }
- return response.json();
- })
- .then((data) => {
- csrf = data.csrf;
-
- let chatTest = url.match(chatRegex);
- if (chatTest.length > 0) {
- let chatChannel = chatTest[1];
-
- fetch(`${baseUrl}/chat/${chatChannel}.json`, {
- credentials: "include",
- headers: {
- "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
- "X-CSRF-Token": csrf,
- },
- body: `message=${event.reply}`,
- method: "POST",
- mode: "cors",
- });
- }
- });
- } else {
- // This looks to see if the current window is already open and
- // focuses if it is
- event.waitUntil(
- clients.matchAll({ type: "window" }).then(function (clientList) {
- // Skip nested frames (e.g. full-app embed iframes) — we want to
- // focus/open a standalone Discourse window, not navigate an embed.
- var topLevelClients = clientList.filter(function (client) {
- return client.frameType !== "nested";
- });
-
- var reusedClientWindow = topLevelClients.some(function (client) {
- if (client.url === baseUrl + url && "focus" in client) {
- client.focus();
- return true;
- }
-
- if ("postMessage" in client && "focus" in client) {
- client.focus();
- client.postMessage({ url: url });
- return true;
- }
- return false;
- });
-
- if (!reusedClientWindow && clients.openWindow)
- return clients.openWindow(baseUrl + url);
- })
- );
+ if (event.action) {
+ var handler = self.notificationActionHandlers[event.action];
+ if (handler) {
+ event.waitUntil(
+ Promise.resolve()
+ .then(function () { return handler(event); })
+ .catch(function (err) {
+ console.error("Push notification action handler failed", event.action, err);
+ return focusOrOpenWindow(event);
+ })
+ );
+ return;
+ }
}
+
+ event.waitUntil(focusOrOpenWindow(event));
});
self.addEventListener('pushsubscriptionchange', function(event) {
diff --git a/plugins/chat/app/jobs/regular/chat/notify_mentioned.rb b/plugins/chat/app/jobs/regular/chat/notify_mentioned.rb
index 32d78fb575e..80d185bba79 100644
--- a/plugins/chat/app/jobs/regular/chat/notify_mentioned.rb
+++ b/plugins/chat/app/jobs/regular/chat/notify_mentioned.rb
@@ -79,7 +79,7 @@ module Jobs
post_url: post_url,
channel_id: @chat_channel.id,
is_direct_message_channel: @is_direct_message_channel,
- }
+ }.merge(::Chat::Notifier.push_notification_reply_action(@chat_message, membership.user))
translation_prefix =
(
diff --git a/plugins/chat/app/jobs/regular/chat/notify_watching.rb b/plugins/chat/app/jobs/regular/chat/notify_watching.rb
index 063e8360f22..9172f0f6849 100644
--- a/plugins/chat/app/jobs/regular/chat/notify_watching.rb
+++ b/plugins/chat/app/jobs/regular/chat/notify_watching.rb
@@ -82,7 +82,7 @@ module Jobs
excerpt: @chat_message.push_notification_excerpt,
channel_id: @chat_channel.id,
is_direct_message_channel: @is_direct_message_channel,
- }
+ }.merge(::Chat::Notifier.push_notification_reply_action(@chat_message, user))
if @chat_message.in_thread? && !membership.muted?
thread_membership =
diff --git a/plugins/chat/assets/service-worker/chat-service-worker-extensions.js b/plugins/chat/assets/service-worker/chat-service-worker-extensions.js
new file mode 100644
index 00000000000..8529162f0f2
--- /dev/null
+++ b/plugins/chat/assets/service-worker/chat-service-worker-extensions.js
@@ -0,0 +1,168 @@
+// Registers a "chat-reply" handler for the Web Notifications API "Reply"
+// quick-action button on chat push notifications. Invoked by the core
+// service worker (app/views/static/service-worker.js.erb) when the user
+// types a reply and submits the action button on the notification.
+//
+// If the reply is a single emoji grapheme (typical of smartwatch quick
+// reply chips), it is sent to the chat reaction endpoint instead of
+// posting a one-character message in the channel. Reaction failures
+// transparently fall back to a normal message post so a user's tap is
+// never lost.
+//
+// The matching action button and its action_data payload are produced
+// server-side by Chat::Notifier.push_notification_reply_action.
+
+// Matches a single base pictographic codepoint, optionally followed by
+// a variation selector (U+FE0F) or skin tone (U+1F3FB..U+1F3FF), plus
+// zero or more ZWJ-joined (U+200D) parts. Used as a fallback when
+// Intl.Segmenter is unavailable.
+const SINGLE_EMOJI_FALLBACK_RE =
+ /^(?:\p{Extended_Pictographic}(?:\u{FE0F}|[\u{1F3FB}-\u{1F3FF}])?)(?:\u{200D}\p{Extended_Pictographic}(?:\u{FE0F}|[\u{1F3FB}-\u{1F3FF}])?)*$/u;
+
+function isSingleEmoji(text) {
+ if (!text) {
+ return false;
+ }
+
+ if (typeof Intl !== "undefined" && Intl.Segmenter) {
+ const iter = new Intl.Segmenter(undefined, {
+ granularity: "grapheme",
+ })
+ .segment(text)
+ [Symbol.iterator]();
+ const first = iter.next();
+ if (first.done || !iter.next().done) {
+ return false;
+ }
+ return /\p{Extended_Pictographic}/u.test(first.value.segment);
+ }
+
+ return SINGLE_EMOJI_FALLBACK_RE.test(text);
+}
+
+function fetchCsrfToken(baseUrl) {
+ return fetch(baseUrl + "/session/csrf", {
+ credentials: "include",
+ headers: { Accept: "application/json" },
+ })
+ .then(function (response) {
+ if (!response.ok) {
+ throw new Error("CSRF fetch failed: " + response.status);
+ }
+ return response.json();
+ })
+ .then(function (json) {
+ return json.csrf;
+ });
+}
+
+function postChatMessage({ baseUrl, csrf, channelId, threadId, message }) {
+ const body = new URLSearchParams();
+ body.set("message", message);
+ if (threadId) {
+ body.set("thread_id", String(threadId));
+ }
+
+ return fetch(baseUrl + "/chat/" + encodeURIComponent(channelId), {
+ credentials: "include",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
+ "X-CSRF-Token": csrf,
+ Accept: "application/json",
+ },
+ body: body.toString(),
+ method: "POST",
+ }).then(function (response) {
+ if (!response.ok) {
+ throw new Error("Chat reply POST failed: " + response.status);
+ }
+ return response;
+ });
+}
+
+function reactToChatMessage({ baseUrl, csrf, channelId, messageId, emoji }) {
+ const body = new URLSearchParams();
+ body.set("react_action", "add");
+ body.set("emoji", emoji);
+
+ return fetch(
+ baseUrl +
+ "/chat/" +
+ encodeURIComponent(channelId) +
+ "/react/" +
+ encodeURIComponent(messageId),
+ {
+ credentials: "include",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
+ "X-CSRF-Token": csrf,
+ Accept: "application/json",
+ },
+ body: body.toString(),
+ method: "PUT",
+ }
+ ).then(function (response) {
+ if (!response.ok) {
+ throw new Error("Chat reaction PUT failed: " + response.status);
+ }
+ return response;
+ });
+}
+
+self.registerNotificationActionHandler("chat-reply", function (event) {
+ const data = event.notification.data || {};
+ const actionData = data.actionData || {};
+ const baseUrl = data.baseUrl || "";
+ const fallbackUrl = data.url || "";
+ const reply = (event.reply || "").trim();
+
+ function openFallback() {
+ if (!fallbackUrl || !self.clients || !self.clients.openWindow) {
+ return Promise.resolve();
+ }
+ return self.clients.openWindow(baseUrl + fallbackUrl);
+ }
+
+ if (!actionData.channel_id || !reply) {
+ return openFallback();
+ }
+
+ const tryReact =
+ actionData.message_id && isSingleEmoji(reply)
+ ? function (csrf) {
+ return reactToChatMessage({
+ baseUrl,
+ csrf,
+ channelId: actionData.channel_id,
+ messageId: actionData.message_id,
+ emoji: reply,
+ }).catch(function (err) {
+ // eslint-disable-next-line no-console
+ console.warn("Chat reaction failed, falling back to message", err);
+ return postChatMessage({
+ baseUrl,
+ csrf,
+ channelId: actionData.channel_id,
+ threadId: actionData.thread_id,
+ message: reply,
+ });
+ });
+ }
+ : function (csrf) {
+ return postChatMessage({
+ baseUrl,
+ csrf,
+ channelId: actionData.channel_id,
+ threadId: actionData.thread_id,
+ message: reply,
+ });
+ };
+
+ return fetchCsrfToken(baseUrl)
+ .then(tryReact)
+ .catch(function (err) {
+ // eslint-disable-next-line no-console
+ console.error("Chat quick reply failed", err);
+ return openFallback();
+ });
+});
diff --git a/plugins/chat/config/locales/server.en.yml b/plugins/chat/config/locales/server.en.yml
index f2ba2a65cdb..702c90d17b7 100644
--- a/plugins/chat/config/locales/server.en.yml
+++ b/plugins/chat/config/locales/server.en.yml
@@ -236,6 +236,10 @@ en:
other_type: "%{username} mentioned %{identifier} in personal chat"
new_chat_message: '%{username} sent a message in "%{channel}"'
new_direct_chat_message: "%{username} sent a message in personal chat"
+ actions:
+ chat_reply:
+ title: Reply
+ placeholder: Reply…
discourse_automation:
scriptables:
diff --git a/plugins/chat/lib/chat/message_reactor.rb b/plugins/chat/lib/chat/message_reactor.rb
index 0cb9ce14399..e9d8ae80bd1 100644
--- a/plugins/chat/lib/chat/message_reactor.rb
+++ b/plugins/chat/lib/chat/message_reactor.rb
@@ -13,6 +13,7 @@ module Chat
end
def react!(message_id:, react_action:, emoji:)
+ emoji = Emoji.unicode_replacements[emoji] || emoji
@guardian.ensure_can_join_chat_channel!(@chat_channel)
@guardian.ensure_can_react!
validate_channel_status!
diff --git a/plugins/chat/lib/chat/notifier.rb b/plugins/chat/lib/chat/notifier.rb
index 2849e09b8d7..2a64e481fbe 100644
--- a/plugins/chat/lib/chat/notifier.rb
+++ b/plugins/chat/lib/chat/notifier.rb
@@ -37,6 +37,32 @@ module Chat
"#{Discourse.current_hostname}-chat-#{type}-#{chat_channel_id}"
end
+ # Builds the `actions`/`action_data` fields that enable a "Reply"
+ # quick-action button on web push notifications for a chat message.
+ # The chat plugin's service worker dispatches on the "chat-reply"
+ # action name (see plugins/chat/assets/service-worker/chat-service-worker-extensions.js).
+ def push_notification_reply_action(chat_message, user)
+ I18n.with_locale(user.effective_locale) do
+ {
+ actions: [
+ {
+ action: "chat-reply",
+ title: I18n.t("discourse_push_notifications.actions.chat_reply.title"),
+ placeholder: I18n.t("discourse_push_notifications.actions.chat_reply.placeholder"),
+ type: "text",
+ icon:
+ ActionController::Base.helpers.image_url("push-notifications/inline_reply.png"),
+ },
+ ],
+ action_data: {
+ channel_id: chat_message.chat_channel_id,
+ message_id: chat_message.id,
+ thread_id: chat_message.thread_id,
+ }.compact,
+ }
+ end
+ end
+
def notify_edit(chat_message:, timestamp:)
Jobs.enqueue(
Jobs::Chat::SendMessageNotifications,
diff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rb
index 292360f8077..15bda0f0c80 100644
--- a/plugins/chat/plugin.rb
+++ b/plugins/chat/plugin.rb
@@ -16,6 +16,8 @@ register_asset "stylesheets/common/index.scss"
register_asset "stylesheets/desktop/index.scss", :desktop
register_asset "stylesheets/mobile/index.scss", :mobile
+register_service_worker "service-worker/chat-service-worker-extensions.js"
+
register_svg_icon "comment-slash"
register_svg_icon "comment-dots"
register_svg_icon "lock"
diff --git a/plugins/chat/spec/jobs/regular/chat/notify_mentioned_spec.rb b/plugins/chat/spec/jobs/regular/chat/notify_mentioned_spec.rb
index dff889157f0..f68c588f1b3 100644
--- a/plugins/chat/spec/jobs/regular/chat/notify_mentioned_spec.rb
+++ b/plugins/chat/spec/jobs/regular/chat/notify_mentioned_spec.rb
@@ -252,16 +252,18 @@ describe Jobs::Chat::NotifyMentioned do
PostAlerter.expects(:push_notification).with(
user_2,
- {
- notification_type: Notification.types[:chat_mention],
- username: user_1.username,
- tag: Chat::Notifier.push_notification_tag(:mention, public_channel.id),
- excerpt: message.push_notification_excerpt,
- post_url: "/chat/c/#{public_channel.slug}/#{public_channel.id}/#{message.id}",
- translated_title: payload_translated_title,
- channel_id: public_channel.id,
- is_direct_message_channel: false,
- },
+ has_entries(
+ {
+ notification_type: Notification.types[:chat_mention],
+ username: user_1.username,
+ tag: Chat::Notifier.push_notification_tag(:mention, public_channel.id),
+ excerpt: message.push_notification_excerpt,
+ post_url: "/chat/c/#{public_channel.slug}/#{public_channel.id}/#{message.id}",
+ translated_title: payload_translated_title,
+ channel_id: public_channel.id,
+ is_direct_message_channel: false,
+ },
+ ),
)
job.execute(
diff --git a/plugins/chat/spec/lib/chat/message_reactor_spec.rb b/plugins/chat/spec/lib/chat/message_reactor_spec.rb
index b32aeb3073c..a5079f2fc0a 100644
--- a/plugins/chat/spec/lib/chat/message_reactor_spec.rb
+++ b/plugins/chat/spec/lib/chat/message_reactor_spec.rb
@@ -56,6 +56,17 @@ describe Chat::MessageReactor do
}.to raise_error(Discourse::InvalidParameters)
end
+ it "accepts a raw unicode emoji and stores its shortcode" do
+ reactor.react!(message_id: message_1.id, react_action: :add, emoji: "👍")
+ expect(message_1.reactions.where(user: reacting_user).pluck(:emoji)).to eq(["+1"])
+ end
+
+ it "leaves an unknown unicode string to fail validation" do
+ expect {
+ reactor.react!(message_id: message_1.id, react_action: :add, emoji: "🫥🫥")
+ }.to raise_error(Discourse::InvalidParameters)
+ end
+
it "raises an error if the message is not found" do
expect {
reactor.react!(message_id: -999, react_action: :add, emoji: ":woohoo:")
diff --git a/plugins/chat/spec/lib/chat/notifier_spec.rb b/plugins/chat/spec/lib/chat/notifier_spec.rb
index 92aeaa9c57d..4efdd5fccc6 100644
--- a/plugins/chat/spec/lib/chat/notifier_spec.rb
+++ b/plugins/chat/spec/lib/chat/notifier_spec.rb
@@ -778,4 +778,57 @@ describe Chat::Notifier do
end
end
end
+
+ describe ".push_notification_reply_action" do
+ fab!(:user)
+ fab!(:channel, :category_channel)
+ fab!(:thread, :chat_thread)
+
+ it "returns a chat-reply action and channel + message data for non-threaded messages" do
+ message = Fabricate(:chat_message, chat_channel: channel)
+
+ payload = described_class.push_notification_reply_action(message, user)
+
+ expect(payload[:actions]).to match(
+ [
+ a_hash_including(
+ action: "chat-reply",
+ type: "text",
+ title: I18n.t("discourse_push_notifications.actions.chat_reply.title"),
+ placeholder: I18n.t("discourse_push_notifications.actions.chat_reply.placeholder"),
+ ),
+ ],
+ )
+ expect(payload[:actions].first[:icon]).to include("inline_reply")
+ expect(payload[:action_data]).to eq(channel_id: channel.id, message_id: message.id)
+ end
+
+ it "includes thread_id when the source message is in a thread" do
+ message = Fabricate(:chat_message, chat_channel: thread.channel, thread_id: thread.id)
+
+ payload = described_class.push_notification_reply_action(message, user)
+
+ expect(payload[:action_data]).to eq(
+ channel_id: thread.channel_id,
+ message_id: message.id,
+ thread_id: thread.id,
+ )
+ end
+
+ it "translates the action title using the user's locale" do
+ SiteSetting.allow_user_locale = true
+ user.update!(locale: "fr")
+ TranslationOverride.upsert!(
+ "fr",
+ "discourse_push_notifications.actions.chat_reply.title",
+ "Répondre",
+ )
+
+ message = Fabricate(:chat_message, chat_channel: channel)
+
+ payload = described_class.push_notification_reply_action(message, user)
+
+ expect(payload[:actions].first[:title]).to eq("Répondre")
+ end
+ end
end
diff --git a/spec/services/push_notification_pusher_spec.rb b/spec/services/push_notification_pusher_spec.rb
index c430693cd17..eba35973767 100644
--- a/spec/services/push_notification_pusher_spec.rb
+++ b/spec/services/push_notification_pusher_spec.rb
@@ -62,6 +62,45 @@ RSpec.describe PushNotificationPusher do
expect(message[:icon]).to match(%r{\A/assets/push-notifications/mentioned-\w{8}.png\z})
end
+ it "forwards actions and action_data when present in the payload" do
+ actions = [
+ {
+ action: "test-reply",
+ title: "Reply",
+ placeholder: "Reply…",
+ type: "text",
+ icon: "https://example.com/icon.png",
+ },
+ ]
+ action_data = { channel_id: 42, thread_id: 7 }
+
+ message =
+ PushNotificationPusher.push(
+ user,
+ {
+ topic_title: topic_title,
+ username: username,
+ excerpt: "description",
+ topic_id: 1,
+ base_url: base_url,
+ post_url: post_url,
+ notification_type: 1,
+ post_number: 1,
+ actions: actions,
+ action_data: action_data,
+ },
+ )
+
+ expect(message[:actions]).to eq(actions)
+ expect(message[:action_data]).to eq(action_data)
+ end
+
+ it "omits actions and action_data when not present in the payload" do
+ message = execute_push
+ expect(message).not_to have_key(:actions)
+ expect(message).not_to have_key(:action_data)
+ end
+
it "sends notification in user's locale" do
SiteSetting.allow_user_locale = true
user.update!(locale: "pt_BR")