summary refs log tree commit diff
path: root/src/util
diff options
context:
space:
mode:
authorZane Helton <zane99@me.com>2025-06-28 01:38:46 -0400
committerMadeline <46743919+MaddyUnderStars@users.noreply.github.com>2025-06-28 18:30:52 +1000
commitf9cfb46e73b2e51d0c48fe509594bc3338ed65ac (patch)
tree4ba7b3605b6914da738ef5ce428a6f58dfca62db /src/util
parentAdd validation to date_of_birth registration field (diff)
downloadserver-ts-f9cfb46e73b2e51d0c48fe509594bc3338ed65ac.tar.xz
Fix various issues with embeds on message updates
The `postHandleMessage` function is parsing links and adding them to the
EmbedCache table if necessary. In the previous implementation, message
updates would push to the embeds unconditionally.

This commit parses links from the message and:

1. Normalizes the URLs
  - Useful for deduplicating similar URLs
2. Remove embeds with matching normalized URLs
  - Leaves all embeds except for ones with a `.url` property matching
  the updated message
  - This allows embeds to be re-ordered if the URL is moved
3. If no normalized URLs are found, remove all embeds
4. Take the deduplicated + normalized URLs and add an embed to the message and
insert into the EmbedCache table (if necessary)

This enables:

1. Embeds to be re-ordered by re-ordering links
2. Embeds to be removed by removing links

and fixes:

1. Duplicate embeds being attached to a message when edited
Diffstat (limited to 'src/util')
-rw-r--r--src/util/util/Url.ts32
-rw-r--r--src/util/util/index.ts1
2 files changed, 33 insertions, 0 deletions
diff --git a/src/util/util/Url.ts b/src/util/util/Url.ts
new file mode 100644

index 000000000..a23491261 --- /dev/null +++ b/src/util/util/Url.ts
@@ -0,0 +1,32 @@ +/** + * Normalize a URL by: + * - Removing trailing slashes (except root path) + * - Sorting query params alphabetically + * - Removing empty query strings + * - Removing fragments + */ +export function normalizeUrl(input: string): string { + try { + const u = new URL(input); + // Remove fragment + u.hash = ""; + // Normalize pathname - remove trailing slash except for root "/" + if (u.pathname !== "/" && u.pathname.endsWith("/")) { + u.pathname = u.pathname.slice(0, -1); + } + // Normalize query params: sort by key + if (u.search) { + const params = Array.from(u.searchParams.entries()); + params.sort(([a], [b]) => a.localeCompare(b)); + u.search = params.length + ? "?" + params.map(([k, v]) => `${k}=${v}`).join("&") + : ""; + } else { + // Ensure no empty search string + u.search = ""; + } + return u.toString(); + } catch (e) { + return input; + } +} diff --git a/src/util/util/index.ts b/src/util/util/index.ts
index f55315e3a..4383c1d90 100644 --- a/src/util/util/index.ts +++ b/src/util/util/index.ts
@@ -41,6 +41,7 @@ export * from "./String"; export * from "./Token"; export * from "./TraverseDirectory"; export * from "./WebAuthn"; +export * from "./Url"; export * from "./Gifs"; export * from "./Application"; export * from "./NameValidation";