pyicloud icon indicating copy to clipboard operation
pyicloud copied to clipboard

Unable to execute this code KeyError: 'familyMembers'

Open juanfrilla opened this issue 3 years ago • 0 comments

The problem

I'm testing this script and it gives me the error referenced in Traceback/Error logs.

#!/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


# Enable general debug logging
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)

What I'm doing wrong here?

Environment

  • pyiCloud release with the issue (pip show pyicloud): 1.0.0
  • Last working pyiCloud release (if known):
  • Service causing this issue:
  • Python version (python -V): 3.9.6
  • Operating environment (project deps/Docker/Windows/etc.): I'm using WSL: Distributor ID: Debian Description: Debian GNU/Linux 9.13 (stretch) Release: 9.13 Codename: stretch

Traceback/Error logs

DEBUG:http.client:header: Set-Cookie: X-APPLE-WEBAUTH-TOKEN="v=2:t=AQ==BST_IAAAAAAABLwIAAAAAGLnmbYRDmdzLmljbG91ZC5hdXRovQDeCviPV4iHdtEjjSu9irSh8t-8NnbFwBWKxpsB72FNvcKUZbw6WxSRCAz6PsVyi617ObcuVKP7SWu_T6igf7lIxalFCDGxzzliovlysURm1EYxpYeBoOAmV7BwhVIv1Mlo-kbOC4x8FIedVGPtos1fnI0Y4A~~";Expires=Mon, 15-Aug-2022 21:49:50 GMT;Path=/;Domain=icloud.com;Secure;HttpOnly
DEBUG:http.client:header: Strict-Transport-Security: max-age=31536000; includeSubDomains
DEBUG:http.client:header: x-apple-user-partition: 28
DEBUG:http.client:header: via: 631194250daa17e24277dea86cf30319:1f04534b34c2b1c25db65b4172b8994e:gbmnc1
DEBUG:http.client:header: X-Apple-Request-UUID: 49d76501-cf32-4894-ae82-30eebb2b740a
DEBUG:http.client:header: access-control-expose-headers: X-Apple-Request-UUID,Via
DEBUG:http.client:header: X-Apple-Edge-Response-Time: 170
DEBUG:urllib3.connectionpool:https://p28-setup.icloud.com:443 "GET /setup/web/family/getFamilyDetails HTTP/1.1" 200 163
DEBUG:pyicloud.base:Saved session data to file
DEBUG:pyicloud.base:Cookies saved to /tmp/pyicloud/juanfran/juanframarogmailcom
DEBUG:pyicloud.services.account.http:{'status-message': 'This invitation to join a family is no longer valid. Ask the organizer of the family to add you again.', 'isMemberOfFamily': False, 'title': 'Family Sharing invitation is no longer valid.', 'status': 0}
{'status-message': 'This invitation to join a family is no longer valid. Ask the organizer of the family to add you again.', 'isMemberOfFamily': False, 'title': 'Family Sharing invitation is no longer valid.', 'status': 0}
[]
Traceback (most recent call last):
  File "/home/juanfran/tucalendi_api_arch/app/app/integrations/apple/2fa.py", line 99, in <module>
    pprint(api.account)
  File "/usr/local/lib/python3.9/pprint.py", line 53, in pprint
    printer.pprint(object)
  File "/usr/local/lib/python3.9/pprint.py", line 148, in pprint
    self._format(object, self._stream, 0, 0, {}, 0)
  File "/usr/local/lib/python3.9/pprint.py", line 170, in _format
    rep = self._repr(object, context, level)
  File "/usr/local/lib/python3.9/pprint.py", line 431, in _repr
    repr, readable, recursive = self.format(object, context.copy(),
  File "/usr/local/lib/python3.9/pprint.py", line 444, in format
    return _safe_repr(object, context, maxlevels, level, self._sort_dicts)
  File "/usr/local/lib/python3.9/pprint.py", line 596, in _safe_repr
    rep = repr(object)
  File "/home/juanfran/tucalendi_api_arch/venv/lib/python3.9/site-packages/pyicloud/services/account.py", line 78, in __repr__
    return f"<{type(self).__name__}: {self}>"
  File "/home/juanfran/tucalendi_api_arch/venv/lib/python3.9/site-packages/pyicloud/services/account.py", line 73, in __str__
    len(self.family),
  File "/home/juanfran/tucalendi_api_arch/venv/lib/python3.9/site-packages/pyicloud/services/account.py", line 47, in family
    for member_info in response["familyMembers"]:
KeyError: 'familyMembers'

Checklist

  • [X ] I've looked informations into the README.
  • [ X] I've looked informations into the pyiCloud's code.
  • [ X] I've looked informations in Google.

Additional information

juanfrilla avatar Aug 01 '22 21:08 juanfrilla