Ejemplo n.º 1
0
    async def async_setup_flow(msg):
        """Return a setup flow for mfa auth module."""
        flow_manager = hass.data[DATA_SETUP_FLOW_MGR]

        flow_id = msg.get('flow_id')
        if flow_id is not None:
            result = await flow_manager.async_configure(
                flow_id, msg.get('user_input'))
            connection.send_message_outside(
                websocket_api.result_message(
                    msg['id'], _prepare_result_json(result)))
            return

        mfa_module_id = msg.get('mfa_module_id')
        mfa_module = hass.auth.get_auth_mfa_module(mfa_module_id)
        if mfa_module is None:
            connection.send_message_outside(websocket_api.error_message(
                msg['id'], 'no_module',
                'MFA module {} is not found'.format(mfa_module_id)))
            return

        result = await flow_manager.async_init(
            mfa_module_id, data={'user_id': connection.user.id})

        connection.send_message_outside(
            websocket_api.result_message(
                msg['id'], _prepare_result_json(result)))
    async def delete_creds():
        """Delete user credentials."""
        provider = _get_provider(hass)
        await provider.async_initialize()

        credentials = await provider.async_get_or_create_credentials({
            'username': msg['username']
        })

        # if not new, an existing credential exists.
        # Removing the credential will also remove the auth.
        if not credentials.is_new:
            await hass.auth.async_remove_credentials(credentials)

            connection.to_write.put_nowait(
                websocket_api.result_message(msg['id']))
            return

        try:
            provider.data.async_remove_auth(msg['username'])
            await provider.data.async_save()
        except auth_ha.InvalidUser:
            connection.to_write.put_nowait(websocket_api.error_message(
                msg['id'], 'auth_not_found', 'Given username was not found.'))
            return

        connection.to_write.put_nowait(
            websocket_api.result_message(msg['id']))
    async def create_creds():
        """Create credentials."""
        provider = _get_provider(hass)
        await provider.async_initialize()

        user = await hass.auth.async_get_user(msg['user_id'])

        if user is None:
            connection.send_message_outside(websocket_api.error_message(
                msg['id'], 'not_found', 'User not found'))
            return

        if user.system_generated:
            connection.send_message_outside(websocket_api.error_message(
                msg['id'], 'system_generated',
                'Cannot add credentials to a system generated user.'))
            return

        try:
            await hass.async_add_executor_job(
                provider.data.add_auth, msg['username'], msg['password'])
        except auth_ha.InvalidUser:
            connection.send_message_outside(websocket_api.error_message(
                msg['id'], 'username_exists', 'Username already exists'))
            return

        credentials = await provider.async_get_or_create_credentials({
            'username': msg['username']
        })
        await hass.auth.async_link_user(user, credentials)

        await provider.data.async_save()
        connection.to_write.put_nowait(websocket_api.result_message(msg['id']))
Ejemplo n.º 4
0
    async def websocket_device_clusters(hass, connection, msg):
        """Return a list of device clusters."""
        ieee = msg[ATTR_IEEE]
        zha_device = zha_gateway.get_device(ieee)
        response_clusters = []
        if zha_device is not None:
            clusters_by_endpoint = await zha_device.get_clusters()
            for ep_id, clusters in clusters_by_endpoint.items():
                for c_id, cluster in clusters[IN].items():
                    response_clusters.append({
                        TYPE: IN,
                        ID: c_id,
                        NAME: cluster.__class__.__name__,
                        'endpoint_id': ep_id
                    })
                for c_id, cluster in clusters[OUT].items():
                    response_clusters.append({
                        TYPE: OUT,
                        ID: c_id,
                        NAME: cluster.__class__.__name__,
                        'endpoint_id': ep_id
                    })

        connection.send_message(websocket_api.result_message(
            msg[ID],
            response_clusters
        ))
