From c3c689fec11a305037fa4fe0775d028d70f8e0a1 Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Sun, 29 Oct 2023 15:22:13 -0300 Subject: thumbs: determineMediaCachePath --- src/gen-thumbs.js | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) (limited to 'src/gen-thumbs.js') diff --git a/src/gen-thumbs.js b/src/gen-thumbs.js index 3d1d66e6..4ceb1bd4 100644 --- a/src/gen-thumbs.js +++ b/src/gen-thumbs.js @@ -88,9 +88,17 @@ const thumbnailSpec = { import {spawn} from 'node:child_process'; import {createHash} from 'node:crypto'; import {createReadStream} from 'node:fs'; -import {mkdir, readFile, rename, stat, writeFile} from 'node:fs/promises'; import * as path from 'node:path'; +import { + mkdir, + readdir, + readFile, + rename, + stat, + writeFile, +} from 'node:fs/promises'; + import dimensionsOf from 'image-size'; import {delay, empty, queue} from '#sugar'; @@ -333,6 +341,82 @@ function generateImageThumbnails({ promisifyProcess(convert('.' + name, details), false))); } +export async function determineMediaCachePath({ + mediaPath, + providedMediaCachePath, + disallowDoubling = false, +}) { + if (!mediaPath) { + return { + annotation: 'media path not provided', + mediaCachePath: null, + }; + } + + if (providedMediaCachePath) { + return { + annotation: 'custom path provided', + mediaCachePath: providedMediaCachePath, + }; + } + + let mediaIncludesThumbnailCache; + + try { + const files = await readdir(mediaPath); + mediaIncludesThumbnailCache = files.includes(CACHE_FILE); + } catch (error) { + mediaIncludesThumbnailCache = false; + } + + if (mediaIncludesThumbnailCache === true && !disallowDoubling) { + return { + annotation: 'media path doubles as cache', + mediaCachePath: mediaPath, + }; + } + + const inferredPath = + path.join( + path.dirname(mediaPath), + path.basename(mediaPath) + '-cache'); + + let inferredIncludesThumbnailCache; + + try { + const files = await readdir(inferredPath); + inferredIncludesThumbnailCache = files.includes(CACHE_FILE); + } catch (error) { + if (error.code === 'ENOENT') { + inferredIncludesThumbnailCache = null; + } else { + inferredIncludesThumbnailCache = undefined; + } + } + + if (inferredIncludesThumbnailCache === true) { + return { + annotation: 'inferred path has cache', + mediaCachePath: inferredPath, + }; + } else if (inferredIncludesThumbnailCache === false) { + return { + annotation: 'inferred path does not have cache', + mediaCachePath: null, + }; + } else if (inferredIncludesThumbnailCache === null) { + return { + annotation: 'inferred path will be created', + mediaCachePath: inferredPath, + }; + } else { + return { + annotation: 'inferred path not readable', + mediaCachePath: null, + }; + } +} + export async function migrateThumbsIntoDedicatedCacheDirectory({ mediaPath, mediaCachePath, -- cgit 1.3.0-6-gf8a5