webapp/src/utils/getImageUrl.ts

54 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-02-04 11:25:21 +00:00
import { cdnUrl, thumborUrl } from './config'
2024-01-23 15:21:37 +00:00
const getSizeUrlPart = (options: { width?: number; height?: number; noSizeUrlPart?: boolean } = {}) => {
const widthString = options.width ? options.width.toString() : ''
const heightString = options.height ? options.height.toString() : ''
2024-02-04 17:40:15 +00:00
if (!(widthString || heightString) || options.noSizeUrlPart) {
return ''
}
return `${widthString}x${heightString}/`
}
export const getImageUrl = (
src: string,
options: { width?: number; height?: number; noSizeUrlPart?: boolean } = {},
) => {
if (!src.includes('discours.io') && src.includes('http')) {
return src
}
const filename = src.toLowerCase().split('/').pop()
const ext = filename.split('.').pop()
const isAudio = ext in ['wav', 'mp3', 'ogg', 'aif', 'flac']
const base = isAudio ? cdnUrl : `${thumborUrl}/unsafe/`
const suffix = isAudio || options.noSizeUrlPart ? '' : getSizeUrlPart(options)
const subfolder = isAudio ? 'audio' : 'image'
return `${base}${suffix}production/${subfolder}/${filename}`
}
export const getOpenGraphImageUrl = (
src: string,
options: {
topic: string
title: string
author: string
width?: number
height?: number
},
) => {
const sizeUrlPart = getSizeUrlPart(options)
const filtersPart = `filters:discourstext('${encodeURIComponent(options.topic)}','${encodeURIComponent(
options.author,
)}','${encodeURIComponent(options.title)}')/`
2024-01-22 20:38:31 +00:00
if (src.startsWith(thumborUrl)) {
2024-02-04 09:03:15 +00:00
const thumborKey = src.replace(`${thumborUrl}/unsafe`, '')
return `${thumborUrl}/unsafe/${sizeUrlPart}${filtersPart}${thumborKey}`
}
return `${thumborUrl}/unsafe/${sizeUrlPart}${filtersPart}${src}`
}