Coverage for src/sync_photos.py: 100%
303 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"""Sync photos module.
3This module provides the main photo synchronization functionality,
4orchestrating the downloading of photos from iCloud to local storage.
5"""
7___author___ = "Mandar Patil <mandarons@pm.me>"
9import os
11import requests
12from icloudpy import exceptions
14from src import config_parser, configure_icloudpy_logging, get_logger, recycle_bin
15from src.album_sync_orchestrator import sync_album_photos
16from src.download_report import log_download_summary, reset_download_report
17from src.hardlink_registry import create_hardlink_registry
18from src.photo_cleanup_utils import remove_obsolete_files
19from src.photo_path_utils import version_record_id
21# Configure icloudpy logging immediately after import
22configure_icloudpy_logging()
24LOGGER = get_logger()
27# Legacy functions preserved for backward compatibility with existing tests
28# These functions are now implemented using the new modular architecture
31def get_max_threads(config):
32 """Get maximum number of threads for parallel downloads.
34 Legacy function - now delegates to config_parser.
36 Args:
37 config: Configuration dictionary
39 Returns:
40 Maximum number of threads to use for downloads
41 """
42 return config_parser.get_app_max_threads(config)
45def get_name_and_extension(photo, file_size):
46 """Extract filename and extension.
48 Legacy function - now delegates to photo_path_utils.
50 Args:
51 photo: Photo object from iCloudPy
52 file_size: File size variant
54 Returns:
55 Tuple of (name, extension)
56 """
57 from src.photo_path_utils import get_photo_name_and_extension
59 return get_photo_name_and_extension(photo, file_size)
62def photo_wanted(photo, extensions):
63 """Check if photo is wanted based on extension.
65 Legacy function - now delegates to photo_filter_utils.
67 Args:
68 photo: Photo object from iCloudPy
69 extensions: List of allowed extensions
71 Returns:
72 True if photo should be synced, False otherwise
73 """
74 from src.photo_filter_utils import is_photo_wanted
76 return is_photo_wanted(photo, extensions)
79def generate_file_name(photo, file_size, destination_path, folder_format):
80 """Generate full path to file.
82 Legacy function - now delegates to photo_download_manager.
84 Args:
85 photo: Photo object from iCloudPy
86 file_size: File size variant
87 destination_path: Base destination path
88 folder_format: Folder format string
90 Returns:
91 Full file path
92 """
93 from src.photo_download_manager import generate_photo_path
95 return generate_photo_path(photo, file_size, destination_path, folder_format)
98def photo_exists(photo, file_size, local_path):
99 """Check if photo exist locally.
101 Legacy function - now delegates to photo_file_utils.
103 Args:
104 photo: Photo object from iCloudPy
105 file_size: File size variant
106 local_path: Local file path to check
108 Returns:
109 True if photo exists with correct size, False otherwise
110 """
111 from src.photo_file_utils import check_photo_exists
113 return check_photo_exists(photo, file_size, local_path)
116def create_hardlink(source_path, destination_path):
117 """Create a hard link from source to destination.
119 Legacy function - now delegates to photo_file_utils.
121 Args:
122 source_path: Path to source file
123 destination_path: Path for new hardlink
125 Returns:
126 True if successful, False otherwise
127 """
128 from src.photo_file_utils import create_hardlink as create_hardlink_impl
130 return create_hardlink_impl(source_path, destination_path)
133def download_photo(photo, file_size, destination_path):
134 """Download photo from server.
136 Legacy function - now delegates to photo_file_utils.
138 Args:
139 photo: Photo object from iCloudPy
140 file_size: File size variant
141 destination_path: Where to save the photo
143 Returns:
144 True if successful, False otherwise
145 """
146 from src.photo_file_utils import download_photo_from_server
148 return download_photo_from_server(photo, file_size, destination_path)
151def process_photo(photo, file_size, destination_path, files, folder_format, hardlink_registry=None):
152 """Process photo details (legacy function for backward compatibility).
154 Args:
155 photo: Photo object from iCloudPy
156 file_size: File size variant
157 destination_path: Base destination path
158 files: Set to track downloaded files
159 folder_format: Folder format string
160 hardlink_registry: Registry for hardlinks (legacy dict format)
162 Returns:
163 True if photo was processed successfully, False otherwise
164 """
165 from src.photo_download_manager import collect_download_task, execute_download_task
167 # Convert legacy hardlink registry dict to new registry format if needed
168 converted_registry = None
169 if hardlink_registry is not None:
170 from src.hardlink_registry import HardlinkRegistry
172 converted_registry = HardlinkRegistry()
173 for key, path in hardlink_registry.items():
174 # Legacy format: photo_id_file_size -> path
175 if "_" in key:
176 parts = key.rsplit("_", 1)
177 if len(parts) == 2:
178 photo_id, file_sz = parts
179 converted_registry.register_photo_path(photo_id, file_sz, path)
181 # Collect download task
182 task_info = collect_download_task(
183 photo,
184 file_size,
185 destination_path,
186 files,
187 folder_format,
188 converted_registry,
189 )
191 if task_info is None:
192 return False
194 # Execute task
195 result = execute_download_task(task_info)
197 # Update legacy registry if provided
198 if result and hardlink_registry is not None:
199 photo_key = f"{version_record_id(photo, file_size)}_{file_size}"
200 hardlink_registry[photo_key] = task_info.photo_path
202 return result
205def collect_photo_for_download(photo, file_size, destination_path, files, folder_format, hardlink_registry=None):
206 """Collect photo info for parallel download without immediately downloading.
208 Legacy function - now delegates to photo_download_manager.
210 Args:
211 photo: Photo object from iCloudPy
212 file_size: File size variant
213 destination_path: Base destination path
214 files: Set to track downloaded files
215 folder_format: Folder format string
216 hardlink_registry: Registry for hardlinks (legacy dict format)
218 Returns:
219 Download task info or None
220 """
221 from src.photo_download_manager import collect_download_task
223 # Convert legacy hardlink registry dict to new registry format if needed
224 converted_registry = None
225 if hardlink_registry is not None:
226 from src.hardlink_registry import HardlinkRegistry
228 converted_registry = HardlinkRegistry()
229 for key, path in hardlink_registry.items():
230 if "_" in key:
231 parts = key.rsplit("_", 1)
232 if len(parts) == 2:
233 photo_id, file_sz = parts
234 converted_registry.register_photo_path(photo_id, file_sz, path)
236 task_info = collect_download_task(
237 photo,
238 file_size,
239 destination_path,
240 files,
241 folder_format,
242 converted_registry,
243 )
245 if task_info is None:
246 return None
248 # Convert back to legacy format for compatibility
249 return {
250 "photo": task_info.photo,
251 "file_size": task_info.file_size,
252 "photo_path": task_info.photo_path,
253 "hardlink_source": task_info.hardlink_source,
254 "hardlink_registry": hardlink_registry,
255 }
258def download_photo_task(download_info):
259 """Download a single photo or create hardlink as part of parallel execution.
261 Legacy function - maintains original implementation for backward compatibility.
263 Args:
264 download_info: Dictionary with download task information
266 Returns:
267 True if successful, False otherwise
268 """
269 photo = download_info["photo"]
270 file_size = download_info["file_size"]
271 photo_path = download_info["photo_path"]
272 hardlink_source = download_info.get("hardlink_source")
273 hardlink_registry = download_info.get("hardlink_registry")
275 LOGGER.debug(f"[Thread] Starting processing of {photo_path}")
277 try:
278 # Try hardlink first if source exists
279 if hardlink_source:
280 if create_hardlink(hardlink_source, photo_path):
281 LOGGER.debug(f"[Thread] Created hardlink for {photo_path}")
282 return True
283 else:
284 # Fallback to download if hard link creation fails
285 LOGGER.warning(f"Hard link creation failed, downloading {photo_path} instead")
287 # Download the photo - this maintains the original function call for test compatibility
288 result = download_photo(photo, file_size, photo_path)
289 if result:
290 # Register for future hard links if enabled
291 if hardlink_registry is not None:
292 photo_key = f"{version_record_id(photo, file_size)}_{file_size}"
293 hardlink_registry[photo_key] = photo_path
294 LOGGER.debug(f"[Thread] Completed download of {photo_path}")
295 return result
296 except Exception as e:
297 LOGGER.error(f"[Thread] Failed to process {photo_path}: {e!s}")
298 return False
301def sync_album(
302 album,
303 destination_path,
304 file_sizes,
305 extensions=None,
306 files=None,
307 folder_format=None,
308 hardlink_registry=None,
309 config=None,
310):
311 """Sync given album.
313 Legacy function - now delegates to album_sync_orchestrator with conversion
314 for legacy hardlink registry format.
316 Args:
317 album: Album object from iCloudPy
318 destination_path: Path where photos should be saved
319 file_sizes: List of file size variants to download
320 extensions: List of allowed file extensions
321 files: Set to track downloaded files
322 folder_format: Folder format string
323 hardlink_registry: Registry for hardlinks (legacy dict format)
324 config: Configuration dictionary
326 Returns:
327 True on success, None on invalid input
328 """
329 # Convert legacy hardlink registry dict to new registry format if needed
330 converted_registry = None
331 if hardlink_registry is not None:
332 from src.hardlink_registry import HardlinkRegistry
334 converted_registry = HardlinkRegistry()
335 for key, path in hardlink_registry.items():
336 if "_" in key:
337 parts = key.rsplit("_", 1)
338 if len(parts) == 2:
339 photo_id, file_sz = parts
340 converted_registry.register_photo_path(photo_id, file_sz, path)
342 result = sync_album_photos(
343 album=album,
344 destination_path=destination_path,
345 file_sizes=file_sizes,
346 extensions=extensions,
347 files=files,
348 folder_format=folder_format,
349 hardlink_registry=converted_registry,
350 config=config,
351 )
353 # Update legacy registry if provided and new registry was created
354 if hardlink_registry is not None and converted_registry is not None:
355 # This is a simplified approach - in practice, we'd need to track new entries
356 # But for legacy compatibility, we'll maintain the existing behavior
357 pass
359 return result
362def remove_obsolete(destination_path, files):
363 """Remove local obsolete file.
365 Legacy function - now delegates to photo_cleanup_utils.
367 Args:
368 destination_path: Path to search for obsolete files
369 files: Set of files that should be kept
371 Returns:
372 Set of removed file paths
373 """
374 return remove_obsolete_files(destination_path, files)
377def sync_photos(config, photos):
378 """Sync all photos.
380 Main orchestration function that coordinates the entire photo sync process.
381 This function has been refactored to use the new modular architecture while
382 maintaining backward compatibility.
384 Args:
385 config: Configuration dictionary
386 photos: Photos object from iCloudPy
388 Returns:
389 Tuple of (total_successful, total_failed) download counts
390 """
391 # A new report per run: failures are reported once per asset per pass.
392 reset_download_report()
393 # Parse configuration using centralized config parser
394 destination_path = config_parser.prepare_photos_destination(config=config)
395 library_destinations = config_parser.get_photos_library_destinations(config=config)
396 # Apply the requested filename convention for this sync run. The module-level
397 # default in photo_path_utils flows down through generate_photo_path -> all
398 # downloads without requiring a per-call signature change.
399 from src.photo_path_utils import set_default_filename_format, set_file_format
400 set_default_filename_format(config_parser.get_photos_filename_format(config=config))
401 set_file_format(
402 config_parser.get_photos_file_format(config=config),
403 config_parser.get_photos_variant_separator(config=config),
404 )
405 filters = config_parser.get_photos_filters(config=config)
406 file_sizes = filters.get("file_sizes") or []
407 # preserve_originals_as_bak invariant: at least ONE visible file per
408 # photo must always land on disk. The suffix only hides ``original``
409 # behind ``.bak`` -- so if the edit (``full``) is not ALSO being
410 # downloaded, enabling the suffix would leave nothing visible. Gate the
411 # toggle on both ``preserve_originals_as_bak: true`` AND ``full`` in
412 # ``file_sizes``. ``original_alt`` is the RAW/JPEG pair alternate, not an
413 # edit, and no longer activates the toggle. If a photo is later removed
414 # from iCloud, the normal remove_obsolete sweep cascades to both the
415 # visible file AND the ``.bak`` sidecar (neither is in tracked_files, both
416 # get deleted) -- so there's no risk of orphan ``.bak`` files outliving
417 # their parent.
418 from src.photo_download_manager import set_fallback_to_original
419 from src.photo_path_utils import set_adjusted_suffix, set_preserve_originals_as_bak
421 set_preserve_originals_as_bak(
422 config_parser.get_photos_preserve_originals_as_bak(config=config)
423 and "full" in file_sizes,
424 )
425 # With both the original and the edit requested, a plain filename can
426 # resolve the two versions to one path; mark the edit so one cannot
427 # overwrite the other.
428 set_adjusted_suffix("original" in file_sizes and "full" in file_sizes)
429 # When ``original`` is itself requested it is downloaded on its own, so a
430 # fallback task for a missing size would target the same path and race that
431 # download. Only substitute when the original is not already in the list.
432 set_fallback_to_original(
433 bool(filters.get("fallback_to_original")) and "original" not in file_sizes,
434 )
435 files = set()
436 download_all = config_parser.get_photos_all_albums(config=config)
437 use_hardlinks = config_parser.get_photos_use_hardlinks(config=config)
438 libraries = filters["libraries"] if filters["libraries"] is not None else photos.libraries
439 folder_format = config_parser.get_photos_folder_format(config=config)
440 # The scope switch is inert without a format to apply; say so instead of
441 # leaving the user to wonder why their new key changed nothing.
442 if folder_format is None and not config_parser.get_photos_folder_format_in_albums(config=config):
443 LOGGER.info(
444 "photos.folder_format_in_albums is false, but photos.folder_format "
445 "is not set; album folders are already flat.",
446 )
448 # Initialize hard link registry using new modular approach
449 hardlink_registry = create_hardlink_registry(use_hardlinks)
451 total_successful, total_failed = 0, 0
452 # Libraries we could not read. They must be barred from the cleanup
453 # below: a library that failed contributes nothing to ``files``, so
454 # cleaning its destination would read as "the server has none of these"
455 # and delete every local copy.
456 failed_libraries: set = set()
457 libraries = _listed_libraries(photos, libraries, failed_libraries)
458 # Libraries Apple is still indexing. They are synced -- the listing is
459 # usually complete long before the index says so -- but, like a failed
460 # library, kept out of cleanup: an incomplete listing would read as
461 # deletions.
462 indexing_libraries = _libraries_still_indexing(photos, libraries)
464 # Special handling for "All Photos" when hardlinks are enabled
465 if use_hardlinks and download_all:
466 sub_successful, sub_failed = _sync_all_photos_first_for_hardlinks(
467 photos,
468 libraries,
469 destination_path,
470 filters,
471 files,
472 folder_format,
473 hardlink_registry,
474 config,
475 library_destinations=library_destinations,
476 failed_libraries=failed_libraries,
477 )
478 total_successful += sub_successful
479 total_failed += sub_failed
481 # Sync albums based on configuration
482 sub_successful, sub_failed = _sync_albums_by_configuration(
483 photos,
484 libraries,
485 download_all,
486 destination_path,
487 filters,
488 files,
489 folder_format,
490 hardlink_registry,
491 config,
492 library_destinations=library_destinations,
493 failed_libraries=failed_libraries,
494 )
495 total_successful += sub_successful
496 total_failed += sub_failed
498 # Clean up obsolete files if enabled. When per-library destinations are
499 # configured we walk each library's subdir independently, otherwise the
500 # legacy single-destination walk preserves backward compatibility.
501 if config_parser.get_photos_remove_obsolete(config=config):
502 marker_filename = config_parser.get_mount_marker_filename(config=config)
503 exclude = {marker_filename}
504 limit = config_parser.get_photos_obsolete_delete_limit_percent(config=config)
505 bin_ = recycle_bin.from_config(config, "photos")
506 if library_destinations:
507 for library in libraries:
508 if library in failed_libraries:
509 LOGGER.warning(
510 f"Skipping obsolete-file cleanup for {library}: it could not "
511 f"be read this run, so its local files cannot be verified.",
512 )
513 continue
514 if library in indexing_libraries:
515 LOGGER.warning(
516 f"Skipping obsolete-file cleanup for {library}: Apple is still "
517 f"indexing it, or its index could not be checked, so its "
518 f"listing may be incomplete.",
519 )
520 continue
521 lib_dest = _library_destination(destination_path, library, library_destinations)
522 if lib_dest == destination_path:
523 # An unmapped library falls through to the shared root,
524 # which holds every other library's tree -- and anything
525 # else the user keeps there. Cleaning it on behalf of one
526 # library would delete all of them. Apple invents
527 # libraries (backend migration zones), so this is reached
528 # by doing nothing wrong.
529 LOGGER.warning(
530 f"Skipping obsolete-file cleanup for {library}: it has no "
531 f"library_destinations entry, so its destination is the "
532 f"shared root and cleaning it would affect other libraries.",
533 )
534 continue
535 remove_obsolete_files(
536 lib_dest,
537 files,
538 exclude_filenames=exclude,
539 limit_percent=limit,
540 recycle_bin=bin_ and bin_.within(_bin_subfolder(lib_dest, destination_path, library)),
541 )
542 elif failed_libraries:
543 # One shared destination: ``files`` cannot say which library a
544 # path came from, so a single failure makes the whole set
545 # untrustworthy for deletion.
546 LOGGER.warning(
547 "Skipping obsolete-file cleanup: "
548 f"{len(failed_libraries)} library(ies) could not be read this run.",
549 )
550 elif indexing_libraries:
551 # Same reasoning: one shared destination cannot be cleaned while
552 # any library's listing may be incomplete.
553 LOGGER.warning(
554 "Skipping obsolete-file cleanup: Apple is still indexing (or could "
555 f"not be checked for) {', '.join(sorted(indexing_libraries))}, so the "
556 "listing may be incomplete.",
557 )
558 else:
559 remove_obsolete_files(
560 destination_path,
561 files,
562 exclude_filenames=exclude,
563 limit_percent=limit,
564 recycle_bin=bin_,
565 )
567 log_download_summary()
568 return total_successful, total_failed
571def _bin_subfolder(lib_dest: str, destination_path: str, library: str) -> str:
572 """Where a library's files go inside the shared Photos bin.
574 The library's folder under the Photos destination, as it appears on
575 disk, so a restore is the same relative move. A mapping that points
576 outside the destination has no such folder, so the library's own name
577 stands in for it.
578 """
579 relative = os.path.relpath(lib_dest, destination_path)
580 if relative == os.pardir or relative.startswith(os.pardir + os.sep):
581 return library
582 return relative
585def _library_destination(base_destination: str, library: str, library_destinations: dict) -> str:
586 """Resolve the on-disk destination for a given iCloud photo library.
588 When ``library_destinations`` provides a mapping for ``library``, joins
589 the configured subdirectory under ``base_destination`` and ensures the
590 directory exists. Otherwise returns ``base_destination`` unchanged
591 (preserving mandarons' legacy single-destination behaviour).
593 Library-name matching has three rules, in priority order:
595 1. **Exact match.** ``library_destinations[library]`` if present.
596 2. **Role alias for `SharedLibrary`.** Apple's modern iCloud Shared
597 Photo Library is exposed by icloudpy under a GUID-based zone name
598 like ``SharedSync-<guid>``. A config
599 key of ``SharedLibrary`` matches any zone whose name starts with
600 ``SharedSync-`` so users don't need to discover and hardcode the
601 per-account GUID. (Configs that already use the literal current
602 Apple zone name still work via rule 1.)
603 3. **Fallthrough.** Returns ``base_destination`` unchanged.
604 """
605 if not library_destinations:
606 return base_destination
607 # ``get`` returns None only when the key is absent -- the config parser
608 # coerces every configured value to str, so an explicit "" stays "".
609 # Key on ``is None`` (not falsiness) so an explicitly-mapped library
610 # always wins over the SharedLibrary alias and the default, honouring
611 # the rule 1 > rule 2 > rule 3 priority documented above.
612 subdir = library_destinations.get(library)
613 if subdir is None and library.startswith("SharedSync-"):
614 subdir = library_destinations.get("SharedLibrary")
615 if subdir is None:
616 return base_destination
617 dest = os.path.join(base_destination, subdir)
618 os.makedirs(dest, exist_ok=True)
619 return dest
622# An account can be shown libraries it never created -- zones left behind
623# by Apple's own backend migrations -- and some of them answer every query
624# with ZONE_NOT_FOUND or BAD_REQUEST. One of those must not be able to
625# abort the sync for the libraries that work.
626_LIBRARY_FAULTS = (exceptions.ICloudPyAPIResponseException, requests.exceptions.RequestException)
629def _signal_library(action: str, library: str, **kwargs) -> None:
630 """Publish per-library progress for the dashboard, best effort.
632 A library can take an hour, so "which one is running right now" is
633 only knowable while it runs. Wrapped because the web-signal module is
634 optional and a dashboard write must never affect the sync.
635 """
636 try:
637 from src import web_signals
639 getattr(web_signals, action)(library, **kwargs)
640 except Exception as e: # noqa: BLE001 -- reporting must not break syncing
641 LOGGER.debug(f"web_signals: {action} for {library} raised: {e!s}")
644def _libraries_still_indexing(photos, libraries) -> set:
645 """Names of the libraries to sync that Apple has not finished indexing.
647 icloudpy opens such a library when asked to and records how far Apple
648 got as ``indexing_state``. Only an explicit ``FINISHED`` counts as
649 finished: a missing or empty state is treated as still indexing,
650 since a partial listing would read as deletions.
652 Fails closed: if the libraries cannot be listed here, every one is
653 returned, because a later attempt in the same cycle can succeed and
654 would otherwise let cleanup run on a library whose state was never
655 seen. A configured library that is not listed is returned for the
656 same reason.
657 """
658 try:
659 available = photos.libraries
660 except _LIBRARY_FAULTS as e:
661 LOGGER.warning(
662 f"Could not check whether Apple has finished indexing the photo "
663 f"libraries ({e!s}); obsolete-file cleanup is skipped this cycle.",
664 )
665 return set(libraries)
666 indexing = set()
667 for name in libraries:
668 if name not in available:
669 indexing.add(name)
670 continue
671 # Anything but an explicit FINISHED, a missing or empty state
672 # included, keeps the library out of cleanup.
673 state = getattr(available[name], "indexing_state", None)
674 still_indexing = state != "FINISHED"
675 _signal_library("record_library_indexing", name, state=str(state) if still_indexing else None)
676 if still_indexing:
677 LOGGER.warning(
678 f"Apple is still indexing {name} ({state}). Downloading what it "
679 f"lists; obsolete-file cleanup waits until the index finishes.",
680 )
681 indexing.add(name)
682 return indexing
685def _listed_libraries(photos, libraries, failed_libraries) -> list:
686 """The configured libraries Apple lists; the others are failed, not fatal.
688 ``filters.libraries`` can name a library Apple no longer lists, such as
689 a Shared Library that was left. Looking one up raises a KeyError outside
690 the per-library isolation, which stopped Photos for every library. Each
691 one dropped here is barred from cleanup like any failed library.
693 If the libraries cannot be listed, all are kept, and each fails on its
694 own when it is synced.
695 """
696 try:
697 available = photos.libraries
698 except _LIBRARY_FAULTS:
699 return list(libraries)
700 listed = []
701 for library in libraries:
702 if library in available:
703 listed.append(library)
704 continue
705 _note_library_failure(library, "Apple does not list this library", failed_libraries)
706 _signal_library("record_library_finished", library, ok=False, error="Apple does not list this library")
707 return listed
710def _note_library_failure(library, error, failed_libraries) -> None:
711 """Record a library we could not read, and say so in the log.
713 Never silent: the count is reported as failures by the caller, and the
714 library is barred from obsolete-file cleanup so an unreadable library
715 can never be mistaken for an empty one.
716 """
717 LOGGER.error(f"Library {library} could not be synced, skipping it: {error!s}")
718 if failed_libraries is not None:
719 failed_libraries.add(library)
722def _sync_all_photos_first_for_hardlinks(
723 photos,
724 libraries,
725 destination_path,
726 filters,
727 files,
728 folder_format,
729 hardlink_registry,
730 config,
731 library_destinations: dict | None = None,
732 failed_libraries: set | None = None,
733) -> tuple[int, int]:
734 """Sync 'All Photos' album first to populate hardlink registry.
736 Args:
737 photos: Photos object from iCloudPy
738 libraries: List of photo libraries to sync
739 destination_path: Base destination path
740 filters: Photo filters configuration
741 files: Set to track downloaded files
742 folder_format: Folder format string
743 hardlink_registry: Registry for tracking downloaded files
744 config: Configuration dictionary
746 Returns:
747 Tuple of (total_successful, total_failed) download counts
748 """
749 for library in libraries:
750 try:
751 if library == "PrimarySync" and "All Photos" in photos.libraries[library].albums:
752 LOGGER.info("Syncing 'All Photos' album first for hard link reference...")
753 lib_dest = _library_destination(destination_path, library, library_destinations or {})
754 result = sync_album_photos(
755 album=photos.libraries[library].albums["All Photos"],
756 destination_path=os.path.join(lib_dest, "All Photos"),
757 file_sizes=filters["file_sizes"],
758 extensions=filters["extensions"],
759 files=files,
760 folder_format=folder_format,
761 hardlink_registry=hardlink_registry,
762 config=config,
763 )
764 if hardlink_registry:
765 LOGGER.info(
766 f"'All Photos' sync complete. Hard link registry populated with "
767 f"{hardlink_registry.get_registry_size()} reference files.",
768 )
769 if result is not None:
770 return result
771 break
772 except _LIBRARY_FAULTS as e:
773 _note_library_failure(library, e, failed_libraries)
774 return 0, 0
777def _folder_format_for_album(album_title: str, folder_format: str | None, config) -> str | None:
778 """Folder format to use inside one album directory.
780 ``photos.folder_format_in_albums`` only scopes ``folder_format``; it
781 never supplies a format of its own. When it is false, user albums are
782 written flat, while ``All Photos`` keeps the configured structure --
783 it is the whole-library view, not an album the user created, so
784 flattening it would collapse months of the entire library into one
785 directory. Subalbums receive their parent album's value through
786 ``sync_album_photos`` and so inherit the same choice.
787 """
788 if album_title == "All Photos":
789 return folder_format
790 if config_parser.get_photos_folder_format_in_albums(config=config):
791 return folder_format
792 return None
795def _sync_albums_by_configuration(
796 photos,
797 libraries,
798 download_all,
799 destination_path,
800 filters,
801 files,
802 folder_format,
803 hardlink_registry,
804 config,
805 library_destinations: dict | None = None,
806 failed_libraries: set | None = None,
807) -> tuple[int, int]:
808 """Sync albums based on configuration settings.
810 Args:
811 photos: Photos object from iCloudPy
812 libraries: List of photo libraries to sync
813 download_all: Whether to download all albums
814 destination_path: Base destination path
815 filters: Photo filters configuration
816 files: Set to track downloaded files
817 folder_format: Folder format string
818 hardlink_registry: Registry for tracking downloaded files
819 config: Configuration dictionary
821 Returns:
822 Tuple of (total_successful, total_failed) aggregated across all libraries
823 """
824 total_successful, total_failed = 0, 0
825 for library in libraries:
826 try:
827 _signal_library("record_library_started", library)
828 lib_dest = _library_destination(destination_path, library, library_destinations or {})
829 if download_all and library == "PrimarySync":
830 sub_successful, sub_failed = _sync_all_albums_except_filtered(
831 photos,
832 library,
833 filters,
834 lib_dest,
835 files,
836 folder_format,
837 hardlink_registry,
838 config,
839 )
840 elif filters["albums"] and library == "PrimarySync":
841 sub_successful, sub_failed = _sync_filtered_albums(
842 photos,
843 library,
844 filters,
845 lib_dest,
846 files,
847 folder_format,
848 hardlink_registry,
849 config,
850 )
851 elif filters["albums"]:
852 sub_successful, sub_failed = _sync_filtered_albums_in_library(
853 photos,
854 library,
855 filters,
856 lib_dest,
857 files,
858 folder_format,
859 hardlink_registry,
860 config,
861 )
862 else:
863 sub_successful, sub_failed = _sync_all_photos_in_library(
864 photos,
865 library,
866 lib_dest,
867 filters,
868 files,
869 folder_format,
870 hardlink_registry,
871 config,
872 )
873 total_successful += sub_successful
874 total_failed += sub_failed
875 _signal_library(
876 "record_library_finished",
877 library,
878 ok=True,
879 downloaded=sub_successful,
880 skipped=sub_failed,
881 )
882 # Per-iteration by design: isolating one library from the next is
883 # the whole point, so the handler cannot be hoisted out of the loop.
884 except _LIBRARY_FAULTS as e: # noqa: PERF203
885 _note_library_failure(library, e, failed_libraries)
886 _signal_library("record_library_finished", library, ok=False, error=str(e))
887 return total_successful, total_failed
890def _sync_all_albums_except_filtered(
891 photos,
892 library,
893 filters,
894 destination_path,
895 files,
896 folder_format,
897 hardlink_registry,
898 config,
899) -> tuple[int, int]:
900 """Sync all albums except those in the filter exclusion list.
902 Args:
903 photos: Photos object from iCloudPy
904 library: Library name to sync
905 filters: Photo filters configuration
906 destination_path: Base destination path
907 files: Set to track downloaded files
908 folder_format: Folder format string
909 hardlink_registry: Registry for tracking downloaded files
910 config: Configuration dictionary
912 Returns:
913 Tuple of (total_successful, total_failed) aggregated across all synced albums
914 """
915 total_successful, total_failed = 0, 0
916 for album in photos.libraries[library].albums.keys():
917 # Skip All Photos if we already synced it first
918 if hardlink_registry and album == "All Photos":
919 continue
920 if filters["albums"] and album in iter(filters["albums"]):
921 continue
922 result = sync_album_photos(
923 album=photos.libraries[library].albums[album],
924 destination_path=os.path.join(destination_path, album),
925 file_sizes=filters["file_sizes"],
926 extensions=filters["extensions"],
927 files=files,
928 folder_format=_folder_format_for_album(album, folder_format, config),
929 hardlink_registry=hardlink_registry,
930 config=config,
931 )
932 if result is not None:
933 sub_successful, sub_failed = result
934 total_successful += sub_successful
935 total_failed += sub_failed
936 return total_successful, total_failed
939def _sync_filtered_albums(
940 photos,
941 library,
942 filters,
943 destination_path,
944 files,
945 folder_format,
946 hardlink_registry,
947 config,
948) -> tuple[int, int]:
949 """Sync only albums specified in filters.
951 Args:
952 photos: Photos object from iCloudPy
953 library: Library name to sync
954 filters: Photo filters configuration
955 destination_path: Base destination path
956 files: Set to track downloaded files
957 folder_format: Folder format string
958 hardlink_registry: Registry for tracking downloaded files
959 config: Configuration dictionary
961 Returns:
962 Tuple of (total_successful, total_failed) aggregated across all synced albums
963 """
964 total_successful, total_failed = 0, 0
965 for album in iter(filters["albums"]):
966 result = sync_album_photos(
967 album=photos.libraries[library].albums[album],
968 destination_path=os.path.join(destination_path, album),
969 file_sizes=filters["file_sizes"],
970 extensions=filters["extensions"],
971 files=files,
972 folder_format=_folder_format_for_album(album, folder_format, config),
973 hardlink_registry=hardlink_registry,
974 config=config,
975 )
976 if result is not None:
977 sub_successful, sub_failed = result
978 total_successful += sub_successful
979 total_failed += sub_failed
980 return total_successful, total_failed
983def _sync_filtered_albums_in_library(
984 photos,
985 library,
986 filters,
987 destination_path,
988 files,
989 folder_format,
990 hardlink_registry,
991 config,
992) -> tuple[int, int]:
993 """Sync filtered albums in a specific library.
995 Args:
996 photos: Photos object from iCloudPy
997 library: Library name to sync
998 filters: Photo filters configuration
999 destination_path: Base destination path
1000 files: Set to track downloaded files
1001 folder_format: Folder format string
1002 hardlink_registry: Registry for tracking downloaded files
1003 config: Configuration dictionary
1005 Returns:
1006 Tuple of (total_successful, total_failed) aggregated across all synced albums
1007 """
1008 total_successful, total_failed = 0, 0
1009 for album in iter(filters["albums"]):
1010 if album in photos.libraries[library].albums:
1011 result = sync_album_photos(
1012 album=photos.libraries[library].albums[album],
1013 destination_path=os.path.join(destination_path, album),
1014 file_sizes=filters["file_sizes"],
1015 extensions=filters["extensions"],
1016 files=files,
1017 folder_format=_folder_format_for_album(album, folder_format, config),
1018 hardlink_registry=hardlink_registry,
1019 config=config,
1020 )
1021 if result is not None:
1022 sub_successful, sub_failed = result
1023 total_successful += sub_successful
1024 total_failed += sub_failed
1025 else:
1026 LOGGER.warning(f"Album {album} not found in {library}. Skipping the album {album} ...")
1027 return total_successful, total_failed
1030def _sync_all_photos_in_library(
1031 photos,
1032 library,
1033 destination_path,
1034 filters,
1035 files,
1036 folder_format,
1037 hardlink_registry,
1038 config,
1039) -> tuple[int, int]:
1040 """Sync all photos in a library.
1042 Args:
1043 photos: Photos object from iCloudPy
1044 library: Library name to sync
1045 destination_path: Base destination path
1046 filters: Photo filters configuration
1047 files: Set to track downloaded files
1048 folder_format: Folder format string
1049 hardlink_registry: Registry for tracking downloaded files
1050 config: Configuration dictionary
1052 Returns:
1053 Tuple of (total_successful, total_failed) download counts
1054 """
1055 result = sync_album_photos(
1056 album=photos.libraries[library].all,
1057 destination_path=os.path.join(destination_path, "all"),
1058 file_sizes=filters["file_sizes"],
1059 extensions=filters["extensions"],
1060 files=files,
1061 folder_format=folder_format,
1062 hardlink_registry=hardlink_registry,
1063 config=config,
1064 )
1065 if result is not None:
1066 return result
1067 return 0, 0