mirror of
https://github.com/home-assistant/core.git
synced 2025-09-02 09:01:05 +00:00
.devcontainer
.github
.vscode
homeassistant
auth
backports
brands
components
3_day_blinds
abode
accuweather
acer_projector
acmeda
acomax
actiontec
adax
adguard
ads
advantage_air
aemet
aep_ohio
aep_texas
aftership
agent_dvr
air_quality
airgradient
airly
airnow
airq
airthings
airthings_ble
airtouch4
airtouch5
airvisual
airvisual_pro
airzone
airzone_cloud
aladdin_connect
alarm_control_panel
alarmdecoder
alert
alexa
alpha_vantage
amazon_polly
amberelectric
ambient_network
ambient_station
amcrest
amp_motorization
ampio
analytics
analytics_insights
android_ip_webcam
androidtv
androidtv_remote
anel_pwrctrl
anova
anthemav
anwb_energie
aosmith
apache_kafka
apcupsd
api
appalachianpower
apple_tv
application_credentials
apprise
aprilaire
aprs
apsystems
aqualogic
aquostv
aranet
arcam_fmj
arest
arris_tg2492lg
aruba
arve
arwn
aseko_pool_live
assist_pipeline
asterisk_cdr
asterisk_mbox
asuswrt
atag
aten_pe
atlanticcityelectric
atome
august
august_ble
aurora
aurora_abb_powerone
aussie_broadband
auth
automation
avea
avion
awair
aws
axis
azure_data_explorer
azure_devops
azure_event_hub
azure_service_bus
backup
baf
baidu
balboa
bang_olufsen
bayesian
bbox
beewi_smartclim
bge
binary_sensor
bitcoin
bizkaibus
blackbird
blebox
blink
blinksticklight
bliss_automation
bloc_blinds
blockchain
bloomsky
blue_current
bluemaestro
blueprint
bluesound
bluetooth
bluetooth_adapters
bluetooth_le_tracker
bluetooth_tracker
bmw_connected_drive
bond
bosch_shc
brandt
braviatv
brel_home
bring
broadlink
brother
brottsplatskartan
browser
brunt
bsblan
bswitch
bt_home_hub_5
bt_smarthub
bthome
bticino
bubendorff
buienradar
button
caldav
calendar
camera
canary
cast
ccm15
cert_expiry
channels
circuit
cisco_ios
cisco_mobility_express
cisco_webex_teams
citybikes
clementine
clickatell
clicksend
clicksend_tts
climate
cloud
cloudflare
cmus
co2signal
coautilities
coinbase
color_extractor
comed
comed_hourly_pricing
comelit
comfoconnect
command_line
compensation
concord232
coned
config
configurator
control4
conversation
coolmaster
counter
cover
cozytouch
cppm_tracker
cpuspeed
cribl
crownstone
cups
currencylayer
dacia
daikin
danfoss_air
datadog
date
datetime
ddwrt
debugpy
deconz
decora
decora_wifi
default_config
delijn
delmarva
deluge
demo
denon
denonavr
derivative
devialet
device_automation
device_sun_light_trigger
device_tracker
devolo_home_control
devolo_home_network
dexcom
dhcp
diagnostics
dialogflow
diaz
digital_loggers
digital_ocean
directv
discogs
discord
discovergy
dlib_face_detect
dlib_face_identify
dlink
dlna_dmr
dlna_dms
dnsip
dominos
doods
doorbird
dooya
dormakaba_dkey
dovado
downloader
dremel_3d_printer
drop_connect
dsmr
dsmr_reader
dte_energy_bridge
dublin_bus_transport
duckdns
dunehd
duotecno
duquesne_light
dwd_weather_warnings
dweet
dynalite
eafm
eastron
easyenergy
ebox
ebusd
ecoal_boiler
ecobee
ecoforest
econet
ecovacs
ecowitt
eddystone_temperature
edimax
edl21
efergy
egardia
eight_sleep
electrasmart
electric_kiwi
elgato
eliqonline
elkm1
elmax
elv
elvia
emby
emoncms
emoncms_history
emonitor
emulated_hue
emulated_kasa
emulated_roku
energenie_power_sockets
energie_vanons
energy
energyzero
enigma2
enmax
enocean
enphase_envoy
entur_public_transport
environment_canada
envisalink
ephember
epic_games_store
epion
epson
eq3btsmart
escea
esera_onewire
esphome
etherscan
eufy
eufylife_ble
event
evergy
everlights
evil_genius_labs
evohome
ezviz
faa_delays
facebook
fail2ban
familyhub
fan
fastdotcom
feedreader
ffmpeg
ffmpeg_motion
ffmpeg_noise
fibaro
fido
file
file_upload
filesize
filter
fints
fire_tv
fireservicerota
firmata
fitbit
fivem
fixer
fjaraskupan
fleetgo
flexit
flexit_bacnet
flexom
flic
flick_electric
flipr
flo
flock
flume
flux
flux_led
folder
folder_watcher
foobot
forecast_solar
forked_daapd
fortios
foscam
foursquare
free_mobile
freebox
freedns
freedompro
fritz
fritzbox
fritzbox_callmonitor
fronius
frontend
frontier_silicon
fujitsu_anywair
fully_kiosk
futurenow
fyta
garadget
garages_amsterdam
gardena_bluetooth
gaviota
gc100
gdacs
generic
generic_hygrostat
generic_thermostat
geniushub
geo_json_events
geo_location
geo_rss_events
geocaching
geofency
geonetnz_quakes
geonetnz_volcano
gios
github
gitlab_ci
gitter
glances
goalzero
gogogate2
goodwe
google
google_assistant
google_assistant_sdk
google_cloud
google_domains
google_generative_ai_conversation
google_mail
google_maps
google_pubsub
google_sheets
google_tasks
google_translate
google_travel_time
google_wifi
govee_ble
govee_light_local
gpsd
gpslogger
graphite
gree
greeneye_monitor
greenwave
group
growatt_server
gstreamer
gtfs
guardian
habitica
hardkernel
hardware
harman_kardon_avr
harmony
hassio
havana_shade
haveibeenpwned
hddtemp
hdmi_cec
heatmiser
heiwa
heos
here_travel_time
hexaom
hi_kumo
hikvision
hikvisioncam
hisense_aehw4a1
history
history_stats
hitron_coda
hive
hko
hlk_sw16
holiday
home_connect
home_plus_control
homeassistant
homeassistant_alerts
homeassistant_green
homeassistant_hardware
homeassistant_sky_connect
homeassistant_yellow
homekit
homekit_controller
homematic
homematicip_cloud
homewizard
homeworks
honeywell
horizon
hp_ilo
html5
__init__.py
const.py
icons.json
manifest.json
notify.py
services.yaml
strings.json
http
huawei_lte
hue
huisbaasje
humidifier
hunterdouglas_powerview
hurrican_shutters_wholesale
husqvarna_automower
huum
hvv_departures
hydrawise
hyperion
ialarm
iammeter
iaqualink
ibeacon
icloud
idasen_desk
idteck_prox
ifttt
iglo
ign_sismologia
ihc
image
image_processing
image_upload
imap
imgw_pib
improv_ble
incomfort
indianamichiganpower
influxdb
inkbird
input_boolean
input_button
input_datetime
input_number
input_select
input_text
inspired_shades
insteon
integration
intellifire
intent
intent_script
intesishome
ios
iotawatt
iperf3
ipma
ipp
iqvia
irish_rail_transport
isal
islamic_prayer_times
ismartwindow
iss
isy994
itach
itunes
izone
jellyfin
jewish_calendar
joaoapps_join
juicenet
justnimbus
jvc_projector
kaiterra
kaleidescape
kankun
keba
keenetic_ndms2
kef
kegtron
kentuckypower
keyboard
keyboard_remote
keymitt_ble
kira
kitchen_sink
kiwi
kmtronic
knx
kodi
konnected
kostal_plenticore
kraken
krispol
kulersky
kwb
lacrosse
lacrosse_view
lamarzocco
lametric
landisgyr_heat_meter
lannouncer
lastfm
launch_library
laundrify
lawn_mower
lcn
ld2410_ble
leaone
led_ble
legrand
lg_netcast
lg_soundbar
lidarr
life360
lifx
lifx_cloud
light
lightwave
limitlessled
linear_garage_door
linksys_smart
linode
linux_battery
lirc
litejet
litterrobot
livisi
llamalab_automate
local_calendar
local_file
local_ip
local_todo
locative
lock
logbook
logentries
logger
logi_circle
london_air
london_underground
lookin
loqed
lovelace
luci
luftdaten
lupusec
lutron
lutron_caseta
luxaflex
lw12wifi
lyric
madeco
mailbox
mailgun
manual
manual_mqtt
map
marantz
martec
marytts
mastodon
matrix
matter
maxcube
mazda
meater
medcom_ble
media_extractor
media_player
media_source
mediaroom
melcloud
melissa
melnor
meraki
message_bird
met
met_eireann
meteo_france
meteoalarm
meteoclimatic
metoffice
mfi
microbees
microsoft
microsoft_face
microsoft_face_detect
microsoft_face_identify
mijndomein_energie
mikrotik
mill
min_max
minecraft_server
minio
mjpeg
moat
mobile_app
mochad
modbus
modem_callerid
modern_forms
moehlenhoff_alpha2
mold_indicator
monessen
monoprice
monzo
moon
mopeka
motion_blinds
motionblinds_ble
motioneye
motionmount
mpd
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
msteams
mullvad
mutesync
mvglive
my
mycroft
myq
mysensors
mystrom
mythicbeastsdns
myuplink
nad
nam
namecheapdns
nanoleaf
neato
nederlandse_spoorwegen
ness_alarm
nest
netatmo
netdata
netgear
netgear_lte
netio
network
neurio_energy
nexia
nexity
nextbus
nextcloud
nextdns
nfandroidtv
nibe_heatpump
nightscout
niko_home_control
nilu
nina
nissan_leaf
nmap_tracker
nmbs
no_ip
noaa_tides
nobo_hub
norway_air
notify
notify_events
notion
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nuki
numato
number
nut
nutrichef
nws
nx584
nzbget
oasa_telematics
obihai
octoprint
oem
ohmconnect
ollama
ombi
omnilogic
onboarding
oncue
ondilo_ico
onewire
onkyo
onvif
open_meteo
openai_conversation
openalpr_cloud
openerz
openevse
openexchangerates
opengarage
openhardwaremonitor
openhome
opensensemap
opensky
opentherm_gw
openuv
openweathermap
opnsense
opower
opple
oralb
oru
oru_opower
orvibo
osoenergy
osramlightify
otbr
otp
ourgroceries
overkiz
ovo_energy
owntracks
p1_monitor
panasonic_bluray
panasonic_viera
pandora
panel_custom
panel_iframe
pcs_lighting
peco
peco_opower
pegel_online
pencom
pepco
permobil
persistent_notification
person
pge
philips_js
pi_hole
picnic
picotts
pilight
ping
pioneer
piper
pjlink
plaato
plant
plex
plugwise
plum_lightpad
pocketcasts
point
poolsense
portlandgeneral
powerwall
private_ble_device
profiler
progettihwsw
proliphix
prometheus
prosegur
prowl
proximity
proxmoxve
proxy
prusalink
ps4
pse
psoklahoma
pulseaudio_loopback
pure_energie
purpleair
push
pushbullet
pushover
pushsafer
pvoutput
pvpc_hourly_pricing
pyload
python_script
qbittorrent
qingping
qld_bushfire
qnap
qnap_qsw
qrcode
quadrafire
quantum_gateway
qvr_pro
qwikswitch
rabbitair
rachio
radarr
radio_browser
radiotherm
rainbird
raincloud
rainforest_eagle
rainforest_raven
rainmachine
random
rapt_ble
raspberry_pi
raspyrfm
raven_rock_mfg
rdw
recollect_waste
recorder
recovery_mode
recswitch
reddit
refoss
rejseplanen
remember_the_milk
remote
remote_rpi_gpio
renault
renson
reolink
repairs
repetier
rest
rest_command
rexel
rflink
rfxtrx
rhasspy
ridwell
ring
ripple
risco
rituals_perfume_genie
rmvtransport
roborock
rocketchat
roku
romy
roomba
roon
route53
rova
rpi_camera
rpi_power
rss_feed_template
rtorrent
rtsp_to_webrtc
ruckus_unleashed
russound_rio
russound_rnet
ruuvi_gateway
ruuvitag_ble
rympro
sabnzbd
saj
samsam
samsungtv
sanix
satel_integra
scene
schedule
schlage
schluter
scl
scrape
screenaway
screenlogic
script
scsgate
search
season
select
sendgrid
sense
sensibo
sensirion_ble
sensor
sensorblue
sensorpro
sensorpush
sentry
senz
serial
serial_pm
sesame
seven_segments
seventeentrack
sfr_box
sharkiq
shell_command
shelly
shodan
shopping_list
sia
sigfox
sighthound
signal_messenger
simplepush
simplisafe
simply_automated
simu
simulated
sinch
siren
sisyphus
sky_hub
skybeacon
skybell
slack
sleepiq
slide
slimproto
sma
smappee
smart_blinds
smart_home
smart_meter_texas
smarther
smartthings
smarttub
smarty
smhi
sms
smtp
smud
snapcast
snips
snmp
snooz
solaredge
solaredge_local
solarlog
solax
soma
somfy
somfy_mylink
sonarr
songpal
sonos
sony_projector
soundtouch
spaceapi
spc
speedtestdotnet
spider
splunk
spotify
sql
squeezebox
srp_energy
ssdp
starline
starlingbank
starlink
startca
statistics
statsd
steam_online
steamist
stiebel_eltron
stookalert
stookwijzer
stream
streamlabswater
stt
subaru
suez_water
sun
sunweg
supervisord
supla
surepetcare
swepco
swiss_hydrological_data
swiss_public_transport
swisscom
switch
switch_as_x
switchbee
switchbot
switchbot_cloud
switcher_kis
switchmate
symfonisk
syncthing
syncthru
synology_chat
synology_dsm
synology_srm
syslog
system_bridge
system_health
system_log
systemmonitor
tado
tag
tailscale
tailwind
tami4
tank_utility
tankerkoenig
tapsaff
tasmota
tautulli
tcp
technove
ted5000
tedee
telegram
telegram_bot
tellduslive
tellstick
telnet
temper
template
tensorflow
tesla_wall_connector
teslemetry
tessie
text
tfiac
thermobeacon
thermoplus
thermopro
thermoworks_smoke
thethingsnetwork
thingspeak
thinkingcleaner
thomson
thread
threshold
tibber
tikteck
tile
tilt_ble
time
time_date
timer
tmb
tod
todo
todoist
tolo
tomato
tomorrowio
toon
torque
totalconnect
touchline
tplink
tplink_lte
tplink_omada
tplink_tapo
traccar
traccar_server
trace
tractive
tradfri
trafikverket_camera
trafikverket_ferry
trafikverket_train
trafikverket_weatherstation
transmission
transport_nsw
travisci
trend
tts
tuya
twentemilieu
twilio
twilio_call
twilio_sms
twinkly
twitch
twitter
ubiwizz
ubus
ue_smart_radio
uk_transport
ukraine_alarm
ultraloq
unifi
unifi_direct
unifiled
unifiprotect
universal
upb
upc_connect
upcloud
update
upnp
uprise_smart_shades
uptime
uptimerobot
usb
usgs_earthquakes_feed
utility_meter
uvc
v2c
vacuum
vallox
valve
vasttrafik
velbus
velux
venstar
vera
verisure
vermont_castings
versasense
version
vesync
viaggiatreno
vicare
vilfo
vivotek
vizio
vlc
vlc_telnet
vodafone_station
voicerss
voip
volkszaehler
volumio
volvooncall
vulcan
vultr
w800rf32
wake_on_lan
wake_word
wallbox
waqi
water_heater
waterfurnace
watson_iot
watson_tts
watttime
waze_travel_time
weather
weatherflow
weatherflow_cloud
weatherkit
webhook
webmin
webostv
websocket_api
wemo
whirlpool
whisper
whois
wiffi
wilight
wirelesstag
withings
wiz
wled
wolflink
workday
worldclock
worldtidesinfo
worxlandroid
ws66i
wsdot
wyoming
x10
xbox
xeoma
xiaomi
xiaomi_aqara
xiaomi_ble
xiaomi_miio
xiaomi_tv
xmpp
xs1
yale_home
yale_smart_alarm
yalexs_ble
yamaha
yamaha_musiccast
yandex_transport
yandextts
yardian
yeelight
yeelightsunflower
yi
yolink
youless
youtube
zabbix
zamg
zengge
zeroconf
zerproc
zestimate
zeversolar
zha
zhong_hong
ziggo_mediabox_xl
zodiac
zondergas
zone
zoneminder
zwave_js
zwave_me
__init__.py
generated
helpers
scripts
util
__init__.py
__main__.py
block_async_io.py
bootstrap.py
config.py
config_entries.py
const.py
core.py
data_entry_flow.py
exceptions.py
loader.py
package_constraints.txt
py.typed
requirements.py
runner.py
setup.py
strings.json
machine
pylint
rootfs
script
tests
.core_files.yaml
.coveragerc
.dockerignore
.git-blame-ignore-revs
.gitattributes
.gitignore
.hadolint.yaml
.pre-commit-config.yaml
.prettierignore
.strict-typing
.yamllint
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
Dockerfile.dev
LICENSE.md
MANIFEST.in
README.rst
build.yaml
codecov.yml
mypy.ini
pyproject.toml
requirements.txt
requirements_all.txt
requirements_test.txt
requirements_test_all.txt
requirements_test_pre_commit.txt