Ejemplo n.º 5
0
    async def websocket_device_cluster_attributes(hass, connection, msg):
        """Return a list of cluster attributes."""
        ieee = msg[ATTR_IEEE]
        endpoint_id = msg[ATTR_ENDPOINT_ID]
        cluster_id = msg[ATTR_CLUSTER_ID]
        cluster_type = msg[ATTR_CLUSTER_TYPE]
        cluster_attributes = []
        zha_device = zha_gateway.get_device(ieee)
        attributes = None
        if zha_device is not None:
            attributes = await zha_device.get_cluster_attributes(
                endpoint_id,
                cluster_id,
                cluster_type)
            if attributes is not None:
                for attr_id in attributes:
                    cluster_attributes.append(
                        {
                            ID: attr_id,
                            NAME: attributes[attr_id][0]
                        }
                    )
        _LOGGER.debug("Requested attributes for: %s %s %s %s",
                      "{}: [{}]".format(ATTR_CLUSTER_ID, cluster_id),
                      "{}: [{}]".format(ATTR_CLUSTER_TYPE, cluster_type),
                      "{}: [{}]".format(ATTR_ENDPOINT_ID, endpoint_id),
                      "{}: [{}]".format(RESPONSE, cluster_attributes)
                      )

        connection.send_message(websocket_api.result_message(
            msg[ID],
            cluster_attributes
        ))
Ejemplo n.º 6
0
 async def websocket_read_zigbee_cluster_attributes(hass, connection, msg):
     """Read zigbee attribute for cluster on zha entity."""
     ieee = msg[ATTR_IEEE]
     endpoint_id = msg[ATTR_ENDPOINT_ID]
     cluster_id = msg[ATTR_CLUSTER_ID]
     cluster_type = msg[ATTR_CLUSTER_TYPE]
     attribute = msg[ATTR_ATTRIBUTE]
     manufacturer = msg.get(ATTR_MANUFACTURER) or None
     zha_device = zha_gateway.get_device(ieee)
     success = failure = None
     if zha_device is not None:
         cluster = await zha_device.get_cluster(
             endpoint_id, cluster_id, cluster_type=cluster_type)
         success, failure = await cluster.read_attributes(
             [attribute],
             allow_cache=False,
             only_cache=False,
             manufacturer=manufacturer
         )
     _LOGGER.debug("Read attribute for: %s %s %s %s %s %s %s",
                   "{}: [{}]".format(ATTR_CLUSTER_ID, cluster_id),
                   "{}: [{}]".format(ATTR_CLUSTER_TYPE, cluster_type),
                   "{}: [{}]".format(ATTR_ENDPOINT_ID, endpoint_id),
                   "{}: [{}]".format(ATTR_ATTRIBUTE, attribute),
                   "{}: [{}]".format(ATTR_MANUFACTURER, manufacturer),
                   "{}: [{}]".format(RESPONSE, str(success.get(attribute))),
                   "{}: [{}]".format('failure', failure)
                   )
     connection.send_message(websocket_api.result_message(
         msg[ID],
         str(success.get(attribute))
     ))
Ejemplo n.º 7
0
async def websocket_subscription(hass, connection, msg):
    """Handle request for account info."""
    cloud = hass.data[DOMAIN]

    with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop):
        response = await cloud.fetch_subscription_info()

    if response.status != 200:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'request_failed', 'Failed to request subscription'))

    data = await response.json()

    # Check if a user is subscribed but local info is outdated
    # In that case, let's refresh and reconnect
    if data.get('provider') and cloud.iot.state != STATE_CONNECTED:
        _LOGGER.debug(
            "Found disconnected account with valid subscriotion, connecting")
        await hass.async_add_executor_job(
            auth_api.renew_access_token, cloud)

        # Cancel reconnect in progress
        if cloud.iot.state != STATE_DISCONNECTED:
            await cloud.iot.disconnect()

        hass.async_create_task(cloud.iot.connect())

    connection.send_message(websocket_api.result_message(msg['id'], data))
Ejemplo n.º 8
0
async def websocket_handle_thumbnail(hass, connection, msg):
    """Handle get media player cover command.

    Async friendly.
    """
    component = hass.data[DOMAIN]
    player = component.get_entity(msg['entity_id'])

    if player is None:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'entity_not_found', 'Entity not found'))
        return

    data, content_type = await player.async_get_media_image()

    if data is None:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'thumbnail_fetch_failed',
            'Failed to fetch thumbnail'))
        return

    connection.send_message(websocket_api.result_message(
        msg['id'], {
            'content_type': content_type,
            'content': base64.b64encode(data).decode('utf-8')
        }))
