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AC,IAAI,CAAC,UAAU,EAAE,cAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IAC9E,MAAM,cAAc,CAAC,QAAQ,CAAC,IAAI,EAAE,kBAAE,CAAC,iBAAiB,CAAC,SAAS,CAAC,CAAC,CAAC;IAErE,4EAA4E;IAC5E,MAAM,GAAG,GAAG,MAAM,sBAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACvC,MAAM,IAAI,GAAG,GAAG,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAG,CAAC;IAC7C,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;QAC7B,MAAM,OAAO,GAAG,cAAI,CAAC,IAAI,CAAC,UAAU,EAAE,SAAS,IAAI,EAAE,CAAC,CAAC;QACvD,MAAM,kBAAE,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAClC,OAAO,OAAO,CAAC;KAChB;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAvBD,sCAuBC","sourcesContent":["import fs from 'fs-extra';\n// @ts-ignore\nimport Jimp from 'jimp-compact';\nimport fetch from 'node-fetch';\nimport path from 'path';\nimport stream from 'stream';\nimport temporary from 'tempy';\nimport util from 'util';\n\n// cache downloaded images into memory\nconst cacheDownloadedKeys: Record<string, string> = {};\n\nfunction stripQueryParams(url: string): string {\n return url.split('?')[0].split('#')[0];\n}\n\nexport async function downloadOrUseCachedImage(url: string): Promise<string> {\n if (url in cacheDownloadedKeys) {\n return cacheDownloadedKeys[url];\n }\n if (url.startsWith('http')) {\n cacheDownloadedKeys[url] = await downloadImage(url);\n } else {\n cacheDownloadedKeys[url] = url;\n }\n return cacheDownloadedKeys[url];\n}\n\nexport async function downloadImage(url: string): Promise<string> {\n const outputPath = temporary.directory();\n\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`It was not possible to download image from '${url}'`);\n }\n\n // Download to local file\n const streamPipeline = util.promisify(stream.pipeline);\n const localPath = path.join(outputPath, path.basename(stripQueryParams(url)));\n await streamPipeline(response.body, fs.createWriteStream(localPath));\n\n // If an image URL doesn't have a name, get the mime type and move the file.\n const img = await Jimp.read(localPath);\n const mime = img.getMIME().split('/').pop()!;\n if (!localPath.endsWith(mime)) {\n const newPath = path.join(outputPath, `image.${mime}`);\n await fs.move(localPath, newPath);\n return newPath;\n }\n\n return localPath;\n}\n"]} |