Coverage for src/photo_file_utils.py: 100%
213 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 file operations module.
3This module contains utilities for photo file operations including
4downloading, hardlink creation, and file existence checking.
5"""
7___author___ = "Mandar Patil <mandarons@pm.me>"
9import contextlib
10import json
11import os
12import shutil
13import threading
14from datetime import UTC
15from typing import Any
16from urllib.parse import urlencode
18from src import DEFAULT_REQUEST_TIMEOUT_SEC, get_logger, served_size_ledger
19from src.photo_path_utils import version_record_id
21LOGGER = get_logger()
23# Module-level lock to protect thread-safe mutation of photo._versions during retries
24_versions_refresh_lock = threading.Lock()
26# Consecutive download-URL refresh failures, and how often to escalate them to WARNING.
27# Downloads run in parallel, so the counter is guarded by its own lock.
28_refresh_failure_lock = threading.Lock()
29_consecutive_refresh_failures = 0
30_REFRESH_FAILURE_WARN_INTERVAL = 3
32# CloudKit fields to request when re-fetching a photo record for fresh download URLs.
33# Mirrors the desiredKeys list used by icloudpy's PhotoAlbum._list_query_gen().
34_DESIRED_KEYS = [
35 "resJPEGFullWidth",
36 "resJPEGFullHeight",
37 "resJPEGFullFileType",
38 "resJPEGFullFingerprint",
39 "resJPEGFullRes",
40 "resJPEGLargeWidth",
41 "resJPEGLargeHeight",
42 "resJPEGLargeFileType",
43 "resJPEGLargeFingerprint",
44 "resJPEGLargeRes",
45 "resJPEGMedWidth",
46 "resJPEGMedHeight",
47 "resJPEGMedFileType",
48 "resJPEGMedFingerprint",
49 "resJPEGMedRes",
50 "resJPEGThumbWidth",
51 "resJPEGThumbHeight",
52 "resJPEGThumbFileType",
53 "resJPEGThumbFingerprint",
54 "resJPEGThumbRes",
55 "resVidFullWidth",
56 "resVidFullHeight",
57 "resVidFullFileType",
58 "resVidFullFingerprint",
59 "resVidFullRes",
60 "resVidMedWidth",
61 "resVidMedHeight",
62 "resVidMedFileType",
63 "resVidMedFingerprint",
64 "resVidMedRes",
65 "resVidSmallWidth",
66 "resVidSmallHeight",
67 "resVidSmallFileType",
68 "resVidSmallFingerprint",
69 "resVidSmallRes",
70 "resSidecarWidth",
71 "resSidecarHeight",
72 "resSidecarFileType",
73 "resSidecarFingerprint",
74 "resSidecarRes",
75 "itemType",
76 "dataClassType",
77 "filenameEnc",
78 "originalOrientation",
79 "resOriginalWidth",
80 "resOriginalHeight",
81 "resOriginalFileType",
82 "resOriginalFingerprint",
83 "resOriginalRes",
84 "resOriginalAltWidth",
85 "resOriginalAltHeight",
86 "resOriginalAltFileType",
87 "resOriginalAltFingerprint",
88 "resOriginalAltRes",
89 "resOriginalVidComplWidth",
90 "resOriginalVidComplHeight",
91 "resOriginalVidComplFileType",
92 "resOriginalVidComplFingerprint",
93 "resOriginalVidComplRes",
94 "isDeleted",
95 "isExpunged",
96 "dateExpunged",
97 "remappedRef",
98 "recordName",
99 "recordType",
100 "recordChangeTag",
101 "masterRef",
102 "adjustmentRenderType",
103 "assetDate",
104 "addedDate",
105 "isFavorite",
106 "isHidden",
107 "orientation",
108 "duration",
109 "assetSubtype",
110 "assetSubtypeV2",
111 "assetHDRType",
112 "burstFlags",
113 "burstFlagsExt",
114 "burstId",
115 "captionEnc",
116 "extendedDescEnc",
117 "locationEnc",
118 "locationV2Enc",
119 "locationLatitude",
120 "locationLongitude",
121 "adjustmentType",
122 "timeZoneOffset",
123 "vidComplDurValue",
124 "vidComplDurScale",
125 "vidComplDispValue",
126 "vidComplDispScale",
127 "vidComplVisibilityState",
128 "customRenderedValue",
129 "containerId",
130 "itemId",
131 "position",
132 "isKeyAsset",
133 "importedByBundleIdentifierEnc",
134 "importedByDisplayNameEnc",
135 "importedBy",
136]
139def _note_refresh_success() -> None:
140 """Reset the consecutive refresh-failure streak after a successful refresh."""
141 global _consecutive_refresh_failures # noqa: PLW0603
142 with _refresh_failure_lock:
143 _consecutive_refresh_failures = 0
146def _note_refresh_failure(record_name: str, reason: str) -> None:
147 """Record a failed URL refresh, escalating to WARNING once failures repeat.
149 URL refresh is the last line of defence before a download is abandoned, so a
150 systematically broken refresh path (rather than an occasional miss) should be
151 visible without turning on debug logging. Individual failures stay at DEBUG;
152 every ``_REFRESH_FAILURE_WARN_INTERVAL`` consecutive failures emits a WARNING.
154 Args:
155 record_name: CloudKit recordName of the photo being refreshed
156 reason: Human-readable description of why the refresh failed
157 """
158 global _consecutive_refresh_failures # noqa: PLW0603
159 with _refresh_failure_lock:
160 _consecutive_refresh_failures += 1
161 failures = _consecutive_refresh_failures
163 if failures % _REFRESH_FAILURE_WARN_INTERVAL == 0:
164 LOGGER.warning(
165 f"Download URL refresh has failed {failures} times in a row - expired-URL (HTTP 410) "
166 f"recovery is not working, so affected photos will be reported as failed downloads. "
167 f"Most recent failure: {record_name} - {reason}",
168 )
169 else:
170 LOGGER.debug(f"Failed to refresh download URL for {record_name}: {reason}")
173def _refresh_photo_download_url(photo, timeout: int = DEFAULT_REQUEST_TIMEOUT_SEC) -> bool:
174 """Re-fetch the photo's CloudKit records from iCloud for fresh download URLs.
176 iCloud download URLs are signed CDN tokens that expire after ~30–40 minutes.
177 When a URL expires (HTTP 410 Gone), clearing ``photo._versions`` alone is
178 insufficient because icloudpy re-parses the same stale records which still
179 contain the expired URL. This function makes a ``records/lookup`` API call
180 for the records that carry renditions -- the ``CPLMaster`` record and, for
181 an edited asset, the ``CPLAsset`` record whose ``resJPEGFull*`` fields hold
182 the edit's URL -- then updates them in place and clears ``_versions`` so
183 the next ``download()`` call uses the fresh URLs.
185 The two records have different ``recordName``s (the asset record links to
186 the master through ``masterRef``), so looking up only the master leaves the
187 ``full`` URL stale and an edited photo never recovers from a 410.
189 ``records/lookup`` is used rather than ``records/query`` because ``CPLMaster``
190 is not a query-indexable CloudKit type: querying it fails every time with
191 ``Type is not marked indexable: CPLMaster (BAD_REQUEST)``. Lookup fetches
192 records by name and returns the same ``{"records": [...]}`` shape.
194 Args:
195 photo: PhotoAsset object from icloudpy
196 timeout: HTTP read timeout in seconds for the lookup POST. Without
197 one a stalled connection blocks the calling worker forever,
198 the same hang the download timeout fixed for transfers.
200 Returns:
201 True if every record that carries a rendition was refreshed, False
202 otherwise.
203 """
204 try:
205 record_name = photo._master_record["recordName"] # noqa: SLF001
206 # The record's own zone. icloudpy gives every asset the photos
207 # service, whose zone is always the primary library, so a Shared
208 # Library asset looked up there is never found.
209 record_zone = photo._master_record.get("zoneID") # noqa: SLF001
210 except (AttributeError, KeyError, TypeError):
211 _note_refresh_failure("<unknown>", "photo missing _master_record or recordName")
212 return False
214 # The edited rendition lives on the asset (``CPLAsset``) record, which has
215 # its own ``recordName`` -- CloudKit links it to the master through
216 # ``masterRef``, and the two names differ. Refreshing only the master
217 # leaves a stale ``full`` URL, so the retry hits 410 again and the photo is
218 # reported as a failed download.
219 asset_record = getattr(photo, "_asset_record", None)
220 asset_name = asset_record.get("recordName") if isinstance(asset_record, dict) else None
221 asset_fields = (asset_record.get("fields") or {}) if isinstance(asset_record, dict) else {}
222 # Only ask for the asset record when it carries a rendition: an unedited
223 # asset's record holds dates and metadata, not download URLs.
224 needs_asset = bool(
225 asset_name
226 and asset_name != record_name
227 and any(key.endswith("Res") for key in asset_fields),
228 )
229 record_names = [record_name]
230 if needs_asset:
231 record_names.append(asset_name)
233 service = getattr(photo, "_service", None)
234 if service is None:
235 _note_refresh_failure(record_name, "photo missing _service")
236 return False
238 endpoint = getattr(service, "_service_endpoint", None)
239 session = getattr(service, "session", None)
240 params = getattr(service, "params", None)
241 zone_id = record_zone if isinstance(record_zone, dict) and record_zone else getattr(service, "zone_id", None)
243 if not all([endpoint, session, params, zone_id]):
244 _note_refresh_failure(record_name, "photo._service missing required attributes")
245 return False
247 try:
248 url = f"{endpoint}/records/lookup?{urlencode(params)}"
249 query = {
250 "records": [{"recordName": name} for name in record_names],
251 "desiredKeys": _DESIRED_KEYS,
252 "zoneID": zone_id,
253 }
254 request = session.post(
255 url,
256 data=json.dumps(query),
257 headers={"Content-type": "text/plain"},
258 timeout=timeout,
259 )
260 response = request.json()
261 records = response.get("records", [])
263 # A failed lookup is not an HTTP error: CloudKit returns it as a
264 # record inside ``records`` carrying the requested recordName and a
265 # ``serverErrorCode``/``reason`` in place of ``fields``. Matching on
266 # the name alone therefore accepts an error payload as a fresh
267 # record -- the refresh reports success, and the retrying download
268 # raises KeyError('fields') deep inside icloudpy, which surfaces as an
269 # unexplained "Failed to download <path>: 'fields'" and is charged to
270 # the download rather than to the refresh.
271 #
272 # An empty ``fields`` is no better than a missing one: icloudpy builds
273 # ``versions`` by testing ``f"{prefix}Res" in fields``, so an empty
274 # dict yields no versions at all, ``download()`` returns None, and the
275 # caller dereferences ``.raw`` on it. Accepting either shape also
276 # discards the still-valid record we already hold, poisoning the asset
277 # for the rest of the sync.
278 #
279 # Failures are collected per record so a master that refreshed is not
280 # thrown away because the asset lookup failed for an unedited photo --
281 # and, conversely, a stale ``full`` URL never reports success.
282 refreshed = {}
283 failures = {}
284 for rec in records:
285 name = rec.get("recordName")
286 if name not in record_names:
287 continue
288 if rec.get("serverErrorCode"):
289 failures[name] = (
290 f"CloudKit error {rec['serverErrorCode']}: "
291 f"{rec.get('reason') or 'no reason given'}"
292 )
293 continue
294 if not rec.get("fields"):
295 failures[name] = "record came back with no usable fields"
296 continue
297 refreshed[name] = rec
299 if record_name not in refreshed:
300 _note_refresh_failure(
301 record_name,
302 failures.get(record_name, "record not found in iCloud response"),
303 )
304 return False
305 if needs_asset and asset_name is not None and asset_name not in refreshed:
306 _note_refresh_failure(
307 asset_name,
308 failures.get(asset_name, "record not found in iCloud response"),
309 )
310 return False
312 photo._master_record = refreshed[record_name] # noqa: SLF001
313 if asset_name in refreshed:
314 photo._asset_record = refreshed[asset_name] # noqa: SLF001
315 with _versions_refresh_lock:
316 photo._versions = None # noqa: SLF001
317 LOGGER.debug(f"Refreshed download URL for {record_name}")
318 _note_refresh_success()
319 return True
321 except Exception as e: # noqa: BLE001
322 _note_refresh_failure(record_name, str(e))
323 return False
326def _ledger_key(photo: Any, file_size: str) -> tuple[str, str] | None:
327 """The ledger key for this rendition, or None when the photo has no id.
329 Ledger bookkeeping must never fail a transfer that already verified: a
330 partial/mock photo object without ``id`` simply gets no exception entry.
331 """
332 try:
333 return version_record_id(photo, file_size), file_size
334 except (AttributeError, KeyError, TypeError):
335 return None
338def check_photo_exists(photo, file_size: str, local_path: str) -> bool:
339 """Check if photo exists locally with correct size.
341 Args:
342 photo: Photo object from iCloudPy
343 file_size: File size variant (original, medium, thumb, etc.)
344 local_path: Local file path to check
346 Returns:
347 True if photo exists locally with correct size, False otherwise
348 """
349 if not (photo and local_path and os.path.isfile(local_path)):
350 return False
352 local_size = os.path.getsize(local_path)
353 remote_size = int(photo.versions[file_size]["size"])
355 if local_size == remote_size:
356 LOGGER.debug(f"No changes detected. Skipping the file {local_path} ...")
357 return True
359 # A complete response whose byte count differed from the declared size was
360 # kept by the download path. Recognise it here too, or every sync would
361 # treat the file as missing and download it again forever. The entry pins
362 # both sizes, so a changed declaration or a different file length does not
363 # inherit the exception.
364 key = _ledger_key(photo, file_size)
365 if key is not None and served_size_ledger.matches(*key, remote_size, local_size):
366 LOGGER.debug(
367 f"No changes detected. Skipping the file {local_path}: it matches the "
368 f"accepted {local_size}-byte transfer for a declared {remote_size} bytes.",
369 )
370 return True
372 LOGGER.debug(f"Change detected: local_file_size is {local_size} and remote_file_size is {remote_size}.")
373 return False
376def create_hardlink(source_path: str, destination_path: str) -> bool:
377 """Create a hard link from source to destination.
379 Args:
380 source_path: Path to existing file to link from
381 destination_path: Path where hardlink should be created
383 Returns:
384 True if hardlink was created successfully, False otherwise
385 """
386 try:
387 # Ensure destination directory exists
388 os.makedirs(os.path.dirname(destination_path), exist_ok=True)
389 # Create hard link
390 os.link(source_path, destination_path)
391 LOGGER.info(f"Created hard link: {destination_path} (linked to existing file: {source_path})")
392 return True
393 except (OSError, FileNotFoundError) as e:
394 LOGGER.warning(f"Failed to create hard link {destination_path}: {e!s}")
395 return False
398def _asset_record_id(photo: Any) -> str | None:
399 """The asset record's id when icloudpy carries one, else the master id."""
400 record = getattr(photo, "_asset_record", None)
401 if isinstance(record, dict) and record.get("recordName"):
402 return record["recordName"]
403 try:
404 return photo.id
405 except (AttributeError, KeyError):
406 return None
409def _note_failure(
410 failure: dict | None,
411 photo: Any,
412 file_size: str,
413 path: str,
414 reason: str,
415 declared: int | None,
416 received: int | None,
417) -> None:
418 """Fill the caller's failure record, if it asked for one."""
419 if failure is None:
420 return
421 failure.update(
422 path=path,
423 file_size=file_size,
424 asset_id=_asset_record_id(photo),
425 reason=reason,
426 declared_bytes=declared,
427 received_bytes=received,
428 )
431def _header_value(response: Any, name: str) -> str | None:
432 """Return a response header as text, or None when absent/unreadable."""
433 try:
434 value = response.headers.get(name)
435 except AttributeError: # pragma: no cover - a response without headers
436 return None
437 return value if isinstance(value, str) else None
440def _content_length(response: Any) -> int | None:
441 """Return the response's own Content-Length, or None when it does not say."""
442 value = _header_value(response, "Content-Length")
443 try:
444 return int(value) if value is not None else None
445 except ValueError:
446 return None
449def _transfer_is_complete(response: Any, written: int) -> bool:
450 """Whether a size-mismatching body is nonetheless a complete transfer.
452 iCloud's declared size can be stale for a ``full`` rendition whose signed
453 URL serves a different encoding. Accept that body only when the response
454 is a success, is not content-encoded (so the bytes on disk are the bytes
455 Content-Length describes), and its own Content-Length equals what was
456 written. Anything else stays a failure rather than risking a partial file
457 or an error page being recorded as the photo.
458 """
459 status = getattr(response, "status_code", None)
460 if isinstance(status, int) and status >= 400:
461 return False
462 encoding = (_header_value(response, "Content-Encoding") or "").lower()
463 if encoding not in ("", "identity"):
464 return False
465 served = _content_length(response)
466 return served is not None and served == written
469def _finalize_download(photo: Any, partial: str, destination_path: str) -> None:
470 """Move a verified transfer into place and stamp the photo's added date."""
471 os.replace(partial, destination_path)
473 # Set file modification time to photo's added date.
474 # iCloudPy returns added_date as an aware UTC datetime; replace() is a
475 # safe no-op here because tzinfo is already UTC. If it ever returns a
476 # naive datetime, replace(tzinfo=utc) correctly treats it as UTC.
477 local_modified_time = photo.added_date.replace(tzinfo=UTC).timestamp()
478 os.utime(destination_path, (local_modified_time, local_modified_time))
481def download_photo_from_server(
482 photo,
483 file_size: str,
484 destination_path: str,
485 max_retries: int = 1,
486 timeout: int = DEFAULT_REQUEST_TIMEOUT_SEC,
487 failure: dict | None = None,
488) -> bool:
489 """Download photo from iCloud server to local path.
491 This function implements automatic retry logic for HTTP 410 (Gone) errors,
492 which occur when iCloud download URLs expire. When a 410 error is detected,
493 the function re-fetches the photo's master record from iCloud to obtain
494 fresh download URLs, then retries the download.
496 Args:
497 photo: Photo object from iCloudPy
498 file_size: File size variant (original, medium, thumb, etc.)
499 destination_path: Local path where photo should be saved
500 max_retries: Maximum number of retries on 410 errors (default: 1)
501 timeout: HTTP read timeout in seconds. Without one a stalled CDN
502 connection blocks the worker thread forever.
503 failure: Optional dict filled with the failure's asset id, reason and
504 declared/received byte counts when the transfer cannot be used.
506 Returns:
507 True if download was successful, False otherwise
508 """
509 if not (photo and file_size and destination_path):
510 return False
512 LOGGER.info(f"Downloading {destination_path} ...")
514 max_retries = max(0, max_retries) # Clamp to minimum 0 for predictable behavior
515 attempt = 0
516 max_attempts = max_retries + 1 # Initial attempt + retries
518 # Download beside the target and move it into place only once it is
519 # complete. Writing straight to destination_path left a failed transfer's
520 # partial file where the real photo belongs, where anything reading the
521 # library (an Immich external library, a backup) takes it for the photo,
522 # and it also destroyed the previous good copy before the new one existed.
523 # A partial stranded by a killed process is untracked, so obsolete-file
524 # cleanup removes it.
525 partial = f"{destination_path}.part"
527 while attempt < max_attempts: # noqa: PERF203
528 try:
529 download = photo.download(file_size, timeout=timeout)
530 with open(partial, "wb") as file_out:
531 shutil.copyfileobj(download.raw, file_out)
533 # iCloud declares every version's size, and photo_exists already
534 # treats a mismatch as "not this file". Check it here too, so a
535 # body that is short or is not the photo at all (an error page)
536 # fails now instead of being recorded as downloaded.
537 expected = _declared_size(photo, file_size)
538 written = os.path.getsize(partial)
539 if expected is not None and written != expected:
540 # The declared size can be stale for a ``full`` rendition
541 # whose signed URL serves a different encoding. A success
542 # response that carried exactly its own Content-Length is a
543 # complete transfer, so keep it rather than downloading it
544 # again on every sync; anything less complete stays a failure.
545 if _transfer_is_complete(download, written):
546 _finalize_download(photo, partial, destination_path)
547 key = _ledger_key(photo, file_size)
548 if key is not None:
549 served_size_ledger.record(*key, expected, written)
550 LOGGER.warning(
551 f"Accepted {destination_path}: iCloud declares {expected} bytes, "
552 f"but the served response is a complete {written}-byte transfer.",
553 )
554 return True
555 _discard(partial)
556 _note_failure(
557 failure, photo, file_size, destination_path, "size_mismatch", expected, written,
558 )
559 if failure is None:
560 LOGGER.error(
561 f"Incomplete download of {destination_path}: got {written} of {expected} bytes. "
562 "Will retry on the next sync.",
563 )
564 return False
565 _finalize_download(photo, partial, destination_path)
566 # The declared size matches again: drop any acceptance exception
567 # recorded for this rendition so it cannot outlive its cause.
568 key = _ledger_key(photo, file_size)
569 if key is not None:
570 served_size_ledger.forget(*key)
572 return True
574 except Exception as e: # noqa: PERF203
575 _discard(partial)
576 # Enhanced error logging with file path context
577 # This catches all exceptions including iCloudPy errors like ObjectNotFoundException
578 error_msg = str(e)
580 # Check for HTTP 410 Gone error - download URL has expired
581 # The iCloudPy library raises exceptions with "Gone (410)" in the message
582 # when the download URL has expired (typically after 30-40 minutes)
583 if "Gone (410)" in error_msg:
584 attempt += 1
585 if attempt < max_attempts:
586 LOGGER.warning(
587 f"Download URL expired (410) for {destination_path}. "
588 f"Refreshing URL and retrying (attempt {attempt}/{max_attempts})...",
589 )
590 # Re-fetch the master record from iCloud to obtain fresh download URLs.
591 # Simply clearing _versions is insufficient because icloudpy re-parses
592 # the same stale _master_record which still contains the expired URL.
593 _refresh_photo_download_url(photo, timeout=timeout)
594 continue
595 else:
596 _note_failure(
597 failure,
598 photo,
599 file_size,
600 destination_path,
601 "gone_410",
602 _declared_size(photo, file_size),
603 None,
604 )
605 LOGGER.error(
606 f"Failed to download {destination_path} after {max_retries} retries: {error_msg}",
607 )
608 return False
610 # Handle other errors
611 reason = "not_found" if "ObjectNotFoundException" in error_msg or "NOT_FOUND" in error_msg else "download_error"
612 _note_failure(
613 failure,
614 photo,
615 file_size,
616 destination_path,
617 reason,
618 _declared_size(photo, file_size),
619 None,
620 )
621 if reason == "not_found":
622 LOGGER.error(f"Photo not found in iCloud Photos - {destination_path}: {error_msg}")
623 else:
624 LOGGER.error(f"Failed to download {destination_path}: {error_msg}")
625 return False
627 # This line should never be reached due to the logic above, but is kept as defensive programming
628 return False # pragma: no cover
631def _declared_size(photo, file_size: str) -> int | None:
632 """The size iCloud declares for this version, or None if it does not say."""
633 try:
634 return int(photo.versions[file_size]["size"])
635 except (AttributeError, KeyError, TypeError, ValueError):
636 return None
639def _discard(path: str) -> None:
640 """Remove a partial download if one was written."""
641 with contextlib.suppress(FileNotFoundError):
642 os.remove(path)
645def rename_legacy_file_if_exists(old_path: str, new_path: str) -> None:
646 """Rename legacy file format to new format if it exists.
648 Args:
649 old_path: Path to legacy file format
650 new_path: Path to new file format
651 """
652 if os.path.isfile(old_path):
653 os.rename(old_path, new_path)