Ejemplo n.º 9
0
async def websocket_update_entity(hass, connection, msg):
    """Handle get camera thumbnail websocket command.

    Async friendly.
    """
    registry = await async_get_registry(hass)

    if msg['entity_id'] not in registry.entities:
        connection.send_message(websocket_api.error_message(
            msg['id'], ERR_NOT_FOUND, 'Entity not found'))
        return

    changes = {}

    if 'name' in msg:
        changes['name'] = msg['name']

    if 'new_entity_id' in msg:
        changes['new_entity_id'] = msg['new_entity_id']

    try:
        if changes:
            entry = registry.async_update_entity(
                msg['entity_id'], **changes)
    except ValueError as err:
        connection.send_message(websocket_api.error_message(
            msg['id'], 'invalid_info', str(err)
        ))
    else:
        connection.send_message(websocket_api.result_message(
            msg['id'], _entry_dict(entry)
        ))
Ejemplo n.º 10
0
async def websocket_read_zigbee_cluster_attributes(hass, connection, msg):
    """Read zigbee attribute for cluster on zha entity."""
    entity_id = msg[ATTR_ENTITY_ID]
    cluster_id = msg[ATTR_CLUSTER_ID]
    cluster_type = msg[ATTR_CLUSTER_TYPE]
    attribute = msg[ATTR_ATTRIBUTE]
    component = hass.data.get(entity_id.split('.')[0])
    entity = component.get_entity(entity_id)
    clusters = await entity.get_clusters()
    cluster = clusters[cluster_type][cluster_id]
    manufacturer = msg.get(ATTR_MANUFACTURER) or None
    success = failure = None
    if entity is not None:
        success, failure = await cluster.read_attributes(
            [attribute],
            allow_cache=False,
            only_cache=False,
            manufacturer=manufacturer
        )
    _LOGGER.debug("Read attribute for: %s %s %s %s %s %s %s",
                  "{}: [{}]".format(ATTR_CLUSTER_ID, cluster_id),
                  "{}: [{}]".format(ATTR_CLUSTER_TYPE, cluster_type),
                  "{}: [{}]".format(ATTR_ENTITY_ID, entity_id),
                  "{}: [{}]".format(ATTR_ATTRIBUTE, attribute),
                  "{}: [{}]".format(ATTR_MANUFACTURER, manufacturer),
                  "{}: [{}]".format(RESPONSE, str(success.get(attribute))),
                  "{}: [{}]".format('failure', failure)
                  )
    connection.send_message(websocket_api.result_message(
        msg[ID],
        str(success.get(attribute))
    ))
Ejemplo n.º 11
0
    async def update_entity():
        """Get entity from registry."""
        registry = await async_get_registry(hass)

        if msg['entity_id'] not in registry.entities:
            connection.send_message_outside(websocket_api.error_message(
                msg['id'], websocket_api.ERR_NOT_FOUND, 'Entity not found'))
            return

        changes = {}

        if 'name' in msg:
            changes['name'] = msg['name']

        if 'new_entity_id' in msg:
            changes['new_entity_id'] = msg['new_entity_id']

        try:
            if changes:
                entry = registry.async_update_entity(
                    msg['entity_id'], **changes)
        except ValueError as err:
            connection.send_message_outside(websocket_api.error_message(
                msg['id'], 'invalid_info', str(err)
            ))
        else:
            connection.send_message_outside(websocket_api.result_message(
                msg['id'], _entry_dict(entry)
            ))
Ejemplo n.º 12
0
    async def websocket_entity_clusters(hass, connection, msg):
        """Return a list of entity clusters."""
        entity_id = msg[ATTR_ENTITY_ID]
        entities = listener.get_entities_for_ieee(msg[ATTR_IEEE])
        entity = next(
            ent for ent in entities if ent.entity_id == entity_id)
        entity_clusters = await entity.get_clusters()
        clusters = []

        for cluster_id, cluster in entity_clusters[IN].items():
            clusters.append({
                TYPE: IN,
                ID: cluster_id,
                NAME: cluster.__class__.__name__
            })
        for cluster_id, cluster in entity_clusters[OUT].items():
            clusters.append({
                TYPE: OUT,
                ID: cluster_id,
                NAME: cluster.__class__.__name__
            })

        connection.send_message(websocket_api.result_message(
            msg[ID],
            clusters
        ))
Ejemplo n.º 13
0
def websocket_sign_path(
        hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg):
    """Handle a sign path request."""
    connection.send_message(websocket_api.result_message(msg['id'], {
        'path': async_sign_path(hass, connection.refresh_token_id, msg['path'],
                                timedelta(seconds=msg['expires']))
        }))
