mirror of
https://github.com/home-assistant/core.git
synced 2025-09-02 09:01:05 +00:00
.github
docs
homeassistant
auth
components
abode
ads
air_quality
alarm_control_panel
alarmdecoder
alert
alexa
ambient_station
amcrest
android_ip_webcam
androidtv
apcupsd
api
apple_tv
aqualogic
arduino
arlo
asterisk_mbox
asuswrt
august
auth
automation
axis
bbb_gpio
binary_sensor
blink
bloomsky
bmw_connected_drive
browser
calendar
camera
canary
cast
cisco_mobility_express
climate
cloud
__init__.py
client.py
const.py
http_api.py
prefs.py
services.yaml
utils.py
cloudflare
coinbase
comfoconnect
config
configurator
conversation
counter
cover
cppm_tracker
daikin
danfoss_air
datadog
deconz
default_config
demo
device_sun_light_trigger
device_tracker
dialogflow
digital_ocean
discovery
dominos
doorbird
dovado
downloader
duckdns
dweet
dyson
ebusd
ecoal_boiler
ecobee
ecovacs
edp_redy
egardia
eight_sleep
elkm1
emoncms_history
emulated_hue
emulated_roku
enigma2
enocean
envisalink
esphome
eufy
evohome
fan
fastdotcom
feedreader
ffmpeg
fibaro
folder_watcher
foursquare
freebox
freedns
fritzbox
frontend
gc100
geo_location
geofency
goalfeed
google
google_assistant
google_domains
google_pubsub
googlehome
gpslogger
graphite
greeneye_monitor
group
habitica
hangouts
harmony
hassio
hdmi_cec
history
history_graph
hive
hlk_sw16
homekit
homekit_controller
homematic
homematicip_cloud
homeworks
http
huawei_lte
hue
hydrawise
idteck_prox
ifttt
ihc
image_processing
influxdb
input_boolean
input_datetime
input_number
input_select
input_text
insteon
insteon_local
insteon_plm
intent_script
introduction
ios
iota
iperf3
ipma
isy994
itach
joaoapps_join
juicenet
keyboard
keyboard_remote
kira
knx
konnected
lametric
lcn
lifx
light
lightwave
linode
lirc
litejet
locative
lock
logbook
logentries
logger
logi_circle
lovelace
luftdaten
lupusec
lutron
lutron_caseta
mailbox
mailgun
map
matrix
maxcube
media_extractor
media_player
melissa
meteo_france
microsoft_face
mobile_app
mochad
modbus
mqtt
mqtt_eventstream
mqtt_statestream
mychevy
mycroft
mysensors
mythicbeastsdns
namecheapdns
neato
ness_alarm
nest
netatmo
netgear_lte
nissan_leaf
no_ip
notify
nuheat
nuimo_controller
octoprint
onboarding
opentherm_gw
openuv
owlet
owntracks
panel_custom
panel_iframe
persistent_notification
person
pilight
plant
plum_lightpad
point
prometheus
proximity
ps4
python_script
qwikswitch
rachio
rainbird
raincloud
rainmachine
raspihats
recorder
reddit
remember_the_milk
remote
rest_command
rflink
rfxtrx
ring
roku
route53
rpi_gpio
rpi_pfio
rss_feed_template
sabnzbd
satel_integra
scene
script
scsgate
sense
sensor
shell_command
shiftr
shopping_list
simplisafe
sisyphus
skybell
sleepiq
smappee
smartthings
smhi
snips
sonos
spaceapi
spc
speedtestdotnet
spider
splunk
statsd
stream
sun
switch
system_health
system_log
tado
tahoma
telegram_bot
tellduslive
tellstick
tesla
thethingsnetwork
thingspeak
thinkingcleaner
tibber
timer
tof
toon
tplink
tplink_lte
tradfri
transmission
tts
tuya
twilio
unifi
upcloud
updater
upnp
usps
utility_meter
vacuum
velbus
velux
vera
verisure
volvooncall
vultr
w800rf32
wake_on_lan
water_heater
waterfurnace
watson_iot
weather
webhook
weblink
webostv
websocket_api
wemo
wink
wirelesstag
wunderlist
xiaomi_aqara
xiaomi_miio
xs1
zabbix
zeroconf
zha
zigbee
zone
zoneminder
zwave
__init__.py
services.yaml
helpers
scripts
util
__init__.py
__main__.py
bootstrap.py
config.py
config_entries.py
const.py
core.py
data_entry_flow.py
exceptions.py
loader.py
monkey_patch.py
package_constraints.txt
requirements.py
setup.py
script
tests
virtualization
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hound.yml
.ignore
.readthedocs.yml
.travis.yml
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
LICENSE.md
MANIFEST.in
README.rst
mypy.ini
pylintrc
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
setup.cfg
setup.py
tox.ini

