mirror of
https://github.com/FranP-code/Baileys.git
synced 2025-10-13 00:32:22 +00:00
feat: link previews on MD
This commit is contained in:
42
src/Utils/link-preview.ts
Normal file
42
src/Utils/link-preview.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { WAUrlInfo } from '../Types'
|
||||
import { extractImageThumb, getHttpStream } from './messages-media'
|
||||
|
||||
const THUMBNAIL_WIDTH_PX = 128
|
||||
|
||||
/** Fetches an image and generates a thumbnail for it */
|
||||
const getCompressedJpegThumbnail = async(url: string) => {
|
||||
const stream = await getHttpStream(url)
|
||||
const result = await extractImageThumb(stream, THUMBNAIL_WIDTH_PX)
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @returns the URL info required to generate link preview
|
||||
*/
|
||||
export const getUrlInfo = async(text: string): Promise<WAUrlInfo | undefined> => {
|
||||
try {
|
||||
const { getLinkPreview } = await import('link-preview-js')
|
||||
|
||||
const info = await getLinkPreview(text)
|
||||
if(info && 'title' in info) {
|
||||
const [image] = info.images
|
||||
|
||||
const jpegThumbnail = image ? await getCompressedJpegThumbnail(image) : undefined
|
||||
|
||||
return {
|
||||
'canonical-url': info.url,
|
||||
'matched-text': info.url,
|
||||
title: info.title,
|
||||
description: info.description,
|
||||
jpegThumbnail
|
||||
}
|
||||
}
|
||||
} catch(error) {
|
||||
if(!error.message.includes('receive a valid')) {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ const extractVideoThumb = async(
|
||||
})
|
||||
}) as Promise<void>
|
||||
|
||||
export const extractImageThumb = async(bufferOrFilePath: Readable | Buffer | string) => {
|
||||
export const extractImageThumb = async(bufferOrFilePath: Readable | Buffer | string, width = 32) => {
|
||||
if(bufferOrFilePath instanceof Readable) {
|
||||
bufferOrFilePath = await toBuffer(bufferOrFilePath)
|
||||
}
|
||||
@@ -99,7 +99,7 @@ export const extractImageThumb = async(bufferOrFilePath: Readable | Buffer | str
|
||||
const lib = await getImageProcessingLibrary()
|
||||
if('sharp' in lib) {
|
||||
const result = await lib.sharp!.default(bufferOrFilePath)
|
||||
.resize(32)
|
||||
.resize(width)
|
||||
.jpeg({ quality: 50 })
|
||||
.toBuffer()
|
||||
return result
|
||||
@@ -109,7 +109,7 @@ export const extractImageThumb = async(bufferOrFilePath: Readable | Buffer | str
|
||||
const jimp = await read(bufferOrFilePath as any)
|
||||
const result = await jimp
|
||||
.quality(50)
|
||||
.resize(32, AUTO, RESIZE_BILINEAR)
|
||||
.resize(width, AUTO, RESIZE_BILINEAR)
|
||||
.getBufferAsync(MIME_JPEG)
|
||||
return result
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user