Ejemplo n.º 14
0
async def websocket_entity_cluster_attributes(hass, connection, msg):
    """Return a list of cluster attributes."""
    entity_id = msg[ATTR_ENTITY_ID]
    cluster_id = msg[ATTR_CLUSTER_ID]
    cluster_type = msg[ATTR_CLUSTER_TYPE]
    component = hass.data.get(entity_id.split('.')[0])
    entity = component.get_entity(entity_id)
    cluster_attributes = []
    if entity is not None:
        res = await entity.get_cluster_attributes(cluster_id, cluster_type)
        if res is not None:
            for attr_id in res:
                cluster_attributes.append(
                    {
                        ID: attr_id,
                        NAME: res[attr_id][0]
                    }
                )
    _LOGGER.debug("Requested attributes for: %s %s %s %s",
                  "{}: [{}]".format(ATTR_CLUSTER_ID, cluster_id),
                  "{}: [{}]".format(ATTR_CLUSTER_TYPE, cluster_type),
                  "{}: [{}]".format(ATTR_ENTITY_ID, entity_id),
                  "{}: [{}]".format(RESPONSE, cluster_attributes)
                  )

    connection.send_message(websocket_api.result_message(
        msg[ID],
        cluster_attributes
    ))
Ejemplo n.º 15
0
def websocket_cloud_status(hass, connection, msg):
    """Handle request for account info.

    Async friendly.
    """
    cloud = hass.data[DOMAIN]
    connection.send_message(
        websocket_api.result_message(msg['id'], _account_data(cloud)))
Ejemplo n.º 16
0
 async def send_translations():
     """Send a camera still."""
     resources = await async_get_translations(hass, msg['language'])
     connection.send_message_outside(websocket_api.result_message(
         msg['id'], {
             'resources': resources,
         }
     ))
Ejemplo n.º 17
0
async def websocket_create(hass, connection, msg):
    """Create a user."""
    user = await hass.auth.async_create_user(msg['name'])

    connection.send_message(
        websocket_api.result_message(msg['id'], {
            'user': _user_info(user)
        }))
Ejemplo n.º 18
0
async def websocket_list_entities(hass, connection, msg):
    """Handle list registry entries command.

    Async friendly.
    """
    registry = await async_get_registry(hass)
    connection.send_message(websocket_api.result_message(
        msg['id'], [_entry_dict(entry) for entry in registry.entities.values()]
    ))
Ejemplo n.º 19
0
async def websocket_list_areas(hass, connection, msg):
    """Handle list areas command."""
    registry = await async_get_registry(hass)
    connection.send_message(websocket_api.result_message(
        msg['id'], [{
            'name': entry.name,
            'area_id': entry.id,
        } for entry in registry.async_list_areas()]
    ))
Ejemplo n.º 20
0
def websocket_get_themes(hass, connection, msg):
    """Handle get themes command.

    Async friendly.
    """
    connection.send_message(websocket_api.result_message(msg['id'], {
        'themes': hass.data[DATA_THEMES],
        'default_theme': hass.data[DATA_DEFAULT_THEME],
    }))
Ejemplo n.º 21
0
async def websocket_update_device(hass, connection, msg):
    """Handle update area websocket command."""
    registry = await async_get_registry(hass)

    entry = registry.async_update_device(
        msg['device_id'], area_id=msg['area_id'])

    connection.send_message(websocket_api.result_message(
        msg['id'], _entry_dict(entry)
    ))
Ejemplo n.º 22
0
async def websocket_get_user_data(hass, connection, msg, store, data):
    """Handle get global data command.

    Async friendly.
    """
    connection.send_message(websocket_api.result_message(
        msg['id'], {
            'value': data.get(msg['key']) if 'key' in msg else data
        }
    ))
Ejemplo n.º 23
0
async def websocket_set_user_data(hass, connection, msg, store, data):
    """Handle set global data command.

    Async friendly.
    """
    data[msg['key']] = msg['value']
    await store.async_save(data)
    connection.send_message(websocket_api.result_message(
        msg['id'],
    ))
Ejemplo n.º 24
0
async def websocket_update_prefs(hass, connection, msg):
    """Handle request for account info."""
    cloud = hass.data[DOMAIN]

    changes = dict(msg)
    changes.pop('id')
    changes.pop('type')
    await cloud.prefs.async_update(**changes)

    connection.send_message(websocket_api.result_message(msg['id']))
