### Pyicloud Service Initialization and Interaction Source: https://github.com/picklepete/pyicloud/blob/master/CODE_SAMPLES.md This comprehensive Python example demonstrates how to initialize the PyiCloudService, handle two-factor authentication (2FA) using trusted devices and verification codes, and interact with various iCloud services such as devices, location, status, calendar events, contacts, and file storage. ```python import os import click import datetime from pyicloud import PyiCloudService print("Setup Time Zone") time.strftime("%X %x %Z") os.environ["TZ"] = "America/New_York" print("Py iCloud Services") api = PyiCloudService("your@me.com", "password") if api.requires_2fa: print("Two-factor authentication required. Your trusted devices are:") devices = api.trusted_devices for i, device in enumerate(devices): print( " %s: %s" % (i, device.get("deviceName", "SMS to %s" % device.get("phoneNumber"))) ) device = click.prompt("Which device would you like to use?", default=0) device = devices[device] if not api.send_verification_code(device): print("Failed to send verification code") sys.exit(1) code = click.prompt("Please enter validation code") if not api.validate_verification_code(device, code): print("Failed to verify verification code") sys.exit(1) # # Devices # print("Devices") print(api.devices) print(api.devices[0]) print(api.iphone) # # Location # print("Location") print(api.iphone.location()) # # Status # print("Status") print(api.iphone.status()) # # Play Sound # # api.iphone.play_sound() # # Events # print("Events") print(api.calendar.events()) from_dt = datetime.date(2018, 1, 1) to_dt = datetime.date(2018, 1, 31) print(api.calendar.events(from_dt, to_dt)) # ======== # Contacts # ======== print("Contacts") for c in api.contacts.all(): print(c.get("firstName"), c.get("phones")) # ======================= # File Storage (Ubiquity) # ======================= # You can access documents stored in your iCloud account by using the # ``files`` property's ``dir`` method: print("File Storage") print(api.files.dir()) ``` -------------------------------- ### Download iCloud Drive File with Streaming Source: https://github.com/picklepete/pyicloud/blob/master/README.rst Provides an example of downloading a file from iCloud Drive using streaming, similar to the Notes example. It uses `shutil.copyfileobj` to efficiently copy the raw response content to a local file, preventing large files from being loaded entirely into memory. ```python from shutil import copyfileobj with drive_file.open(stream=True) as response: with open(drive_file.name, 'wb') as file_out: copyfileobj(response.raw, file_out) ``` -------------------------------- ### Navigate and Inspect iCloud Drive Files and Folders Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This example demonstrates how to navigate through iCloud Drive directories and access file/folder properties using dictionary-like indexing. It shows how to retrieve folder contents, file names, modification dates, sizes, and types, allowing detailed interaction with iCloud files. ```pycon >>> api.files['com~apple~Notes'] >>> api.files['com~apple~Notes'].type 'folder' >>> api.files['com~apple~Notes'].dir() ['Documents'] >>> api.files['com~apple~Notes']['Documents'].dir() ['Some Document'] >>> api.files['com~apple~Notes']['Documents']['Some Document'].name 'Some Document' >>> api.files['com~apple~Notes']['Documents']['Some Document'].modified datetime.datetime(2012, 9, 13, 2, 26, 17) >>> api.files['com~apple~Notes']['Documents']['Some Document'].size 1308134 >>> api.files['com~apple~Notes']['Documents']['Some Document'].type 'file' ``` -------------------------------- ### Enable Pyicloud Debugging with Proxy and Detailed Logging Source: https://github.com/picklepete/pyicloud/blob/master/CODE_SAMPLES.md This Python example provides a method to enable debugging for pyicloud by disabling SSL verification and logging all HTTP requests and responses. It allows the use of tools like mitmproxy for inspecting network traffic and provides detailed output from the underlying requests module and http.client. ```python #!/usr/bin/env python3 import contextlib import http.client import logging import requests import warnings from pprint import pprint from pyicloud import PyiCloudService from urllib3.exceptions import InsecureRequestWarning # Handle certificate warnings by ignoring them old_merge_environment_settings = requests.Session.merge_environment_settings @contextlib.contextmanager def no_ssl_verification(): opened_adapters = set() def merge_environment_settings(self, url, proxies, stream, verify, cert): # Verification happens only once per connection so we need to close # all the opened adapters once we're done. Otherwise, the effects of # verify=False persist beyond the end of this context manager. opened_adapters.add(self.get_adapter(url)) settings = old_merge_environment_settings( self, url, proxies, stream, verify, cert ) settings["verify"] = False return settings requests.Session.merge_environment_settings = merge_environment_settings try: with warnings.catch_warnings(): warnings.simplefilter("ignore", InsecureRequestWarning) yield finally: requests.Session.merge_environment_settings = old_merge_environment_settings for adapter in opened_adapters: try: adapter.close() except: pass # Monkeypatch the http client for full debugging output httpclient_logger = logging.getLogger("http.client") def httpclient_logging_patch(level=logging.DEBUG): """Enable HTTPConnection debug logging to the logging framework""" def httpclient_log(*args): httpclient_logger.log(level, " ".join(args)) # mask the print() built-in in the http.client module to use # logging instead http.client.print = httpclient_log # enable debugging http.client.HTTPConnection.debuglevel = 1 ``` -------------------------------- ### Fetch iCloud Calendar Events within a Specific Date Range Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This example demonstrates how to fetch iCloud calendar events between a specified start and end date. By passing `datetime` objects to `api.calendar.events()`, users can retrieve events for any custom period. ```python from_dt = datetime(2012, 1, 1) to_dt = datetime(2012, 1, 31) api.calendar.events(from_dt, to_dt) ``` -------------------------------- ### Access Specific iCloud Devices by Index or ID Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This example illustrates how to access individual `AppleDevice` objects from the `api.devices` collection. Devices can be retrieved either by their numerical index or by their unique iCloud device ID, offering flexible access methods. ```pycon >>> api.devices[0] >>> api.devices['i9vbKRGIcLYqJnXMd1b257kUWnoyEBcEh6yM+IfmiMLh7BmOpALS+w=='] ``` -------------------------------- ### Iterate Through All iCloud Contacts Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This example demonstrates how to access and iterate through all contacts stored in the iCloud address book using `api.contacts.all()`. It prints the first name and phone numbers for each contact, noting that only iCloud-stored contacts are included. ```pycon >>> for c in api.contacts.all(): >>> print(c.get('firstName'), c.get('phones')) John [{'field': '+1 555-55-5555-5', 'label': 'MOBILE'}] ``` -------------------------------- ### Get Simplified Status Information for an iCloud Device Source: https://github.com/picklepete/pyicloud/blob/master/README.rst The `api.iphone.status()` method provides a simplified subset of device properties, including display name, status code, battery level, and device name. This method is useful for quickly retrieving essential device information without the full, bloated response. ```pycon >>> api.iphone.status() {'deviceDisplayName': 'iPhone 5', 'deviceStatus': '200', 'batteryLevel': 0.6166913, 'name': "Peter's iPhone"} ``` -------------------------------- ### Activate Lost Mode on an iCloud Device Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This example shows how to enable 'Lost Mode' on an iCloud device, allowing a custom message and a contact phone number to be displayed. The specified phone number can be called without unlocking the device, aiding in its recovery. ```python phone_number = '555-373-383' message = 'Thief! Return my phone immediately.' api.iphone.lost_device(phone_number, message) ``` -------------------------------- ### Retrieve Last Known Location of an iCloud Device Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This snippet shows how to get the last known location of a device using `api.iphone.location()`. It returns a dictionary containing geographical coordinates, timestamp, and accuracy details, provided the Find My iPhone app is active on the device. ```pycon >>> api.iphone.location() {'timeStamp': 1357753796553, 'locationFinished': True, 'longitude': -0.14189, 'positionType': 'GPS', 'locationType': None, 'latitude': 51.501364, 'isOld': False, 'horizontalAccuracy': 5.0} ``` -------------------------------- ### List Available Photo Versions Source: https://github.com/picklepete/pyicloud/blob/master/README.rst Shows how to retrieve the available versions (e.g., 'medium', 'original', 'thumb') for a given photo asset using the `versions` property. This allows users to choose which quality or size of the photo to download. ```pycon >>> photo.versions.keys() ['medium', 'original', 'thumb'] ``` -------------------------------- ### PyiCloudService Initialization and Two-Factor Authentication Workflow Source: https://github.com/picklepete/pyicloud/blob/master/CODE_SAMPLES.md This Python code demonstrates how to initialize the PyiCloudService with a username and password. It includes a complete workflow for handling two-factor authentication (2FA), prompting the user to select a trusted device and enter a verification code. Additionally, it shows how to temporarily disable SSL verification for specific API calls using 'no_ssl_verification'. ```python logging.basicConfig(level=logging.DEBUG) httpclient_logging_patch() api = PyiCloudService(username, password) if api.requires_2sa: print("Two-factor authentication required. Your trusted devices are:") devices = api.trusted_devices for i, device in enumerate(devices): print( " %s: %s" % (i, device.get("deviceName", "SMS to %s") % device.get("phoneNumber")) ) device = click.prompt("Which device would you like to use?", default=0) device = devices[device] if not api.send_verification_code(device): print("Failed to send verification code") sys.exit(1) code = click.prompt("Please enter validation code") if not api.validate_verification_code(device, code): print("Failed to verify verification code") sys.exit(1) # This request will not fail, even if using intercepting proxies. with no_ssl_verification(): pprint(api.account) ``` -------------------------------- ### Download File Content from iCloud Notes Source: https://github.com/picklepete/pyicloud/blob/master/README.rst Demonstrates how to open a file from iCloud Notes and read its content as a string. The `open` method returns a response object from which content can be read. ```pycon >>> api.files['com~apple~Notes']['Documents']['Some Document'].open().content 'Hello, these are the file contents' ``` -------------------------------- ### List Directories and Files in iCloud Drive Source: https://github.com/picklepete/pyicloud/blob/master/README.rst Demonstrates how to list the contents of the root iCloud Drive directory and subdirectories using the `dir()` method. This allows navigation through the iCloud Drive file structure. ```pycon >>> api.drive.dir() ['Holiday Photos', 'Work Files'] >>> api.drive['Holiday Photos']['2013']['Sicily'].dir() ['DSC08116.JPG', 'DSC08117.JPG'] ``` -------------------------------- ### Handle two-factor and two-step authentication with PyiCloudService Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This comprehensive Python snippet demonstrates how to programmatically handle both two-factor authentication (2FA) and two-step authentication (2SA) with `PyiCloudService`. It checks if 2FA or 2SA is required, prompts the user for verification codes, validates them, and manages session trust. ```python if api.requires_2fa: print("Two-factor authentication required.") code = input("Enter the code you received of one of your approved devices: ") result = api.validate_2fa_code(code) print("Code validation result: %s" % result) if not result: print("Failed to verify security code") sys.exit(1) if not api.is_trusted_session: print("Session is not trusted. Requesting trust...") result = api.trust_session() print("Session trust result %s" % result) if not result: print("Failed to request trust. You will likely be prompted for the code again in the coming weeks") elif api.requires_2sa: import click print("Two-step authentication required. Your trusted devices are:") devices = api.trusted_devices for i, device in enumerate(devices): print( " %s: %s" % (i, device.get('deviceName', "SMS to %s" % device.get('phoneNumber'))) ) device = click.prompt('Which device would you like to use?', default=0) device = devices[device] if not api.send_verification_code(device): print("Failed to send verification code") sys.exit(1) code = click.prompt('Please enter validation code') if not api.validate_verification_code(device, code): print("Failed to verify verification code") ``` -------------------------------- ### Download Specific Version of iCloud Photo Source: https://github.com/picklepete/pyicloud/blob/master/README.rst Demonstrates how to download a specific version of a photo asset (e.g., 'thumb' for thumbnail) by passing the version name to the `download()` method. The downloaded content can then be written to a file with the appropriate filename. ```python download = photo.download('thumb') with open(photo.versions['thumb']['filename'], 'wb') as thumb_file: thumb_file.write(download.raw.read()) ``` -------------------------------- ### Manage iCloud Drive Directories and Files (mkdir, rename, delete) Source: https://github.com/picklepete/pyicloud/blob/master/README.rst Illustrates how to perform common file and directory operations in iCloud Drive, including creating a new directory (`mkdir`), renaming an existing one (`rename`), and deleting a directory or file (`delete`). These methods are available on file or folder objects. ```python api.drive['Holiday Photos'].mkdir('2020') api.drive['Holiday Photos']['2020'].rename('2020_copy') api.drive['Holiday Photos']['2020_copy'].delete() ``` -------------------------------- ### Download and Parse JSON File from iCloud Notes Source: https://github.com/picklepete/pyicloud/blob/master/README.rst Shows how to open a JSON file from iCloud Notes and parse its content directly into a Python dictionary using the `json()` method. This is useful when the file is known to contain JSON data. ```pycon >>> api.files['com~apple~Notes']['Documents']['information.json'].open().json() {'How much we love you': 'lots'} >>> api.files['com~apple~Notes']['Documents']['information.json'].open().json()['How much we love you'] 'lots' ``` -------------------------------- ### Upload File to iCloud Drive Source: https://github.com/picklepete/pyicloud/blob/master/README.rst Demonstrates how to upload a file-like object to iCloud Drive. It is recommended to open file handles in binary mode (`'rb'`) to prevent decoding errors during the upload process. ```python with open('Vacation.jpeg', 'rb') as file_in: api.drive['Holiday Photos'].upload(file_in) ``` -------------------------------- ### Authenticate with PyiCloudService using username and password Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This snippet demonstrates the basic way to authenticate with iCloud using the `PyiCloudService` class. It requires passing your Apple ID username and password directly as arguments. An exception `PyiCloudFailedLoginException` is thrown if the credentials are invalid. ```python from pyicloud import PyiCloudService api = PyiCloudService('jappleseed@apple.com', 'password') ``` -------------------------------- ### List iCloud Devices with pyicloud Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This snippet demonstrates how to retrieve a dictionary of all devices associated with the authenticated iCloud account using the `api.devices` property. The output includes device IDs mapped to `AppleDevice` objects, providing a comprehensive overview of linked Apple hardware. ```pycon >>> api.devices { 'i9vbKRGIcLYqJnXMd1b257kUWnoyEBcEh6yM+IfmiMLh7BmOpALS+w==': , 'reGYDh9XwqNWTGIhNBuEwP1ds0F/Lg5t/fxNbI4V939hhXawByErk+HYVNSUzmWV': } ``` -------------------------------- ### Download iCloud Photo Asset Source: https://github.com/picklepete/pyicloud/blob/master/README.rst Illustrates how to download a photo asset from the iCloud Photo Library. The `download` method returns a streamed response object, allowing the raw content to be read and written to a local file. It's advised to use buffered strategies like `shutil.copyfile` for large files. ```python photo = next(iter(api.photos.albums['Screenshots']), None) download = photo.download() with open(photo.filename, 'wb') as opened_file: opened_file.write(download.raw.read()) ``` -------------------------------- ### Stream Large File Download from iCloud Notes Source: https://github.com/picklepete/pyicloud/blob/master/README.rst Illustrates how to download a large file from iCloud Notes using streaming to avoid loading the entire file into memory. The `stream=True` argument is passed to the `open` method, and content is read from the raw response object. ```pycon >>> download = api.files['com~apple~Notes']['Documents']['big_file.zip'].open(stream=True) >>> with open('downloaded_file.zip', 'wb') as opened_file: opened_file.write(download.raw.read()) ``` -------------------------------- ### Access First iCloud Device via Shorthand Property Source: https://github.com/picklepete/pyicloud/blob/master/README.rst For convenience, the `api.iphone` property provides a shorthand to access the first device associated with the iCloud account. While named 'iphone', this property simply returns the first device in the list, which may not always be an iPhone. ```pycon >>> api.iphone ``` -------------------------------- ### List Contents of iCloud Drive Root Directory Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This snippet shows how to list the contents of the root directory in iCloud Drive using `api.files.dir()`. It returns a list of file and folder names, providing an overview of the top-level items in your iCloud file storage. ```pycon >>> api.files.dir() ['.do-not-delete', '.localized', 'com~apple~Notes', 'com~apple~Preview', 'com~apple~mail', 'com~apple~shoebox', 'com~apple~system~spotlight' ] ``` -------------------------------- ### Access iCloud Photo Library Albums Source: https://github.com/picklepete/pyicloud/blob/master/README.rst Shows how to access the 'All Photos' album and specific photo albums (e.g., 'Screenshots') within the iCloud Photo Library using the `api.photos` property. Albums are accessible via the `albums` property. ```pycon >>> api.photos.all >>> api.photos.albums['Screenshots'] ``` -------------------------------- ### Authenticate PyiCloudService using password from keyring Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This Python snippet shows how to authenticate with `PyiCloudService` when the password has already been stored in the system keyring. Only the username is required, as the service will automatically retrieve the password from the keyring. ```python api = PyiCloudService('jappleseed@apple.com') ``` -------------------------------- ### Iterate and List Photos in iCloud Photo Album Source: https://github.com/picklepete/pyicloud/blob/master/README.rst Demonstrates how to iterate through photos within a specific iCloud Photo Album. It shows how to access photo objects and their filenames. The 'All Photos' album is sorted by `added_date`, while other albums are sorted by `asset_date` (EXIF date). ```pycon >>> for photo in api.photos.albums['Screenshots']: print(photo, photo.filename) IMG_6045.JPG ``` -------------------------------- ### Trigger Sound Playback on an iCloud Device Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This Python snippet demonstrates how to remotely trigger a sound on an iCloud device using `api.iphone.play_sound()`. The device will play a ringtone and display a default notification, with a confirmation email sent to the user. ```python api.iphone.play_sound() ``` -------------------------------- ### Store iCloud password in system keyring via command line Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This command-line snippet demonstrates how to use the `icloud` tool to store your iCloud password in the system keyring. This allows subsequent interactions with the `PyiCloudService` or command-line tool to not require a password. ```console $ icloud --username=jappleseed@apple.com ICloud Password for jappleseed@apple.com: Save password in keyring? (y/N) ``` -------------------------------- ### Access iCloud Drive File Properties Source: https://github.com/picklepete/pyicloud/blob/master/README.rst Shows how to access various properties of an iCloud Drive file object, such as its name, last modification date, size, and type. The date is returned as a `datetime` object in UTC. ```pycon >>> drive_file = api.drive['Holiday Photos']['2013']['Sicily']['DSC08116.JPG'] >>> drive_file.name 'DSC08116.JPG' >>> drive_file.date_modified datetime.datetime(2013, 3, 21, 12, 28, 12) # NB this is UTC >>> drive_file.size 2021698 >>> drive_file.type 'file' ``` -------------------------------- ### Fetch Current Month's iCloud Calendar Events Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This snippet retrieves all calendar events for the current month from the authenticated iCloud account. The `api.calendar.events()` method provides a straightforward way to access upcoming or past events within the current monthly scope. ```python api.calendar.events() ``` -------------------------------- ### Authenticate PyiCloudService for China mainland Apple ID Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This snippet shows how to authenticate with iCloud when your Apple ID's country/region is set to China mainland. You need to pass `china_mainland=True` as an additional argument to the `PyiCloudService` constructor. ```python from pyicloud import PyiCloudService api = PyiCloudService('jappleseed@apple.com', 'password', china_mainland=True) ``` -------------------------------- ### Retrieve Details for a Single iCloud Calendar Event Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This snippet shows how to fetch the detailed information for a specific iCloud calendar event. The `api.calendar.get_event_detail()` method requires the calendar name and the event ID to retrieve the event's full details. ```python api.calendar.get_event_detail('CALENDAR', 'EVENT_ID') ``` -------------------------------- ### Delete iCloud password from system keyring via command line Source: https://github.com/picklepete/pyicloud/blob/master/README.rst This command-line snippet illustrates how to remove a previously stored iCloud password from the system keyring. The `--delete-from-keyring` option is used along with the username to clear the stored credential. ```console $ icloud --username=jappleseed@apple.com --delete-from-keyring ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.