Skip to content

Photos

Bases: BaseService

Modern CloudKit-backed Photos service.

Source code in pyicloud/services/photos/service.py
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
class PhotosService(BaseService):
    """Modern CloudKit-backed Photos service."""

    def __init__(
        self,
        service_root: str,
        session: PyiCloudSession,
        params: dict[str, Any],
        upload_url: str | None,
        shared_streams_url: str | None,
        photos_upload_url: str | None = None,
        upload_hydration_timeout: float = UPLOAD_HYDRATION_TIMEOUT,
        upload_hydration_interval: float = UPLOAD_HYDRATION_INTERVAL,
    ) -> None:
        super().__init__(service_root=service_root, session=session, params=params)
        self.params.update({"remapEnums": True, "getCurrentSyncToken": True})
        private_endpoint = (
            f"{self.service_root}/database/1/com.apple.photos.cloud/production/private"
        )
        shared_endpoint = (
            f"{self.service_root}/database/1/com.apple.photos.cloud/production/shared"
        )
        self.service_endpoint = private_endpoint
        self._private_primary_zone: dict[str, str] | None = None
        self._private_primary_binding: tuple[Any, str] | None = None
        self._private_client = PhotosCloudKitClient(
            base_url=private_endpoint,
            session=session,
            base_params=self.params,
            upload_url=upload_url,
            photos_upload_url=photos_upload_url,
        )
        self._shared_client = PhotosCloudKitClient(
            base_url=shared_endpoint,
            session=session,
            base_params=self.params,
        )
        self._upload_url = upload_url
        self._photos_upload_url = photos_upload_url
        self._upload_hydration_timeout = upload_hydration_timeout
        self._upload_hydration_interval = upload_hydration_interval
        self._shared_streams_url = shared_streams_url
        self._libraries: "dict[str, BasePhotoLibrary | PhotoStreamLibrary] | None" = (
            None
        )
        self._legacy_service = None
        self._root_library: PhotoLibrary | None = None
        shared_streams_album_url = (
            f"{shared_streams_url}/{self.params['dsid']}/sharedstreams/webgetalbumslist"
            if shared_streams_url
            else None
        )

        # pylint: disable=import-outside-toplevel
        from .shared_streams import PhotoStreamLibrary

        self._shared_library: "PhotoStreamLibrary | None" = (
            PhotoStreamLibrary(
                self,
                shared_streams_url=shared_streams_album_url,
            )
            if shared_streams_album_url
            else None
        )

    def _get_root_library(self) -> PhotoLibrary:
        """Build the primary library lazily so shared-only callers still work."""
        if self._root_library is None:
            self._root_library = PhotoLibrary(
                self,
                zone_id=PRIMARY_ZONE,
                client=self._private_client
                if _can_use_typed_cloudkit(self.session)
                else None,
                asset_type=PhotoAsset,
                upload_url=self._upload_url,
                photos_upload_url=self._photos_upload_url,
                upload_hydration_timeout=self._upload_hydration_timeout,
                upload_hydration_interval=self._upload_hydration_interval,
                scope="private",
            )
        return self._root_library

    @property
    def private_client(self) -> PhotosCloudKitClient:
        """Return the private CloudKit client."""
        return self._private_client

    @property
    def private_primary_zone(self) -> dict[str, str] | None:
        """Passive observed private PrimarySync identity, bound to its account."""
        if self._private_primary_binding != (
            self.params.get("dsid"),
            self.service_endpoint,
        ):
            return None
        return (
            dict(self._private_primary_zone)
            if self._private_primary_zone is not None
            else None
        )

    @property
    def upload_root(self) -> str | None:
        """Return the observed modern Photos upload service route, without fallback."""
        return self._photos_upload_url

    @property
    def libraries(self) -> "dict[str, BasePhotoLibrary | PhotoStreamLibrary]":
        """Return the available photo libraries, discovering them on first access."""
        # pylint: disable=import-outside-toplevel

        if self._libraries is not None:
            return self._libraries

        libraries: "dict[str, BasePhotoLibrary | PhotoStreamLibrary]" = {}
        if self._shared_library is not None:
            libraries["shared"] = self._shared_library
        try:
            libraries["root"] = self._get_root_library()
        except (PyiCloudServiceNotActivatedException, PhotosZoneNotFoundError):
            if _can_use_typed_cloudkit(self.session):
                self._discover_shared_typed_zones(libraries)
            if not libraries:
                raise
            # Do not cache a partial discovery: private indexing may finish later.
            return libraries
        if _can_use_typed_cloudkit(self.session):
            if not self._discover_typed_zones(libraries):
                return libraries
        else:
            self._discover_legacy_zones(libraries)
        self._libraries = libraries
        return self._libraries

    def _discover_typed_zones(
        self,
        libraries: "dict[str, BasePhotoLibrary | PhotoStreamLibrary]",
    ) -> bool:
        """Discover typed zones, returning whether the result is complete."""
        self._private_primary_zone = None
        self._private_primary_binding = None
        try:
            private_zones = self._private_client.zones_list()
        except PyiCloudException:  # pylint: disable=broad-exception-caught
            LOGGER.debug("Private CloudKit photos zones unavailable", exc_info=True)
            self._discover_shared_typed_zones(libraries)
            return False
        primary = [
            zone
            for zone in private_zones.zones
            if not zone.deleted and zone.zoneID.zoneName == PRIMARY_ZONE["zoneName"]
        ]
        if len(primary) == 1:
            self._private_primary_zone = primary[0].zoneID.model_dump(exclude_none=True)
            self._private_primary_binding = (
                self.params.get("dsid"),
                self.service_endpoint,
            )
        for zone in private_zones.zones:
            if zone.deleted:
                continue
            zone_dict = zone.zoneID.model_dump(exclude_none=True)
            zone_name = zone.zoneID.zoneName
            if zone_name == PRIMARY_ZONE["zoneName"]:
                self._get_root_library().current_sync_token = zone.syncToken
                continue
            key = zone_name
            scope = "private"
            if _is_shared_library_zone_name(zone_name):
                key = f"shared:{zone_name}"
                scope = "shared-library"
            libraries[key] = PhotoLibrary(
                self,
                zone_id=zone_dict,
                client=self._private_client,
                upload_url=self._upload_url,
                upload_hydration_timeout=self._upload_hydration_timeout,
                upload_hydration_interval=self._upload_hydration_interval,
                scope=scope,
            )
        return self._discover_shared_typed_zones(libraries)

    def _discover_shared_typed_zones(
        self,
        libraries: "dict[str, BasePhotoLibrary | PhotoStreamLibrary]",
    ) -> bool:
        """Discover shared zones, returning False when discovery needs a retry."""
        try:
            shared_zones = self._shared_client.zones_list()
            for zone in shared_zones.zones:
                if zone.deleted:
                    continue
                zone_dict = zone.zoneID.model_dump(exclude_none=True)
                zone_name = zone.zoneID.zoneName
                key = f"shared:{zone_name}"
                if key in libraries:
                    continue
                libraries[key] = PhotoLibrary(
                    self,
                    zone_id=zone_dict,
                    client=self._shared_client,
                    upload_hydration_timeout=self._upload_hydration_timeout,
                    upload_hydration_interval=self._upload_hydration_interval,
                    scope="shared-library",
                )
        except PyiCloudException:  # pylint: disable=broad-exception-caught
            LOGGER.debug("Shared CloudKit photos zones unavailable", exc_info=True)
            return False
        return True

    def _discover_legacy_zones(
        self,
        libraries: "dict[str, BasePhotoLibrary | PhotoStreamLibrary]",
    ) -> None:
        """Discover additional zones via the legacy REST zones/list endpoint."""
        response = self.session.post(
            f"{self.service_endpoint}/zones/list?{urlencode(self.params)}",
            json={},
            headers={CONTENT_TYPE: CONTENT_TYPE_TEXT},
        ).json()
        for zone in response.get("zones", []):
            if zone.get("deleted"):
                continue
            zone_id = zone.get("zoneID", {})
            zone_name = zone_id.get("zoneName")
            if zone_name == PRIMARY_ZONE["zoneName"]:
                self._get_root_library().current_sync_token = zone.get("syncToken")
                continue
            key = zone_name
            scope = "private"
            if _is_shared_library_zone_name(zone_name):
                key = f"shared:{zone_name}"
                scope = "shared-library"
            libraries[key] = PhotoLibrary(
                self,
                zone_id=zone_id,
                upload_url=self._upload_url,
                upload_hydration_timeout=self._upload_hydration_timeout,
                upload_hydration_interval=self._upload_hydration_interval,
                scope=scope,
            )

    @property
    def all(self) -> PhotoAlbum:
        """Return the root library's All Photos album."""
        return self._get_root_library().all

    @property
    def albums(self) -> AlbumContainer:
        """Return the root library's albums."""
        return self._get_root_library().albums

    @property
    def shared_streams(self) -> AlbumContainer:
        """Return the shared photo stream albums.

        Raises ``PyiCloudServiceUnavailable`` when the account does not
        advertise the shared-streams host, since the rest of the service is
        usable without it.
        """
        if self._shared_library is None:
            raise PyiCloudServiceUnavailable(
                "Shared photo streams are not available for this account"
            )
        return AlbumContainer(
            cast(list[BasePhotoAlbum], list(self._shared_library.albums))
        )

    def create_album(
        self,
        name: str,
        album_type: AlbumTypeEnum = AlbumTypeEnum.ALBUM,
    ) -> PhotoAlbum | None:
        """Create a new album in the root library and return it."""
        return self._get_root_library().create_album(name, album_type)

    def upload(
        self,
        path: str,
        *,
        album: str | BasePhotoAlbum | None = None,
    ) -> PhotoAsset | None:
        """
        Upload a file into the root library or a specific album.

        ``album`` may be omitted for the root library, provided as an album
        object, or provided as an album name/fullname.
        """

        if album is None:
            return self._get_root_library().upload_file(path)

        album_obj: BasePhotoAlbum | None
        if isinstance(album, str):
            album_obj = self.albums.find(album)
            if album_obj is None:
                album_obj = self._get_root_library().refresh_albums().find(album)
            if album_obj is None:
                raise PhotosServiceException(f"No album matched '{album}'")
        else:
            album_obj = album

        return cast(PhotoAlbum, album_obj).upload(path)

    def sync_cursor(self) -> str:
        """Return the root library's current sync cursor."""
        return self._get_root_library().sync_cursor()

    def iter_changes(self, *, since: str | None = None) -> Iterator[PhotoChangeEvent]:
        """Yield photo change events from the root library."""
        yield from self._get_root_library().iter_changes(since=since)

    def sync(self, options: PhotoSyncOptions) -> PhotoSyncResult:
        """Synchronize photo resources into a local output directory."""

        return run_photo_sync(self, options)

    def watch(
        self,
        options: PhotoSyncOptions,
        *,
        interval_seconds: int,
        iterations: int | None = None,
    ) -> Iterator[PhotoSyncResult]:
        """Yield repeated sync runs for the given sync target."""

        yield from watch_photo_sync(
            self,
            options,
            interval_seconds=interval_seconds,
            iterations=iterations,
        )

    def _upload_into_album(self, album: PhotoAlbum, path: str) -> PhotoAsset | None:
        photo = self._get_root_library().upload_file(path)
        if photo is None:
            return None
        if album.id != SmartAlbumEnum.ALL_PHOTOS.value:
            album.add_photo(photo)
        return photo

