Fix viewer image detection and file name parsing when the URL includes a query

This commit is contained in:
chylex 2022-07-17 13:37:37 +02:00
parent 176a81e055
commit cd418f4871
No known key found for this signature in database
GPG Key ID: 4DE42C8F19A80548
2 changed files with 24 additions and 5 deletions

View File

@ -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,

View File

@ -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;
}
}
}