* Add cloud status * Expose certificate details * store & reset last state * Fix tests * update tests * update req * fix lint
186 lines
6.0 KiB
Python
186 lines
6.0 KiB
Python
"""Interface implementation for cloud client."""
|
|
import asyncio
|
|
from pathlib import Path
|
|
from typing import Any, Dict
|
|
|
|
import aiohttp
|
|
from hass_nabucasa.client import CloudClient as Interface
|
|
|
|
from homeassistant.components.alexa import smart_home as alexa_sh
|
|
from homeassistant.components.google_assistant import (
|
|
helpers as ga_h, smart_home as ga)
|
|
from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES
|
|
from homeassistant.helpers.typing import HomeAssistantType
|
|
from homeassistant.util.aiohttp import MockRequest
|
|
|
|
from . import utils
|
|
from .const import CONF_ENTITY_CONFIG, CONF_FILTER, DOMAIN
|
|
from .prefs import CloudPreferences
|
|
|
|
|
|
class CloudClient(Interface):
|
|
"""Interface class for Home Assistant Cloud."""
|
|
|
|
def __init__(self, hass: HomeAssistantType, prefs: CloudPreferences,
|
|
websession: aiohttp.ClientSession,
|
|
alexa_config: Dict[str, Any], google_config: Dict[str, Any]):
|
|
"""Initialize client interface to Cloud."""
|
|
self._hass = hass
|
|
self._prefs = prefs
|
|
self._websession = websession
|
|
self._alexa_user_config = alexa_config
|
|
self._google_user_config = google_config
|
|
|
|
self._alexa_config = None
|
|
self._google_config = None
|
|
|
|
@property
|
|
def base_path(self) -> Path:
|
|
"""Return path to base dir."""
|
|
return Path(self._hass.config.config_dir)
|
|
|
|
@property
|
|
def prefs(self) -> CloudPreferences:
|
|
"""Return Cloud preferences."""
|
|
return self._prefs
|
|
|
|
@property
|
|
def loop(self) -> asyncio.BaseEventLoop:
|
|
"""Return client loop."""
|
|
return self._hass.loop
|
|
|
|
@property
|
|
def websession(self) -> aiohttp.ClientSession:
|
|
"""Return client session for aiohttp."""
|
|
return self._websession
|
|
|
|
@property
|
|
def aiohttp_runner(self) -> aiohttp.web.AppRunner:
|
|
"""Return client webinterface aiohttp application."""
|
|
return self._hass.http.runner
|
|
|
|
@property
|
|
def cloudhooks(self) -> Dict[str, Dict[str, str]]:
|
|
"""Return list of cloudhooks."""
|
|
return self._prefs.cloudhooks
|
|
|
|
@property
|
|
def remote_autostart(self) -> bool:
|
|
"""Return true if we want start a remote connection."""
|
|
return self._prefs.remote_enabled
|
|
|
|
@property
|
|
def alexa_config(self) -> alexa_sh.Config:
|
|
"""Return Alexa config."""
|
|
if not self._alexa_config:
|
|
alexa_conf = self._alexa_user_config
|
|
|
|
self._alexa_config = alexa_sh.Config(
|
|
endpoint=None,
|
|
async_get_access_token=None,
|
|
should_expose=alexa_conf[CONF_FILTER],
|
|
entity_config=alexa_conf.get(CONF_ENTITY_CONFIG),
|
|
)
|
|
|
|
return self._alexa_config
|
|
|
|
@property
|
|
def google_config(self) -> ga_h.Config:
|
|
"""Return Google config."""
|
|
if not self._google_config:
|
|
google_conf = self._google_user_config
|
|
|
|
def should_expose(entity):
|
|
"""If an entity should be exposed."""
|
|
if entity.entity_id in CLOUD_NEVER_EXPOSED_ENTITIES:
|
|
return False
|
|
|
|
return google_conf['filter'](entity.entity_id)
|
|
|
|
self._google_config = ga_h.Config(
|
|
should_expose=should_expose,
|
|
allow_unlock=self._prefs.google_allow_unlock,
|
|
entity_config=google_conf.get(CONF_ENTITY_CONFIG),
|
|
)
|
|
|
|
return self._google_config
|
|
|
|
@property
|
|
def google_user_config(self) -> Dict[str, Any]:
|
|
"""Return google action user config."""
|
|
return self._google_user_config
|
|
|
|
async def cleanups(self) -> None:
|
|
"""Cleanup some stuff after logout."""
|
|
self._alexa_config = None
|
|
self._google_config = None
|
|
|
|
async def async_user_message(
|
|
self, identifier: str, title: str, message: str) -> None:
|
|
"""Create a message for user to UI."""
|
|
self._hass.components.persistent_notification.async_create(
|
|
message, title, identifier
|
|
)
|
|
|
|
async def async_alexa_message(
|
|
self, payload: Dict[Any, Any]) -> Dict[Any, Any]:
|
|
"""Process cloud alexa message to client."""
|
|
return await alexa_sh.async_handle_message(
|
|
self._hass, self.alexa_config, payload,
|
|
enabled=self._prefs.alexa_enabled
|
|
)
|
|
|
|
async def async_google_message(
|
|
self, payload: Dict[Any, Any]) -> Dict[Any, Any]:
|
|
"""Process cloud google message to client."""
|
|
if not self._prefs.google_enabled:
|
|
return ga.turned_off_response(payload)
|
|
|
|
cloud = self._hass.data[DOMAIN]
|
|
return await ga.async_handle_message(
|
|
self._hass, self.google_config,
|
|
cloud.claims['cognito:username'], payload
|
|
)
|
|
|
|
async def async_webhook_message(
|
|
self, payload: Dict[Any, Any]) -> Dict[Any, Any]:
|
|
"""Process cloud webhook message to client."""
|
|
cloudhook_id = payload['cloudhook_id']
|
|
|
|
found = None
|
|
for cloudhook in self._prefs.cloudhooks.values():
|
|
if cloudhook['cloudhook_id'] == cloudhook_id:
|
|
found = cloudhook
|
|
break
|
|
|
|
if found is None:
|
|
return {
|
|
'status': 200
|
|
}
|
|
|
|
request = MockRequest(
|
|
content=payload['body'].encode('utf-8'),
|
|
headers=payload['headers'],
|
|
method=payload['method'],
|
|
query_string=payload['query'],
|
|
)
|
|
|
|
response = await self._hass.components.webhook.async_handle_webhook(
|
|
found['webhook_id'], request)
|
|
|
|
response_dict = utils.aiohttp_serialize_response(response)
|
|
body = response_dict.get('body')
|
|
|
|
return {
|
|
'body': body,
|
|
'status': response_dict['status'],
|
|
'headers': {
|
|
'Content-Type': response.content_type
|
|
}
|
|
}
|
|
|
|
async def async_cloudhooks_update(
|
|
self, data: Dict[str, Dict[str, str]]) -> None:
|
|
"""Update local list of cloudhooks."""
|
|
await self._prefs.async_update(cloudhooks=data)
|