@kitschpatrol/aphex 0.1.6 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aphex-swift +0 -0
- package/dist/assets/applescript-gui.applescript +293 -179
- package/dist/index.d.ts +351 -23
- package/dist/index.js +533 -125
- package/package.json +17 -15
- package/readme.md +92 -19
package/dist/index.js
CHANGED
|
@@ -6,8 +6,8 @@ import { spawn } from "node:child_process";
|
|
|
6
6
|
import { ExifTool } from "exiftool-vendored";
|
|
7
7
|
import { createLogger, injectionHelper } from "lognow";
|
|
8
8
|
import os from "node:os";
|
|
9
|
-
import { slug } from "github-slugger";
|
|
10
9
|
import { fileURLToPath } from "node:url";
|
|
10
|
+
import { slug } from "github-slugger";
|
|
11
11
|
import { createDefu } from "defu";
|
|
12
12
|
import { imageSizeFromFile } from "image-size/fromFile";
|
|
13
13
|
import { lookup, mimes } from "mrmime";
|
|
@@ -36,10 +36,13 @@ function setLogger(logger) {
|
|
|
36
36
|
* management to prevent hanging processes. The exiftool-vendored library spawns
|
|
37
37
|
* persistent Perl processes that must be explicitly ended.
|
|
38
38
|
*/
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
39
|
+
function createExiftool() {
|
|
40
|
+
return new ExifTool({
|
|
41
|
+
maxProcs: 4,
|
|
42
|
+
onIdleIntervalMillis: 1e3
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
let exiftoolInstance = createExiftool();
|
|
43
46
|
let cleanupScheduled = false;
|
|
44
47
|
let processExitHandlerInstalled = false;
|
|
45
48
|
/**
|
|
@@ -47,13 +50,15 @@ let processExitHandlerInstalled = false;
|
|
|
47
50
|
*/
|
|
48
51
|
function getExiftool() {
|
|
49
52
|
scheduleProcessCleanup();
|
|
53
|
+
if (exiftoolInstance.ended) exiftoolInstance = createExiftool();
|
|
50
54
|
return exiftoolInstance;
|
|
51
55
|
}
|
|
52
56
|
/**
|
|
53
57
|
* End the exiftool process gracefully
|
|
54
58
|
*
|
|
55
59
|
* This should be called when you're done using exiftool to prevent hanging
|
|
56
|
-
* processes. It's safe to call multiple times
|
|
60
|
+
* processes. It's safe to call multiple times, and exiftool starts again the
|
|
61
|
+
* next time it's needed.
|
|
57
62
|
*/
|
|
58
63
|
async function endExiftool() {
|
|
59
64
|
if (exiftoolInstance.pids.length === 0) return;
|
|
@@ -193,7 +198,7 @@ function ensureArray(value) {
|
|
|
193
198
|
return Array.isArray(value) ? value : [value];
|
|
194
199
|
}
|
|
195
200
|
/**
|
|
196
|
-
*
|
|
201
|
+
* Assert that the array has exactly one element
|
|
197
202
|
*/
|
|
198
203
|
function assertSingleElement(array) {
|
|
199
204
|
if (array.length !== 1) throw new Error(`Expected array of length 1, got ${array.length}`);
|
|
@@ -216,7 +221,7 @@ function getPackageAssetsPath(meta) {
|
|
|
216
221
|
return path.basename(dirname) === "dist" ? path.join(dirname, "assets") : path.join("src", "assets");
|
|
217
222
|
}
|
|
218
223
|
/**
|
|
219
|
-
*
|
|
224
|
+
* Workers directory path of package or distribution folder (Copied by tsdown)
|
|
220
225
|
*/
|
|
221
226
|
function getPackageWorkersPath(meta) {
|
|
222
227
|
const dirname = getDirname(meta);
|
|
@@ -231,58 +236,80 @@ function getPackageBinPath(meta) {
|
|
|
231
236
|
return path.basename(dirname) === "dist" ? path.join(dirname) : path.join("dist");
|
|
232
237
|
}
|
|
233
238
|
// src/aphex-swift/cli-bridge.ts
|
|
234
|
-
const
|
|
239
|
+
const SHELL_SAFE_REGEX = /^[\w\-.\/:=+,%@]+$/v;
|
|
240
|
+
const SESSION_RESTART_EXIT_CODE = 75;
|
|
235
241
|
let interactiveProcess;
|
|
236
242
|
let currentRequest;
|
|
243
|
+
let commandQueue = [];
|
|
244
|
+
const stoppedProcesses = /* @__PURE__ */ new WeakSet();
|
|
237
245
|
/**
|
|
238
246
|
* Start an interactive session with aphex-swift. Commands will be sent to this
|
|
239
247
|
* persistent process instead of spawning new ones.
|
|
240
248
|
*
|
|
249
|
+
* If the process ends on its own after it has answered a command, or to get rid
|
|
250
|
+
* of a render that timed out, another one takes its place and carries on with
|
|
251
|
+
* the commands that were waiting.
|
|
252
|
+
*
|
|
241
253
|
* @throws {Error} If the session is already active or fails to start
|
|
242
254
|
*/
|
|
243
255
|
async function interactiveSessionStart() {
|
|
244
256
|
if (interactiveProcess !== void 0) throw new Error("Interactive session is already active");
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
257
|
+
spawnInteractiveProcess();
|
|
258
|
+
await new Promise((resolve) => {
|
|
259
|
+
setTimeout(resolve, 100);
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
function spawnInteractiveProcess() {
|
|
263
|
+
const child = spawn("./aphex-swift", ["interactive"], {
|
|
264
|
+
cwd: getPackageBinPath(import.meta),
|
|
248
265
|
stdio: [
|
|
249
266
|
"pipe",
|
|
250
267
|
"pipe",
|
|
251
268
|
"pipe"
|
|
252
269
|
]
|
|
253
270
|
});
|
|
254
|
-
interactiveProcess
|
|
255
|
-
|
|
271
|
+
interactiveProcess = child;
|
|
272
|
+
let hasResponded = false;
|
|
273
|
+
child.stdin.on("error", () => void 0);
|
|
274
|
+
child.stdout.on("data", (data) => {
|
|
275
|
+
if (interactiveProcess !== child || currentRequest === void 0) return;
|
|
256
276
|
currentRequest.buffer += data.toString();
|
|
257
277
|
try {
|
|
258
278
|
JSON.parse(currentRequest.buffer);
|
|
259
279
|
const response = currentRequest.buffer;
|
|
260
280
|
const request = currentRequest;
|
|
261
281
|
currentRequest = void 0;
|
|
282
|
+
hasResponded = true;
|
|
262
283
|
request.resolve(response);
|
|
263
284
|
processNextCommand();
|
|
264
285
|
} catch {}
|
|
265
286
|
});
|
|
266
|
-
|
|
267
|
-
if (currentRequest === void 0) return;
|
|
287
|
+
child.stderr.on("data", (data) => {
|
|
288
|
+
if (interactiveProcess !== child || currentRequest === void 0) return;
|
|
268
289
|
const error = new Error(data.toString().trim());
|
|
269
290
|
const request = currentRequest;
|
|
270
291
|
currentRequest = void 0;
|
|
271
292
|
request.reject(error);
|
|
272
293
|
processNextCommand();
|
|
273
294
|
});
|
|
274
|
-
|
|
295
|
+
child.on("close", (code) => {
|
|
296
|
+
if (interactiveProcess !== child) return;
|
|
297
|
+
interactiveProcess = void 0;
|
|
298
|
+
const interrupted = currentRequest;
|
|
299
|
+
currentRequest = void 0;
|
|
275
300
|
const error = /* @__PURE__ */ new Error(`Interactive session exited with code ${code}`);
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
301
|
+
const restart = !stoppedProcesses.has(child) && (hasResponded || code === SESSION_RESTART_EXIT_CODE);
|
|
302
|
+
if (interrupted !== void 0) {
|
|
303
|
+
if (restart && code === SESSION_RESTART_EXIT_CODE) commandQueue.unshift(interrupted);
|
|
304
|
+
else interrupted.reject(error);
|
|
305
|
+
}
|
|
306
|
+
if (restart) {
|
|
307
|
+
spawnInteractiveProcess();
|
|
308
|
+
processNextCommand();
|
|
309
|
+
return;
|
|
279
310
|
}
|
|
280
311
|
for (const queued of commandQueue) queued.reject(error);
|
|
281
312
|
commandQueue = [];
|
|
282
|
-
interactiveProcess = void 0;
|
|
283
|
-
});
|
|
284
|
-
await new Promise((resolve) => {
|
|
285
|
-
setTimeout(resolve, 100);
|
|
286
313
|
});
|
|
287
314
|
}
|
|
288
315
|
/**
|
|
@@ -291,6 +318,7 @@ async function interactiveSessionStart() {
|
|
|
291
318
|
async function interactiveSessionStop() {
|
|
292
319
|
if (interactiveProcess === void 0) return;
|
|
293
320
|
const processToStop = interactiveProcess;
|
|
321
|
+
stoppedProcesses.add(processToStop);
|
|
294
322
|
processToStop.stdin?.write("exit\n");
|
|
295
323
|
processToStop.stdin?.end();
|
|
296
324
|
await new Promise((resolve) => {
|
|
@@ -313,14 +341,12 @@ async function interactiveSessionStop() {
|
|
|
313
341
|
function isInteractiveSessionActive() {
|
|
314
342
|
return interactiveProcess !== void 0;
|
|
315
343
|
}
|
|
316
|
-
let commandQueue = [];
|
|
317
344
|
function processNextCommand() {
|
|
318
345
|
if (currentRequest !== void 0 || interactiveProcess === void 0 || commandQueue.length === 0) return;
|
|
319
346
|
const next = commandQueue.shift();
|
|
320
347
|
currentRequest = {
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
resolve: next.resolve
|
|
348
|
+
...next,
|
|
349
|
+
buffer: ""
|
|
324
350
|
};
|
|
325
351
|
interactiveProcess.stdin?.write(next.command + "\n");
|
|
326
352
|
}
|
|
@@ -340,10 +366,11 @@ async function executeInteractiveCommand(command) {
|
|
|
340
366
|
}
|
|
341
367
|
/**
|
|
342
368
|
* Escape and join arguments into a single command string for interactive mode.
|
|
343
|
-
*
|
|
369
|
+
* Any argument that isn't plainly safe is wrapped in single quotes, which a
|
|
370
|
+
* shell takes literally.
|
|
344
371
|
*/
|
|
345
372
|
function escapeCommand(args) {
|
|
346
|
-
return args.map((arg) =>
|
|
373
|
+
return args.map((arg) => SHELL_SAFE_REGEX.test(arg) ? arg : `'${arg.replaceAll("'", String.raw`'\''`)}'`).join(" ");
|
|
347
374
|
}
|
|
348
375
|
/**
|
|
349
376
|
* Runtime type guard for ResourceInfo
|
|
@@ -398,10 +425,16 @@ function assertAlbumInfoArray(value) {
|
|
|
398
425
|
if (!isAlbumInfoArray(value)) throw new Error("Invalid AlbumInfo array");
|
|
399
426
|
}
|
|
400
427
|
/**
|
|
401
|
-
*
|
|
402
|
-
* or photo path)
|
|
428
|
+
* Look up photos in the Photos.app library.
|
|
403
429
|
*
|
|
404
|
-
* @
|
|
430
|
+
* @param identifiers Photo UUIDs, paths like `Album/Title` or
|
|
431
|
+
* `Album/IMG_1234.jpeg`, or album UUIDs and paths, which stand for every
|
|
432
|
+
* photo in the album.
|
|
433
|
+
* @param caseSensitive Whether titles, file names, and album paths have to
|
|
434
|
+
* match exactly.
|
|
435
|
+
*
|
|
436
|
+
* @returns One entry per photo found. Empty if no identifiers are passed.
|
|
437
|
+
* @throws {Error} If nothing matches, or the command fails.
|
|
405
438
|
*/
|
|
406
439
|
async function aphexPhotoInfo(identifiers, caseSensitive = false) {
|
|
407
440
|
const identifiersArray = ensureArray(identifiers);
|
|
@@ -423,9 +456,13 @@ async function aphexPhotoInfo(identifiers, caseSensitive = false) {
|
|
|
423
456
|
}
|
|
424
457
|
}
|
|
425
458
|
/**
|
|
426
|
-
*
|
|
459
|
+
* Look up albums in the Photos.app library.
|
|
460
|
+
*
|
|
461
|
+
* @param identifiers Album UUIDs, or paths like `Album` or `Folder/Album`.
|
|
462
|
+
* @param caseSensitive Whether album paths have to match exactly.
|
|
427
463
|
*
|
|
428
|
-
* @
|
|
464
|
+
* @returns One entry per album found. Empty if no identifiers are passed.
|
|
465
|
+
* @throws {Error} If nothing matches, or the command fails.
|
|
429
466
|
*/
|
|
430
467
|
async function aphexAlbumInfo(identifiers, caseSensitive = false) {
|
|
431
468
|
const identifiersArray = ensureArray(identifiers);
|
|
@@ -446,12 +483,38 @@ async function aphexAlbumInfo(identifiers, caseSensitive = false) {
|
|
|
446
483
|
throw new Error(`Error fetching album info: ${stdout}`);
|
|
447
484
|
}
|
|
448
485
|
}
|
|
486
|
+
const LEADING_HASH_REGEX = /^#/v;
|
|
487
|
+
function getRenderArguments(options) {
|
|
488
|
+
const { background, bitDepth, colorProfile, format, includeLocation, includeMetadata, maxHeight, maxWidth, preserveAlpha, quality } = options;
|
|
489
|
+
const canHoldAlpha = format === "png" || format === "tiff";
|
|
490
|
+
return [
|
|
491
|
+
"--format",
|
|
492
|
+
format,
|
|
493
|
+
...colorProfile === void 0 ? [] : ["--color-profile", colorProfile],
|
|
494
|
+
...quality !== void 0 && format === "jpeg" ? ["--quality", String(quality)] : [],
|
|
495
|
+
...bitDepth !== void 0 && format === "tiff" ? ["--bit-depth", String(bitDepth)] : [],
|
|
496
|
+
...maxWidth === void 0 ? [] : ["--max-width", String(Math.floor(maxWidth))],
|
|
497
|
+
...maxHeight === void 0 ? [] : ["--max-height", String(Math.floor(maxHeight))],
|
|
498
|
+
...includeMetadata === true ? ["--include-metadata"] : [],
|
|
499
|
+
...includeLocation === true ? ["--include-location"] : [],
|
|
500
|
+
...background === void 0 ? [] : ["--background", background.replace(LEADING_HASH_REGEX, "")],
|
|
501
|
+
...preserveAlpha === true && background === void 0 && canHoldAlpha ? ["--preserve-alpha"] : []
|
|
502
|
+
];
|
|
503
|
+
}
|
|
449
504
|
/**
|
|
450
|
-
* Export photos
|
|
505
|
+
* Export photos from the Photos.app library to a directory with aphex-swift.
|
|
451
506
|
*
|
|
452
|
-
*
|
|
507
|
+
* By default this copies the image stored in the library: the original, or for
|
|
508
|
+
* an edited photo, the edited image Photos.app saved.
|
|
509
|
+
*
|
|
510
|
+
* @param identifiers Photo or album identifiers, see `aphexPhotoInfo`.
|
|
511
|
+
* @param destination An existing directory.
|
|
512
|
+
*
|
|
513
|
+
* @returns The paths of the exported files.
|
|
514
|
+
* @throws {Error} If nothing could be exported, or the command fails.
|
|
453
515
|
*/
|
|
454
|
-
async function aphexExport(identifiers, destination,
|
|
516
|
+
async function aphexExport(identifiers, destination, options = {}) {
|
|
517
|
+
const { caseSensitive = false, originals = false, render } = options;
|
|
455
518
|
const identifiersArray = ensureArray(identifiers);
|
|
456
519
|
if (identifiersArray.length === 0) return [];
|
|
457
520
|
const args = [
|
|
@@ -460,7 +523,8 @@ async function aphexExport(identifiers, destination, caseSensitive = false, orig
|
|
|
460
523
|
"--destination",
|
|
461
524
|
destination,
|
|
462
525
|
...caseSensitive ? ["--case-sensitive"] : [],
|
|
463
|
-
...originals ? ["--originals"] : []
|
|
526
|
+
...originals ? ["--originals"] : [],
|
|
527
|
+
...render === void 0 ? [] : getRenderArguments(render)
|
|
464
528
|
];
|
|
465
529
|
let stdout;
|
|
466
530
|
if (isInteractiveSessionActive()) stdout = await executeInteractiveCommand(escapeCommand(args));
|
|
@@ -872,12 +936,22 @@ async function getImageDimensions(imagePath) {
|
|
|
872
936
|
height
|
|
873
937
|
};
|
|
874
938
|
}
|
|
939
|
+
const RAW_MIME_TYPES = /* @__PURE__ */ new Set([
|
|
940
|
+
"arw",
|
|
941
|
+
"cr2",
|
|
942
|
+
"cr3",
|
|
943
|
+
"crw",
|
|
944
|
+
"dng",
|
|
945
|
+
"nef",
|
|
946
|
+
"pef"
|
|
947
|
+
]);
|
|
875
948
|
/**
|
|
876
|
-
* Check if an image has an alpha channel
|
|
949
|
+
* Check if an image has transparency: an alpha channel in which at least one
|
|
950
|
+
* pixel is not fully opaque
|
|
877
951
|
*/
|
|
878
952
|
async function hasAlpha(imagePath) {
|
|
879
953
|
const mime = lookupImageMimeType(imagePath, true);
|
|
880
|
-
if (mime === "jpeg") return false;
|
|
954
|
+
if (mime === "jpeg" || RAW_MIME_TYPES.has(mime)) return false;
|
|
881
955
|
if (mime !== "psd" && mime !== "tiff") {
|
|
882
956
|
const { stdout: channelOutput } = await execa("identify", [
|
|
883
957
|
"-format",
|
|
@@ -911,16 +985,21 @@ function escapeForAppleScript(text) {
|
|
|
911
985
|
return text.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");
|
|
912
986
|
}
|
|
913
987
|
/**
|
|
914
|
-
* Export a photo
|
|
988
|
+
* Export a photo with the `export` command of the Photos.app AppleScript
|
|
989
|
+
* dictionary.
|
|
990
|
+
*
|
|
991
|
+
* Photos.app decides what comes out: a JPEG it renders from the photo and its
|
|
992
|
+
* edits, or with `forceOriginal`, the original file as it was imported.
|
|
915
993
|
*
|
|
916
994
|
* @param photoUuid - UUID of the photo to export
|
|
917
|
-
* @param forceOriginal - Whether to
|
|
995
|
+
* @param forceOriginal - Whether to export the original file, ignoring edits
|
|
918
996
|
*
|
|
919
|
-
* @returns
|
|
997
|
+
* @returns The path of the exported file, in a new temporary directory. Move it
|
|
998
|
+
* and remove the directory afterwards.
|
|
920
999
|
*/
|
|
921
1000
|
async function exportViaAppleScript(photoUuid, forceOriginal = false) {
|
|
922
1001
|
const tempDirectory = await getTempDirectory("engine", "applescript");
|
|
923
|
-
const exportFlag = forceOriginal ? "with originals" : "without originals";
|
|
1002
|
+
const exportFlag = forceOriginal ? "with using originals" : "without using originals";
|
|
924
1003
|
const appleScript = `
|
|
925
1004
|
tell application "Photos"
|
|
926
1005
|
-- Find the media item by UUID
|
|
@@ -928,22 +1007,19 @@ async function exportViaAppleScript(photoUuid, forceOriginal = false) {
|
|
|
928
1007
|
|
|
929
1008
|
-- Export the photo to temp directory
|
|
930
1009
|
export {targetPhoto} to POSIX file "${escapeForAppleScript(tempDirectory)}" ${exportFlag}
|
|
931
|
-
|
|
932
|
-
-- Get the exported file name
|
|
933
|
-
set photoFilename to filename of targetPhoto
|
|
934
|
-
|
|
935
|
-
-- Return the filename for path construction
|
|
936
|
-
return photoFilename
|
|
937
1010
|
end tell
|
|
938
1011
|
`;
|
|
939
1012
|
try {
|
|
940
|
-
|
|
941
|
-
const exportedFileName = stdout.trim();
|
|
942
|
-
return path.join(tempDirectory, exportedFileName);
|
|
1013
|
+
await execa("osascript", ["-e", appleScript]);
|
|
943
1014
|
} catch (error) {
|
|
944
1015
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
945
1016
|
throw new Error(`Failed to export photo via AppleScript: ${errorMessage}`, { cause: error });
|
|
946
1017
|
}
|
|
1018
|
+
const entries = await fse.readdir(tempDirectory);
|
|
1019
|
+
const images = entries.filter((name) => lookupImageMimeType(name) !== void 0);
|
|
1020
|
+
const [exportedFileName] = images;
|
|
1021
|
+
if (exportedFileName === void 0 || images.length > 1) throw new Error(`Expected the AppleScript export of photo "${photoUuid}" to produce one image, but found ${String(images.length)}: ${JSON.stringify(entries)}`);
|
|
1022
|
+
return path.join(tempDirectory, exportedFileName);
|
|
947
1023
|
}
|
|
948
1024
|
// src/pipeline/engines/applescript-gui.ts
|
|
949
1025
|
/** Apple's defaults, but these are overridden by Aphex by default */
|
|
@@ -961,41 +1037,130 @@ const defaultExportViaAppleScriptGuiOptions = {
|
|
|
961
1037
|
subfolderFormat: "None",
|
|
962
1038
|
tiffBitDepth: 8
|
|
963
1039
|
};
|
|
1040
|
+
const GUI_COLOR_PROFILES = {
|
|
1041
|
+
"adobe-rgb": "AdobeRGB",
|
|
1042
|
+
"display-p3": "Display P3",
|
|
1043
|
+
"most-compatible": "Most Compatible",
|
|
1044
|
+
original: "Original",
|
|
1045
|
+
srgb: "sRGB"
|
|
1046
|
+
};
|
|
1047
|
+
const GUI_PHOTO_KINDS = {
|
|
1048
|
+
heic: "HEIC",
|
|
1049
|
+
jpeg: "JPEG",
|
|
1050
|
+
png: "PNG",
|
|
1051
|
+
tiff: "TIFF"
|
|
1052
|
+
};
|
|
1053
|
+
const GUI_JPEG_QUALITIES = [
|
|
1054
|
+
{
|
|
1055
|
+
name: "Low (smallest Size)",
|
|
1056
|
+
quality: .25
|
|
1057
|
+
},
|
|
1058
|
+
{
|
|
1059
|
+
name: "Medium",
|
|
1060
|
+
quality: .5
|
|
1061
|
+
},
|
|
1062
|
+
{
|
|
1063
|
+
name: "High",
|
|
1064
|
+
quality: .75
|
|
1065
|
+
},
|
|
1066
|
+
{
|
|
1067
|
+
name: "Maximum",
|
|
1068
|
+
quality: 1
|
|
1069
|
+
}
|
|
1070
|
+
];
|
|
1071
|
+
/**
|
|
1072
|
+
* Work out the export sheet settings that come closest to a set of
|
|
1073
|
+
* `swift-render` options, for exporting through the GUI what couldn't be
|
|
1074
|
+
* rendered. The sheet drives the same renderer, so matching settings give the
|
|
1075
|
+
* same image.
|
|
1076
|
+
*
|
|
1077
|
+
* Transparency is not covered: the sheet always flattens it onto white,
|
|
1078
|
+
* whatever `preserveAlpha` and `background` say.
|
|
1079
|
+
*
|
|
1080
|
+
* @returns The settings, and whether they match the options exactly. They can't
|
|
1081
|
+
* for a JPEG quality between the sheet's four levels, or for a width and a
|
|
1082
|
+
* height limit that differ.
|
|
1083
|
+
*/
|
|
1084
|
+
function getAppleScriptGuiOptionsForRender(renderOptions) {
|
|
1085
|
+
const { bitDepth, colorProfile, format, includeLocation, includeMetadata, quality } = renderOptions;
|
|
1086
|
+
const maxWidth = renderOptions.maxWidth === void 0 ? void 0 : Math.floor(renderOptions.maxWidth);
|
|
1087
|
+
const maxHeight = renderOptions.maxHeight === void 0 ? void 0 : Math.floor(renderOptions.maxHeight);
|
|
1088
|
+
let exact = true;
|
|
1089
|
+
const options = {
|
|
1090
|
+
colorProfile: GUI_COLOR_PROFILES[colorProfile],
|
|
1091
|
+
includeLocation,
|
|
1092
|
+
includeMetadata,
|
|
1093
|
+
photoKind: GUI_PHOTO_KINDS[format],
|
|
1094
|
+
photoSize: "Full Size",
|
|
1095
|
+
tiffBitDepth: bitDepth
|
|
1096
|
+
};
|
|
1097
|
+
if (format === "jpeg") {
|
|
1098
|
+
let closest = GUI_JPEG_QUALITIES[0];
|
|
1099
|
+
for (const level of GUI_JPEG_QUALITIES) if (Math.abs(level.quality - quality) < Math.abs(closest.quality - quality)) closest = level;
|
|
1100
|
+
options.jpegQuality = closest.name;
|
|
1101
|
+
exact &&= closest.quality === quality;
|
|
1102
|
+
}
|
|
1103
|
+
if (maxWidth !== void 0 || maxHeight !== void 0) {
|
|
1104
|
+
options.photoSize = "Custom";
|
|
1105
|
+
if (maxWidth === void 0 || maxHeight === void 0) {
|
|
1106
|
+
options.maxSizeType = maxWidth === void 0 ? "Height" : "Width";
|
|
1107
|
+
options.maxSizeValue = maxWidth ?? maxHeight;
|
|
1108
|
+
} else {
|
|
1109
|
+
options.maxSizeType = "Dimension";
|
|
1110
|
+
options.maxSizeValue = Math.min(maxWidth, maxHeight);
|
|
1111
|
+
exact &&= maxWidth === maxHeight;
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
return {
|
|
1115
|
+
exact,
|
|
1116
|
+
options
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
964
1119
|
/**
|
|
965
|
-
* Export a photo
|
|
966
|
-
*
|
|
1120
|
+
* Export a photo, or every photo in an album, through the Photos.app export
|
|
1121
|
+
* sheet, by automating its GUI with AppleScript.
|
|
1122
|
+
*
|
|
1123
|
+
* @returns The paths of the exported files, in a new temporary directory. Move
|
|
1124
|
+
* them and remove the directory afterwards.
|
|
967
1125
|
*/
|
|
968
1126
|
async function exportViaAppleScriptGui(uuid, options) {
|
|
969
1127
|
const tempDirectory = await getTempDirectory("engine", "applescript-gui");
|
|
970
1128
|
const { colorProfile, fileName, includeLocation, includeMetadata, jpegQuality, maxSizeType, maxSizeValue, photoKind, photoSize, sequentialPrefix, subfolderFormat, tiffBitDepth } = mergeDefaults(options, defaultExportViaAppleScriptGuiOptions);
|
|
971
1129
|
const appleScriptPath = path.join(getPackageAssetsPath(import.meta), "applescript-gui.applescript");
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
1130
|
+
let stderr;
|
|
1131
|
+
try {
|
|
1132
|
+
stderr = (await execa("osascript", [
|
|
1133
|
+
appleScriptPath,
|
|
1134
|
+
uuid,
|
|
1135
|
+
tempDirectory,
|
|
1136
|
+
photoKind,
|
|
1137
|
+
jpegQuality,
|
|
1138
|
+
tiffBitDepth.toString(),
|
|
1139
|
+
colorProfile,
|
|
1140
|
+
photoSize,
|
|
1141
|
+
maxSizeType,
|
|
1142
|
+
maxSizeValue.toString(),
|
|
1143
|
+
includeMetadata.toString(),
|
|
1144
|
+
includeLocation.toString(),
|
|
1145
|
+
fileName,
|
|
1146
|
+
sequentialPrefix,
|
|
1147
|
+
subfolderFormat
|
|
1148
|
+
])).stderr;
|
|
1149
|
+
} catch (error) {
|
|
1150
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
1151
|
+
throw new Error(`Failed to export "${uuid}" via the Photos GUI: ${errorMessage}`, { cause: error });
|
|
1152
|
+
}
|
|
1153
|
+
const results = stderr.split("\n").filter((line) => line.startsWith(`${tempDirectory}/`));
|
|
1154
|
+
if (results.length === 0) throw new Error(`No files exported for "${uuid}" via the Photos GUI. Output: ${stderr}`);
|
|
993
1155
|
return results;
|
|
994
1156
|
}
|
|
995
1157
|
// src/pipeline/engines/file-system.ts
|
|
996
1158
|
/**
|
|
997
|
-
* Export a photo
|
|
998
|
-
*
|
|
1159
|
+
* Export a photo by copying its file straight out of the Photos.app library
|
|
1160
|
+
* folder: the edited image if the photo has edits, the original otherwise.
|
|
1161
|
+
*
|
|
1162
|
+
* @returns The path of the copy, in a new temporary directory. Move it and
|
|
1163
|
+
* remove the directory afterwards.
|
|
999
1164
|
*/
|
|
1000
1165
|
async function exportViaFileSystem(photoUuid, forceOriginal = false) {
|
|
1001
1166
|
const [photoInfo] = isPhotoInfo(photoUuid) ? [photoUuid] : await aphexPhotoInfo(photoUuid);
|
|
@@ -1013,13 +1178,80 @@ async function exportViaFileSystem(photoUuid, forceOriginal = false) {
|
|
|
1013
1178
|
}
|
|
1014
1179
|
// src/pipeline/engines/swift-photokit.ts
|
|
1015
1180
|
/**
|
|
1016
|
-
* Export a photo
|
|
1181
|
+
* Export a photo by asking PhotoKit for the image stored in the library, via
|
|
1182
|
+
* the aphex-swift command line tool. That is the untouched original, or for an
|
|
1183
|
+
* edited photo, the compressed image Photos.app saved with the edit.
|
|
1184
|
+
*
|
|
1185
|
+
* @returns The path of the file, in a new temporary directory. Move it and
|
|
1186
|
+
* remove the directory afterwards.
|
|
1017
1187
|
*/
|
|
1018
1188
|
async function exportViaSwiftPhotoKit(photoUuid) {
|
|
1019
1189
|
const [result] = await aphexExport(photoUuid, await getTempDirectory("engine", "swift-photokit"));
|
|
1020
1190
|
if (result === void 0) throw new Error(`Export via PhotoKit returned no files for photo "${photoUuid}"`);
|
|
1021
1191
|
return result;
|
|
1022
1192
|
}
|
|
1193
|
+
// src/pipeline/engines/swift-render.ts
|
|
1194
|
+
/** Equivalent to what the Photos.app export sheet starts out with */
|
|
1195
|
+
const defaultExportViaSwiftRenderOptions = {
|
|
1196
|
+
background: void 0,
|
|
1197
|
+
bitDepth: 8,
|
|
1198
|
+
colorProfile: "most-compatible",
|
|
1199
|
+
format: "jpeg",
|
|
1200
|
+
includeLocation: true,
|
|
1201
|
+
includeMetadata: true,
|
|
1202
|
+
maxHeight: void 0,
|
|
1203
|
+
maxWidth: void 0,
|
|
1204
|
+
preserveAlpha: false,
|
|
1205
|
+
quality: .75
|
|
1206
|
+
};
|
|
1207
|
+
const HEX_COLOR_REGEX = /^#?[\da-f]{6}$/iv;
|
|
1208
|
+
/**
|
|
1209
|
+
* Check render options before anything is exported with them. A bad value would
|
|
1210
|
+
* otherwise only show up as a failed render, one photo at a time.
|
|
1211
|
+
*
|
|
1212
|
+
* @throws {TypeError} Naming the option that is wrong
|
|
1213
|
+
*/
|
|
1214
|
+
function assertValidSwiftRenderOptions(options) {
|
|
1215
|
+
const { background, maxHeight, maxWidth, quality } = options;
|
|
1216
|
+
if (!(quality >= 0) || !(quality <= 1)) throw new TypeError(`swiftRenderOptions.quality must be from 0 to 1, got ${String(quality)}`);
|
|
1217
|
+
for (const [name, value] of [["maxWidth", maxWidth], ["maxHeight", maxHeight]]) if (value !== void 0 && !(value >= 1)) throw new TypeError(`swiftRenderOptions.${name} must be at least 1, got ${String(value)}`);
|
|
1218
|
+
if (background !== void 0 && !HEX_COLOR_REGEX.test(background)) throw new TypeError(`swiftRenderOptions.background must be six hexadecimal digits like "ff8800", got "${background}"`);
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* Export a photo by re-rendering it, and any edits made to it in Photos.app, at
|
|
1222
|
+
* full quality via the aphex-swift command line tool.
|
|
1223
|
+
*
|
|
1224
|
+
* This produces the same pixels as File → Export in Photos.app without
|
|
1225
|
+
* automating its GUI, where the other engines return the compressed image that
|
|
1226
|
+
* Photos.app saved when the photo was edited. It can also keep transparency,
|
|
1227
|
+
* which Photos.app flattens onto white. It relies on private Photos APIs, so it
|
|
1228
|
+
* can stop working after a macOS update.
|
|
1229
|
+
*
|
|
1230
|
+
* @returns The path of the rendered file, in a new temporary directory. Move it
|
|
1231
|
+
* and remove the directory afterwards.
|
|
1232
|
+
*/
|
|
1233
|
+
async function exportViaSwiftRender(photoUuid, options) {
|
|
1234
|
+
const resolvedOptions = mergeDefaults(options, defaultExportViaSwiftRenderOptions);
|
|
1235
|
+
assertValidSwiftRenderOptions(resolvedOptions);
|
|
1236
|
+
const { background, maxHeight, maxWidth, ...rest } = resolvedOptions;
|
|
1237
|
+
const tempDirectory = await getTempDirectory("engine", "swift-render");
|
|
1238
|
+
try {
|
|
1239
|
+
const [result] = await aphexExport(photoUuid, tempDirectory, { render: {
|
|
1240
|
+
...rest,
|
|
1241
|
+
background,
|
|
1242
|
+
maxHeight,
|
|
1243
|
+
maxWidth
|
|
1244
|
+
} });
|
|
1245
|
+
if (result === void 0) throw new Error(`Export via render returned no files for photo "${photoUuid}"`);
|
|
1246
|
+
return result;
|
|
1247
|
+
} catch (error) {
|
|
1248
|
+
await fse.rm(tempDirectory, {
|
|
1249
|
+
force: true,
|
|
1250
|
+
recursive: true
|
|
1251
|
+
});
|
|
1252
|
+
throw error;
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1023
1255
|
// src/pipeline/image-export.ts
|
|
1024
1256
|
const defaultExportApplePhotoOptions = {
|
|
1025
1257
|
appleScriptGuiOptions: {
|
|
@@ -1036,24 +1268,24 @@ const defaultExportApplePhotoOptions = {
|
|
|
1036
1268
|
subfolderFormat: "None",
|
|
1037
1269
|
tiffBitDepth: 8
|
|
1038
1270
|
},
|
|
1039
|
-
engineEdited: "
|
|
1040
|
-
engineEditedAlpha: "swift-
|
|
1271
|
+
engineEdited: "swift-render",
|
|
1272
|
+
engineEditedAlpha: "swift-render",
|
|
1041
1273
|
engineOriginal: {
|
|
1042
|
-
arw: "
|
|
1274
|
+
arw: "swift-render",
|
|
1043
1275
|
avif: "swift-photokit",
|
|
1044
|
-
cr2: "
|
|
1045
|
-
cr3: "
|
|
1046
|
-
crw: "
|
|
1047
|
-
dng: "
|
|
1276
|
+
cr2: "swift-render",
|
|
1277
|
+
cr3: "swift-render",
|
|
1278
|
+
crw: "swift-render",
|
|
1279
|
+
dng: "swift-render",
|
|
1048
1280
|
gif: "swift-photokit",
|
|
1049
1281
|
heic: "swift-photokit",
|
|
1050
1282
|
heif: "swift-photokit",
|
|
1051
1283
|
jpeg: "swift-photokit",
|
|
1052
|
-
nef: "
|
|
1053
|
-
pef: "
|
|
1054
|
-
png: "
|
|
1055
|
-
psd: "
|
|
1056
|
-
tiff: "
|
|
1284
|
+
nef: "swift-render",
|
|
1285
|
+
pef: "swift-render",
|
|
1286
|
+
png: "swift-render",
|
|
1287
|
+
psd: "swift-render",
|
|
1288
|
+
tiff: "swift-render",
|
|
1057
1289
|
webp: "swift-photokit"
|
|
1058
1290
|
},
|
|
1059
1291
|
engineOriginalAlpha: "swift-photokit",
|
|
@@ -1064,21 +1296,37 @@ const defaultExportApplePhotoOptions = {
|
|
|
1064
1296
|
"fileName",
|
|
1065
1297
|
"uuid"
|
|
1066
1298
|
],
|
|
1067
|
-
fileNameSluggify: true
|
|
1299
|
+
fileNameSluggify: true,
|
|
1300
|
+
swiftRenderOptions: {
|
|
1301
|
+
background: void 0,
|
|
1302
|
+
bitDepth: 8,
|
|
1303
|
+
colorProfile: "srgb",
|
|
1304
|
+
format: "png",
|
|
1305
|
+
includeLocation: false,
|
|
1306
|
+
includeMetadata: false,
|
|
1307
|
+
maxHeight: void 0,
|
|
1308
|
+
maxWidth: void 0,
|
|
1309
|
+
preserveAlpha: true,
|
|
1310
|
+
quality: 1
|
|
1311
|
+
}
|
|
1068
1312
|
};
|
|
1069
1313
|
/**
|
|
1070
|
-
* Export a
|
|
1314
|
+
* Export photos and albums from the Photos.app library to a directory, each
|
|
1315
|
+
* photo through the engine the options pick for it. No processing, metadata, or
|
|
1316
|
+
* sync.
|
|
1071
1317
|
*/
|
|
1072
1318
|
async function exportApplePhotos(identifiers, destinationDirectory, options) {
|
|
1073
1319
|
const resolvedOptions = mergeDefaults(options, defaultExportApplePhotoOptions);
|
|
1320
|
+
assertValidSwiftRenderOptions(resolvedOptions.swiftRenderOptions);
|
|
1074
1321
|
const photoInfos = await resolveIdentifiers(identifiers);
|
|
1075
1322
|
const exportedPhotos = [];
|
|
1076
1323
|
for (const photoInfo of photoInfos) {
|
|
1077
|
-
const engine = await getEngineForPhoto(photoInfo, resolvedOptions);
|
|
1324
|
+
const { degraded, engine, path: exportedPath } = await exportPhotoWithEngine(photoInfo, await getEngineForPhoto(photoInfo, resolvedOptions), resolvedOptions);
|
|
1078
1325
|
const exportedPhoto = {
|
|
1326
|
+
exportDegraded: degraded,
|
|
1079
1327
|
exportEngine: engine,
|
|
1080
1328
|
exportOptions: resolvedOptions,
|
|
1081
|
-
path:
|
|
1329
|
+
path: exportedPath,
|
|
1082
1330
|
photoInfo
|
|
1083
1331
|
};
|
|
1084
1332
|
const resolvedDestinationDirectory = await ensureDirectoryExists(destinationDirectory);
|
|
@@ -1094,19 +1342,75 @@ async function exportApplePhotos(identifiers, destinationDirectory, options) {
|
|
|
1094
1342
|
}
|
|
1095
1343
|
return exportedPhotos;
|
|
1096
1344
|
}
|
|
1345
|
+
/**
|
|
1346
|
+
* Returns the engine along with the path, since an engine can fall back to
|
|
1347
|
+
* another one, and whether that left the file short of what the options ask
|
|
1348
|
+
* for
|
|
1349
|
+
*/
|
|
1097
1350
|
async function exportPhotoWithEngine(photoInfo, engine, options) {
|
|
1098
1351
|
switch (engine) {
|
|
1099
|
-
case "applescript": return
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1352
|
+
case "applescript": return {
|
|
1353
|
+
degraded: false,
|
|
1354
|
+
engine,
|
|
1355
|
+
path: await exportViaAppleScript(photoInfo.uuid)
|
|
1356
|
+
};
|
|
1357
|
+
case "file-system": return {
|
|
1358
|
+
degraded: false,
|
|
1359
|
+
engine,
|
|
1360
|
+
path: await exportViaFileSystem(photoInfo)
|
|
1361
|
+
};
|
|
1362
|
+
case "photos-gui": return {
|
|
1363
|
+
degraded: false,
|
|
1364
|
+
engine,
|
|
1365
|
+
path: await exportViaPhotosGui(photoInfo, options.appleScriptGuiOptions)
|
|
1366
|
+
};
|
|
1367
|
+
case "swift-photokit": return {
|
|
1368
|
+
degraded: false,
|
|
1369
|
+
engine,
|
|
1370
|
+
path: await exportViaSwiftPhotoKit(photoInfo.uuid)
|
|
1371
|
+
};
|
|
1372
|
+
case "swift-render": try {
|
|
1373
|
+
return {
|
|
1374
|
+
degraded: false,
|
|
1375
|
+
engine,
|
|
1376
|
+
path: await exportViaSwiftRender(photoInfo.uuid, options.swiftRenderOptions)
|
|
1377
|
+
};
|
|
1378
|
+
} catch (error) {
|
|
1379
|
+
return exportViaPhotosGuiInsteadOfRender(photoInfo, options, error);
|
|
1105
1380
|
}
|
|
1106
|
-
case "swift-photokit": return exportViaSwiftPhotoKit(photoInfo.uuid);
|
|
1107
1381
|
}
|
|
1108
1382
|
}
|
|
1109
|
-
|
|
1383
|
+
async function exportViaPhotosGui(photoInfo, guiOptions) {
|
|
1384
|
+
const [exportedPath] = await exportViaAppleScriptGui(photoInfo.uuid, guiOptions);
|
|
1385
|
+
if (exportedPath === void 0) throw new Error(`Photos GUI export returned no files for photo "${photoInfo.uuid}"`);
|
|
1386
|
+
return exportedPath;
|
|
1387
|
+
}
|
|
1388
|
+
/**
|
|
1389
|
+
* Export a photo that failed to render through the Photos.app GUI instead.
|
|
1390
|
+
*
|
|
1391
|
+
* Rendering depends on private Photos APIs that a macOS update can break. The
|
|
1392
|
+
* export sheet drives the same renderer the slow way, so it is set up to match
|
|
1393
|
+
* the render options instead of `appleScriptGuiOptions`, which only supply the
|
|
1394
|
+
* settings that have no counterpart, like file naming.
|
|
1395
|
+
*/
|
|
1396
|
+
async function exportViaPhotosGuiInsteadOfRender(photoInfo, options, renderError) {
|
|
1397
|
+
const { exact, options: guiOptions } = getAppleScriptGuiOptionsForRender(options.swiftRenderOptions);
|
|
1398
|
+
const shortfall = [...rendersTransparency(options.swiftRenderOptions) && await originalHasTransparency(photoInfo) ? ["its transparency is flattened onto white"] : [], ...exact ? [] : ["the size or JPEG quality is only approximate"]];
|
|
1399
|
+
log.warn(`Rendering photo "${photoInfo.title ?? photoInfo.uuid}" failed, falling back to the Photos.app GUI: ${renderError instanceof Error ? renderError.message : String(renderError)}${shortfall.length === 0 ? "" : ` The GUI can't match the render options: ${shortfall.join(", and ")}. The photo will be exported again on the next sync.`}`);
|
|
1400
|
+
return {
|
|
1401
|
+
degraded: shortfall.length > 0,
|
|
1402
|
+
engine: "photos-gui",
|
|
1403
|
+
path: await exportViaPhotosGui(photoInfo, {
|
|
1404
|
+
...options.appleScriptGuiOptions,
|
|
1405
|
+
...guiOptions
|
|
1406
|
+
})
|
|
1407
|
+
};
|
|
1408
|
+
}
|
|
1409
|
+
/**
|
|
1410
|
+
* Work out the path an exported photo should end up at: the directory and
|
|
1411
|
+
* extension of `filePath`, with a file name chosen by the first naming strategy
|
|
1412
|
+
* the photo has a value for.
|
|
1413
|
+
*/
|
|
1110
1414
|
function getImagePathWithFileName(photoInfo, filePath, sluggify = true, fileNameAppendUuidFragment = false, normalizeExtensions = true, namingStrategyPrecedence = [
|
|
1111
1415
|
"title",
|
|
1112
1416
|
"fileName",
|
|
@@ -1147,14 +1451,35 @@ async function getEngineForPhoto(photoInfo, options) {
|
|
|
1147
1451
|
if (engine === void 0) throw new Error(`No export engine found for original photo "${photoInfo.title}" of type "${type}"${alpha ? " with alpha channel" : ""}`);
|
|
1148
1452
|
return engine;
|
|
1149
1453
|
}
|
|
1150
|
-
const alpha = await
|
|
1151
|
-
if (alpha) log.warn(`Edited photo "${photoInfo.title}" has true transparency, it probably won't export correctly. Only un-edited files preserve transparency on export.`);
|
|
1454
|
+
const alpha = await originalHasTransparency(photoInfo);
|
|
1152
1455
|
const type = lookupImageMimeType(photoInfo.edited.filePath, true);
|
|
1153
1456
|
const engine = alpha ? typeof engineEditedAlpha === "string" ? engineEditedAlpha : engineEditedAlpha[type] : typeof engineEdited === "string" ? engineEdited : engineEdited[type];
|
|
1457
|
+
if (alpha && (engine !== "swift-render" || !rendersTransparency(options.swiftRenderOptions))) log.warn(`Edited photo "${photoInfo.title ?? photoInfo.uuid}" has transparency, which the "${String(engine)}" engine will flatten onto white. Only swift-render can keep it, with "preserveAlpha" and a "png" or "tiff" format.`);
|
|
1154
1458
|
if (engine === void 0) throw new Error(`No export engine found for edited photo "${photoInfo.title}" of type "${type}"${alpha ? " with alpha channel" : ""}`);
|
|
1155
1459
|
return engine;
|
|
1156
1460
|
}
|
|
1157
1461
|
/**
|
|
1462
|
+
* Whether a photo's original has transparency. An original that can't be
|
|
1463
|
+
* inspected, such as a camera raw format ImageMagick doesn't know, is taken to
|
|
1464
|
+
* have none, so that it doesn't stop the export.
|
|
1465
|
+
*/
|
|
1466
|
+
async function originalHasTransparency(photoInfo) {
|
|
1467
|
+
try {
|
|
1468
|
+
return await hasAlpha(photoInfo.original.filePath);
|
|
1469
|
+
} catch (error) {
|
|
1470
|
+
log.debug(`Could not check "${photoInfo.original.fileName}" for transparency, assuming it has none: ${error instanceof Error ? error.message : String(error)}`);
|
|
1471
|
+
return false;
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
/**
|
|
1475
|
+
* Whether swift-render will deal with transparency itself, by keeping it or by
|
|
1476
|
+
* flattening it onto a chosen color, instead of leaving it to be flattened onto
|
|
1477
|
+
* white
|
|
1478
|
+
*/
|
|
1479
|
+
function rendersTransparency(options) {
|
|
1480
|
+
return options.background !== void 0 || options.preserveAlpha && (options.format === "png" || options.format === "tiff");
|
|
1481
|
+
}
|
|
1482
|
+
/**
|
|
1158
1483
|
* Export a single album to a folder Optionally sync the output directory with
|
|
1159
1484
|
* the album, deleting any images that are no longer in the album Optionally
|
|
1160
1485
|
* audit the album for duplicate titles Does NOT further process the images
|
|
@@ -1176,19 +1501,23 @@ const defaultManageMetadataOptions = {
|
|
|
1176
1501
|
/**
|
|
1177
1502
|
* Manage metadata for a batch of photos
|
|
1178
1503
|
*/
|
|
1179
|
-
async function manageMetadataBatch(identifiers, targetFilePaths,
|
|
1504
|
+
async function manageMetadataBatch(identifiers, targetFilePaths, { exportOptions, exportResults, options } = {}) {
|
|
1180
1505
|
const photoInfos = await resolveIdentifiers(identifiers);
|
|
1181
1506
|
if (photoInfos.length !== targetFilePaths.length) throw new Error("Photo infos and target files length mismatch");
|
|
1182
1507
|
return Promise.all(photoInfos.map(async (photoInfo, index) => {
|
|
1183
1508
|
const targetFilePath = targetFilePaths[index];
|
|
1184
1509
|
if (targetFilePath === void 0) throw new Error(`Missing target file path for photo "${photoInfo.uuid}"`);
|
|
1185
|
-
return manageMetadata(photoInfo, targetFilePath,
|
|
1510
|
+
return manageMetadata(photoInfo, targetFilePath, {
|
|
1511
|
+
exportOptions,
|
|
1512
|
+
exportResult: exportResults?.[index],
|
|
1513
|
+
options
|
|
1514
|
+
});
|
|
1186
1515
|
}));
|
|
1187
1516
|
}
|
|
1188
1517
|
/**
|
|
1189
|
-
*
|
|
1518
|
+
* Carry metadata over to one exported photo, as configured in `options`
|
|
1190
1519
|
*/
|
|
1191
|
-
async function manageMetadata(identifier, targetFilePath,
|
|
1520
|
+
async function manageMetadata(identifier, targetFilePath, { exportOptions, exportResult, options } = {}) {
|
|
1192
1521
|
const resolvedOptions = mergeDefaults(options, defaultManageMetadataOptions);
|
|
1193
1522
|
const photoInfo = await resolvePhotoIdentifier(identifier);
|
|
1194
1523
|
let tagsToTarget;
|
|
@@ -1196,6 +1525,7 @@ async function manageMetadata(identifier, targetFilePath, options, exportOptions
|
|
|
1196
1525
|
let tagsToEdited;
|
|
1197
1526
|
if (photoInfo.edited && resolvedOptions.syncToEdited) tagsToEdited = await cloneTags(photoInfo.original.filePath, photoInfo.edited.filePath, resolvedOptions.tagsToSync);
|
|
1198
1527
|
if (exportOptions !== void 0 && resolvedOptions.writeAphexMetadata) await setTags(targetFilePath, { aphexMetadata: {
|
|
1528
|
+
...exportResult,
|
|
1199
1529
|
exportOptions,
|
|
1200
1530
|
photoInfo
|
|
1201
1531
|
} });
|
|
@@ -1249,7 +1579,7 @@ async function resizePngToFit(imagePath, destinationDirectory, maxWidth, maxHeig
|
|
|
1249
1579
|
return destinationImagePath;
|
|
1250
1580
|
}
|
|
1251
1581
|
/**
|
|
1252
|
-
*
|
|
1582
|
+
* Convert an image to a JPEG
|
|
1253
1583
|
*/
|
|
1254
1584
|
async function convertToJpeg(sourceImagePath, destinationDirectory, quality, force = false, engine = "mozjpeg") {
|
|
1255
1585
|
const mime = lookupImageMimeType(sourceImagePath, [
|
|
@@ -1774,7 +2104,7 @@ async function getDestinationFiles(destinationDirectory) {
|
|
|
1774
2104
|
*
|
|
1775
2105
|
* TODO how to handle non-image files?
|
|
1776
2106
|
*/
|
|
1777
|
-
async function getSyncPlanForImages(identifiers, destinationDirectory,
|
|
2107
|
+
async function getSyncPlanForImages(identifiers, destinationDirectory, { exportOptions, options } = {}) {
|
|
1778
2108
|
const resolvedOptions = mergeDefaults(options, defaultSyncOptions);
|
|
1779
2109
|
const resolvedExportOptions = mergeDefaults(exportOptions, defaultExportOptions);
|
|
1780
2110
|
const photoInfos = await resolveIdentifiers(identifiers);
|
|
@@ -1818,9 +2148,17 @@ async function getSyncPlanForImages(identifiers, destinationDirectory, options,
|
|
|
1818
2148
|
return syncResult;
|
|
1819
2149
|
}
|
|
1820
2150
|
/**
|
|
2151
|
+
* The options an export was made with are kept as JSON in the exported file.
|
|
2152
|
+
* JSON drops options that are `undefined`, so current options only compare
|
|
2153
|
+
* equal to stored ones after the same round trip.
|
|
2154
|
+
*/
|
|
2155
|
+
function asStored(options) {
|
|
2156
|
+
return JSON.parse(JSON.stringify(options));
|
|
2157
|
+
}
|
|
2158
|
+
/**
|
|
1821
2159
|
* See if there's a difference between the source image and the target image
|
|
1822
2160
|
*
|
|
1823
|
-
* @returns
|
|
2161
|
+
* @returns The first strategy that found a difference, or false if none did
|
|
1824
2162
|
*/
|
|
1825
2163
|
async function isDifferent(diffStrategies, sourcePhotoInfo, sourcePhotoFileBaseName, matchPhotoFilePath, matchPhotoTags, exportOptions, forceUpdate) {
|
|
1826
2164
|
if (forceUpdate) return "force-update";
|
|
@@ -1830,14 +2168,14 @@ async function isDifferent(diffStrategies, sourcePhotoInfo, sourcePhotoFileBaseN
|
|
|
1830
2168
|
case "exif-tags":
|
|
1831
2169
|
sourceTags ??= await getTags(sourcePhotoInfo.original.filePath);
|
|
1832
2170
|
return matchPhotoTags === void 0 || sourceTags.credit !== matchPhotoTags.credit || sourceTags.creator !== matchPhotoTags.creator || sourceTags.description !== matchPhotoTags.description || sourceTags.preservedFileName !== matchPhotoTags.preservedFileName || sourceTags.label !== matchPhotoTags.label;
|
|
1833
|
-
case "export-options": return matchPhotoTags === void 0 || !deepEqual(exportOptions.exportOptions, matchPhotoTags.aphexMetadata?.exportOptions.exportOptions);
|
|
2171
|
+
case "export-options": return matchPhotoTags === void 0 || matchPhotoTags.aphexMetadata?.exportDegraded === true || !deepEqual(asStored(exportOptions.exportOptions), matchPhotoTags.aphexMetadata?.exportOptions.exportOptions);
|
|
1834
2172
|
case "file-name": return stripExtension(path.basename(matchPhotoFilePath)) !== sourcePhotoFileBaseName;
|
|
1835
2173
|
case "force-update": return true;
|
|
1836
2174
|
case "metadata-options":
|
|
1837
2175
|
sourceTags ??= await getTags(sourcePhotoInfo.original.filePath);
|
|
1838
|
-
return matchPhotoTags === void 0 || !deepEqual(exportOptions.metadataOptions, matchPhotoTags.aphexMetadata?.exportOptions.metadataOptions);
|
|
2176
|
+
return matchPhotoTags === void 0 || !deepEqual(asStored(exportOptions.metadataOptions), matchPhotoTags.aphexMetadata?.exportOptions.metadataOptions);
|
|
1839
2177
|
case "photo-info": return matchPhotoTags === void 0 || !deepEqual(sourcePhotoInfo, matchPhotoTags.aphexMetadata?.photoInfo);
|
|
1840
|
-
case "process-options": return matchPhotoTags === void 0 || !deepEqual(exportOptions.processOptions, matchPhotoTags.aphexMetadata?.exportOptions.processOptions);
|
|
2178
|
+
case "process-options": return matchPhotoTags === void 0 || !deepEqual(asStored(exportOptions.processOptions), matchPhotoTags.aphexMetadata?.exportOptions.processOptions);
|
|
1841
2179
|
}
|
|
1842
2180
|
}
|
|
1843
2181
|
for (const diffStrategy of diffStrategies) if (await strategyFindsDifference(diffStrategy)) return diffStrategy;
|
|
@@ -1845,8 +2183,8 @@ async function isDifferent(diffStrategies, sourcePhotoInfo, sourcePhotoFileBaseN
|
|
|
1845
2183
|
}
|
|
1846
2184
|
// src/index.ts
|
|
1847
2185
|
/**
|
|
1848
|
-
*
|
|
1849
|
-
* Exported for unplugin-aphex.
|
|
2186
|
+
* Fill in everything a partial `ExportOptions` object leaves out with the
|
|
2187
|
+
* library defaults. Exported for unplugin-aphex.
|
|
1850
2188
|
*/
|
|
1851
2189
|
function mergeDefaultExportOptions(options) {
|
|
1852
2190
|
return mergeDefaults(options, defaultExportOptions);
|
|
@@ -1871,7 +2209,14 @@ const defaultExportOptions = {
|
|
|
1871
2209
|
syncOptions: defaultSyncOptions
|
|
1872
2210
|
};
|
|
1873
2211
|
/**
|
|
1874
|
-
* Export a single photo
|
|
2212
|
+
* Export a single photo from the Photos.app library to a directory.
|
|
2213
|
+
*
|
|
2214
|
+
* @param identifier A photo's UUID, a path like `Album/Title` or
|
|
2215
|
+
* `Folder/Album/IMG_1234.jpeg`, or a `PhotoInfo` from `getPhotoInfo`.
|
|
2216
|
+
* @param destinationDirectory Created if it doesn't exist. A leading `~` is
|
|
2217
|
+
* expanded.
|
|
2218
|
+
* @param options Anything left out falls back to the library defaults.
|
|
2219
|
+
* @throws {Error} If the identifier matches no photo, or more than one.
|
|
1875
2220
|
*/
|
|
1876
2221
|
async function exportPhoto(identifier, destinationDirectory, options) {
|
|
1877
2222
|
const result = await exportPhotos([await resolvePhotoIdentifier(identifier)], destinationDirectory, options);
|
|
@@ -1879,7 +2224,23 @@ async function exportPhoto(identifier, destinationDirectory, options) {
|
|
|
1879
2224
|
return result[0];
|
|
1880
2225
|
}
|
|
1881
2226
|
/**
|
|
1882
|
-
* Export photos
|
|
2227
|
+
* Export any number of photos and albums from the Photos.app library to a
|
|
2228
|
+
* directory.
|
|
2229
|
+
*
|
|
2230
|
+
* Each photo goes through the stages that are enabled in `options`: checking
|
|
2231
|
+
* whether an up-to-date export already exists, exporting from Photos.app,
|
|
2232
|
+
* processing, and writing metadata.
|
|
2233
|
+
*
|
|
2234
|
+
* @param identifiers Any mix of photo and album identifiers: UUIDs, paths like
|
|
2235
|
+
* `Album/Title` or `Folder/Album`, and `PhotoInfo` or `AlbumInfo` objects. An
|
|
2236
|
+
* album stands for every photo in it.
|
|
2237
|
+
* @param destinationDirectory Created if it doesn't exist. A leading `~` is
|
|
2238
|
+
* expanded.
|
|
2239
|
+
* @param options Anything left out falls back to the library defaults.
|
|
2240
|
+
*
|
|
2241
|
+
* @returns One result per photo, in a flat list. A photo that is identified
|
|
2242
|
+
* more than once is exported once.
|
|
2243
|
+
* @throws {Error} If the identifiers match no photos.
|
|
1883
2244
|
*/
|
|
1884
2245
|
async function exportPhotos(identifiers, destinationDirectory, options) {
|
|
1885
2246
|
const resolvedOptions = mergeDefaultExportOptions(options);
|
|
@@ -1888,8 +2249,10 @@ async function exportPhotos(identifiers, destinationDirectory, options) {
|
|
|
1888
2249
|
const photoInfos = await resolveIdentifiers(identifiers);
|
|
1889
2250
|
let syncResult;
|
|
1890
2251
|
if (syncOptions !== "disabled") {
|
|
1891
|
-
syncResult = await getSyncPlanForImages(photoInfos, resolvedDestinationDirectory,
|
|
1892
|
-
|
|
2252
|
+
syncResult = await getSyncPlanForImages(photoInfos, resolvedDestinationDirectory, {
|
|
2253
|
+
exportOptions: resolvedOptions,
|
|
2254
|
+
options: syncOptions
|
|
2255
|
+
});
|
|
1893
2256
|
if (syncResult.plan.length !== photoInfos.length) throw new Error("Sync plan length does not match photos length");
|
|
1894
2257
|
}
|
|
1895
2258
|
const exportResults = photoInfos.map((photoInfo, index) => {
|
|
@@ -1906,7 +2269,10 @@ async function exportPhotos(identifiers, destinationDirectory, options) {
|
|
|
1906
2269
|
}
|
|
1907
2270
|
};
|
|
1908
2271
|
});
|
|
1909
|
-
if (exportResults.every((exportResult) => exportResult.results.syncResult?.status === "unchanged"))
|
|
2272
|
+
if (exportResults.every((exportResult) => exportResult.results.syncResult?.status === "unchanged")) {
|
|
2273
|
+
await deleteStaleFiles(syncResult?.toDelete, exportResults);
|
|
2274
|
+
return exportResults;
|
|
2275
|
+
}
|
|
1910
2276
|
const seenBaseNames = /* @__PURE__ */ new Set();
|
|
1911
2277
|
let hasCollision = false;
|
|
1912
2278
|
for (const exportResult of exportResults) {
|
|
@@ -1949,16 +2315,58 @@ async function exportPhotos(identifiers, destinationDirectory, options) {
|
|
|
1949
2315
|
}
|
|
1950
2316
|
if (metadataOptions !== "disabled") {
|
|
1951
2317
|
const targetPhotos = exportResults.filter((exportResult) => exportResult.results.syncResult?.status !== "unchanged");
|
|
1952
|
-
const metadataResults = await manageMetadataBatch(targetPhotos.map((exportResult) => exportResult.photoInfo), targetPhotos.map((exportResult) => exportResult.path),
|
|
2318
|
+
const metadataResults = await manageMetadataBatch(targetPhotos.map((exportResult) => exportResult.photoInfo), targetPhotos.map((exportResult) => exportResult.path), {
|
|
2319
|
+
exportOptions: resolvedOptions,
|
|
2320
|
+
exportResults: targetPhotos.map((exportResult) => exportResult.results.exportResult),
|
|
2321
|
+
options: metadataOptions
|
|
2322
|
+
});
|
|
1953
2323
|
for (const exportResult of exportResults) {
|
|
1954
2324
|
const matchingMetadataResult = metadataResults.find((photoExportResult) => photoExportResult.photoInfo.uuid === exportResult.photoInfo.uuid);
|
|
1955
2325
|
if (matchingMetadataResult) exportResult.results.metadataResult = cleanMetadataResults(matchingMetadataResult);
|
|
1956
2326
|
}
|
|
1957
2327
|
}
|
|
2328
|
+
await deleteStaleFiles(syncResult?.toDelete, exportResults);
|
|
1958
2329
|
return exportResults;
|
|
1959
2330
|
}
|
|
2331
|
+
/**
|
|
2332
|
+
* Delete the files a sync plan marked for deletion, now that the export has
|
|
2333
|
+
* gone through.
|
|
2334
|
+
*
|
|
2335
|
+
* A file that a result points to stays, since a new export can take the place
|
|
2336
|
+
* of an old one under the same name. So does an out-of-date export that nothing
|
|
2337
|
+
* took the place of.
|
|
2338
|
+
*/
|
|
2339
|
+
async function deleteStaleFiles(toDelete, exportResults) {
|
|
2340
|
+
if (toDelete === void 0 || toDelete.length === 0) return;
|
|
2341
|
+
const keep = /* @__PURE__ */ new Set();
|
|
2342
|
+
for (const { path: resultPath, results } of exportResults) {
|
|
2343
|
+
const identity = resultPath === "" ? void 0 : await getFileIdentity(resultPath);
|
|
2344
|
+
const staleIdentity = identity === void 0 && results.syncResult?.matchFilePath !== void 0 ? await getFileIdentity(results.syncResult.matchFilePath) : void 0;
|
|
2345
|
+
for (const kept of [identity, staleIdentity]) if (kept !== void 0) keep.add(kept);
|
|
2346
|
+
}
|
|
2347
|
+
for (const file of toDelete) {
|
|
2348
|
+
const identity = await getFileIdentity(file);
|
|
2349
|
+
if (identity !== void 0 && !keep.has(identity)) await fse.rm(file, { force: true });
|
|
2350
|
+
}
|
|
2351
|
+
}
|
|
2352
|
+
/**
|
|
2353
|
+
* A string that is the same for every path that leads to one file
|
|
2354
|
+
*
|
|
2355
|
+
* @returns Undefined if there is no file at the path
|
|
2356
|
+
*/
|
|
2357
|
+
async function getFileIdentity(filePath) {
|
|
2358
|
+
try {
|
|
2359
|
+
const { dev, ino } = await fse.stat(filePath, { bigint: true });
|
|
2360
|
+
return `${dev}:${ino}`;
|
|
2361
|
+
} catch {
|
|
2362
|
+
return;
|
|
2363
|
+
}
|
|
2364
|
+
}
|
|
1960
2365
|
function cleanExportResults(result) {
|
|
1961
|
-
return {
|
|
2366
|
+
return {
|
|
2367
|
+
exportDegraded: result.exportDegraded,
|
|
2368
|
+
exportEngine: result.exportEngine
|
|
2369
|
+
};
|
|
1962
2370
|
}
|
|
1963
2371
|
function cleanMetadataResults(result) {
|
|
1964
2372
|
const { photoInfo: _, ...rest } = result;
|