diff options
author | (quasar) nebula <qznebula@protonmail.com> | 2023-10-29 15:22:13 -0300 |
---|---|---|
committer | (quasar) nebula <qznebula@protonmail.com> | 2023-10-29 15:22:13 -0300 |
commit | c3c689fec11a305037fa4fe0775d028d70f8e0a1 (patch) | |
tree | 17eba46442d556a489c428846eaaabea18ba4878 | |
parent | 5074a2d0182590d1645af26e402c35ed9333e1d7 (diff) |
thumbs: determineMediaCachePath
-rw-r--r-- | src/gen-thumbs.js | 86 |
1 files changed, 85 insertions, 1 deletions
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, |