Ejemplo n.º 25
0
def websocket_get_panels(hass, connection, msg):
    """Handle get panels command.

    Async friendly.
    """
    panels = {
        panel: connection.hass.data[DATA_PANELS][panel].to_response()
        for panel in connection.hass.data[DATA_PANELS]}

    connection.send_message(websocket_api.result_message(
        msg['id'], panels))
Ejemplo n.º 26
0
def websocket_list(hass, connection, msg):
    """Return a list of webhooks."""
    handlers = hass.data.setdefault(DOMAIN, {})
    result = [{
        'webhook_id': webhook_id,
        'domain': info['domain'],
        'name': info['name'],
    } for webhook_id, info in handlers.items()]

    connection.send_message(
        websocket_api.result_message(msg['id'], result))
Ejemplo n.º 27
0
async def websocket_get_translations(hass, connection, msg):
    """Handle get translations command.

    Async friendly.
    """
    resources = await async_get_translations(hass, msg['language'])
    connection.send_message(websocket_api.result_message(
        msg['id'], {
            'resources': resources,
        }
    ))
Ejemplo n.º 28
0
def websocket_get_notifications(
        hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg):
    """Return a list of persistent_notifications."""
    connection.to_write.put_nowait(
        websocket_api.result_message(msg['id'], [
            {
                key: data[key] for key in (ATTR_NOTIFICATION_ID, ATTR_MESSAGE,
                                           ATTR_STATUS, ATTR_TITLE)
            }
            for data in hass.data[DOMAIN]['notifications'].values()
        ])
    )
Ejemplo n.º 29
0
    async def async_delete_refresh_token(user, refresh_token_id):
        """Delete a refresh token."""
        refresh_token = connection.user.refresh_tokens.get(refresh_token_id)

        if refresh_token is None:
            return websocket_api.error_message(
                msg['id'], 'invalid_token_id', 'Received invalid token')

        await hass.auth.async_remove_refresh_token(refresh_token)

        connection.send_message(
            websocket_api.result_message(msg['id'], {}))
Ejemplo n.º 30
0
async def websocket_update_device(hass, connection, msg):
    """Handle update area websocket command."""
    registry = await async_get_registry(hass)

    msg.pop('type')
    msg_id = msg.pop('id')

    entry = registry.async_update_device(**msg)

    connection.send_message(websocket_api.result_message(
        msg_id, _entry_dict(entry)
    ))
Ejemplo n.º 31
0
 def get_devices():
     """Handle to get devices. Only for default account"""
     devices = get_spotify_devices(hass)
     resp = {"devices": devices}
     connection.send_message(
         websocket_api.result_message(msg["id"], resp))
Ejemplo n.º 32
0
 def websocket_handle_accounts(hass, connection, msg):
     """Handle to get accounts"""
     _LOGGER.debug("websocket_handle_accounts msg: %s", msg)
     resp = list(accounts.keys()) if accounts is not None else []
     resp.append("default")
     connection.send_message(websocket_api.result_message(msg["id"], resp))