private_client property

Return the private CloudKit client.

private_primary_zone property

Passive observed private PrimarySync identity, bound to its account.

upload_root property

Return the observed modern Photos upload service route, without fallback.

libraries property

Return the available photo libraries, discovering them on first access.

all property

Return the root library's All Photos album.

albums property

Return the root library's albums.

shared_streams property

Return the shared photo stream albums.

Raises PyiCloudServiceUnavailable when the account does not advertise the shared-streams host, since the rest of the service is usable without it.

create_album(name, album_type=AlbumTypeEnum.ALBUM)

Create a new album in the root library and return it.

Source code in pyicloud/services/photos/service.py
2980
2981
2982
2983
2984
2985
2986
def create_album(
    self,
    name: str,
    album_type: AlbumTypeEnum = AlbumTypeEnum.ALBUM,
) -> PhotoAlbum | None:
    """Create a new album in the root library and return it."""
    return self._get_root_library().create_album(name, album_type)

upload(path, *, album=None)

Upload a file into the root library or a specific album.

album may be omitted for the root library, provided as an album object, or provided as an album name/fullname.

Source code in pyicloud/services/photos/service.py
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
def upload(
    self,
    path: str,
    *,
    album: str | BasePhotoAlbum | None = None,
) -> PhotoAsset | None:
    """
    Upload a file into the root library or a specific album.

    ``album`` may be omitted for the root library, provided as an album
    object, or provided as an album name/fullname.
    """

    if album is None:
        return self._get_root_library().upload_file(path)

    album_obj: BasePhotoAlbum | None
    if isinstance(album, str):
        album_obj = self.albums.find(album)
        if album_obj is None:
            album_obj = self._get_root_library().refresh_albums().find(album)
        if album_obj is None:
            raise PhotosServiceException(f"No album matched '{album}'")
    else:
        album_obj = album

    return cast(PhotoAlbum, album_obj).upload(path)

