chore: more modular link preview generation

This commit is contained in:
Adhiraj Singh
2022-05-27 13:30:37 +05:30
parent 3eeded66b2
commit 15761ca9df
3 changed files with 18 additions and 9 deletions

View File

@@ -13,4 +13,5 @@ export * from './auth-utils'
export * from './legacy-msgs'
export * from './baileys-event-stream'
export * from './use-single-file-auth-state'
export * from './use-multi-file-auth-state'
export * from './use-multi-file-auth-state'
export * from './link-preview'

View File

@@ -28,9 +28,10 @@ export const getUrlInfo = async(
try {
const { getLinkPreview } = await import('link-preview-js')
let previewLink = text
if (!text.startsWith('https://') && !text.startsWith('http://')) {
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

View File

@@ -54,6 +54,18 @@ const MessageTypeProto = {
const ButtonType = proto.ButtonsMessage.ButtonsMessageHeaderType
export const generateLinkPreviewIfRequired = async(text: string, getUrlInfo: MessageGenerationOptions['getUrlInfo'], logger: MessageGenerationOptions['logger']) => {
const matchedUrls = text.match(URL_REGEX)
if(!!getUrlInfo && matchedUrls) {
try {
const urlInfo = await getUrlInfo(matchedUrls[0])
return urlInfo
} catch(error) { // ignore if fails
logger?.warn({ trace: error.stack }, 'url generation failed')
}
}
}
export const prepareWAMessageMedia = async(
message: AnyMediaMessageContent,
options: MediaGenerationOptions
@@ -249,13 +261,8 @@ export const generateWAMessageContent = async(
const extContent = { text: message.text } as WATextMessage
let urlInfo = message.linkPreview
const matchedUrls = message.text.match(URL_REGEX)
if(!urlInfo && !!options.getUrlInfo && matchedUrls) {
try {
urlInfo = await options.getUrlInfo(matchedUrls[0])
} catch(error) { // ignore if fails
options.logger?.warn({ trace: error.stack }, 'url generation failed')
}
if(!urlInfo) {
urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger)
}
if(urlInfo) {