Ejemplo n.º 33
0
async def shelly_get_config(hass, connection, msg):
    app = hass.data[DOMAIN]
    resources = await async_get_translations(
        hass, msg["language"], 'frontend',
        {'shelly'} if app.is_ver('2022.6.0') else 'shelly')
    #print("GET CONFIG*****************")
    """Handle get config command."""
    content = {}
    content["type"] = 's4h/get_config'  #Debug
    instances = []
    for entity_id, instance in app.instances.items():
        options = {}
        options[
            'yaml'] = instance.config_entry.source and not instance.config_entry.options
        options['name'] = instance.config_entry.title
        options['instance_id'] = entity_id
        #options['conf'] = json.dumps(instance.conf, sort_keys=True,
        #                             indent=4, separators=(',', ': '))
        settings = []
        cfgAttr = instance.conf.get("attributes", [])
        cfgSensor = instance.conf.get("sensors", [])
        ALL = ALL_SENSORS.keys() | ALL_ATTRIBUTES
        conf_settings = instance.conf.get(CONF_SETTINGS, {})
        for id in ALL:
            attr = id in cfgAttr
            sensor = id in cfgSensor
            conf_setting = conf_settings.get(id, {})
            unit = conf_setting.get(CONF_UNIT, "")
            div = conf_setting.get(CONF_DIV, "")
            decimals = conf_setting.get(CONF_DECIMALS, "")
            default = DEFAULT_SETTINGS.get(id, {})
            base = "component.shelly.frontend.settings." + id
            title = resources.get(base, id)

            settings.append({
                'id': id,
                'title': title,
                'has': {
                    'sensor': id in ALL_SENSORS,
                    'attrib': id in ALL_ATTRIBUTES,
                    'decimals': CONF_DECIMALS in default,
                    'div': CONF_DIV in default,
                    'unit': CONF_UNIT in default
                },
                'value': {
                    'sensor': sensor,
                    'attrib': attr,
                    'unit': unit,
                    'div': div,
                    'decimals': decimals
                },
                'default': {
                    'decimals': default.get(CONF_DECIMALS),
                    'div': default.get(CONF_DIV),
                    'unit': default.get(CONF_UNIT)
                }
            })
        settings.sort(key=lambda x: x.get('title'))
        options["settings"] = settings
        configs = []
        config_list = GLOBAL_CONFIG
        if (os.getenv("SHELLY_DEBUG")):
            config_list = GLOBAL_CONFIG + DEBUG_CONFIG
        for key in config_list:
            value = ALL_CONFIG[key]
            base = "component.shelly.frontend.config." + key + "."
            name = resources.get(base + "title", key)
            desc = resources.get(base + "desc")
            group = value.get("group")
            group = resources.get(
                "component.shelly.frontend.config.groups." + group, group)
            if "type" in value:
                configs.append({
                    "id": key,
                    "title": name,
                    "desc": desc,
                    "group": group,
                    "type": value["type"],
                    "value": instance.conf.get(key, ''),
                    "default": value.get('def', '')
                })
        options["configs"] = configs
        instances.append(options)

    content["instances"] = instances
    connection.send_message(websocket_api.result_message(msg["id"], content))
Ejemplo n.º 34
0
async def hacs_repository(hass, connection, msg):
    """Handle get media player cover command."""
    hacs = get_hacs()
    try:
        repo_id = msg.get("repository")
        action = msg.get("action")

        if repo_id is None or action is None:
            return

        repository = hacs.get_by_id(repo_id)
        hacs.logger.debug(f"Running {action} for {repository.data.full_name}")

        if action == "update":
            await repository.update_repository(True)
            repository.status.updated_info = True

        elif action == "install":
            repository.data.new = False
            was_installed = repository.data.installed
            await repository.install()
            if not was_installed:
                hass.bus.async_fire("hacs/reload", {"force": True})

        elif action == "not_new":
            repository.data.new = False

        elif action == "uninstall":
            repository.data.new = False
            await repository.uninstall()

        elif action == "hide":
            repository.data.hide = True

        elif action == "unhide":
            repository.data.hide = False

        elif action == "show_beta":
            repository.data.show_beta = True
            await repository.update_repository()

        elif action == "hide_beta":
            repository.data.show_beta = False
            await repository.update_repository()

        elif action == "toggle_beta":
            repository.data.show_beta = not repository.data.show_beta
            await repository.update_repository()

        elif action == "delete":
            repository.data.show_beta = False
            repository.remove()

        elif action == "set_version":
            if msg["version"] == repository.data.default_branch:
                repository.data.selected_tag = None
            else:
                repository.data.selected_tag = msg["version"]
            await repository.update_repository()

            hass.bus.async_fire("hacs/reload", {"force": True})

        else:
            hacs.logger.error(f"WS action '{action}' is not valid")

        await hacs.data.async_write()
        message = None
    except AIOGitHubAPIException as exception:
        message = str(exception)
        hass.bus.async_fire("hacs/error", {"message": str(exception)})
    except AttributeError as exception:
        message = f"Could not use repository with ID {repo_id} ({exception})"
    except Exception as exception:  # pylint: disable=broad-except
        message = str(exception)

    if message is not None:
        hacs.logger.error(message)
        hass.bus.async_fire("hacs/error", {"message": message})

    repository.state = None
    connection.send_message(websocket_api.result_message(msg["id"], {}))
Ejemplo n.º 35
0
async def websocket_handle_clear(hass, connection, msg):
    """Handle clearing shopping_list items."""
    await hass.data[DOMAIN].async_clear_completed()
    hass.bus.async_fire(EVENT, {"action": "clear"})
    connection.send_message(websocket_api.result_message(msg["id"]))
Ejemplo n.º 36
0
 def websocket_appkey(hass, connection, msg):
     connection.send_message(
         websocket_api.result_message(msg["id"], vapid_pub_key))