sync_cursor()

Return the root library's current sync cursor.

Source code in pyicloud/services/photos/service.py
3016
3017
3018
def sync_cursor(self) -> str:
    """Return the root library's current sync cursor."""
    return self._get_root_library().sync_cursor()

iter_changes(*, since=None)

Yield photo change events from the root library.

Source code in pyicloud/services/photos/service.py
3020
3021
3022
def iter_changes(self, *, since: str | None = None) -> Iterator[PhotoChangeEvent]:
    """Yield photo change events from the root library."""
    yield from self._get_root_library().iter_changes(since=since)

sync(options)

Synchronize photo resources into a local output directory.

Source code in pyicloud/services/photos/service.py
3024
3025
3026
3027
def sync(self, options: PhotoSyncOptions) -> PhotoSyncResult:
    """Synchronize photo resources into a local output directory."""

    return run_photo_sync(self, options)

watch(options, *, interval_seconds, iterations=None)

Yield repeated sync runs for the given sync target.

Source code in pyicloud/services/photos/service.py
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
def watch(
    self,
    options: PhotoSyncOptions,
    *,
    interval_seconds: int,
    iterations: int | None = None,
) -> Iterator[PhotoSyncResult]:
    """Yield repeated sync runs for the given sync target."""

    yield from watch_photo_sync(
        self,
        options,
        interval_seconds=interval_seconds,
        iterations=iterations,
    )