From 2228da3b08063c0c3e54d1334cce6c0014789939 Mon Sep 17 00:00:00 2001 From: Ilya Borodin <48887908+ilyaborodin@users.noreply.github.com> Date: Fri, 29 Apr 2022 16:02:13 +0300 Subject: [PATCH] Preview link fix (#1548) * Preview link fix * Preview link refactor * Deleted empty line * Redundant unnecessary changes * Added checker for http/https prefix in link Co-authored-by: Ilya Borodin --- src/Utils/link-preview.ts | 11 +++++++---- src/Utils/messages.ts | 5 +++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/Utils/link-preview.ts b/src/Utils/link-preview.ts index 2bc0205..10bae83 100644 --- a/src/Utils/link-preview.ts +++ b/src/Utils/link-preview.ts @@ -18,7 +18,7 @@ export type URLGenerationOptions = { /** * Given a piece of text, checks for any URL present, generates link preview for the same and returns it * Return undefined if the fetch failed or no URL was found - * @param text the text containing URL + * @param text first matched URL in text * @returns the URL info required to generate link preview */ export const getUrlInfo = async( @@ -27,8 +27,11 @@ export const getUrlInfo = async( ): Promise => { try { const { getLinkPreview } = await import('link-preview-js') - - const info = await getLinkPreview(text, { timeout: opts.timeoutMs }) + let previewLink = text + if (!text.startsWith('https://') && !text.startsWith('http://')) { + previewLink = 'https://' + previewLink + } + const info = await getLinkPreview(previewLink, { timeout: opts.timeoutMs }) if(info && 'title' in info) { const [image] = info.images @@ -38,7 +41,7 @@ export const getUrlInfo = async( return { 'canonical-url': info.url, - 'matched-text': info.url, + 'matched-text': text, title: info.title, description: info.description, jpegThumbnail diff --git a/src/Utils/messages.ts b/src/Utils/messages.ts index baaa1b4..658722b 100644 --- a/src/Utils/messages.ts +++ b/src/Utils/messages.ts @@ -248,9 +248,10 @@ export const generateWAMessageContent = async( const extContent = { text: message.text } as WATextMessage let urlInfo = message.linkPreview - if(!urlInfo && !!options.getUrlInfo && message.text.match(URL_REGEX)) { + const matchedUrls = message.text.match(URL_REGEX) + if(!urlInfo && !!options.getUrlInfo && matchedUrls) { try { - urlInfo = await options.getUrlInfo(message.text) + urlInfo = await options.getUrlInfo(matchedUrls[0]) } catch(error) { // ignore if fails options.logger?.warn({ trace: error.stack }, 'url generation failed') }