Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@
import java.security.Security;
import java.time.Duration;
import java.time.Instant;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
Expand Down Expand Up @@ -49,6 +54,13 @@ public class PushNotificationService {
private static final Logger log = LoggerFactory.getLogger(PushNotificationService.class);
private static final int TTL_SECONDS = 60 * 60 * 24; // keep undelivered pushes for a day
private static final int MAX_BODY_CHARS = 140;
// The markers Messages puts in a body for the page to read: a reply's quote, shared files,
// a code block, a pin, and the course chats' events and lessons. A phone shouldn't show them.
// Pages lists the same names in ANY_MARKER_PATTERN (assets/js/chat/chat-reply.js), so a
// marker added there needs adding here too, or its raw text shows up in DM notifications.
// No marker Pages writes has a bracket inside it (it escapes or URL-encodes them), so the
// payload leaves out "[" as well: that keeps matching linear when a body is full of "[[".
private static final Pattern CHAT_MARKER = Pattern.compile("\\[\\[(reply|event|lesson|files|code|pin|unpin):[^\\[\\]]*\\]\\]");
/** How long an unchanged subscription goes before a re-send refreshes last_used_at. */
private static final Duration RESEEN_AFTER = Duration.ofDays(1);

Expand Down Expand Up @@ -174,7 +186,7 @@ public void notifyPerson(Person person, String title, String body, String url, S
}
Map<String, Object> payload = Map.of(
"title", title == null ? "New message" : title,
"body", snippet(body),
"body", pushText(body),
"url", url == null ? "/dm" : url,
"tag", tag == null ? "ocs" : tag);
Long personId = person.getId();
Expand All @@ -191,6 +203,17 @@ public void afterCommit() {
}
}

// notifyPerson never throws, and it runs inside the message's transaction, so a body the
// text can't be made from still sends the message and its notification, without text.
private static String pushText(String body) {
try {
return snippet(body);
} catch (RuntimeException ex) {
log.warn("Web push: could not make the notification's text ({})", ex.getMessage());
return "";
}
}

/** Runs on the sender thread: loads the person's subscriptions and pushes to each. */
private void sendToPerson(Long personId, Map<String, Object> payload) {
List<PushSubscriptionEntity> subscriptions;
Expand Down Expand Up @@ -236,12 +259,47 @@ private void send(PushSubscriptionEntity subscription, String json) {
}
}

/**
* The notification's text: the message as a reader sees it in the chat, cut to
* {@value #MAX_BODY_CHARS} characters. The chat's markers are left out, and the rich
* composer's HTML becomes plain text (tags gone, entities decoded, {@code &nbsp;} a space).
* If no words are left, the text says what the message did instead, such as "pinned a
* message", or just "sent a message".
*/
static String snippet(String body) {
if (body == null) {
if (body == null || body.isBlank()) {
return "";
}
String oneLine = body.replaceAll("\\s+", " ").trim();
return oneLine.length() <= MAX_BODY_CHARS ? oneLine : oneLine.substring(0, MAX_BODY_CHARS - 1) + "…";
Set<String> markers = new HashSet<>();
Matcher marker = CHAT_MARKER.matcher(body);
StringBuilder words = new StringBuilder();
while (marker.find()) {
markers.add(marker.group(1));
marker.appendReplacement(words, " ");
}
marker.appendTail(words);
String text = Jsoup.parse(words.toString()).text().replace('\u00A0', ' ').replaceAll("\\s+", " ").trim();
if (text.isEmpty()) {
text = onlyMarkers(markers);
}
return text.length() <= MAX_BODY_CHARS ? text : text.substring(0, MAX_BODY_CHARS - 1) + "…";
}

// What a message that was only markers did, said after the sender's name (the title).
private static String onlyMarkers(Set<String> markers) {
if (markers.contains("pin")) {
return "pinned a message";
}
if (markers.contains("unpin")) {
return "unpinned a message";
}
if (markers.contains("code")) {
return "sent code";
}
if (markers.contains("files")) {
return "shared files";
}
return "sent a message";
}

@PreDestroy
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.open.spring.mvc.push;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;

import java.time.Duration;

import org.junit.jupiter.api.Test;

/**
* The text a phone shows for a direct message: the words a reader sees in the chat, without
* the markers the page reads ([[reply:…]], [[files:…]], [[code:…]], [[pin:…]]) or the rich
* composer's HTML.
*/
class PushNotificationSnippetTest {

@Test
void chatMarkersAreLeftOut() {
assertEquals("thanks!", PushNotificationService.snippet("[[reply:9|Bob|hey%20there]] thanks!"));
assertEquals("look", PushNotificationService.snippet("[[files:f~shots%2Fa.png~5]] look"));
// Pages escapes brackets, "|", "%", "<", ">" and "&" in code, but keeps quotes, tabs and newlines.
assertEquals("try this", PushNotificationService.snippet(
"[[code:python|print(\"hi\")\nfor i in range(3):\n\tprint(i)]] try this"));
assertEquals("see this", PushNotificationService.snippet(
"[[reply:9|Bob|hey]] [[files:f~a.txt~1]] [[code:java|int x;]] see this"));
}

@Test
void aMessageThatIsOnlyAMarkerSaysWhatItDid() {
assertEquals("pinned a message", PushNotificationService.snippet("[[pin:401]]"));
assertEquals("unpinned a message", PushNotificationService.snippet("[[unpin:401]]"));
assertEquals("sent code", PushNotificationService.snippet("[[code:python|print(1)]]"));
assertEquals("shared files", PushNotificationService.snippet("[[files:f~a.png~5]]"));
// A reply that only attaches an image has nothing but its reply marker in the body.
assertEquals("sent a message", PushNotificationService.snippet("[[reply:9|Bob|hey]]"));
}

@Test
void theComposersHtmlBecomesPlainText() {
assertEquals("check https://github.com/o/r/pull/3", PushNotificationService.snippet(
"check <a href=\"https://github.com/o/r/pull/3\" target=\"_blank\" rel=\"noopener noreferrer\">"
+ "https://github.com/o/r/pull/3</a>&nbsp;"));
assertEquals("Fish & chips tonight", PushNotificationService.snippet("<b>Fish</b> &amp; chips<br>tonight"));
assertEquals("a < b", PushNotificationService.snippet("a &lt; b"));
}

@Test
void longTextIsCutAndBlankStaysBlank() {
String cut = PushNotificationService.snippet("x".repeat(200));
assertEquals(140, cut.length());
assertEquals('…', cut.charAt(139));
assertEquals("", PushNotificationService.snippet(null));
assertEquals("", PushNotificationService.snippet(" "));
}

@Test
void markerOpeningsThatNeverCloseStayFast() {
// None of these markers closes, so a pattern that rescans the rest of the body at each
// "[[" takes seconds here; matching has to stay linear.
String body = "[[code:".repeat(20_000);
String text = assertTimeoutPreemptively(Duration.ofSeconds(1), () -> PushNotificationService.snippet(body));
assertEquals(140, text.length());
}
}