From cd418f48710761f60d577b298702ea38675671a4 Mon Sep 17 00:00:00 2001 From: chylex Date: Sun, 17 Jul 2022 13:37:37 +0200 Subject: [PATCH] Fix viewer image detection and file name parsing when the URL includes a query --- app/Resources/Viewer/scripts/discord.js | 18 +++++++++++++----- app/Resources/Viewer/scripts/dom.js | 11 +++++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/app/Resources/Viewer/scripts/discord.js b/app/Resources/Viewer/scripts/discord.js index 71e96b7..fe05813 100644 --- a/app/Resources/Viewer/scripts/discord.js +++ b/app/Resources/Viewer/scripts/discord.js @@ -78,6 +78,12 @@ const DISCORD = (function() { } }; + const isImageUrl = function(url) { + const dot = url.pathname.lastIndexOf("."); + const ext = dot === -1 ? "" : url.pathname.substring(dot).toLowerCase(); + return ext === ".png" || ext === ".gif" || ext === ".jpg" || ext === ".jpeg"; + }; + return { setup() { templateChannelServer = new TEMPLATE([ @@ -176,9 +182,8 @@ const DISCORD = (function() { }, isImageAttachment(attachment) { - const dot = attachment.url.lastIndexOf("."); - const ext = dot === -1 ? "" : attachment.url.substring(dot).toLowerCase(); - return ext === ".png" || ext === ".gif" || ext === ".jpg" || ext === ".jpeg"; + const url = DOM.tryParseUrl(attachment.url); + return url != null && isImageUrl(url); }, getChannelHTML(channel) { // noinspection FunctionWithInconsistentReturnsJS @@ -235,11 +240,14 @@ const DISCORD = (function() { } return value.map(attachment => { - if (this.isImageAttachment(attachment) && SETTINGS.enableImagePreviews) { + const url = DOM.tryParseUrl(attachment.url); + + if (url != null && isImageUrl(url) && SETTINGS.enableImagePreviews) { return templateEmbedImage.apply({ url: attachment.url, src: attachment.url }); } else { - const sliced = attachment.url.split("/"); + const path = url == null ? attachment.url : url.pathname; + const sliced = path.split("/"); return templateAttachmentDownload.apply({ "url": attachment.url, diff --git a/app/Resources/Viewer/scripts/dom.js b/app/Resources/Viewer/scripts/dom.js index 60211cf..4ab22c1 100644 --- a/app/Resources/Viewer/scripts/dom.js +++ b/app/Resources/Viewer/scripts/dom.js @@ -51,4 +51,15 @@ class DOM { const date = new Date(timestamp); return date.toLocaleDateString() + ", " + date.toLocaleTimeString(); }; + + /** + * Parses a url string into a URL object and returns it. If the parsing fails, returns null. + */ + static tryParseUrl(url) { + try { + return new URL(url); + } catch (ignore) { + return null; + } + } }