1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-13 15:30:03 +00:00
Files
.devcontainer
.github
.vscode
docs
homeassistant
auth
components
abode
accuweather
acer_projector
acmeda
actiontec
adguard
ads
advantage_air
aemet
aftership
agent_dvr
air_quality
airly
airnow
airvisual
aladdin_connect
alarm_control_panel
alarmdecoder
alert
alexa
almond
alpha_vantage
amazon_polly
ambiclimate
ambient_station
amcrest
ampio
analytics
__init__.py
analytics.py
const.py
manifest.json
android_ip_webcam
androidtv
anel_pwrctrl
anthemav
apache_kafka
apcupsd
api
apns
apple_tv
apprise
aprs
aqualogic
aquostv
arcam_fmj
arduino
arest
arlo
arris_tg2492lg
aruba
arwn
asterisk_cdr
asterisk_mbox
asuswrt
atag
aten_pe
atome
august
aurora
aurora_abb_powerone
auth
automation
avea
avion
awair
aws
axis
azure_devops
azure_event_hub
azure_service_bus
baidu
bayesian
bbb_gpio
bbox
beewi_smartclim
bh1750
binary_sensor
bitcoin
bizkaibus
blackbird
blebox
blink
blinksticklight
blinkt
blockchain
bloomsky
blueprint
bluesound
bluetooth_le_tracker
bluetooth_tracker
bme280
bme680
bmp280
bmw_connected_drive
bond
braviatv
broadlink
brother
brottsplatskartan
browser
brunt
bsblan
bt_home_hub_5
bt_smarthub
buienradar
caldav
calendar
camera
canary
cast
cert_expiry
channels
circuit
cisco_ios
cisco_mobility_express
cisco_webex_teams
citybikes
clementine
clickatell
clicksend
clicksend_tts
climacell
climate
cloud
cloudflare
cmus
co2signal
coinbase
color_extractor
comed_hourly_pricing
comfoconnect
command_line
compensation
concord232
config
configurator
control4
conversation
coolmaster
coronavirus
counter
cover
cppm_tracker
cpuspeed
cups
currencylayer
daikin
danfoss_air
darksky
datadog
ddwrt
debugpy
deconz
decora
decora_wifi
default_config
delijn
deluge
demo
denon
denonavr
derivative
deutsche_bahn
device_automation
device_sun_light_trigger
device_tracker
devolo_home_control
dexcom
dhcp
dht
dialogflow
digital_ocean
digitalloggers
directv
discogs
discord
discovery
dlib_face_detect
dlib_face_identify
dlink
dlna_dmr
dnsip
dominos
doods
doorbird
dovado
downloader
dsmr
dsmr_reader
dte_energy_bridge
dublin_bus_transport
duckdns
dunehd
dwd_weather_warnings
dweet
dynalite
dyson
eafm
ebox
ebusd
ecoal_boiler
ecobee
econet
ecovacs
eddystone_temperature
edimax
edl21
ee_brightbox
efergy
egardia
eight_sleep
elgato
eliqonline
elkm1
elv
emby
emoncms
emoncms_history
emonitor
emulated_hue
emulated_kasa
emulated_roku
enigma2
enocean
enphase_envoy
entur_public_transport
environment_canada
envirophat
envisalink
ephember
epson
epsonworkforce
eq3btsmart
esphome
essent
etherscan
eufy
everlights
evohome
ezviz
faa_delays
facebook
facebox
fail2ban
familyhub
fan
fastdotcom
feedreader
ffmpeg
ffmpeg_motion
ffmpeg_noise
fibaro
fido
file
filesize
filter
fints
fireservicerota
firmata
fitbit
fixer
fleetgo
flexit
flic
flick_electric
flo
flock
flume
flunearyou
flux
flux_led
folder
folder_watcher
foobot
forked_daapd
fortios
foscam
foursquare
free_mobile
freebox
freedns
fritz
fritzbox
fritzbox_callmonitor
fritzbox_netmonitor
fronius
frontend
frontier_silicon
futurenow
garadget
garmin_connect
gc100
gdacs
generic
generic_thermostat
geniushub
geo_json_events
geo_location
geo_rss_events
geofency
geonetnz_quakes
geonetnz_volcano
gios
github
gitlab_ci
gitter
glances
gntp
goalfeed
goalzero
gogogate2
google
google_assistant
google_cloud
google_domains
google_maps
google_pubsub
google_translate
google_travel_time
google_wifi
gpmdp
gpsd
gpslogger
graphite
gree
greeneye_monitor
greenwave
group
growatt_server
gstreamer
gtfs
guardian
habitica
hangouts
harman_kardon_avr
harmony
hassio
haveibeenpwned
hddtemp
hdmi_cec
heatmiser
heos
here_travel_time
hikvision
hikvisioncam
hisense_aehw4a1
history
history_stats
hitron_coda
hive
hlk_sw16
home_connect
home_plus_control
homeassistant
homekit
homekit_controller
homematic
homematicip_cloud
homeworks
honeywell
horizon
hp_ilo
html5
http
htu21d
huawei_lte
huawei_router
hue
huisbaasje
humidifier
hunterdouglas_powerview
hvv_departures
hydrawise
hyperion
iammeter
iaqualink
icloud
idteck_prox
ifttt
iglo
ign_sismologia
ihc
image
image_processing
imap
imap_email_content
incomfort
influxdb
input_boolean
input_datetime
input_number
input_select
input_text
insteon
integration
intent
intent_script
intesishome
ios
iota
iperf3
ipma
ipp
iqvia
irish_rail_transport
islamic_prayer_times
iss
isy994
itach
itunes
izone
jewish_calendar
joaoapps_join
juicenet
kaiterra
kankun
keba
keenetic_ndms2
kef
keyboard
keyboard_remote
kira
kiwi
kmtronic
knx
kodi
konnected
kostal_plenticore
kulersky
kwb
lacrosse
lametric
lannouncer
lastfm
launch_library
lcn
lg_netcast
lg_soundbar
life360
lifx
lifx_cloud
lifx_legacy
light
lightwave
limitlessled
linksys_smart
linode
linux_battery
lirc
litejet
litterrobot
llamalab_automate
local_file
local_ip
locative
lock
logbook
logentries
logger
logi_circle
london_air
london_underground
loopenergy
lovelace
luci
luftdaten
lupusec
lutron
lutron_caseta
lw12wifi
lyft
lyric
magicseaweed
mailbox
mailgun
manual
manual_mqtt
map
marytts
mastodon
matrix
maxcube
mazda
mcp23017
media_extractor
media_player
media_source
mediaroom
melcloud
melissa
meraki
message_bird
met
met_eireann
meteo_france
meteoalarm
metoffice
mfi
mhz19
microsoft
microsoft_face
microsoft_face_detect
microsoft_face_identify
miflora
mikrotik
mill
min_max
minecraft_server
minio
mitemp_bt
mjpeg
mobile_app
mochad
modbus
modem_callerid
mold_indicator
monoprice
moon
motion_blinds
mpchc
mpd
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
msteams
mullvad
mvglive
my
mychevy
mycroft
myq
mysensors
mystrom
mythicbeastsdns
n26
nad
namecheapdns
nanoleaf
neato
nederlandse_spoorwegen
nello
ness_alarm
nest
netatmo
netdata
netgear
netgear_lte
netio
neurio_energy
nexia
nextbus
nextcloud
nfandroidtv
nightscout
niko_home_control
nilu
nissan_leaf
nmap_tracker
nmbs
no_ip
noaa_tides
norway_air
notify
notify_events
notion
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nuki
numato
number
nut
nws
nx584
nzbget
oasa_telematics
obihai
octoprint
oem
ohmconnect
ombi
omnilogic
onboarding
ondilo_ico
onewire
onkyo
onvif
openalpr_cloud
openalpr_local
opencv
openerz
openevse
openexchangerates
opengarage
openhardwaremonitor
openhome
opensensemap
opensky
opentherm_gw
openuv
openweathermap
opnsense
opple
orangepi_gpio
oru
orvibo
osramlightify
otp
ovo_energy
owntracks
ozw
panasonic_bluray
panasonic_viera
pandora
panel_custom
panel_iframe
pcal9535a
pencom
persistent_notification
person
philips_js
pi4ioe5v9xxxx
pi_hole
picotts
piglow
pilight
ping
pioneer
pjlink
plaato
plant
plex
plugwise
plum_lightpad
pocketcasts
point
poolsense
powerwall
profiler
progettihwsw
proliphix
prometheus
prowl
proximity
proxmoxve
proxy
ps4
pulseaudio_loopback
push
pushbullet
pushover
pushsafer
pvoutput
pvpc_hourly_pricing
pyload
python_script
qbittorrent
qld_bushfire
qnap
qrcode
quantum_gateway
qvr_pro
qwikswitch
rachio
radarr
radiotherm
rainbird
raincloud
rainforest_eagle
rainmachine
random
raspihats
raspyrfm
recollect_waste
recorder
recswitch
reddit
rejseplanen
remember_the_milk
remote
remote_rpi_gpio
repetier
rest
rest_command
rflink
rfxtrx
ring
ripple
risco
rituals_perfume_genie
rmvtransport
rocketchat
roku
roomba
roon
route53
rova
rpi_camera
rpi_gpio
rpi_gpio_pwm
rpi_pfio
rpi_power
rpi_rf
rss_feed_template
rtorrent
ruckus_unleashed
russound_rio
russound_rnet
sabnzbd
safe_mode
saj
samsungtv
satel_integra
scene
schluter
scrape
screenlogic
script
scsgate
search
season
sendgrid
sense
sensehat
sensibo
sensor
sentry
serial
serial_pm
sesame
seven_segments
seventeentrack
sharkiq
shell_command
shelly
shiftr
shodan
shopping_list
sht31
sigfox
sighthound
signal_messenger
simplepush
simplisafe
simulated
sinch
sisyphus
sky_hub
skybeacon
skybell
slack
sleepiq
slide
sma
smappee
smart_meter_texas
smarthab
smartthings
smarttub
smarty
smhi
sms
smtp
snapcast
snips
snmp
sochain
solaredge
solaredge_local
solarlog
solax
soma
somfy
somfy_mylink
sonarr
songpal
sonos
sony_projector
soundtouch
spaceapi
spc
speedtestdotnet
spider
splunk
spotcrime
spotify
sql
squeezebox
srp_energy
ssdp
starline
starlingbank
startca
statistics
statsd
steam_online
stiebel_eltron
stookalert
stream
streamlabswater
stt
subaru
suez_water
sun
supervisord
supla
surepetcare
swiss_hydrological_data
swiss_public_transport
swisscom
switch
switchbot
switcher_kis
switchmate
syncthru
synology_chat
synology_dsm
synology_srm
syslog
system_health
system_log
systemmonitor
tado
tag
tahoma
tank_utility
tankerkoenig
tapsaff
tasmota
tautulli
tcp
ted5000
telegram
telegram_bot
tellduslive
tellstick
telnet
temper
template
tensorflow
tesla
tfiac
thermoworks_smoke
thethingsnetwork
thingspeak
thinkingcleaner
thomson
threshold
tibber
tikteck
tile
time_date
timer
tmb
tod
todoist
tof
tomato
toon
torque
totalconnect
touchline
tplink
tplink_lte
traccar
trace
trackr
tradfri
trafikverket_train
trafikverket_weatherstation
transmission
transport_nsw
travisci
trend
tts
tuya
twentemilieu
twilio
twilio_call
twilio_sms
twinkly
twitch
twitter
ubus
ue_smart_radio
uk_transport
unifi
unifi_direct
unifiled
universal
upb
upc_connect
upcloud
updater
upnp
uptime
uptimerobot
uscis
usgs_earthquakes_feed
utility_meter
uvc
vacuum
vallox
vasttrafik
velbus
velux
venstar
vera
verisure
versasense
version
vesync
viaggiatreno
vicare
vilfo
vivotek
vizio
vlc
vlc_telnet
voicerss
volkszaehler
volumio
volvooncall
vultr
w800rf32
wake_on_lan
waqi
water_heater
waterfurnace
watson_iot
watson_tts
waze_travel_time
weather
webhook
webostv
websocket_api
wemo
whois
wiffi
wilight
wink
wirelesstag
withings
wled
wolflink
workday
worldclock
worldtidesinfo
worxlandroid
wsdot
wunderground
x10
xbee
xbox
xbox_live
xeoma
xiaomi
xiaomi_aqara
xiaomi_miio
xiaomi_tv
xmpp
xs1
yale_smart_alarm
yamaha
yamaha_musiccast
yandex_transport
yandextts
yeelight
yeelightsunflower
yi
zabbix
zamg
zengge
zeroconf
zerproc
zestimate
zha
zhong_hong
ziggo_mediabox_xl
zodiac
zone
zoneminder
zwave
zwave_js
__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
requirements.py
runner.py
setup.py
strings.json
machine
pylint
rootfs
script
tests
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hadolint.yaml
.ignore
.pre-commit-config.yaml
.prettierignore
.readthedocs.yml
.yamllint
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
Dockerfile.dev
LICENSE.md
MANIFEST.in
README.rst
azure-pipelines-ci.yml
azure-pipelines-release.yml
azure-pipelines-translation.yml
azure-pipelines-wheels.yml
build.json
codecov.yml
pyproject.toml
requirements.txt
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
requirements_test_pre_commit.txt
setup.cfg
setup.py
tox.ini
core/homeassistant/components/analytics/analytics.py
2021-04-06 19:33:08 -07:00

