From 4966b2152eb213bac34cbcb0ff01c246b7746f5c Mon Sep 17 00:00:00 2001 From: Paul Frazee Date: Wed, 14 Dec 2022 15:35:15 -0600 Subject: Add post embeds (images and external links) --- src/lib/download.ts | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/lib/download.ts (limited to 'src/lib/download.ts') diff --git a/src/lib/download.ts b/src/lib/download.ts new file mode 100644 index 000000000..96d93fc27 --- /dev/null +++ b/src/lib/download.ts @@ -0,0 +1,61 @@ +import RNFetchBlob from 'rn-fetch-blob' +import ImageResizer from '@bam.tech/react-native-image-resizer' + +interface DownloadAndResizeOpts { + uri: string + width: number + height: number + mode: 'contain' | 'cover' | 'stretch' + timeout: number +} + +export async function downloadAndResize(opts: DownloadAndResizeOpts) { + let appendExt + try { + const urip = new URL(opts.uri) + const ext = urip.pathname.split('.').pop() + if (ext === 'jpg' || ext === 'jpeg') { + appendExt = 'jpeg' + } else if (ext === 'png') { + appendExt = 'png' + } else { + return + } + } catch (e: any) { + console.error('Invalid URI', opts.uri, e) + return + } + + let downloadRes + try { + const downloadResPromise = RNFetchBlob.config({ + fileCache: true, + appendExt, + }).fetch('GET', opts.uri) + const to1 = setTimeout(() => downloadResPromise.cancel(), opts.timeout) + downloadRes = await downloadResPromise + clearTimeout(to1) + + let localUri = downloadRes.path() + if (!localUri.startsWith('file://')) { + localUri = `file://${localUri}` + } + + const resizeRes = await ImageResizer.createResizedImage( + localUri, + opts.width, + opts.height, + 'JPEG', + 0.7, + undefined, + undefined, + undefined, + {mode: opts.mode}, + ) + return resizeRes + } finally { + if (downloadRes) { + downloadRes.flush() + } + } +} -- cgit 1.4.1