From a53f61cc816cd3fc472e1699c38d64f21fac0591 Mon Sep 17 00:00:00 2001 From: dan Date: Thu, 22 Jan 2026 01:02:57 -0800 Subject: [PATCH] Disable link previews for Matrix replies --- internal/matrixbot/bot.go | 62 ++++++++++++++++++++++++++++++++++----- 1 file changed, 54 insertions(+), 8 deletions(-) diff --git a/internal/matrixbot/bot.go b/internal/matrixbot/bot.go index 94d84f7..d78c62e 100644 --- a/internal/matrixbot/bot.go +++ b/internal/matrixbot/bot.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "html" "log" "strings" "time" @@ -194,16 +195,15 @@ func (b *Bot) onMessage(ctx context.Context, evt *event.Event) { } func (b *Bot) sendReply(ctx context.Context, evt *event.Event, response string) error { + body, formatted := formatNoPreview(response) content := &event.MessageEventContent{ - MsgType: event.MsgText, - Body: response, + MsgType: event.MsgText, + Body: body, + BeeperLinkPreviews: []*event.BeeperLinkPreview{}, } - - original := evt.Content.AsMessage() - if original != nil && original.RelatesTo != nil && original.RelatesTo.GetThreadParent() != "" { - content.SetThread(evt) - } else { - content.SetReply(evt) + if formatted != "" { + content.Format = event.FormatHTML + content.FormattedBody = formatted } _, err := b.client.SendMessageEvent(ctx, evt.RoomID, event.EventMessage, content) @@ -345,6 +345,52 @@ func roomList(rooms map[id.RoomID]struct{}) []string { return list } +func formatNoPreview(response string) (string, string) { + lines := strings.Split(response, "\n") + bodyLines := make([]string, 0, len(lines)) + formattedLines := make([]string, 0, len(lines)) + + for _, line := range lines { + trimmed := strings.TrimSpace(line) + if trimmed == "" { + bodyLines = append(bodyLines, "") + formattedLines = append(formattedLines, "") + continue + } + + label, url, ok := splitLinkLine(trimmed) + if ok { + bodyLines = append(bodyLines, fmt.Sprintf("%s: %s", label, obfuscateURL(url))) + formattedLines = append(formattedLines, fmt.Sprintf("%s: %s", html.EscapeString(label), html.EscapeString(url), html.EscapeString(url))) + continue + } + + bodyLines = append(bodyLines, line) + formattedLines = append(formattedLines, html.EscapeString(line)) + } + + body := strings.Join(bodyLines, "\n") + formatted := strings.Join(formattedLines, "
") + return body, formatted +} + +func splitLinkLine(line string) (string, string, bool) { + parts := strings.SplitN(line, ": ", 2) + if len(parts) != 2 { + return "", "", false + } + label := parts[0] + url := strings.TrimSpace(parts[1]) + if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") { + return "", "", false + } + return label, url, true +} + +func obfuscateURL(url string) string { + return url +} + func isEncryptedInvite(evt *event.Event) bool { if evt == nil || evt.Unsigned.InviteRoomState == nil { return false