241 lines
8.5 KiB
Python

"""Analytics helper class for the analytics integration."""
import asyncio
import uuid
import aiohttp
import async_timeout
from homeassistant.components import hassio
from homeassistant.components.api import ATTR_INSTALLATION_TYPE
from homeassistant.components.automation.const import DOMAIN as AUTOMATION_DOMAIN
from homeassistant.const import ATTR_DOMAIN, __version__ as HA_VERSION
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.storage import Store
from homeassistant.helpers.system_info import async_get_system_info
from homeassistant.loader import IntegrationNotFound, async_get_integration
from homeassistant.setup import async_get_loaded_integrations
from .const import (
ANALYTICS_ENDPOINT_URL,
ATTR_ADDON_COUNT,
ATTR_ADDONS,
ATTR_AUTO_UPDATE,
ATTR_AUTOMATION_COUNT,
ATTR_BASE,
ATTR_CUSTOM_INTEGRATIONS,
ATTR_DIAGNOSTICS,
ATTR_HEALTHY,
ATTR_INTEGRATION_COUNT,
ATTR_INTEGRATIONS,
ATTR_ONBOARDED,
ATTR_PREFERENCES,
ATTR_PROTECTED,
ATTR_SLUG,
ATTR_STATE_COUNT,
ATTR_STATISTICS,
ATTR_SUPERVISOR,
ATTR_SUPPORTED,
ATTR_USAGE,
ATTR_USER_COUNT,
ATTR_UUID,
ATTR_VERSION,
LOGGER,
PREFERENCE_SCHEMA,
STORAGE_KEY,
STORAGE_VERSION,
)
class Analytics:
"""Analytics helper class for the analytics integration."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the Analytics class."""
self.hass: HomeAssistant = hass
self.session = async_get_clientsession(hass)
self._data = {ATTR_PREFERENCES: {}, ATTR_ONBOARDED: False, ATTR_UUID: None}
self._store: Store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
@property
def preferences(self) -> dict:
"""Return the current active preferences."""
preferences = self._data[ATTR_PREFERENCES]
return {
ATTR_BASE: preferences.get(ATTR_BASE, False),
ATTR_DIAGNOSTICS: preferences.get(ATTR_DIAGNOSTICS, False),
ATTR_USAGE: preferences.get(ATTR_USAGE, False),
ATTR_STATISTICS: preferences.get(ATTR_STATISTICS, False),
}
@property
def onboarded(self) -> bool:
"""Return bool if the user has made a choice."""
return self._data[ATTR_ONBOARDED]
@property
def uuid(self) -> bool:
"""Return the uuid for the analytics integration."""
return self._data[ATTR_UUID]
@property
def supervisor(self) -> bool:
"""Return bool if a supervisor is present."""
return hassio.is_hassio(self.hass)
async def load(self) -> None:
"""Load preferences."""
stored = await self._store.async_load()
if stored:
self._data = stored
if self.supervisor:
supervisor_info = hassio.get_supervisor_info(self.hass)
if not self.onboarded:
# User have not configured analytics, get this setting from the supervisor
if supervisor_info[ATTR_DIAGNOSTICS] and not self.preferences.get(
ATTR_DIAGNOSTICS, False
):
self._data[ATTR_PREFERENCES][ATTR_DIAGNOSTICS] = True
elif not supervisor_info[ATTR_DIAGNOSTICS] and self.preferences.get(
ATTR_DIAGNOSTICS, False
):
self._data[ATTR_PREFERENCES][ATTR_DIAGNOSTICS] = False
async def save_preferences(self, preferences: dict) -> None:
"""Save preferences."""
preferences = PREFERENCE_SCHEMA(preferences)
self._data[ATTR_PREFERENCES].update(preferences)
self._data[ATTR_ONBOARDED] = True
await self._store.async_save(self._data)
if self.supervisor:
await hassio.async_update_diagnostics(
self.hass, self.preferences.get(ATTR_DIAGNOSTICS, False)
)
async def send_analytics(self, _=None) -> None:
"""Send analytics."""
supervisor_info = None
if not self.onboarded or not self.preferences.get(ATTR_BASE, False):
LOGGER.debug("Nothing to submit")
return
if self._data.get(ATTR_UUID) is None:
self._data[ATTR_UUID] = uuid.uuid4().hex
await self._store.async_save(self._data)
if self.supervisor:
supervisor_info = hassio.get_supervisor_info(self.hass)
system_info = await async_get_system_info(self.hass)
integrations = []
custom_integrations = []
addons = []
payload: dict = {
ATTR_UUID: self.uuid,
ATTR_VERSION: HA_VERSION,
ATTR_INSTALLATION_TYPE: system_info[ATTR_INSTALLATION_TYPE],
}
if supervisor_info is not None:
payload[ATTR_SUPERVISOR] = {
ATTR_HEALTHY: supervisor_info[ATTR_HEALTHY],
ATTR_SUPPORTED: supervisor_info[ATTR_SUPPORTED],
}
if self.preferences.get(ATTR_USAGE, False) or self.preferences.get(
ATTR_STATISTICS, False
):
configured_integrations = await asyncio.gather(
*[
async_get_integration(self.hass, domain)
for domain in async_get_loaded_integrations(self.hass)
],
return_exceptions=True,
)
for integration in configured_integrations:
if isinstance(integration, IntegrationNotFound):
continue
if isinstance(integration, BaseException):
raise integration
if integration.disabled:
continue
if not integration.is_built_in:
custom_integrations.append(
{
ATTR_DOMAIN: integration.domain,
ATTR_VERSION: integration.version,
}
)
continue
integrations.append(integration.domain)
if supervisor_info is not None:
installed_addons = await asyncio.gather(
*[
hassio.async_get_addon_info(self.hass, addon[ATTR_SLUG])
for addon in supervisor_info[ATTR_ADDONS]
]
)
for addon in installed_addons:
addons.append(
{
ATTR_SLUG: addon[ATTR_SLUG],
ATTR_PROTECTED: addon[ATTR_PROTECTED],
ATTR_VERSION: addon[ATTR_VERSION],
ATTR_AUTO_UPDATE: addon[ATTR_AUTO_UPDATE],
}
)
if self.preferences.get(ATTR_USAGE, False):
payload[ATTR_INTEGRATIONS] = integrations
payload[ATTR_CUSTOM_INTEGRATIONS] = custom_integrations
if supervisor_info is not None:
payload[ATTR_ADDONS] = addons
if self.preferences.get(ATTR_STATISTICS, False):
payload[ATTR_STATE_COUNT] = len(self.hass.states.async_all())
payload[ATTR_AUTOMATION_COUNT] = len(
self.hass.states.async_all(AUTOMATION_DOMAIN)
)
payload[ATTR_INTEGRATION_COUNT] = len(integrations)
if supervisor_info is not None:
payload[ATTR_ADDON_COUNT] = len(addons)
payload[ATTR_USER_COUNT] = len(
[
user
for user in await self.hass.auth.async_get_users()
if not user.system_generated
]
)
try:
with async_timeout.timeout(30):
response = await self.session.post(ANALYTICS_ENDPOINT_URL, json=payload)
if response.status == 200:
LOGGER.info(
(
"Submitted analytics to Home Assistant servers. "
"Information submitted includes %s"
),
payload,
)
else:
LOGGER.warning(
"Sending analytics failed with statuscode %s", response.status
)
except asyncio.TimeoutError:
LOGGER.error("Timeout sending analytics to %s", ANALYTICS_ENDPOINT_URL)
except aiohttp.ClientError as err:
LOGGER.error(
"Error sending analytics to %s: %r", ANALYTICS_ENDPOINT_URL, err
)