Coverage for src/photo_path_utils.py: 100%
141 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 03:08 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 03:08 +0000
1"""Photo path utils
2 Extract filename and extension from photo.
4 Args:
5 photo: Photo object from iCloudPy
6 file_size: File size variant (original, medium, thumb, etc.)
8 Returns:
9 Tuple of (name, extension) where name is filename without extension
10 and extension is the file extension.
12This module contains utilities for generating photo file paths and managing
13file naming conventions for photo synchronization.
14"""
16___author___ = "Mandar Patil <mandarons@pm.me>"
18import base64
19import os
20import re
21import unicodedata
22from urllib.parse import unquote
24from src import get_logger
26LOGGER = get_logger()
28# The Live Photo paired-video file_size variants. These are QuickTime movies,
29# not images, even though the parent asset's filename ends in .HEIC/.JPG.
30_LIVE_VIDEO_SIZES = frozenset({"live_video_original", "live_video_medium", "live_video_thumb"})
33def get_photo_name_and_extension(photo, file_size: str) -> tuple[str, str]:
34 """Extract filename and extension from photo.
36 Args:
37 photo: Photo object from iCloudPy
38 file_size: File size variant (original, medium, thumb, etc.)
40 Returns:
41 Tuple of (name, extension) where name is filename without extension
42 and extension is the file extension
43 """
44 # Decode URL-encoded filename from iCloud API
45 # This handles special characters like %CC%88 (combining diacritical marks)
46 filename = unquote(photo.filename)
47 name, extension = filename.rsplit(".", 1) if "." in filename else [filename, ""]
49 # Renditions whose container differs from the asset filename: the
50 # RAW/JPEG pair alternate (``original_alt``) and Apple's rendered edit
51 # (``full``), which can be HEIC or JPEG regardless of what the original
52 # was -- and, for an edited video, QuickTime or MPEG-4. Derive the
53 # extension from the version's own MIME type, not the name.
54 if file_size in ("original_alt", "full") and file_size in photo.versions:
55 filetype = photo.versions[file_size].get("type")
56 mapped = _get_image_filetype_mapping().get(filetype)
57 # A ``full`` rendition can be a movie (a trimmed or otherwise edited
58 # video), whose container belongs to the video mapping.
59 if mapped is None and file_size == "full":
60 mapped = _get_video_filetype_mapping().get(filetype)
61 if mapped is None:
62 LOGGER.warning(
63 f"Unknown filetype {filetype} for {file_size} version of {filename}",
64 )
65 else:
66 extension = mapped
68 # Handle Live Photo paired-video versions. photo.filename is the STILL
69 # (e.g. IMG_1234.HEIC), but the live_video_* versions are the QuickTime
70 # movie half of the Live Photo. Without this the .mov is written with the
71 # still's extension (IMG_1234__live_video_original__<id>.HEIC), which every
72 # downstream image tool then rejects as "unsupported image format" because
73 # it is really a video. Map to the real container extension instead.
74 elif file_size in _LIVE_VIDEO_SIZES and file_size in photo.versions:
75 filetype = photo.versions[file_size].get("type")
76 extension = _get_video_filetype_mapping().get(filetype, "MOV")
78 return name, extension
81# Module-level toggle for hiding untouched originals of edited photos via
82# the ``.original.bak`` suffix convention. ``sync_photos`` sets this once
83# per sync run from ``photos.preserve_originals_as_bak``.
84_PRESERVE_ORIGINALS_AS_BAK = False
87def set_preserve_originals_as_bak(value: bool) -> None:
88 """Set the module-level toggle for hiding untouched originals via .original.bak."""
89 global _PRESERVE_ORIGINALS_AS_BAK
90 _PRESERVE_ORIGINALS_AS_BAK = bool(value)
93# The rendition fields Apple writes to the ``CPLAsset`` record for an edit:
94# the still (``resJPEGFullRes``) and the movie (``resVidFullRes``). A ``full``
95# that icloudpy read from the ``CPLMaster`` record is a different thing -- the
96# display render iCloud generates for formats it does not show natively (PNG,
97# RAW, GIF, some MP4) -- and those assets were never edited.
98_EDIT_RENDITION_PREFIXES = ("resJPEGFull", "resVidFull")
101def version_record_id(photo, file_size: str) -> str:
102 """ID of the CloudKit record a version's bytes come from.
104 ``photo.id`` is the ``CPLMaster`` record, which every copy of a photo
105 shares: Photos' Duplicate, and editors such as Snapseed that save an
106 edit as a new photo, add a ``CPLAsset`` pointing at the same master.
107 Each copy's edit lives on its own asset record, so naming (or
108 hardlinking) an asset-carried version after the master gives every
109 copy's edit the same identity, and they overwrite one another on disk
110 and download again every sync. Master-carried versions keep
111 ``photo.id``, and so does every original (``resOriginal*``) whatever
112 record carries it, so no original's name ever changes.
114 Soft check: anything unexpected falls back to ``photo.id``.
115 """
116 try:
117 asset_record = getattr(photo, "_asset_record", None)
118 if not isinstance(asset_record, dict) or not asset_record.get("recordName"):
119 return photo.id
120 lookup = photo.VIDEO_VERSION_LOOKUP if photo.item_type == "movie" else photo.PHOTO_VERSION_LOOKUP
121 prefix = lookup.get(file_size)
122 if prefix and prefix.startswith("resOriginal"):
123 return photo.id
124 if prefix and f"{prefix}Res" in (asset_record.get("fields") or {}):
125 return asset_record["recordName"]
126 except Exception: # noqa: BLE001 - naming must not break on a partial record
127 pass
128 return photo.id
131# Extensions that name the same JPEG container; ``IMG_1.JPG`` and a JPEG edit
132# of it must be recognised as colliding even though the strings differ.
133_JPEG_EXTENSIONS = frozenset({"jpg", "jpeg"})
136def photo_has_edit(photo) -> bool:
137 """Check whether the asset has an edited (``full``) version on iCloud.
139 The signal is ``resJPEGFullRes`` / ``resVidFullRes`` on the ``CPLAsset``
140 record. icloudpy reads versions asset-first and falls back to the
141 ``CPLMaster`` record per version, so ``"full" in photo.versions`` is not
142 enough: a master-carried ``full`` is Apple's display rendition for a
143 format it does not render natively (PNG screenshots, RAW, GIF, some MP4),
144 not an edit. ``original_alt`` is the RAW/JPEG pair alternate, not an edit,
145 so it must not be treated as one here.
147 Soft check -- exceptions are treated as "no edit" so a partial CloudKit
148 record cannot break the filename pipeline. An object that does not expose
149 ``_asset_record`` as a dict (test doubles, older icloudpy objects) keeps
150 the previous ``"full" in versions`` answer.
151 """
152 try:
153 asset_record = getattr(photo, "_asset_record", None)
154 if isinstance(asset_record, dict):
155 fields = asset_record.get("fields") or {}
156 return any(f"{prefix}Res" in fields for prefix in _EDIT_RENDITION_PREFIXES)
157 return "full" in photo.versions
158 except Exception:
159 return False
162# When both the untouched original and the edit are requested, a plain
163# filename format (``simple``, or a user template that omits
164# ``${photo.file_size}``) can resolve both versions to the same name.
165# ``sync_photos`` sets this once per run so the edit gets a marker instead of
166# silently overwriting the original.
167_ADJUSTED_SUFFIX = False
170def set_adjusted_suffix(value: bool) -> None:
171 """Set whether the edit needs a ``-adjusted`` marker to stay distinct."""
172 global _ADJUSTED_SUFFIX
173 _ADJUSTED_SUFFIX = bool(value)
176def _same_image_container(left: str, right: str) -> bool:
177 """Whether two extensions name the same container (``jpg`` == ``jpeg``)."""
178 left, right = left.lower(), right.lower()
179 if left in _JPEG_EXTENSIONS and right in _JPEG_EXTENSIONS:
180 return True
181 return left == right
184def _adjusted_name_suffix(photo, file_size: str) -> str:
185 """Return the ``-adjusted`` marker for an edit that would collide.
187 Applies only to ``full`` when both ``original`` and ``full`` were
188 requested *and* the two resolve to the same container: a HEIC original
189 plus a JPEG edit already have distinct filenames and need no marker, but
190 ``.JPG`` and ``.jpeg`` are one container and do.
191 """
192 if not (_ADJUSTED_SUFFIX and file_size == "full"):
193 return ""
194 original_extension = get_photo_name_and_extension(photo, "original")[1]
195 edit_extension = get_photo_name_and_extension(photo, file_size)[1]
196 return "-adjusted" if _same_image_container(original_extension, edit_extension) else ""
199_TEMPLATE_TOKEN_RE = re.compile(r"\$\{([^}]+)\}")
200_DEFAULT_FILENAME_FORMAT = "metadata"
203def set_default_filename_format(filename_format: str) -> None:
204 """Set the module-level default filename format. See get_photos_filename_format."""
205 global _DEFAULT_FILENAME_FORMAT
206 if filename_format in ("metadata", "simple"):
207 _DEFAULT_FILENAME_FORMAT = filename_format
210# Module-level toggle for hiding untouched originals of edited photos via
211# the ``.original.bak`` suffix convention. ``sync_photos`` sets this once
212# per sync run from ``photos.preserve_originals_as_bak``.
213def get_default_filename_format() -> str:
214 """Read the current module-level default filename format.
216 Public accessor so callers in other modules can observe live updates
217 from ``set_default_filename_format`` without reaching into the
218 underscore-prefixed module global (which violates SLF001).
219 """
220 return _DEFAULT_FILENAME_FORMAT
223# photos.file_format: a single template applied to EVERY downloaded version
224# (mirrors folder_format). None means "no template; use filename_format".
225_FILE_FORMAT: str | None = None
226_VARIANT_SEPARATOR = "_"
227# Versions that are the "primary" copy and get no variant tag in ${photo.variant*}.
228_PRIMARY_VERSIONS = frozenset({"original", "full"})
231def set_file_format(template: str | None, variant_separator: str = "_") -> None:
232 """Set the single filename template + variant separator (photos.file_format)."""
233 global _FILE_FORMAT, _VARIANT_SEPARATOR
234 _FILE_FORMAT = template or None
235 _VARIANT_SEPARATOR = variant_separator if variant_separator is not None else "_"
238def get_file_format() -> str | None:
239 """Read the single filename template (public accessor; avoids SLF001)."""
240 return _FILE_FORMAT
243def render_filename_template(template: str, photo, file_size: str, record_id: str | None = None) -> str:
244 """Render photos.file_format for one photo version.
246 Tokens (unknown ones left literal): ``${photo.filename}`` ``${photo.ext}``
247 ``${photo.id}`` (base64url asset id) ``${photo.file_size}`` and the
248 created-date parts ``${photo.year}`` ``${photo.month}`` ``${photo.day}``.
250 Variant tokens are empty for the primary versions (original/full) and the
251 version name otherwise: ``${photo.variant}`` (bare, e.g. ``medium``) and
252 ``${photo.variant_suffix}`` (separator + variant, e.g. ``_medium``) so the
253 separator only appears when there actually is a variant. ``full`` counts
254 as a variant when ``original`` is requested in the same run, so a template
255 cannot resolve the edit and the original to one name.
256 """
257 name, extension = get_photo_name_and_extension(photo, file_size)
258 if record_id is None:
259 record_id = version_record_id(photo, file_size)
260 created = getattr(photo, "created", None)
261 # ``full`` is a primary only while it is the sole copy requested; with
262 # ``original`` also in the list the template needs a distinct variant so
263 # the two files cannot land on the same name.
264 is_primary = file_size in _PRIMARY_VERSIONS and not (
265 _ADJUSTED_SUFFIX and file_size == "full"
266 )
267 variant = "" if is_primary else file_size
268 variant_suffix = "" if is_primary else f"{_VARIANT_SEPARATOR}{file_size}"
269 values = {
270 "photo.filename": name,
271 "photo.ext": extension,
272 "photo.id": base64.urlsafe_b64encode(record_id.encode()).decode(),
273 "photo.file_size": file_size,
274 "photo.variant": variant,
275 "photo.variant_suffix": variant_suffix,
276 "photo.year": f"{created.year:04d}" if created else "",
277 "photo.month": f"{created.month:02d}" if created else "",
278 "photo.day": f"{created.day:02d}" if created else "",
279 }
281 def _sub(match: re.Match) -> str:
282 token = match.group(1).strip()
283 replacement = values.get(token)
284 return replacement if replacement is not None else match.group(0)
286 return _TEMPLATE_TOKEN_RE.sub(_sub, template)
289def generate_photo_filename_with_metadata(
290 photo,
291 file_size: str,
292 filename_format: str | None = None,
293 record_id: str | None = None,
294) -> str:
295 """Generate filename for a photo asset.
297 Two conventions (controlled by ``filename_format`` or module default):
298 - ``"metadata"`` (default): ``name__filesize__base64id.extension``
299 - ``"simple"``: ``name.extension``
301 In ``simple`` mode, when both ``original`` and ``full`` are requested and
302 both resolve to the same extension, the edit gains a ``-adjusted`` marker
303 (``IMG_1234-adjusted.jpeg``) so it cannot overwrite the original.
305 When ``_PRESERVE_ORIGINALS_AS_BAK`` is on AND this is the ``original``
306 size AND the asset has an edited (``full``) version on iCloud, the
307 filename ends with ``.original.bak`` so photo browsers skip it but the
308 file remains filesystem-recoverable.
310 Works uniformly across both ``filename_format`` modes — the
311 ``.original.bak`` qualifier is appended to whatever the base filename
312 would have been (``name__filesize__base64id.ext`` in metadata mode or
313 ``name.ext`` in simple mode).
315 Args:
316 photo: Photo object from iCloudPy
317 file_size: File size variant (original, medium, thumb, etc.)
318 filename_format: ``"metadata"`` or ``"simple"``, or ``None`` to
319 use the module-level default.
320 record_id: ID to encode in the name; ``None`` (the default) uses
321 ``version_record_id``. Passing ``photo.id`` gives the name an
322 asset-carried version had before it was named after its own
323 record, so existing files can be moved rather than re-downloaded.
325 Returns:
326 Filename string in the chosen format, plus ``.original.bak`` suffix
327 when the bak-preservation toggle applies to this file. The bak suffix
328 is appended AFTER the base filename is composed, so it works the same
329 whether the base came from ``simple`` (``IMG_1234.HEIC``) or
330 ``metadata`` (``IMG_1234__original__<id>.HEIC``) mode.
331 """
332 forced = filename_format # explicit value; None means a normal (non-fallback) call
333 if filename_format is None:
334 filename_format = _DEFAULT_FILENAME_FORMAT
335 name, extension = get_photo_name_and_extension(photo, file_size)
336 if record_id is None:
337 record_id = version_record_id(photo, file_size)
339 # photos.file_format wins for normal calls; the collision fallback passes
340 # filename_format="metadata" explicitly to force the always-unique name.
341 if forced != "metadata" and _FILE_FORMAT is not None:
342 rendered = render_filename_template(_FILE_FORMAT, photo, file_size, record_id)
343 if rendered.strip():
344 return rendered
345 # Defensive: a template that renders empty for this version (e.g. a bare
346 # ${photo.variant} on an original) would otherwise yield a path pointing
347 # at the directory. Fall back to filename_format instead.
348 LOGGER.warning(
349 f"photos.file_format rendered an empty name for {file_size}; falling back to {filename_format} naming.",
350 )
352 if filename_format == "simple":
353 name = f"{name}{_adjusted_name_suffix(photo, file_size)}"
354 result = name if extension == "" else f"{name}.{extension}"
355 else:
356 photo_id_encoded = base64.urlsafe_b64encode(record_id.encode()).decode()
357 if extension == "":
358 result = f"{'__'.join([name, file_size, photo_id_encoded])}"
359 else:
360 result = f"{'__'.join([name, file_size, photo_id_encoded])}.{extension}"
362 # Apply .original.bak hide-suffix when applicable. Uniformly handled for
363 # both filename_format modes — simple+bak yields IMG_1234.HEIC.original.bak,
364 # metadata+bak yields IMG_1234__original__<id>.HEIC.original.bak.
365 if _PRESERVE_ORIGINALS_AS_BAK and file_size == "original" and photo_has_edit(photo):
366 result = f"{result}.original.bak"
368 return result
371def resolve_folder_path(destination_path: str, folder_format: str | None, photo) -> str:
372 """Compute the folder path for a photo WITHOUT touching the filesystem.
374 Same result as ``create_folder_path_if_needed`` but never creates the
375 directory. Read-only callers (e.g. the ``--dry-run`` migration checker)
376 use this so a preview never writes to disk.
378 Args:
379 destination_path: Base destination path
380 folder_format: strftime format string for folder creation (e.g., "%Y/%m")
381 photo: Photo object with created date
383 Returns:
384 Full destination path including the created-date folder if folder_format is set
385 """
386 if folder_format is None:
387 return destination_path
388 folder = photo.created.strftime(folder_format)
389 return os.path.join(destination_path, folder)
392def create_folder_path_if_needed(
393 destination_path: str, folder_format: str | None, photo,
394) -> str:
395 """Resolve the folder path and create it on disk if folder_format is set.
397 Args:
398 destination_path: Base destination path
399 folder_format: strftime format string for folder creation (e.g., "%Y/%m")
400 photo: Photo object with created date
402 Returns:
403 Full destination path including created folder if folder_format is specified
404 """
405 full_destination = resolve_folder_path(destination_path, folder_format, photo)
406 if folder_format is not None:
407 os.makedirs(full_destination, exist_ok=True)
408 return full_destination
411def normalize_file_path(file_path: str) -> str:
412 """Normalize file path using Unicode NFC normalization.
414 Args:
415 file_path: File path to normalize
417 Returns:
418 Normalized file path
419 """
420 return unicodedata.normalize("NFC", file_path)
423def rename_legacy_file_if_exists(old_path: str, new_path: str) -> None:
424 """Rename legacy file format to new format if it exists.
426 Args:
427 old_path: Path to legacy file format
428 new_path: Path to new file format
429 """
430 import os
432 # Without folder_format, a "legacy" flat path can be the file's current
433 # path. There is nothing to move, and warning about it would fire for
434 # every existing file on every run.
435 if old_path == new_path or not os.path.isfile(old_path):
436 return
437 if os.path.isfile(new_path):
438 LOGGER.warning(f"Renaming {old_path} over existing {new_path}")
439 else:
440 LOGGER.info(f"Renaming {old_path} -> {new_path}")
441 os.rename(old_path, new_path)
444def _get_video_filetype_mapping() -> dict:
445 """Get mapping of Live Photo paired-video Apple UTI types to extensions.
447 Live Photo videos are QuickTime movies; iCloud reports the UTI in the
448 version's ``type`` field. Anything not listed falls back to ``MOV`` (the
449 only container Apple has ever used for the Live Photo motion component).
451 Returns:
452 Dictionary mapping Apple UTI type strings to file extensions
453 """
454 return {
455 "com.apple.quicktime-movie": "MOV",
456 "public.mpeg-4": "MP4",
457 }
460def _get_image_filetype_mapping() -> dict:
461 """Get mapping of Apple image UTI types to file extensions.
463 Used for renditions whose container may differ from the asset filename:
464 the RAW/JPEG pair alternate and Apple's rendered edit (usually HEIC,
465 JPEG for older edits, and a movie container for an edited video).
467 Returns:
468 Dictionary mapping file types to extensions
469 """
470 return {
471 "public.png": "png",
472 "public.jpeg": "jpeg",
473 "public.heic": "heic",
474 "public.image": "HEIC",
475 "com.sony.arw-raw-image": "arw",
476 "org.webmproject.webp": "webp",
477 "com.compuserve.gif": "gif",
478 "com.adobe.raw-image": "dng",
479 "public.tiff": "tiff",
480 "public.jpeg-2000": "jp2",
481 "com.truevision.tga-image": "tga",
482 "com.sgi.sgi-image": "sgi",
483 "com.adobe.photoshop-image": "psd",
484 "public.pbm": "pbm",
485 "public.heif": "heif",
486 "com.microsoft.bmp": "bmp",
487 "com.fuji.raw-image": "raf",
488 "com.canon.cr2-raw-image": "cr2",
489 "com.panasonic.rw2-raw-image": "rw2",
490 "com.nikon.nrw-raw-image": "nrw",
491 "com.pentax.raw-image": "pef",
492 "com.nikon.raw-image": "nef",
493 "com.olympus.raw-image": "orf",
494 "com.adobe.pdf": "pdf",
495 "com.canon.cr3-raw-image": "cr3",
496 "com.olympus.or-raw-image": "orf",
497 "public.mpo-image": "mpo",
498 "com.dji.mimo.pano.jpeg": "jpg",
499 "public.avif": "avif",
500 "com.canon.crw-raw-image": "crw",
501 }