Fix non thread-safe calls in html5 https://github.com/home-assistant/core/actions/runs/8808425552/job/24177668764?pr=116055
556 lines
18 KiB
Python
556 lines
18 KiB
Python
"""HTML5 Push Messaging notification service."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from contextlib import suppress
|
|
from datetime import datetime, timedelta
|
|
from functools import partial
|
|
from http import HTTPStatus
|
|
import json
|
|
import logging
|
|
import time
|
|
from urllib.parse import urlparse
|
|
import uuid
|
|
|
|
from aiohttp.hdrs import AUTHORIZATION
|
|
import jwt
|
|
from py_vapid import Vapid
|
|
from pywebpush import WebPusher
|
|
import voluptuous as vol
|
|
from voluptuous.humanize import humanize_error
|
|
|
|
from homeassistant.components import websocket_api
|
|
from homeassistant.components.http import KEY_HASS, HomeAssistantView
|
|
from homeassistant.components.notify import (
|
|
ATTR_DATA,
|
|
ATTR_TARGET,
|
|
ATTR_TITLE,
|
|
ATTR_TITLE_DEFAULT,
|
|
PLATFORM_SCHEMA,
|
|
BaseNotificationService,
|
|
)
|
|
from homeassistant.const import ATTR_NAME, URL_ROOT
|
|
from homeassistant.core import HomeAssistant, ServiceCall
|
|
from homeassistant.exceptions import HomeAssistantError
|
|
from homeassistant.helpers import config_validation as cv
|
|
from homeassistant.helpers.json import save_json
|
|
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
|
|
from homeassistant.util import ensure_unique_string
|
|
from homeassistant.util.json import JsonObjectType, load_json_object
|
|
|
|
from .const import DOMAIN, SERVICE_DISMISS
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
REGISTRATIONS_FILE = "html5_push_registrations.conf"
|
|
|
|
ATTR_VAPID_PUB_KEY = "vapid_pub_key"
|
|
ATTR_VAPID_PRV_KEY = "vapid_prv_key"
|
|
ATTR_VAPID_EMAIL = "vapid_email"
|
|
|
|
|
|
def gcm_api_deprecated(value):
|
|
"""Warn user that GCM API config is deprecated."""
|
|
if value:
|
|
_LOGGER.warning(
|
|
"Configuring html5_push_notifications via the GCM api"
|
|
" has been deprecated and stopped working since May 29,"
|
|
" 2019. Use the VAPID configuration instead. For instructions,"
|
|
" see https://www.home-assistant.io/integrations/html5/"
|
|
)
|
|
return value
|
|
|
|
|
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
|
{
|
|
vol.Optional("gcm_sender_id"): vol.All(cv.string, gcm_api_deprecated),
|
|
vol.Optional("gcm_api_key"): cv.string,
|
|
vol.Required(ATTR_VAPID_PUB_KEY): cv.string,
|
|
vol.Required(ATTR_VAPID_PRV_KEY): cv.string,
|
|
vol.Required(ATTR_VAPID_EMAIL): cv.string,
|
|
}
|
|
)
|
|
|
|
ATTR_SUBSCRIPTION = "subscription"
|
|
ATTR_BROWSER = "browser"
|
|
|
|
ATTR_ENDPOINT = "endpoint"
|
|
ATTR_KEYS = "keys"
|
|
ATTR_AUTH = "auth"
|
|
ATTR_P256DH = "p256dh"
|
|
ATTR_EXPIRATIONTIME = "expirationTime"
|
|
|
|
ATTR_TAG = "tag"
|
|
ATTR_ACTION = "action"
|
|
ATTR_ACTIONS = "actions"
|
|
ATTR_TYPE = "type"
|
|
ATTR_URL = "url"
|
|
ATTR_DISMISS = "dismiss"
|
|
ATTR_PRIORITY = "priority"
|
|
DEFAULT_PRIORITY = "normal"
|
|
ATTR_TTL = "ttl"
|
|
DEFAULT_TTL = 86400
|
|
|
|
ATTR_JWT = "jwt"
|
|
|
|
WS_TYPE_APPKEY = "notify/html5/appkey"
|
|
SCHEMA_WS_APPKEY = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend(
|
|
{vol.Required("type"): WS_TYPE_APPKEY}
|
|
)
|
|
|
|
# The number of days after the moment a notification is sent that a JWT
|
|
# is valid.
|
|
JWT_VALID_DAYS = 7
|
|
VAPID_CLAIM_VALID_HOURS = 12
|
|
|
|
KEYS_SCHEMA = vol.All(
|
|
dict,
|
|
vol.Schema(
|
|
{vol.Required(ATTR_AUTH): cv.string, vol.Required(ATTR_P256DH): cv.string}
|
|
),
|
|
)
|
|
|
|
SUBSCRIPTION_SCHEMA = vol.All(
|
|
dict,
|
|
vol.Schema(
|
|
{
|
|
vol.Required(ATTR_ENDPOINT): vol.Url(),
|
|
vol.Required(ATTR_KEYS): KEYS_SCHEMA,
|
|
vol.Optional(ATTR_EXPIRATIONTIME): vol.Any(None, cv.positive_int),
|
|
}
|
|
),
|
|
)
|
|
|
|
DISMISS_SERVICE_SCHEMA = vol.Schema(
|
|
{
|
|
vol.Optional(ATTR_TARGET): vol.All(cv.ensure_list, [cv.string]),
|
|
vol.Optional(ATTR_DATA): dict,
|
|
}
|
|
)
|
|
|
|
REGISTER_SCHEMA = vol.Schema(
|
|
{
|
|
vol.Required(ATTR_SUBSCRIPTION): SUBSCRIPTION_SCHEMA,
|
|
vol.Required(ATTR_BROWSER): vol.In(["chrome", "firefox"]),
|
|
vol.Optional(ATTR_NAME): cv.string,
|
|
}
|
|
)
|
|
|
|
CALLBACK_EVENT_PAYLOAD_SCHEMA = vol.Schema(
|
|
{
|
|
vol.Required(ATTR_TAG): cv.string,
|
|
vol.Required(ATTR_TYPE): vol.In(["received", "clicked", "closed"]),
|
|
vol.Required(ATTR_TARGET): cv.string,
|
|
vol.Optional(ATTR_ACTION): cv.string,
|
|
vol.Optional(ATTR_DATA): dict,
|
|
}
|
|
)
|
|
|
|
NOTIFY_CALLBACK_EVENT = "html5_notification"
|
|
|
|
# Badge and timestamp are Chrome specific (not in official spec)
|
|
HTML5_SHOWNOTIFICATION_PARAMETERS = (
|
|
"actions",
|
|
"badge",
|
|
"body",
|
|
"dir",
|
|
"icon",
|
|
"image",
|
|
"lang",
|
|
"renotify",
|
|
"requireInteraction",
|
|
"tag",
|
|
"timestamp",
|
|
"vibrate",
|
|
)
|
|
|
|
|
|
async def async_get_service(
|
|
hass: HomeAssistant,
|
|
config: ConfigType,
|
|
discovery_info: DiscoveryInfoType | None = None,
|
|
) -> HTML5NotificationService | None:
|
|
"""Get the HTML5 push notification service."""
|
|
json_path = hass.config.path(REGISTRATIONS_FILE)
|
|
|
|
registrations = await hass.async_add_executor_job(_load_config, json_path)
|
|
|
|
vapid_pub_key = config[ATTR_VAPID_PUB_KEY]
|
|
vapid_prv_key = config[ATTR_VAPID_PRV_KEY]
|
|
vapid_email = config[ATTR_VAPID_EMAIL]
|
|
|
|
def websocket_appkey(hass, connection, msg):
|
|
connection.send_message(websocket_api.result_message(msg["id"], vapid_pub_key))
|
|
|
|
websocket_api.async_register_command(
|
|
hass, WS_TYPE_APPKEY, websocket_appkey, SCHEMA_WS_APPKEY
|
|
)
|
|
|
|
hass.http.register_view(HTML5PushRegistrationView(registrations, json_path))
|
|
hass.http.register_view(HTML5PushCallbackView(registrations))
|
|
|
|
return HTML5NotificationService(
|
|
hass, vapid_prv_key, vapid_email, registrations, json_path
|
|
)
|
|
|
|
|
|
def _load_config(filename: str) -> JsonObjectType:
|
|
"""Load configuration."""
|
|
with suppress(HomeAssistantError):
|
|
return load_json_object(filename)
|
|
return {}
|
|
|
|
|
|
class HTML5PushRegistrationView(HomeAssistantView):
|
|
"""Accepts push registrations from a browser."""
|
|
|
|
url = "/api/notify.html5"
|
|
name = "api:notify.html5"
|
|
|
|
def __init__(self, registrations, json_path):
|
|
"""Init HTML5PushRegistrationView."""
|
|
self.registrations = registrations
|
|
self.json_path = json_path
|
|
|
|
async def post(self, request):
|
|
"""Accept the POST request for push registrations from a browser."""
|
|
try:
|
|
data = await request.json()
|
|
except ValueError:
|
|
return self.json_message("Invalid JSON", HTTPStatus.BAD_REQUEST)
|
|
try:
|
|
data = REGISTER_SCHEMA(data)
|
|
except vol.Invalid as ex:
|
|
return self.json_message(humanize_error(data, ex), HTTPStatus.BAD_REQUEST)
|
|
|
|
devname = data.get(ATTR_NAME)
|
|
data.pop(ATTR_NAME, None)
|
|
|
|
name = self.find_registration_name(data, devname)
|
|
previous_registration = self.registrations.get(name)
|
|
|
|
self.registrations[name] = data
|
|
|
|
try:
|
|
hass = request.app[KEY_HASS]
|
|
|
|
await hass.async_add_executor_job(
|
|
save_json, self.json_path, self.registrations
|
|
)
|
|
return self.json_message("Push notification subscriber registered.")
|
|
except HomeAssistantError:
|
|
if previous_registration is not None:
|
|
self.registrations[name] = previous_registration
|
|
else:
|
|
self.registrations.pop(name)
|
|
|
|
return self.json_message(
|
|
"Error saving registration.", HTTPStatus.INTERNAL_SERVER_ERROR
|
|
)
|
|
|
|
def find_registration_name(self, data, suggested=None):
|
|
"""Find a registration name matching data or generate a unique one."""
|
|
endpoint = data.get(ATTR_SUBSCRIPTION).get(ATTR_ENDPOINT)
|
|
for key, registration in self.registrations.items():
|
|
subscription = registration.get(ATTR_SUBSCRIPTION)
|
|
if subscription.get(ATTR_ENDPOINT) == endpoint:
|
|
return key
|
|
return ensure_unique_string(suggested or "unnamed device", self.registrations)
|
|
|
|
async def delete(self, request):
|
|
"""Delete a registration."""
|
|
try:
|
|
data = await request.json()
|
|
except ValueError:
|
|
return self.json_message("Invalid JSON", HTTPStatus.BAD_REQUEST)
|
|
|
|
subscription = data.get(ATTR_SUBSCRIPTION)
|
|
|
|
found = None
|
|
|
|
for key, registration in self.registrations.items():
|
|
if registration.get(ATTR_SUBSCRIPTION) == subscription:
|
|
found = key
|
|
break
|
|
|
|
if not found:
|
|
# If not found, unregistering was already done. Return 200
|
|
return self.json_message("Registration not found.")
|
|
|
|
reg = self.registrations.pop(found)
|
|
|
|
try:
|
|
hass = request.app[KEY_HASS]
|
|
|
|
await hass.async_add_executor_job(
|
|
save_json, self.json_path, self.registrations
|
|
)
|
|
except HomeAssistantError:
|
|
self.registrations[found] = reg
|
|
return self.json_message(
|
|
"Error saving registration.", HTTPStatus.INTERNAL_SERVER_ERROR
|
|
)
|
|
|
|
return self.json_message("Push notification subscriber unregistered.")
|
|
|
|
|
|
class HTML5PushCallbackView(HomeAssistantView):
|
|
"""Accepts push registrations from a browser."""
|
|
|
|
requires_auth = False
|
|
url = "/api/notify.html5/callback"
|
|
name = "api:notify.html5/callback"
|
|
|
|
def __init__(self, registrations):
|
|
"""Init HTML5PushCallbackView."""
|
|
self.registrations = registrations
|
|
|
|
def decode_jwt(self, token):
|
|
"""Find the registration that signed this JWT and return it."""
|
|
|
|
# 1. Check claims w/o verifying to see if a target is in there.
|
|
# 2. If target in claims, attempt to verify against the given name.
|
|
# 2a. If decode is successful, return the payload.
|
|
# 2b. If decode is unsuccessful, return a 401.
|
|
|
|
target_check = jwt.decode(
|
|
token, algorithms=["ES256", "HS256"], options={"verify_signature": False}
|
|
)
|
|
if target_check.get(ATTR_TARGET) in self.registrations:
|
|
possible_target = self.registrations[target_check[ATTR_TARGET]]
|
|
key = possible_target[ATTR_SUBSCRIPTION][ATTR_KEYS][ATTR_AUTH]
|
|
with suppress(jwt.exceptions.DecodeError):
|
|
return jwt.decode(token, key, algorithms=["ES256", "HS256"])
|
|
|
|
return self.json_message(
|
|
"No target found in JWT", status_code=HTTPStatus.UNAUTHORIZED
|
|
)
|
|
|
|
# The following is based on code from Auth0
|
|
# https://auth0.com/docs/quickstart/backend/python
|
|
def check_authorization_header(self, request):
|
|
"""Check the authorization header."""
|
|
if not (auth := request.headers.get(AUTHORIZATION)):
|
|
return self.json_message(
|
|
"Authorization header is expected", status_code=HTTPStatus.UNAUTHORIZED
|
|
)
|
|
|
|
parts = auth.split()
|
|
|
|
if parts[0].lower() != "bearer":
|
|
return self.json_message(
|
|
"Authorization header must start with Bearer",
|
|
status_code=HTTPStatus.UNAUTHORIZED,
|
|
)
|
|
if len(parts) != 2:
|
|
return self.json_message(
|
|
"Authorization header must be Bearer token",
|
|
status_code=HTTPStatus.UNAUTHORIZED,
|
|
)
|
|
|
|
token = parts[1]
|
|
try:
|
|
payload = self.decode_jwt(token)
|
|
except jwt.exceptions.InvalidTokenError:
|
|
return self.json_message(
|
|
"token is invalid", status_code=HTTPStatus.UNAUTHORIZED
|
|
)
|
|
return payload
|
|
|
|
async def post(self, request):
|
|
"""Accept the POST request for push registrations event callback."""
|
|
auth_check = self.check_authorization_header(request)
|
|
if not isinstance(auth_check, dict):
|
|
return auth_check
|
|
|
|
try:
|
|
data = await request.json()
|
|
except ValueError:
|
|
return self.json_message("Invalid JSON", HTTPStatus.BAD_REQUEST)
|
|
|
|
event_payload = {
|
|
ATTR_TAG: data.get(ATTR_TAG),
|
|
ATTR_TYPE: data[ATTR_TYPE],
|
|
ATTR_TARGET: auth_check[ATTR_TARGET],
|
|
}
|
|
|
|
if data.get(ATTR_ACTION) is not None:
|
|
event_payload[ATTR_ACTION] = data.get(ATTR_ACTION)
|
|
|
|
if data.get(ATTR_DATA) is not None:
|
|
event_payload[ATTR_DATA] = data.get(ATTR_DATA)
|
|
|
|
try:
|
|
event_payload = CALLBACK_EVENT_PAYLOAD_SCHEMA(event_payload)
|
|
except vol.Invalid as ex:
|
|
_LOGGER.warning(
|
|
"Callback event payload is not valid: %s",
|
|
humanize_error(event_payload, ex),
|
|
)
|
|
|
|
event_name = f"{NOTIFY_CALLBACK_EVENT}.{event_payload[ATTR_TYPE]}"
|
|
request.app[KEY_HASS].bus.fire(event_name, event_payload)
|
|
return self.json({"status": "ok", "event": event_payload[ATTR_TYPE]})
|
|
|
|
|
|
class HTML5NotificationService(BaseNotificationService):
|
|
"""Implement the notification service for HTML5."""
|
|
|
|
def __init__(self, hass, vapid_prv, vapid_email, registrations, json_path):
|
|
"""Initialize the service."""
|
|
self._vapid_prv = vapid_prv
|
|
self._vapid_email = vapid_email
|
|
self.registrations = registrations
|
|
self.registrations_json_path = json_path
|
|
|
|
async def async_dismiss_message(service: ServiceCall) -> None:
|
|
"""Handle dismissing notification message service calls."""
|
|
kwargs = {}
|
|
|
|
if self.targets is not None:
|
|
kwargs[ATTR_TARGET] = self.targets
|
|
elif service.data.get(ATTR_TARGET) is not None:
|
|
kwargs[ATTR_TARGET] = service.data.get(ATTR_TARGET)
|
|
|
|
kwargs[ATTR_DATA] = service.data.get(ATTR_DATA)
|
|
|
|
await self.async_dismiss(**kwargs)
|
|
|
|
hass.services.async_register(
|
|
DOMAIN,
|
|
SERVICE_DISMISS,
|
|
async_dismiss_message,
|
|
schema=DISMISS_SERVICE_SCHEMA,
|
|
)
|
|
|
|
@property
|
|
def targets(self):
|
|
"""Return a dictionary of registered targets."""
|
|
targets = {}
|
|
for registration in self.registrations:
|
|
targets[registration] = registration
|
|
return targets
|
|
|
|
def dismiss(self, **kwargs):
|
|
"""Dismisses a notification."""
|
|
data = kwargs.get(ATTR_DATA)
|
|
tag = data.get(ATTR_TAG) if data else ""
|
|
payload = {ATTR_TAG: tag, ATTR_DISMISS: True, ATTR_DATA: {}}
|
|
|
|
self._push_message(payload, **kwargs)
|
|
|
|
async def async_dismiss(self, **kwargs):
|
|
"""Dismisses a notification.
|
|
|
|
This method must be run in the event loop.
|
|
"""
|
|
await self.hass.async_add_executor_job(partial(self.dismiss, **kwargs))
|
|
|
|
def send_message(self, message="", **kwargs):
|
|
"""Send a message to a user."""
|
|
tag = str(uuid.uuid4())
|
|
payload = {
|
|
"badge": "/static/images/notification-badge.png",
|
|
"body": message,
|
|
ATTR_DATA: {},
|
|
"icon": "/static/icons/favicon-192x192.png",
|
|
ATTR_TAG: tag,
|
|
ATTR_TITLE: kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT),
|
|
}
|
|
|
|
if data := kwargs.get(ATTR_DATA):
|
|
# Pick out fields that should go into the notification directly vs
|
|
# into the notification data dictionary.
|
|
|
|
data_tmp = {}
|
|
|
|
for key, val in data.items():
|
|
if key in HTML5_SHOWNOTIFICATION_PARAMETERS:
|
|
payload[key] = val
|
|
else:
|
|
data_tmp[key] = val
|
|
|
|
payload[ATTR_DATA] = data_tmp
|
|
|
|
if (
|
|
payload[ATTR_DATA].get(ATTR_URL) is None
|
|
and payload.get(ATTR_ACTIONS) is None
|
|
):
|
|
payload[ATTR_DATA][ATTR_URL] = URL_ROOT
|
|
|
|
self._push_message(payload, **kwargs)
|
|
|
|
def _push_message(self, payload, **kwargs):
|
|
"""Send the message."""
|
|
|
|
timestamp = int(time.time())
|
|
ttl = int(kwargs.get(ATTR_TTL, DEFAULT_TTL))
|
|
priority = kwargs.get(ATTR_PRIORITY, DEFAULT_PRIORITY)
|
|
if priority not in ["normal", "high"]:
|
|
priority = DEFAULT_PRIORITY
|
|
payload["timestamp"] = timestamp * 1000 # Javascript ms since epoch
|
|
|
|
if not (targets := kwargs.get(ATTR_TARGET)):
|
|
targets = self.registrations.keys()
|
|
|
|
for target in list(targets):
|
|
info = self.registrations.get(target)
|
|
try:
|
|
info = REGISTER_SCHEMA(info)
|
|
except vol.Invalid:
|
|
_LOGGER.error(
|
|
"%s is not a valid HTML5 push notification target", target
|
|
)
|
|
continue
|
|
subscription = info[ATTR_SUBSCRIPTION]
|
|
payload[ATTR_DATA][ATTR_JWT] = add_jwt(
|
|
timestamp,
|
|
target,
|
|
payload[ATTR_TAG],
|
|
subscription[ATTR_KEYS][ATTR_AUTH],
|
|
)
|
|
webpusher = WebPusher(info[ATTR_SUBSCRIPTION])
|
|
|
|
endpoint = urlparse(subscription[ATTR_ENDPOINT])
|
|
vapid_claims = {
|
|
"sub": f"mailto:{self._vapid_email}",
|
|
"aud": f"{endpoint.scheme}://{endpoint.netloc}",
|
|
"exp": timestamp + (VAPID_CLAIM_VALID_HOURS * 60 * 60),
|
|
}
|
|
vapid_headers = Vapid.from_string(self._vapid_prv).sign(vapid_claims)
|
|
vapid_headers.update({"urgency": priority, "priority": priority})
|
|
response = webpusher.send(
|
|
data=json.dumps(payload), headers=vapid_headers, ttl=ttl
|
|
)
|
|
|
|
if response.status_code == 410:
|
|
_LOGGER.info("Notification channel has expired")
|
|
reg = self.registrations.pop(target)
|
|
try:
|
|
save_json(self.registrations_json_path, self.registrations)
|
|
except HomeAssistantError:
|
|
self.registrations[target] = reg
|
|
_LOGGER.error("Error saving registration")
|
|
else:
|
|
_LOGGER.info("Configuration saved")
|
|
elif response.status_code > 399:
|
|
_LOGGER.error(
|
|
"There was an issue sending the notification %s: %s",
|
|
response.status,
|
|
response.text,
|
|
)
|
|
|
|
|
|
def add_jwt(timestamp, target, tag, jwt_secret):
|
|
"""Create JWT json to put into payload."""
|
|
|
|
jwt_exp = datetime.fromtimestamp(timestamp) + timedelta(days=JWT_VALID_DAYS)
|
|
jwt_claims = {
|
|
"exp": jwt_exp,
|
|
"nbf": timestamp,
|
|
"iat": timestamp,
|
|
ATTR_TARGET: target,
|
|
ATTR_TAG: tag,
|
|
}
|
|
return jwt.encode(jwt_claims, jwt_secret)
|