Skip to content

Commit

Permalink
Merge branch 'master' of github.com:eifinger/homeassistant-config
Browse files Browse the repository at this point in the history
  • Loading branch information
eifinger committed Oct 9, 2019
2 parents 7df402b + 47f766c commit 3a89499
Show file tree
Hide file tree
Showing 17 changed files with 269 additions and 32 deletions.
33 changes: 27 additions & 6 deletions custom_components/alexa_media/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,8 +429,10 @@ async def update_devices(login_obj):
for dev in preferences['devicePreferences']:
if dev['deviceSerialNumber'] == device['serialNumber']:
device['locale'] = dev['locale']
_LOGGER.debug("Locale %s found for %s",
device['timeZoneId'] = dev['timeZoneId']
_LOGGER.debug("Locale %s timezone %s found for %s",
device['locale'],
device['timeZoneId'],
hide_serial(device['serialNumber']))

if 'doNotDisturbDeviceStatusList' in dnd:
Expand Down Expand Up @@ -496,6 +498,8 @@ async def process_notifications(login_obj, raw_notifications=None):
for notification in raw_notifications:
n_dev_id = notification['deviceSerialNumber']
n_type = notification['type']
if n_type == "MusicAlarm":
n_type = "Alarm"
n_id = notification['notificationIndex']
n_date = notification['originalDate']
n_time = notification['originalTime']
Expand Down Expand Up @@ -634,6 +638,7 @@ async def ws_connect() -> WebsocketEchoClient:
_LOGGER.debug("%s: Websocket creation failed: %s",
hide_email(email),
exception_)
return
return websocket

async def ws_handler(message_obj):
Expand Down Expand Up @@ -755,32 +760,44 @@ async def ws_handler(message_obj):

async def ws_open_handler():
"""Handle websocket open."""
import time
email: Text = login_obj.email
_LOGGER.debug("%s: Websocket succesfully connected",
hide_email(email))
(hass.data[DATA_ALEXAMEDIA]
['accounts'][email]['websocketerror']) = 0 # set errors to 0
(hass.data[DATA_ALEXAMEDIA]['accounts']
[email]['websocket_lastattempt']) = time.time()

async def ws_close_handler():
"""Handle websocket close.
This should attempt to reconnect up to 5 times
"""
from asyncio import sleep
import time
email: Text = login_obj.email
errors: int = (hass.data
[DATA_ALEXAMEDIA]['accounts'][email]['websocketerror'])
delay: int = 5 * 2 ** errors
if (errors < 5):
last_attempt = (hass.data[DATA_ALEXAMEDIA]['accounts']
[email]['websocket_lastattempt'])
now = time.time()
if ((now - last_attempt) < delay):
return
while (errors < 5 and not (hass.data[DATA_ALEXAMEDIA]['accounts']
[email]['websocket'])):
_LOGGER.debug("%s: Websocket closed; reconnect #%i in %is",
hide_email(email),
errors,
delay)
await sleep(delay)
if (not (hass.data
[DATA_ALEXAMEDIA]['accounts'][email]['websocket'])):
(hass.data[DATA_ALEXAMEDIA]['accounts']
[email]['websocket']) = await ws_connect()
(hass.data[DATA_ALEXAMEDIA]['accounts']
[email]['websocket_lastattempt']) = time.time()
(hass.data[DATA_ALEXAMEDIA]['accounts']
[email]['websocket']) = await ws_connect()
errors += 1
delay = 5 * 2 ** errors
else:
_LOGGER.debug("%s: Websocket closed; retries exceeded; polling",
hide_email(email))
Expand Down Expand Up @@ -828,6 +845,10 @@ async def ws_error_handler(message):
['entities']) = {'media_player': {}}
(hass.data[DATA_ALEXAMEDIA]
['accounts'][email]['new_devices']) = True # force initial update
(hass.data[DATA_ALEXAMEDIA]
['accounts'][email]['websocket_lastattempt']) = 0
(hass.data[DATA_ALEXAMEDIA]
['accounts'][email]['websocketerror']) = 0 # set errors to 0
(hass.data[DATA_ALEXAMEDIA]['accounts'][email]['websocket']) = \
await ws_connect()
await update_devices(login_obj, no_throttle=True)
Expand Down
18 changes: 12 additions & 6 deletions custom_components/alexa_media/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,8 @@ async def _test_login(self):
):
_LOGGER.debug("Creating config_flow to request 2FA")
message = "> {0}".format(
login.status["error_message"] if "error_message" in login.status else ""
login.status["error_message"]
if "error_message" in login.status else ""
)
return await self._show_form(
"twofactor",
Expand All @@ -292,18 +293,21 @@ async def _test_login(self):
"claimspicker_required" in login.status
and login.status["claimspicker_required"]
):
message = "> {0}".format(
login.status["error_message"] if "error_message" in login.status else ""
error_message = "> {0}".format(
login.status["error_message"]
if "error_message" in login.status else ""
)
_LOGGER.debug("Creating config_flow to select verification method")
claimspicker_message = login.status["claimspicker_message"]
return await self._show_form(
"claimspicker",
data_schema=vol.Schema(self.claimspicker_schema),
errors={},
placeholders={
"email": login.email,
"url": login.url,
"message": message,
"message": "> {0}\n> {1}".format(claimspicker_message,
error_message),
},
)
elif (
Expand All @@ -312,7 +316,8 @@ async def _test_login(self):
):
_LOGGER.debug("Creating config_flow to select OTA method")
error_message = (
login.status["error_message"] if "error_message" in login.status else ""
login.status["error_message"]
if "error_message" in login.status else ""
)
authselect_message = login.status["authselect_message"]
return await self._show_form(
Expand All @@ -321,7 +326,8 @@ async def _test_login(self):
placeholders={
"email": login.email,
"url": login.url,
"message": "> {0}\n> {1}".format(authselect_message, error_message),
"message": "> {0}\n> {1}".format(authselect_message,
error_message),
},
)
elif (
Expand Down
2 changes: 1 addition & 1 deletion custom_components/alexa_media/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"""
from datetime import timedelta

__version__ = '2.3.0'
__version__ = '2.3.1'
PROJECT_URL = "https://github.com/custom-components/alexa_media_player/"
ISSUE_URL = "{}issues".format(PROJECT_URL)

Expand Down
2 changes: 1 addition & 1 deletion custom_components/alexa_media/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
"documentation": "https://github.com/custom-components/alexa_media_player/wiki",
"dependencies": [],
"codeowners": ["@keatontaylor", "@alandtse"],
"requirements": ["alexapy==1.3.1"],
"requirements": ["alexapy==1.3.2"],
"homeassistant": "0.96.0"
}
2 changes: 2 additions & 0 deletions custom_components/alexa_media/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,8 @@ async def refresh(self, device=None):
self._cluster_members = device['clusterMembers']
self._bluetooth_state = device['bluetooth_state']
self._locale = device['locale'] if 'locale' in device else 'en-US'
self._timezone = (device['timeZoneId']
if 'timeZoneId' in device else 'UTC')
self._dnd = device['dnd'] if 'dnd' in device else None
await self._set_authentication_details(device['auth_info'])
session = None
Expand Down
17 changes: 14 additions & 3 deletions custom_components/alexa_media/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,20 @@ def __init__(self,
self._all = (sorted(self._n_dict.items(),
key=lambda x: x[1][self._sensor_property])
if self._n_dict else [])
self._all = list(map(self._fix_alarm_date_time, self._all))
self._sorted = list(filter(lambda x: x[1]['status'] == 'ON',
self._all)) if self._all else []
self._next = self._sorted[0][1] if self._sorted else None

def _fix_alarm_date_time(self, value):
import pytz
if self._sensor_property != "date_time" or not value:
return value
naive_time = dt.parse_datetime(value[1][self._sensor_property])
timezone = pytz.timezone(self._client._timezone)
value[1][self._sensor_property] = timezone.localize(naive_time)
return value

async def async_added_to_hass(self):
"""Store register state change callback."""
try:
Expand Down Expand Up @@ -224,7 +234,7 @@ def should_poll(self):
@property
def state(self):
"""Return the state of the sensor."""
return dt.parse_datetime(self._next[self._sensor_property]).replace(
return self._next[self._sensor_property].replace(
tzinfo=LOCAL_TIMEZONE) if self._next else 'None'

@property
Expand Down Expand Up @@ -254,6 +264,7 @@ async def async_update(self):
self._all = (sorted(self._n_dict.items(),
key=lambda x: x[1][self._sensor_property])
if self._n_dict else [])
self._all = list(map(self._fix_alarm_date_time, self._all))
self._sorted = list(filter(lambda x: x[1]['status'] == 'ON',
self._all)) if self._all else []
self._next = self._sorted[0][1] if self._sorted else None
Expand Down Expand Up @@ -291,8 +302,8 @@ def device_state_attributes(self):
'recurrence': self.recurrence,
'total_active': len(self._sorted),
'total_all': len(self._all),
'sorted_active': json.dumps(self._sorted),
'sorted_all': json.dumps(self._all),
'sorted_active': json.dumps(self._sorted, default=str),
'sorted_all': json.dumps(self._all, default=str),
}
return attr

Expand Down
3 changes: 2 additions & 1 deletion custom_components/hacs/.translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
}
},
"repository": {
"authors": "Autoren",
"available": "Verfügbar",
"back_to": "Zurück zu",
"changelog": "Changelog",
Expand Down Expand Up @@ -90,6 +91,6 @@
"upgrade_all": "Alle aktualisieren"
},
"store": {
"placeholder_search": "Suchbegriff eingeben..."
"placeholder_search": "Suchbegriff eingeben"
}
}
5 changes: 3 additions & 2 deletions custom_components/hacs/.translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
}
},
"repository": {
"authors": "Auteurs",
"available": "Disponible",
"back_to": "Retour",
"changelog": "Change log",
Expand All @@ -77,9 +78,9 @@
"upgrade": "Mettre à jour"
},
"settings": {
"add_custom_repository": "AJOUTER UN DÉPÔT PERSONNALISE",
"add_custom_repository": "AJOUTER UN DÉPÔT PERSONNALISÉ",
"category": "Catégorie",
"custom_repositories": "DÉPÔT PERSONNALISE",
"custom_repositories": "DÉPÔTS PERSONNALISÉS",
"delete": "Supprimer",
"display": "Affichage",
"grid": "Grille",
Expand Down
96 changes: 96 additions & 0 deletions custom_components/hacs/.translations/it.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
{
"common": {
"appdaemon": "AppDaemon",
"appdaemon_apps": "Applicazioni AppDaemon",
"background_task": "Attività in esecuzione, questa pagina sarà ricaricata al termine.",
"installed": "Installato",
"integration": "Integrazione",
"integrations": "Integrazioni",
"plugin": "Plugin",
"plugins": "Plugin",
"python_script": "Script python",
"python_scripts": "Script python",
"repositories": "Repository",
"settings": "Impostazioni",
"theme": "Tema",
"themes": "Temi",
"version": "Versione"
},
"config": {
"abort": {
"single_instance_allowed": "È consentita una sola configurazione di HACS."
},
"error": {
"auth": "Il token di accesso personale non è corretto."
},
"step": {
"user": {
"data": {
"appdaemon": "Abilita il rilevamento e il monitoraggio delle app AppDaemon",
"python_script": "Abilita il rilevamento e il monitoraggio dei python_scripts",
"sidepanel_icon": "Icona nel pannello laterale",
"sidepanel_title": "Titolo nel pannello laterale",
"theme": "Abilita individuazione e tracciamento dei temi",
"token": "Token di accesso personale GitHub"
},
"description": "Se hai bisogno di aiuto con la configurazione dai un'occhiata qui: https:\/\/hacs.netlify.com\/installation\/configuration\/",
"title": "HACS (Home Assistant Community Store)"
}
},
"title": "HACS (Home Assistant Community Store)"
},
"options": {
"step": {
"user": {
"data": {
"country": "Filtra con prefisso internazionale.",
"experimental": "Abilita funzionalità sperimentali",
"release_limit": "Numero di versioni da mostrare."
}
}
}
},
"repository": {
"authors": "Autori",
"available": "Disponibile",
"back_to": "Indietro",
"changelog": "Change log",
"flag_this": "Spunta questo",
"hide": "Nascondi",
"hide_beta": "Nascondi beta",
"install": "Installa",
"installed": "Installato",
"lovelace_copy_example": "Copia l'esempio negli appunti",
"lovelace_instruction": "Quando lo aggiungi nella configurazione lovelace usa questo ",
"lovelace_no_js_type": "Impossibile determinare il tipo di plugin, verificare il repository.",
"newest": "Nuovo",
"note_appdaemon": "dovrai aggiungerlo nel file 'apps.yaml'",
"note_installed": "Quando installato, sarà posizionato in",
"note_integration": "dovrai aggiungerlo nel file 'configuration.yaml'",
"note_plugin": "Dovrai aggiungerlo nel file 'ui-lovelace.yaml' oppure via editor di configurazione RAW della UI.",
"open_issue": "Apri anomalia",
"open_plugin": "Apri plugin",
"reinstall": "Reinstalla",
"repository": "Repository",
"show_beta": "Visualizza beta",
"uninstall": "Rimuovi",
"update_information": "Aggiorna informazioni",
"upgrade": "Aggiorna"
},
"settings": {
"add_custom_repository": "AGGIUNGI REPOSITORY PERSONALIZZATA",
"category": "Categoria",
"custom_repositories": "REPOSITORY PERSONALIZZATE",
"delete": "Cancella",
"display": "Visualizza",
"grid": "Griglia",
"hacs_repo": "HACS repo",
"reload_data": "Ricarica i dati",
"save": "Salva",
"table": "Tabella",
"upgrade_all": "Aggiorna tutto"
},
"store": {
"placeholder_search": "Prego inserire una stringa di ricerca"
}
}
Loading

0 comments on commit 3a89499

Please sign in to comment.