Ejemplo n.º 37
0
async def websocket_hook_delete(hass, connection, msg):
    """Handle request for account info."""
    cloud = hass.data[DOMAIN]
    await cloud.cloudhooks.async_delete(msg["webhook_id"])
    connection.send_message(websocket_api.result_message(msg["id"]))
Ejemplo n.º 38
0
async def get_critical_repositories(hass, connection, msg):
    """Handle get media player cover command."""
    critical = await async_load_from_store(hass, "critical")
    if not critical:
        critical = []
    connection.send_message(websocket_api.result_message(msg["id"], critical))
Ejemplo n.º 39
0
    """Delete device."""
    device_id = msg["device_id"]
    dev_registry = await hass.helpers.device_registry.async_get_registry()

    if not (device := dev_registry.async_get(device_id)):
        connection.send_error(
            msg["id"], websocket_api.const.ERR_NOT_FOUND, "Device not found"
        )
        return

    for config_entry in device.config_entries:
        config_entry = hass.config_entries.async_get_entry(config_entry)
        # Only delete the device if it belongs to an MQTT device entry
        if config_entry.domain == DOMAIN:
            dev_registry.async_remove_device(device_id)
            connection.send_message(websocket_api.result_message(msg["id"]))
            return

    connection.send_error(
        msg["id"], websocket_api.const.ERR_NOT_FOUND, "Non MQTT device"
    )


@websocket_api.websocket_command(
    {
        vol.Required("type"): "mqtt/subscribe",
        vol.Required("topic"): valid_subscribe_topic,
    }
)
@websocket_api.async_response
async def websocket_subscribe(hass, connection, msg):
Ejemplo n.º 40
0
async def hacs_removed(_hass, connection, msg):
    """Get information about removed repositories."""
    content = []
    for repo in list_removed_repositories():
        content.append(repo.to_json())
    connection.send_message(websocket_api.result_message(msg["id"], content))
Ejemplo n.º 41
0
async def hacs_repository_data(hass, connection, msg):
    """Handle get media player cover command."""
    hacs = get_hacs()
    repo_id = msg.get("repository")
    action = msg.get("action")
    data = msg.get("data")

    if repo_id is None:
        return

    if action == "add":
        if "github." in repo_id:
            repo_id = repo_id.split("github.com/")[1]

        if repo_id in hacs.common.skip:
            hacs.common.skip.remove(repo_id)

        if not hacs.get_by_name(repo_id):
            try:
                registration = await register_repository(repo_id, data.lower())
                if registration is not None:
                    raise HacsException(registration)
            except Exception as exception:  # pylint: disable=broad-except
                hass.bus.async_fire(
                    "hacs/error",
                    {
                        "action": "add_repository",
                        "exception": str(sys.exc_info()[0].__name__),
                        "message": str(exception),
                    },
                )
        else:
            hass.bus.async_fire(
                "hacs/error",
                {
                    "action": "add_repository",
                    "message": f"Repository '{repo_id}' exists in the store.",
                },
            )

        repository = hacs.get_by_name(repo_id)
    else:
        repository = hacs.get_by_id(repo_id)

    if repository is None:
        hass.bus.async_fire("hacs/repository", {})
        return

    hacs.logger.debug(f"Running {action} for {repository.data.full_name}")

    if action == "set_state":
        repository.state = data

    elif action == "set_version":
        repository.data.selected_tag = data
        await repository.update_repository()
        repository.state = None

    elif action == "install":
        was_installed = repository.data.installed
        repository.data.selected_tag = data
        await repository.update_repository()
        await repository.install()
        repository.state = None
        if not was_installed:
            hass.bus.async_fire("hacs/reload", {"force": True})

    elif action == "add":
        repository.state = None

    else:
        repository.state = None
        hacs.logger.error(f"WS action '{action}' is not valid")

    await hacs.data.async_write()
    connection.send_message(websocket_api.result_message(msg["id"], {}))
Ejemplo n.º 42
0
def websocket_handle_items(hass, connection, msg):
    """Handle get shopping_list items."""
    connection.send_message(
        websocket_api.result_message(msg["id"], hass.data[DOMAIN].items))
Ejemplo n.º 43
0
async def websocket_handle_add(hass, connection, msg):
    """Handle add item to shopping_list."""
    item = await hass.data[DOMAIN].async_add(msg["name"])
    hass.bus.async_fire(EVENT, {"action": "add", "item": item})
    connection.send_message(websocket_api.result_message(msg["id"], item))