Ejemplo n.º 1
0
def getDevices(**kwargs):  # pragma: no cover
    """Deprecated, will be removed in v0.3. Get up to date full devices data set as a dict.

    Args:
        **hub_name(str): optional name of hub to query. Will get converted to hubId for use.
        **hub_id(str): optional id of hub to query. A specified hub_id takes presedence over a hub_name or default Hub. Providing incorrect hub_id's will create cruft in your state but it won't hurt anything beyond failing the current operation.
        **remote(bool): Remote or local query.
        **hubId(str): Deprecated. Compatibility keyword for hub_id, to be removed in v0.3
        **hubName(str): Deprecated. Compatibility keyword for hub_name, to be removed in v0.3

    Returns:
        dict: full live device state as returned by the API

    """
    from . import cloud
    cloud.authenticate(
    )  # the old version of getDevices did more than it was supposed to, including making sure there was a valid connection

    hub_id = _get_id(**kwargs)
    hub_token = token(hub_id)
    cloud_token = cloud.token()
    hostname = host(hub_id)

    if 'remote' not in kwargs:
        kwargs['remote'] = remote

    return devices(**kwargs)
Ejemplo n.º 2
0
def main():
    fh, tmp = tempfile.mkstemp()
    config.setStatePath(tmp)

    assert cloud.authenticate()
    config.dump_state()
    print(hub.tz())
    os.remove(tmp)
Ejemplo n.º 3
0
def ping(autorefresh=True, **kwargs):
    """Perform a cheap API call to trigger any potential APIError and return boolean for success/failure. For optional kwargs see cozify.hub_api.get()

    Args:
        autorefresh(bool): Wether to perform a autorefresh after an initially failed ping. If successful, will still return True. Defaults to True.
        **hub_id(str): Hub to ping or default if neither id or name set.
        **hub_name(str): Hub to ping by name.

    Returns:
        bool: True for a valid and working hub authentication state.
    """
    try:
        _fill_kwargs(
            kwargs)  # this can raise an APIError if hub_token has expired
        # Detect remote-ness and flip state if needed
        if not kwargs['remote'] and kwargs['autoremote'] and not kwargs['host']:
            remote(kwargs['hub_id'], True)
            kwargs['remote'] = True
            logging.debug(
                'Ping determined hub is remote and flipped state to remote.')
        # We could still be remote but just have host set. If so, tz will fail.
        timezone = tz(**kwargs)
        logging.debug(
            'Ping performed with tz call, response: {0}'.format(timezone))
    except APIError as e:
        if e.status_code == 401 or e.status_code == 403 or e.status_code == 'connection failure':
            if autorefresh:
                from cozify import cloud
                logging.warning(
                    'Hub token has expired, hub.ping() attempting to renew it.'
                )
                logging.debug('Original APIError was: {0}'.format(e))
                if cloud.authenticate(
                        trustHub=False):  # if this fails we let it fail.
                    return True
            logging.warning(e)
            return False
        else:
            raise
    else:
        return True
Ejemplo n.º 4
0
def ping(autorefresh=True, **kwargs):
    """Perform a cheap API call to trigger any potential APIError and return boolean for success/failure. For optional kwargs see cozify.hub_api.get()

    Args:
        autorefresh(bool): Wether to perform a autorefresh after an initially failed ping. If successful, will still return True. Defaults to True.
        **hub_id(str): Hub to ping or default if neither id or name set.
        **hub_name(str): Hub to ping by name.

    Returns:
        bool: True for a valid and working hub authentication state.
    """
    try:
        _fill_kwargs(
            kwargs)  # this can raise an APIError if hub_token has expired
        # Detect remote-ness and flip state if needed
        if not kwargs['remote'] and kwargs['autoremote'] and not kwargs['host']:
            remote(kwargs['hub_id'], True)
            kwargs['remote'] = True
            logging.debug(
                'Ping determined hub is remote and flipped state to remote.')
        # We could still be remote but just have host set. If so, tz will fail.
        timezone = tz(**kwargs)
        logging.debug(
            'Ping performed with tz call, response: {0}'.format(timezone))
    except APIError as e:
        if e.status_code == 401 or e.status_code == 403:
            if autorefresh:
                from cozify import cloud
                logging.warning(
                    'Hub token has expired, hub.ping() attempting to renew it.'
                )
                logging.debug('Original APIError was: {0}'.format(e))
                if cloud.authenticate(
                        trustHub=False):  # if this fails we let it fail.
                    return True
            logging.error(e)
            return False
        else:
            raise
    except ConnectionError as e:
        logging.warning('Hub connection failed, attempting to rescue it.')
        from cozify import cloud

        # If we're not remote can try to refresh hub ip
        if not kwargs['remote']:
            logging.warning('Verifying we have an up to date ip address')
            from cozify import cloud
            cloud.update_hubs(
            )  # This can succeed even if we don't have a valid cloud token
            # retry the call
            try:
                timezone = tz(**kwargs)
            except ConnectionError as e:
                logging.error('Refreshing hub ip was not enough to rescue it')
            else:
                logging.warning('Hub ip had changed, back in business!')
                return True

        # If we're not remote and allowed to try it, try it!
        if not kwargs['remote'] and kwargs['autoremote']:
            logging.warning('Perhaps we can reach it remotely.')
            # Need an operable cloud connection for this
            if cloud.ping():
                remote(kwargs['hub_id'], True)
                kwargs['remote'] = True

                # retry the call and let it burn to the ground on failure
                try:
                    timezone = tz(**kwargs)
                except (APIError, ConnectionError) as e:
                    logging.error(
                        f'Cannot connect via Cloud either, nothing left to try: {e}'
                    )
                    # undo remote so it doesn't stick around, since the failure was undetermined
                    remote(kwargs['hub_id'], False)
                    return False
                else:
                    logging.info(
                        'Hub connection succeeded remotely, leaving hub configured as remote.'
                    )
                    return True
            else:
                # Failure was to the cloud, we can't salvage that.
                raise
    else:
        return True
Ejemplo n.º 5
0
#!/usr/bin/env python3

from cozify import cloud
cloud.authenticate()
# authenticate() is interactive and usually triggered automatically
# authentication data is stored in ~/.config/python-cozify/python-cozify.cfg
Ejemplo n.º 6
0
def main():
    assert cloud.authenticate()
Ejemplo n.º 7
0
def test_cloud_authenticate_hub():
    assert cloud.authenticate(trustHub=False)
Ejemplo n.º 8
0
def test_cloud_authenticate():
    assert cloud.authenticate()