Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alexa Media Reauthentication Required - continuously appear: Login error detected; not contacting API #2453

Open
Kosztyk opened this issue Aug 10, 2024 · 461 comments

Comments

@Kosztyk
Copy link

Kosztyk commented Aug 10, 2024

IMPORTANT: Please search the issues, including closed issues, and the FAQ before opening a new issue. The template is mandatory; failure to use it will result in issue closure.

Describe the bug

Looks like in Homeassistant OS X64, 2024.8.0 integration Alexa Media Player in continuously asking for authentification or reauthentification.

integration version 4.12.7, amazon.com domain, 2FA enabled.

Even just after authentification no dot speaker is shown.

To Reproduce

  1. Go to Alexa Media Player
  2. Click on reconfigure and authenticate, even the auth process went fine none of my dot speakers are shown and "attention required message is appearing

Reauthenticate xxxxxxxx@hotmail.com on the Integrations page. Relogin required after 0:00:01.582947 and 2 api calls.

Expected behavior

to stop asking for authentification and my dot speakers to appear in HAOS

Screenshots

attached

System details

Core
2024.8.0
Supervisor
2024.08.0
Operating System
12.4
Frontend
20240806.1

alexa_media (version from const.py or HA startup): Which ever is the latest updated new version (08/08/24)
alexapy (version from pip show alexapy or HA startup): Same as above
Amazon [2FA is enabled] - Yes
Screenshot 2024-08-10 at 15 41 12
Screenshot 2024-08-10 at 15 33 34
. <!---We will not debug login issues if unanswered--->:

Logs
Please provide logs.

('Login error detected; not contacting API',)
2024-08-10 15:53:41.987 WARNING (MainThread) [alexapy.helpers] alexaapi.get_bluetooth((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-10 15:53:42.009 WARNING (MainThread) [alexapy.helpers] alexaapi.get_guard_details((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-10 15:53:42.009 WARNING (MainThread) [alexapy.helpers] alexaapi.get_network_details((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-10 15:53:42.022 WARNING (MainThread) [alexapy.helpers] alexaapi.get_authentication((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-10 15:53:42.030 WARNING (MainThread) [alexapy.helpers] alexaapi.get_authentication((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-10 15:53:42.046 WARNING (MainThread) [alexapy.helpers] alexaapi.get_dnd_state((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-10 15:53:42.054 WARNING (MainThread) [alexapy.helpers] alexaapi.get_bluetooth((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-10 15:53:42.095 WARNING (MainThread) [alexapy.helpers] alexaapi.get_devices((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-10 15:53:42.226 WARNING (MainThread) [alexapy.helpers] alexaapi.get_dnd_state((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-10 15:53:42.250 WARNING (MainThread) [alexapy.helpers] alexaapi.get_authentication((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-10 15:53:42.279 WARNING (MainThread) [alexapy.helpers] alexaapi.get_device_preferences((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-10 15:53:42.298 WARNING (MainThread) [alexapy.helpers] alexaapi.get_devices((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-10 15:53:42.313 WARNING (MainThread) [alexapy.helpers] alexaapi.get_device_preferences((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-08-10 15:53:42.356 WARNING (MainThread) [alexapy.helpers] alexaapi.get_device_preferences((<alexapy.alexalogin.AlexaLogin object at 0x7f4392050470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)

Additional context

@Javisen
Copy link

Javisen commented Aug 10, 2024

+1

4 similar comments
@javiges
Copy link

javiges commented Aug 10, 2024

+1

@conorokelly
Copy link

+1

@Mapsy-AI
Copy link

+1

@marco-hacs
Copy link

+1

@javilopezalarcon
Copy link

+1
if you do an automation to reload the integration every 9 minutes it seems that it doesn't fail again... Like the auto restart integration when Home Assistant starts..

@Kosztyk
Copy link
Author

Kosztyk commented Aug 10, 2024

Hi,

The problem is not only the reauthentication, my speakers are not shown at all even after it authenticates, like in my printscreen

@javilopezalarcon
Copy link

Registrador: homeassistant.components.media_player

Fuente: helpers/entity_platform.py:764
integración: Reproductor multimedia (documentación, problemas)
Ocurrió por primera vez: 17:27:39 (141 ocurrencias)
Último inicio de sesión: 22:27:39

Platform alexa_media does not generate unique IDs. ID G0922M0624520K4L already exists - ignoring media_player.alexa_matrimonio
Platform alexa_media does not generate unique IDs. ID G091GM10227401QM already exists - ignoring media_player.alexa_salon
Platform alexa_media does not generate unique IDs. ID 30ba105f4e3a4b3fbfff1e84e90f78b0 already exists - ignoring media_player.nuestra_casita
Platform alexa_media does not generate unique IDs. ID eb94a13bfe07413c9186044f9aa31cf6 already exists - ignoring media_player.amazfit_balance_javi 


Registrador: homeassistant.helpers.entity
Fuente: helpers/entity.py:942
Ocurrió por primera vez: 17:36:40 (140 ocurrencias)
Último inicio de sesión: 22:27:38

Update for media_player.alexa_matrimonio fails
Update for media_player.alexa_salon fails
Update for media_player.nuestra_casita fails
Update for media_player.amazfit_balance_javi fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 942, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1300, in async_device_update
    await self.async_update()
  File "/config/custom_components/alexa_media/helpers.py", line 158, in _catch_login_errors
    result = await func(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/alexa_media/media_player.py", line 918, in async_update
    device = self.hass.data[DATA_ALEXAMEDIA]["accounts"][email]["devices"][
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'G0922M0624520K4L'

Registrador: homeassistant.config_entries
Fuente: config_entries.py:819
Ocurrió por primera vez: 15:25:37 (50 ocurrencias)
Último inicio de sesión: 22:27:30

Error unloading entry Alexa Javi- amazon.es for notify
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 819, in async_unload
    result = await component.async_unload_entry(hass, self)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/notify/__init__.py", line 135, in async_unload_entry
    return await component.async_unload_entry(entry)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 202, in async_unload_entry
    raise ValueError("Config entry was never loaded!")
ValueError: Config entry was never loaded!

Este error se originó a partir de una integración personalizada.

Registrador: alexapy.helpers
Fuente: custom_components/alexa_media/__init__.py:848
integración: Alexa Media Player (documentación, problemas)
Ocurrió por primera vez: 17:27:44 (6 ocurrencias)
Último inicio de sesión: 17:34:56

alexaapi.get_dnd_state((<alexapy.alexalogin.AlexaLogin object at 0x7f81a0aa91c0>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
Este error se originó a partir de una integración personalizada.

Registrador: alexapy.helpers
Fuente: custom_components/alexa_media/media_player.py:639
integración: Alexa Media Player (documentación, problemas)
Ocurrió por primera vez: 14:22:38 (27 ocurrencias)
Último inicio de sesión: 17:32:49

alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0x7f81ae8d97f0>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0x7f81aa35a5a0>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0x7f81aa35aa20>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0x7f81a62d5ac0>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0x7f81a62d6420>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)

Este error se originó a partir de una integración personalizada.

Registrador: alexapy.helpers
Fuente: custom_components/alexa_media/__init__.py:785
integración: Alexa Media Player (documentación, problemas)
Ocurrió por primera vez: 05:27:23 (6 ocurrencias)
Último inicio de sesión: 17:27:38

alexaapi.get_customer_history_records((<alexapy.alexalogin.AlexaLogin object at 0x7f81bd77d160>,), {'max_record_size': 10}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',)
alexaapi.get_last_device_serial((<alexapy.alexalogin.AlexaLogin object at 0x7f81bd77d160>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',)
alexaapi.get_customer_history_records((<alexapy.alexalogin.AlexaLogin object at 0x7f81a0aa91c0>,), {'max_record_size': 10}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',)
alexaapi.get_last_device_serial((<alexapy.alexalogin.AlexaLogin object at 0x7f81a0aa91c0>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',)


Registrador: alexapy.helpers
Fuente: runner.py:190
Ocurrió por primera vez: 09:00:37 (45 ocurrencias)
Último inicio de sesión: 15:25:25

alexaapi.send_sequence((<alexapy.alexaapi.AlexaAPI object at 0x7f81a85b5fd0>, 'Alexa.Speak'), {'customer_id': 'ASDHY88HGVBO6', 'textToSpeak': 'La humedad exterior es 37% menor que la interior. Sería un buen momento para abrir las ventanas y airear la casa.', 'target': {'customerId': 'A*********BO6', 'devices': [{'deviceSerialNumber': 'G************1QM', 'deviceTypeId': 'A15996VY63BQ2D'}]}, 'skillId': 'amzn1.ask.1p.saysomething', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.send_tts((<alexapy.alexaapi.AlexaAPI object at 0x7f81a85b5fd0>, 'La humedad exterior es 37% menor que la interior. Sería un buen momento para abrir las ventanas y airear la casa.'), {'customer_id': 'ASDHY88HGVBO6', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.run_behavior((<alexapy.alexaapi.AlexaAPI object at 0x7f81a85b5fd0>, {'@type': 'com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode', 'type': 'Alexa.Speak', 'operationPayload': {'deviceType': 'A15996VY63BQ2D', 'deviceSerialNumber': 'G************1QM', 'locale': 'es-es', 'customerId': 'A*********BO6', 'textToSpeak': 'Esto es una prueba', 'target': {'customerId': 'A*********BO6', 'devices': [{'deviceSerialNumber': 'G************1QM', 'deviceTypeId': 'A15996VY63BQ2D'}]}, 'skillId': 'amzn1.ask.1p.saysomething'}}), {'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.send_sequence((<alexapy.alexaapi.AlexaAPI object at 0x7f81a85b5fd0>, 'Alexa.Speak'), {'customer_id': 'ASDHY88HGVBO6', 'textToSpeak': 'Esto es una prueba', 'target': {'customerId': 'A*********BO6', 'devices': [{'deviceSerialNumber': 'G************1QM', 'deviceTypeId': 'A15996VY63BQ2D'}]}, 'skillId': 'amzn1.ask.1p.saysomething', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.send_tts((<alexapy.alexaapi.AlexaAPI object at 0x7f81a85b5fd0>, 'Esto es una prueba'), {'customer_id': 'ASDHY88HGVBO6', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)

@TruantRiccardo
Copy link

TruantRiccardo commented Aug 10, 2024

Fixed with HA 2024.8.1 update
edit: My mistake. Reloading the integration works for a few minutes.

@Kosztyk
Copy link
Author

Kosztyk commented Aug 10, 2024

Still the same for me, same error

@ml0renz0
Copy link

ml0renz0 commented Aug 11, 2024

Fixed with HA 2024.8.1 update

Updated and rebooted, just in case.
Still not working for me as well.

In my case it requires to re-authenticate every half hour and it started this week.
I know this because I use the echo dot's temperature sensor

Screenshot_20240811-035805~2.png

@javiges
Copy link

javiges commented Aug 11, 2024

Fixed with HA 2024.8.1 update

Does everything work for you? It no longer asks to authenticate every half hour and notifications always work? Thank you very much.

@DAB42
Copy link

DAB42 commented Aug 11, 2024

This is still happening for me at HA version 2024.8.1

@asmsaifs
Copy link

I am also facing this at HA version 2024.8.1

@vix66
Copy link

vix66 commented Aug 11, 2024

Same situation … stress!

@Catkin75
Copy link

Same here after 2024.8.1 update.

@lankymat
Copy link

Same here after 2024.8.1 update. Continually asking to authenticate and failing to login.

@matte-a
Copy link

matte-a commented Aug 11, 2024

Hi all!

As many others, i'm experiensing the same problem, but i've notice somenthing.
In the configuration section the integration seems it's losing the public url of my hass instance. As soon as i update the configuration with the url, the integration start to work again

image

image

@josemaX
Copy link

josemaX commented Aug 11, 2024

Home-assistant (version): 2024.8.0
alexa_media (version):4.12.7

After reconfiguring the integration as commented above, restarting the computer (no home assistant), Alexa plays the HA messages in automations for a bunch of minutes, after that, no speaking again.

Then if I reload the AMP integration, works again for a while, and fails after a while until reload the integration and so on.

@Kosztyk
Copy link
Author

Kosztyk commented Aug 11, 2024

Not working in my case

@nstyqz
Copy link

nstyqz commented Aug 11, 2024

Another one

Screenshot_20240811-004420.png

Screenshot_20240811-004619.png

@mirlorojiblanco
Copy link

The same here 😭

@sdholden28
Copy link

Same issue here. Logs:
Logger: alexapy.helpers
Source: runner.py:190
First occurred: 6:39:54 PM (6 occurrences)
Last logged: 6:40:14 PM

alexaapi.send_sequence((<alexapy.alexaapi.AlexaAPI object at 0x7f14adfe8410>, 'Alexa.Speak'), {'customer_id': 'A369Q6OMY8A2EE', 'textToSpeak': "Home Assistant reports all doors are closed", 'target': {'customerId': 'A2EE', 'devices': [{'deviceSerialNumber': 'G19C', 'deviceTypeId': 'A7WXQPH584YP'}]}, 'skillId': 'amzn1.ask.1p.saysomething', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',)
alexaapi.send_tts((<alexapy.alexaapi.AlexaAPI object at 0x7f14adfe8410>, "Home Assistant reports all doors are closed"), {'customer_id': 'A369Q6OMY8A2EE', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Unauthorized',)
alexaapi.run_behavior((<alexapy.alexaapi.AlexaAPI object at 0x7f14adfe8410>, {'@type': 'com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode', 'type': 'Alexa.Speak', 'operationPayload': {'deviceType': 'A7WXQPH584YP', 'deviceSerialNumber': 'G
19C', 'locale': 'en-us', 'customerId': 'A2EE', 'textToSpeak': "Home Assistant reports all doors are closed", 'target': {'customerId': 'A2EE', 'devices': [{'deviceSerialNumber': 'G19C', 'deviceTypeId': 'A7WXQPH584YP'}]}, 'skillId': 'amzn1.ask.1p.saysomething'}}), {'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.send_sequence((<alexapy.alexaapi.AlexaAPI object at 0x7f14adfe8410>, 'Alexa.Speak'), {'customer_id': 'A369Q6OMY8A2EE', 'textToSpeak': "Home Assistant reports all doors are closed", 'target': {'customerId': 'A
2EE', 'devices': [{'deviceSerialNumber': 'G****19C', 'deviceTypeId': 'A7WXQPH584YP'}]}, 'skillId': 'amzn1.ask.1p.saysomething', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.send_tts((<alexapy.alexaapi.AlexaAPI object at 0x7f14adfe8410>, "Home Assistant reports all doors are closed"), {'customer_id': 'A369Q6OMY8A2EE', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)

@djeghe
Copy link

djeghe commented Aug 12, 2024

Same problem here with amazon.it domain.
I also try to uninstall and reinstall integration but the problem was unsolved

@djeghe
Copy link

djeghe commented Aug 12, 2024

reload the integration

Ciao. What is the HA service that reload an integration?

@Xploder
Copy link

Xploder commented Aug 12, 2024

Same here, amazon.de

@javilopezalarcon
Copy link

reload the integration

Ciao. What is the HA service that reload an integration?

I'll give you my automation, just using 1 of the speakers is enough, reload the entire integration

`alias: Recarga Alexa hasta que se arregle
description: ""
trigger:

  • platform: homeassistant
    event: start
  • platform: time_pattern
    minutes: /9
    condition: []
    action:
  • delay:
    hours: 0
    minutes: 0
    seconds: 30
    milliseconds: 0
  • metadata: {}
    data: {}
    target:
    entity_id: media_player.alexa_pc
    action: homeassistant.reload_config_entry
    mode: single`

@nstyqz
Copy link

nstyqz commented Aug 12, 2024

Service... I meant action 😎😎😎

@qfina
Copy link

qfina commented Aug 12, 2024

Also suffering this, example:

Reauthenticate a**@**m on the Integrations page. Relogin required after 0:00:04.279868 and 10 api calls.

Simply pressing "Reload" on the integration fixes it temporarily (2FA enabled).

@mpch13
Copy link

mpch13 commented Aug 12, 2024

Same issue on both core versions 2024.8.0 and 2024.8.1 with 4.12.7 Alexa media player.

@mattiapir8
Copy link

With polling disable it keep working for me and for my friends! :-) my suggestion is to disable it!

@serlinGi
Copy link

serlinGi commented Oct 9, 2024

I was lucky enough to be able to use it almost always, with a short break in August; I was forced to use HA in July to avoid unwanted blocks.

then from September onwards I did all the HA and AMP updates without problems even with the echo dot temperature sensor.
This until yesterday (😓): with the latest AMP update I found the connected devices option deactivated (so the temperature sensor was not available); I put the flag back on "connected devices" and from that moment on it no longer works. I can't access it - reauthentication almost always in a loop - and when I do it after a few minutes it breaks again.
a real shame
HA.OS 2013.10.4
AMP 4.13.4

@mattiapir8
Copy link

You are right…but… why is it a real shame?
Because you didn’t pay nothing for this free, open, not official integration that work only via Amazon’s server.
If it’s real shame for you then you can try to do it better!

I think it is not helpful to have this reaction and use these words.

@serlinGi
Copy link

serlinGi commented Oct 9, 2024

Hai ragione... ma... perché è un vero peccato? Perché non hai pagato nulla per questa integrazione gratuita, aperta, non ufficiale che funziona solo tramite il server di Amazon. Se è un vero peccato per te allora puoi provare a fare di meglio!

Penso che non sia utile avere questa reazione e usare queste parole.

I honestly don't understand your comment and your reaction;
I don't think my comment was polemical or expressed a complaint. There will probably be some problem with the translation into English with the help of the apps.
I just wanted to express regret and I have high regard and gratitude for the developers.
I also wrote that it has always worked well for me (except for the August break when I didn't have time to check for any anomalies)
P.S. This evening it started working again by itself and has been maintaining for 4 hours.
Best regards

@mattiapir8
Copy link

It's the word "shame" that didn't seem appropriate to me, but if I misunderstood I apologize!

many times I see sterile complaints about things that are the fruit of the community's work and passion.

@micium
Copy link

micium commented Oct 11, 2024

With polling disable it keep working for me and for my friends! :-) my suggestion is to disable it!

have you programmed an automation to reload the integration every x minutes/hours?

@mattiapir8
Copy link

No, I don’t. In my personal case polling it’s not very relevant, so I give up that feature.

@Kosztyk
Copy link
Author

Kosztyk commented Oct 12, 2024

I tried almost evrything but with no success. This is teh log i get it

2024-10-12 19:36:17.849 WARNING (MainThread) [homeassistant.util.loop] Detected blocking call to load_verify_locations with args (<ssl.SSLContext object at 0x7fa965091050>, '/usr/local/lib/python3.12/site-packages/certifi/cacert.pem', None, None) inside the event loop by custom integration 'alexa_media' at custom_components/alexa_media/config_flow.py, line 280: self.login = AlexaLogin( (offender: /usr/local/lib/python3.12/ssl.py, line 708: context.load_verify_locations(cafile, capath, cadata)), please create a bug report at https://github.com/alandtse/alexa_media_player/issues
For developers, please see https://developers.home-assistant.io/docs/asyncio_blocking_operations/#load_verify_locations
Traceback (most recent call last):
File "", line 198, in _run_module_as_main
File "", line 88, in _run_code
File "/usr/src/homeassistant/homeassistant/main.py", line 223, in
sys.exit(main())
File "/usr/src/homeassistant/homeassistant/main.py", line 209, in main
exit_code = runner.run(runtime_conf)
File "/usr/src/homeassistant/homeassistant/runner.py", line 189, in run
return loop.run_until_complete(setup_and_run_hass(runtime_config))
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 674, in run_until_complete
self.run_forever()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 641, in run_forever
self._run_once()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 1990, in _run_once
handle._run()
File "/usr/local/lib/python3.12/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "/usr/local/lib/python3.12/site-packages/aiohttp/web_protocol.py", line 556, in start
task = asyncio.Task(coro, loop=loop, eager_start=True)
File "/usr/local/lib/python3.12/site-packages/aiohttp/web_protocol.py", line 477, in _handle_request
resp = await request_handler(request)
File "/usr/local/lib/python3.12/site-packages/aiohttp/web_app.py", line 559, in _handle
return await handler(request)
File "/usr/local/lib/python3.12/site-packages/aiohttp/web_middlewares.py", line 117, in impl
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/security_filter.py", line 92, in security_filter_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/forwarded.py", line 83, in forwarded_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/request_context.py", line 26, in request_context_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/ban.py", line 85, in ban_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/auth.py", line 242, in auth_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/headers.py", line 32, in headers_middleware
response = await handler(request)
File "/usr/src/homeassistant/homeassistant/helpers/http.py", line 73, in handle
result = await handler(request, **request.match_info)
File "/usr/src/homeassistant/homeassistant/components/http/decorators.py", line 81, in with_admin
return await func(self, request, *args, **kwargs)
File "/usr/src/homeassistant/homeassistant/components/config/config_entries.py", line 222, in post
return await super().post(request, flow_id)
File "/usr/src/homeassistant/homeassistant/components/http/data_validator.py", line 74, in wrapper
return await method(view, request, data, *args, **kwargs)
File "/usr/src/homeassistant/homeassistant/helpers/data_entry_flow.py", line 122, in post
result = await self._flow_mgr.async_configure(flow_id, data)
File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 370, in async_configure
result = await self._async_configure(flow_id, user_input)
File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 417, in _async_configure
result = await self._async_handle_step(
File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 520, in _async_handle_step
result: _FlowResultT = await getattr(flow, method)(user_input)
File "/config/custom_components/alexa_media/config_flow.py", line 280, in async_step_user
self.login = AlexaLogin(

2024-10-12 19:36:28.005 WARNING (MainThread) [homeassistant.util.loop] Detected blocking call to load_verify_locations with args (<ssl.SSLContext object at 0x7fa9600edad0>,) inside the event loop by custom integration 'alexa_media' at custom_components/alexa_media/config_flow.py, line 374: self.proxy = AlexaProxy( (offender: /usr/local/lib/python3.12/site-packages/httpx/_config.py, line 149: context.load_verify_locations(cafile=cafile)), please create a bug report at https://github.com/alandtse/alexa_media_player/issues
For developers, please see https://developers.home-assistant.io/docs/asyncio_blocking_operations/#load_verify_locations
Traceback (most recent call last):
File "", line 198, in _run_module_as_main
File "", line 88, in _run_code
File "/usr/src/homeassistant/homeassistant/main.py", line 223, in
sys.exit(main())
File "/usr/src/homeassistant/homeassistant/main.py", line 209, in main
exit_code = runner.run(runtime_conf)
File "/usr/src/homeassistant/homeassistant/runner.py", line 189, in run
return loop.run_until_complete(setup_and_run_hass(runtime_config))
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 674, in run_until_complete
self.run_forever()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 641, in run_forever
self._run_once()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 1990, in _run_once
handle._run()
File "/usr/local/lib/python3.12/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "/usr/local/lib/python3.12/site-packages/aiohttp/web_protocol.py", line 477, in _handle_request
resp = await request_handler(request)
File "/usr/local/lib/python3.12/site-packages/aiohttp/web_app.py", line 559, in _handle
return await handler(request)
File "/usr/local/lib/python3.12/site-packages/aiohttp/web_middlewares.py", line 117, in impl
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/security_filter.py", line 92, in security_filter_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/forwarded.py", line 83, in forwarded_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/request_context.py", line 26, in request_context_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/ban.py", line 85, in ban_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/auth.py", line 242, in auth_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/headers.py", line 32, in headers_middleware
response = await handler(request)
File "/usr/src/homeassistant/homeassistant/helpers/http.py", line 73, in handle
result = await handler(request, **request.match_info)
File "/usr/src/homeassistant/homeassistant/components/http/decorators.py", line 81, in with_admin
return await func(self, request, *args, **kwargs)
File "/usr/src/homeassistant/homeassistant/components/config/config_entries.py", line 222, in post
return await super().post(request, flow_id)
File "/usr/src/homeassistant/homeassistant/components/http/data_validator.py", line 74, in wrapper
return await method(view, request, data, *args, **kwargs)
File "/usr/src/homeassistant/homeassistant/helpers/data_entry_flow.py", line 122, in post
result = await self._flow_mgr.async_configure(flow_id, data)
File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 370, in async_configure
result = await self._async_configure(flow_id, user_input)
File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 417, in _async_configure
result = await self._async_handle_step(
File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 520, in _async_handle_step
result: _FlowResultT = await getattr(flow, method)(user_input)
File "/config/custom_components/alexa_media/config_flow.py", line 362, in async_step_user
return await self.async_step_start_proxy(user_input)
File "/config/custom_components/alexa_media/config_flow.py", line 374, in async_step_start_proxy
self.proxy = AlexaProxy(

2024-10-12 19:42:49.732 WARNING (MainThread) [homeassistant.util.loop] Detected blocking call to open with args (PosixPath('/config/.storage/alexa_media.mail.account@hotmail.com.pickle'),) inside the event loop by custom integration 'alexa_media' at custom_components/alexa_media/config_flow.py, line 420: if await self.login.test_loggedin(): (offender: /usr/local/lib/python3.12/site-packages/aiohttp/cookiejar.py, line 121: with file_path.open(mode="wb") as f:), please create a bug report at https://github.com/alandtse/alexa_media_player/issues
For developers, please see https://developers.home-assistant.io/docs/asyncio_blocking_operations/#open
Traceback (most recent call last):
File "", line 198, in _run_module_as_main
File "", line 88, in _run_code
File "/usr/src/homeassistant/homeassistant/main.py", line 223, in
sys.exit(main())
File "/usr/src/homeassistant/homeassistant/main.py", line 209, in main
exit_code = runner.run(runtime_conf)
File "/usr/src/homeassistant/homeassistant/runner.py", line 189, in run
return loop.run_until_complete(setup_and_run_hass(runtime_config))
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 674, in run_until_complete
self.run_forever()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 641, in run_forever
self._run_once()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 1990, in _run_once
handle._run()
File "/usr/local/lib/python3.12/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "/usr/local/lib/python3.12/site-packages/aiohttp/web_protocol.py", line 477, in _handle_request
resp = await request_handler(request)
File "/usr/local/lib/python3.12/site-packages/aiohttp/web_app.py", line 559, in _handle
return await handler(request)
File "/usr/local/lib/python3.12/site-packages/aiohttp/web_middlewares.py", line 117, in impl
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/security_filter.py", line 92, in security_filter_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/forwarded.py", line 210, in forwarded_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/request_context.py", line 26, in request_context_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/ban.py", line 85, in ban_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/auth.py", line 242, in auth_middleware
return await handler(request)
File "/usr/src/homeassistant/homeassistant/components/http/headers.py", line 32, in headers_middleware
response = await handler(request)
File "/usr/src/homeassistant/homeassistant/helpers/http.py", line 73, in handle
result = await handler(request, **request.match_info)
File "/usr/src/homeassistant/homeassistant/components/http/decorators.py", line 81, in with_admin
return await func(self, request, *args, **kwargs)
File "/usr/src/homeassistant/homeassistant/components/config/config_entries.py", line 215, in get
return await super().get(request, flow_id)
File "/usr/src/homeassistant/homeassistant/helpers/data_entry_flow.py", line 108, in get
result = await self._flow_mgr.async_configure(flow_id)
File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 370, in async_configure
result = await self._async_configure(flow_id, user_input)
File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 417, in _async_configure
result = await self._async_handle_step(
File "/usr/src/homeassistant/homeassistant/data_entry_flow.py", line 520, in _async_handle_step
result: _FlowResultT = await getattr(flow, method)(user_input)
File "/config/custom_components/alexa_media/config_flow.py", line 420, in async_step_finish_proxy
if await self.login.test_loggedin():

2024-10-12 19:42:49.825 WARNING (MainThread) [homeassistant.util.loop] Detected blocking call to open with args (PosixPath('/config/.storage/alexa_media.mail.account@hotmail.com.pickle'),) inside the event loop by custom integration 'alexa_media' at custom_components/alexa_media/init.py, line 361: await login.login(cookies=await login.load_cookie()) (offender: /usr/local/lib/python3.12/site-packages/aiohttp/cookiejar.py, line 126: with file_path.open(mode="rb") as f:), please create a bug report at https://github.com/alandtse/alexa_media_player/issues
For developers, please see https://developers.home-assistant.io/docs/asyncio_blocking_operations/#open
Traceback (most recent call last):
File "", line 198, in _run_module_as_main
File "", line 88, in _run_code
File "/usr/src/homeassistant/homeassistant/main.py", line 223, in
sys.exit(main())
File "/usr/src/homeassistant/homeassistant/main.py", line 209, in main
exit_code = runner.run(runtime_conf)
File "/usr/src/homeassistant/homeassistant/runner.py", line 189, in run
return loop.run_until_complete(setup_and_run_hass(runtime_config))
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 674, in run_until_complete
self.run_forever()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 641, in run_forever
self._run_once()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 1990, in _run_once
handle._run()
File "/usr/local/lib/python3.12/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 742, in async_setup_locked
await self.async_setup(hass, integration=integration)
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 594, in async_setup
result = await component.async_setup_entry(hass, self)
File "/config/custom_components/alexa_media/init.py", line 361, in async_setup_entry
await login.login(cookies=await login.load_cookie())

2024-10-12 19:42:57.462 WARNING (MainThread) [alexapy.helpers] alexaapi.get_customer_history_records((<alexapy.alexalogin.AlexaLogin object at 0x7fa94f8376e0>,), {'max_record_size': 10}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Unauthorized',)
2024-10-12 19:42:57.462 WARNING (MainThread) [alexapy.helpers] alexaapi.get_last_device_serial((<alexapy.alexalogin.AlexaLogin object at 0x7fa94f8376e0>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Unauthorized',)
2024-10-12 19:42:57.526 WARNING (MainThread) [alexapy.helpers] alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0x7fa95030e8d0>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-10-12 19:42:58.630 WARNING (MainThread) [hass_nabucasa.cloud_api] Fetched https://alexa-api.nabucasa.com/access_token (400)
2024-10-12 19:42:58.631 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved (None)
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/cloud/alexa_config.py", line 547, in _handle_entity_registry_updated
await self._sync_helper(to_update, to_remove)
File "/usr/src/homeassistant/homeassistant/components/cloud/alexa_config.py", line 487, in _sync_helper
await self.async_get_access_token()
File "/usr/src/homeassistant/homeassistant/components/cloud/alexa_config.py", line 340, in async_get_access_token
raise alexa_errors.RequireRelink
homeassistant.components.alexa.errors.RequireRelink
2024-10-12 19:42:58.635 WARNING (MainThread) [hass_nabucasa.cloud_api] Fetched https://alexa-api.nabucasa.com/access_token (400)
2024-10-12 19:42:58.635 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved (None)
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/cloud/alexa_config.py", line 547, in _handle_entity_registry_updated
await self._sync_helper(to_update, to_remove)
File "/usr/src/homeassistant/homeassistant/components/cloud/alexa_config.py", line 487, in _sync_helper
await self.async_get_access_token()
File "/usr/src/homeassistant/homeassistant/components/cloud/alexa_config.py", line 340, in async_get_access_token
raise alexa_errors.RequireRelink
homeassistant.components.alexa.errors.RequireRelink
2024-10-12 19:42:58.650 WARNING (MainThread) [hass_nabucasa.cloud_api] Fetched https://alexa-api.nabucasa.com/access_token (400)
2024-10-12 19:42:58.650 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved (None)
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/cloud/alexa_config.py", line 547, in _handle_entity_registry_updated
await self._sync_helper(to_update, to_remove)
File "/usr/src/homeassistant/homeassistant/components/cloud/alexa_config.py", line 487, in _sync_helper
await self.async_get_access_token()
File "/usr/src/homeassistant/homeassistant/components/cloud/alexa_config.py", line 340, in async_get_access_token
raise alexa_errors.RequireRelink
homeassistant.components.alexa.errors.RequireRelink
2024-10-12 19:43:07.581 WARNING (MainThread) [alexapy.helpers] alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0x7fa95030e8d0>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-10-12 19:43:11.207 WARNING (MainThread) [alexapy.helpers] alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0x7fa95030e8d0>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-10-12 19:43:29.510 WARNING (MainThread) [alexapy.helpers] alexalogin.login((<alexapy.alexalogin.AlexaLogin object at 0x7fa9502fe690>,), {'cookies': {}}): An error occurred accessing AlexaAPI: An exception of type InvalidUrlClientError occurred. Arguments:
(URL('/errors/validateCaptcha'),)
2024-10-12 19:43:29.511 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry mail.account@hotmail.com - amazon.com for alexa_media
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 594, in async_setup
result = await component.async_setup_entry(hass, self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/config/custom_components/alexa_media/init.py", line 361, in async_setup_entry
await login.login(cookies=await login.load_cookie())
File "/config/deps/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
return await func(args, kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/config/deps/lib/python3.12/site-packages/alexapy/alexalogin.py", line 687, in login
post_resp = await self._session.post(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/aiohttp/client.py", line 588, in _request
raise err_exc_cls(url)
aiohttp.client_exceptions.InvalidUrlClientError: /errors/validateCaptcha
2024-10-12 19:46:18.272 ERROR (MainThread) [msmart.base_device] Network error 192.168.68.76:6444: Transport is closing or closed.
2024-10-12 19:48:33.043 ERROR (MainThread) [msmart.base_device] Network error 192.168.68.76:6444: Transport is closing or closed.
2024-10-12 19:48:54.336 ERROR (MainThread) [msmart.base_device] Network error 192.168.68.76:6444: Unsupported packet: 10e06784d4681db2f320bf1d72fae3a7e79dd2b15e9cd4b9a0c54808f1480220d9e596ccf5e491e17257e18021064b39d8f3a7ab6e9b3e53e28eced4bd4270cc
2024-10-12 19:49:09.254 ERROR (MainThread) [msmart.base_device] Network error 192.168.68.76:6444: Error packet received.
2024-10-12 19:51:18.275 ERROR (MainThread) [msmart.base_device] Network error 192.168.68.76:6444: Transport is closing or closed.
2024-10-12 19:53:33.040 ERROR (MainThread) [msmart.base_device] Network error 192.168.68.76:6444: Transport is closing or closed.
2024-10-12 19:53:37.202 ERROR (MainThread) [homeassistant] Error doing job: Unclosed client session (None)
2024-10-12 19:53:39.690 WARNING (MainThread) [alexapy.helpers] alexalogin.login((<alexapy.alexalogin.AlexaLogin object at 0x7fa9502fe690>,), {'cookies': {}}): An error occurred accessing AlexaAPI: An exception of type InvalidUrlClientError occurred. Arguments:
(URL('/errors/validateCaptcha'),)
2024-10-12 19:53:39.691 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry mail.account@hotmail.com - amazon.com for alexa_media
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 594, in async_setup
result = await component.async_setup_entry(hass, self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/config/custom_components/alexa_media/init.py", line 361, in async_setup_entry
await login.login(cookies=await login.load_cookie())
File "/config/deps/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
return await func(args, kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/config/deps/lib/python3.12/site-packages/alexapy/alexalogin.py", line 687, in login
post_resp = await self._session.post(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/aiohttp/client.py", line 588, in _request
raise err_exc_cls(url)
aiohttp.client_exceptions.InvalidUrlClientError: /errors/validateCaptcha
2024-10-12 19:53:44.260 ERROR (MainThread) [homeassistant] Error doing job: Unclosed client session (None)
2024-10-12 19:53:46.520 WARNING (MainThread) [alexapy.helpers] alexalogin.login((<alexapy.alexalogin.AlexaLogin object at 0x7fa9502fe690>,), {'cookies': {}}): An error occurred accessing AlexaAPI: An exception of type InvalidUrlClientError occurred. Arguments:
(URL('/errors/validateCaptcha'),)
2024-10-12 19:53:46.521 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry mail.account@hotmail.com - amazon.com for alexa_media
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 594, in async_setup
result = await component.async_setup_entry(hass, self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/config/custom_components/alexa_media/init.py", line 361, in async_setup_entry
await login.login(cookies=await login.load_cookie())
File "/config/deps/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
return await func(args, kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/config/deps/lib/python3.12/site-packages/alexapy/alexalogin.py", line 687, in login
post_resp = await self._session.post(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/aiohttp/client.py", line 588, in _request
raise err_exc_cls(url)
aiohttp.client_exceptions.InvalidUrlClientError: /errors/validateCaptcha
2024-10-12 19:54:00.728 DEBUG (MainThread) [custom_components.alexa_media.helpers] c
a@hm: Returning uuid {'uuid': '5690fc01b802acd9dfdd267a477f967c', 'index': 0}
2024-10-12 19:54:00.779 DEBUG (MainThread) [alexapy.alexalogin] Login created for mail.account@hotmail.com - amazon.com
2024-10-12 19:54:00.780 ERROR (MainThread) [homeassistant] Error doing job: Unclosed client session (None)
2024-10-12 19:54:00.783 DEBUG (MainThread) [alexapy.alexalogin] Searching for cookies from /config/.storage/alexa_media.mail.account@hotmail.com.pickle
2024-10-12 19:54:00.784 DEBUG (MainThread) [alexapy.alexalogin] Trying to load cookie from file /config/.storage/alexa_media.mail.account@hotmail.com.pickle
2024-10-12 19:54:00.790 DEBUG (MainThread) [alexapy.alexalogin] Trying to load aiohttpCookieJar to session
2024-10-12 19:54:00.801 DEBUG (MainThread) [alexapy.alexalogin] Searching for cookies from /config/alexa_media.mail.account@hotmail.com.pickle
2024-10-12 19:54:00.801 DEBUG (MainThread) [alexapy.alexalogin] Searching for cookies from /config/.storage/alexa_media.mail.account@hotmail.com.txt
2024-10-12 19:54:00.801 DEBUG (MainThread) [alexapy.alexalogin] Using credentials to log in
2024-10-12 19:54:00.802 DEBUG (MainThread) [alexapy.alexalogin] Attempting oauth login to https://www.amazon.com/ap/signin?openid.return_to=https://www.amazon.com/ap/maplanding&openid.assoc_handle=amzn_dp_project_dee_ios&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&pageId=amzn_dp_project_dee_ios&accountStatusPolicy=P1&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.mode=checkid_setup&openid.ns.oa2=http://www.amazon.com/ap/ext/oauth/2&openid.oa2.client_id=device:353639306663303162383032616364396466646432363761343737663936376332333431333234393536346335363335353634643332353733383331&openid.ns.pape=http://specs.openid.net/extensions/pape/1.0&openid.oa2.response_type=code&openid.ns=http://specs.openid.net/auth/2.0&openid.pape.max_auth_age=0&openid.oa2.scope=device_auth_access&openid.oa2.code_challenge_method=S256&openid.oa2.code_challenge=3KqDC96cJg9cL1AxMbSici-ZaU5MADaVQEoR8uNiwCU&language=en_US
2024-10-12 19:54:00.804 DEBUG (MainThread) [alexapy.alexalogin] Loaded last request to https://www.amazon.com/ap/signin?openid.return_to=https://www.amazon.com/ap/maplanding&openid.assoc_handle=amzn_dp_project_dee_ios&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&pageId=amzn_dp_project_dee_ios&accountStatusPolicy=P1&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.mode=checkid_setup&openid.ns.oa2=http://www.amazon.com/ap/ext/oauth/2&openid.oa2.client_id=device:353639306663303162383032616364396466646432363761343737663936376332333431333234393536346335363335353634643332353733383331&openid.ns.pape=http://specs.openid.net/extensions/pape/1.0&openid.oa2.response_type=code&openid.ns=http://specs.openid.net/auth/2.0&openid.pape.max_auth_age=0&openid.oa2.scope=device_auth_access&openid.oa2.code_challenge_method=S256&openid.oa2.code_challenge=3KqDC96cJg9cL1AxMbSici-ZaU5MADaVQEoR8uNiwCU&language=en_US
2024-10-12 19:54:00.804 DEBUG (MainThread) [alexapy.alexalogin] Processing https://www.amazon.com/ap/signin?openid.return_to=https://www.amazon.com/ap/maplanding&openid.assoc_handle=amzn_dp_project_dee_ios&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&pageId=amzn_dp_project_dee_ios&accountStatusPolicy=P1&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.mode=checkid_setup&openid.ns.oa2=http://www.amazon.com/ap/ext/oauth/2&openid.oa2.client_id=device:353639306663303162383032616364396466646432363761343737663936376332333431333234393536346335363335353634643332353733383331&openid.ns.pape=http://specs.openid.net/extensions/pape/1.0&openid.oa2.response_type=code&openid.ns=http://specs.openid.net/auth/2.0&openid.pape.max_auth_age=0&openid.oa2.scope=device_auth_access&openid.oa2.code_challenge_method=S256&openid.oa2.code_challenge=3KqDC96cJg9cL1AxMbSici-ZaU5MADaVQEoR8uNiwCU&language=en_US
2024-10-12 19:54:00.841 DEBUG (MainThread) [alexapy.alexalogin] Captcha/2FA not requested; confirming login.
2024-10-12 19:54:00.842 DEBUG (MainThread) [alexapy.alexalogin] Attempting to register with amazon.com
2024-10-12 19:54:01.266 DEBUG (MainThread) [alexapy.alexalogin] auth response <ClientResponse(https://api.amazon.com/auth/register) [400 Bad Request]>
<CIMultiDictProxy('Server': 'Server', 'Date': 'Sat, 12 Oct 2024 16:54:01 GMT', 'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': '426', 'Connection': 'keep-alive', 'x-amz-rid': 'W6FZDZSPVF54C075Z1WH', 'x-amzn-RequestId': '85acc166-0b7b-4e57-aa8d-5e1af5b48adb', 'X-Amz-Date': 'Sat, 12 Oct 2024 16:54:01 GMT', 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Vary': 'Content-Type,Accept-Encoding,User-Agent', 'Strict-Transport-Security': 'max-age=47474747; includeSubDomains; preload')>
with
{"requested_extensions": ["device_info", "customer_info"], "cookies": {"website_cookies": [], "domain": ".amazon.com"}, "registration_data": {"domain": "Device", "app_version": "2.2.556530.0", "device_type": "A2IVLV5VM2W81", "device_name": "%FIRST_NAME%'s%DUPE_STRATEGY_1ST%Alexa Media Player", "os_version": "16.6", "device_serial": "5690fc01b802acd9dfdd267a477f967c", "device_model": "iPhone", "app_name": "Alexa Media Player", "software_version": "1"}, "auth_data": {"client_id": "353639306663303162383032616364396466646432363761343737663936376332333431333234393536346335363335353634643332353733383331", "authorization_code": "ANpDQrgDnklpFEFbwHpVANwC", "code_verifier": "tT6JSOFE-tlN9IddpOIFmd4HjjGF26URwevJVgIp2t4", "code_algorithm": "SHA-256", "client_domain": "DeviceLegacy"}, "user_context_map": {"frc": "X1Us5vwnvtc+3XX3IqPURx4/8JzKbWte2R7ySSD3DHgcBnmYAE9VdG49/FDW11zlAqvmx0Aw2UkDm6KvvwWjmKqUbw32hUakbiT8uHyyhRshN77LZ7Ds/XFtFCecbV1xnFXNqOxnkbK0i2f6wU7ky0smgypRLbJB/uObcNO/SITZfsP4M39w98AmXJbuWBq7baHAnYU5vl5BTCUhGXJSQcID/mCqg3nqarVGaswxoYDYk2tzJxcQxm367vb2BkBeaJB+exEX9F33jvWWaTDjhVu4DLlX7SyMnSBDNTWzQQf/jttLgqz5ABNEvzAJcsaVTnDzBOtDFsyOWrsAs3x9BuGXbWE8M1sdPqJRV/T/M3/G7P9xaNW1t3EUQbK6hckpZH/pCkGXg6CDfHWKKzFSxySd9bmLmSGbYg"}, "requested_token_type": ["bearer", "mac_dms", "website_cookies"]}
2024-10-12 19:54:01.266 DEBUG (MainThread) [alexapy.alexalogin] Unable to register with ['amazon.com']
2024-10-12 19:54:01.469 DEBUG (MainThread) [alexapy.alexalogin] capabilities response <ClientResponse(https://api.amazonalexa.com/v1/devices/@self/capabilities) [403 Forbidden]>
<CIMultiDictProxy('Content-Length': '0', 'Connection': 'keep-alive', 'Server': 'Server', 'Date': 'Sat, 12 Oct 2024 16:54:01 GMT', 'Strict-Transport-Security': 'max-age=47474747; includeSubDomains; preload', 'x-amz-rid': 'W2N0NHGYSS3B49SVVB7D', 'Vary': 'Content-Type,Accept-Encoding,User-Agent', 'X-Cache': 'Error from cloudfront', 'Via': '1.1 a58780d22b5e142a1e7e092cfb4a356c.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'OTP50-P1', 'X-Amz-Cf-Id': 'GwJAhoYN61u_EZL9BtqXJQi2gXofkB7DYXLs8Gba8Hdaefbl9LmFzA==')>
with
{"legacyFlags": {"SUPPORTS_COMMS": true, "SUPPORTS_ARBITRATION": true, "SCREEN_WIDTH": 1170, "SUPPORTS_SCRUBBING": true, "SPEECH_SYNTH_SUPPORTS_TTS_URLS": false, "SUPPORTS_HOME_AUTOMATION": true, "SUPPORTS_DROPIN_OUTBOUND": true, "FRIENDLY_NAME_TEMPLATE": "VOX", "SUPPORTS_SIP_OUTBOUND_CALLING": true, "VOICE_PROFILE_SWITCHING_DISABLED": true, "SUPPORTS_LYRICS_IN_CARD": false, "SUPPORTS_DATAMART_NAMESPACE": "Vox", "SUPPORTS_VIDEO_CALLING": true, "SUPPORTS_PFM_CHANGED": true, "SUPPORTS_TARGET_PLATFORM": "TABLET", "SUPPORTS_SECURE_LOCKSCREEN": false, "AUDIO_PLAYER_SUPPORTS_TTS_URLS": false, "SUPPORTS_KEYS_IN_HEADER": false, "SUPPORTS_MIXING_BEHAVIOR_FOR_AUDIO_PLAYER": false, "AXON_SUPPORT": true, "SUPPORTS_TTS_SPEECHMARKS": true}, "envelopeVersion": "20160207", "capabilities": [{"version": "0.1", "interface": "CardRenderer", "type": "AlexaInterface"}, {"interface": "Navigation", "type": "AlexaInterface", "version": "1.1"}, {"type": "AlexaInterface", "version": "2.0", "interface": "Alexa.Comms.PhoneCallController"}, {"type": "AlexaInterface", "version": "1.1", "interface": "ExternalMediaPlayer"}, {"type": "AlexaInterface", "interface": "Alerts", "configurations": {"maximumAlerts": {"timers": 2, "overall": 99, "alarms": 2}}, "version": "1.3"}, {"version": "1.0", "interface": "Alexa.Display.Window", "type": "AlexaInterface", "configurations": {"templates": [{"type": "STANDARD", "id": "app_window_template", "configuration": {"sizes": [{"id": "fullscreen", "type": "DISCRETE", "value": {"value": {"height": 1440, "width": 3200}, "unit": "PIXEL"}}], "interactionModes": ["mobile_mode", "auto_mode"]}}]}}, {"type": "AlexaInterface", "interface": "AccessoryKit", "version": "0.1"}, {"type": "AlexaInterface", "interface": "Alexa.AudioSignal.ActiveNoiseControl", "version": "1.0", "configurations": {"ambientSoundProcessingModes": [{"name": "ACTIVE_NOISE_CONTROL"}, {"name": "PASSTHROUGH"}]}}, {"interface": "PlaybackController", "type": "AlexaInterface", "version": "1.0"}, {"version": "1.0", "interface": "Speaker", "type": "AlexaInterface"}, {"version": "1.0", "interface": "SpeechSynthesizer", "type": "AlexaInterface"}, {"version": "1.0", "interface": "AudioActivityTracker", "type": "AlexaInterface"}, {"type": "AlexaInterface", "interface": "Alexa.Camera.LiveViewController", "version": "1.0"}, {"type": "AlexaInterface", "version": "1.0", "interface": "Alexa.Input.Text"}, {"type": "AlexaInterface", "interface": "Alexa.PlaybackStateReporter", "version": "1.0"}, {"version": "1.1", "interface": "Geolocation", "type": "AlexaInterface"}, {"interface": "Alexa.Health.Fitness", "version": "1.0", "type": "AlexaInterface"}, {"interface": "Settings", "type": "AlexaInterface", "version": "1.0"}, {"configurations": {"interactionModes": [{"dialog": "SUPPORTED", "interactionDistance": {"value": 18, "unit": "INCHES"}, "video": "SUPPORTED", "keyboard": "SUPPORTED", "id": "mobile_mode", "uiMode": "MOBILE", "touch": "SUPPORTED"}, {"video": "UNSUPPORTED", "dialog": "SUPPORTED", "interactionDistance": {"value": 36, "unit": "INCHES"}, "uiMode": "AUTO", "touch": "SUPPORTED", "id": "auto_mode", "keyboard": "UNSUPPORTED"}]}, "type": "AlexaInterface", "interface": "Alexa.InteractionMode", "version": "1.0"}, {"type": "AlexaInterface", "configurations": {"catalogs": [{"type": "IOS_APP_STORE", "identifierTypes": ["URI_HTTP_SCHEME", "URI_CUSTOM_SCHEME"]}]}, "version": "0.2", "interface": "Alexa.Launcher"}, {"interface": "System", "version": "1.0", "type": "AlexaInterface"}, {"interface": "Alexa.IOComponents", "type": "AlexaInterface", "version": "1.4"}, {"type": "AlexaInterface", "interface": "Alexa.FavoritesController", "version": "1.0"}, {"version": "1.0", "type": "AlexaInterface", "interface": "Alexa.Mobile.Push"}, {"type": "AlexaInterface", "interface": "InteractionModel", "version": "1.1"}, {"interface": "Alexa.PlaylistController", "type": "AlexaInterface", "version": "1.0"}, {"interface": "SpeechRecognizer", "type": "AlexaInterface", "version": "2.1"}, {"interface": "AudioPlayer", "type": "AlexaInterface", "version": "1.3"}, {"type": "AlexaInterface", "version": "3.1", "interface": "Alexa.RTCSessionController"}, {"interface": "VisualActivityTracker", "version": "1.1", "type": "AlexaInterface"}, {"interface": "Alexa.PlaybackController", "version": "1.0", "type": "AlexaInterface"}, {"type": "AlexaInterface", "interface": "Alexa.SeekController", "version": "1.0"}, {"interface": "Alexa.Comms.MessagingController", "type": "AlexaInterface", "version": "1.0"}]}
{"User-Agent": "AmazonWebView/Amazon Alexa/2.2.556530.0/iOS/16.6/iPhone", "Accept-Language": "en-US", "Accept-Charset": "utf-8", "Connection": "keep-alive", "Content-type": "application/json; charset=UTF-8", "authorization": "Bearer None"}
2024-10-12 19:54:01.469 DEBUG (MainThread) [alexapy.alexalogin] Failed to register capabilities
2024-10-12 19:54:01.758 DEBUG (MainThread) [alexapy.alexalogin] 5 cookies successfully exchanged for refresh token for domain .amazon.com
2024-10-12 19:54:01.758 DEBUG (MainThread) [alexapy.alexalogin] Attempting to discover CSRF token
2024-10-12 19:54:01.964 DEBUG (MainThread) [alexapy.alexalogin] CSRF token not found from /spa/index.html
2024-10-12 19:54:02.445 DEBUG (MainThread) [alexapy.alexalogin] CSRF token not found from /api/devices-v2/device?cached=false
2024-10-12 19:54:02.602 DEBUG (MainThread) [alexapy.alexalogin] CSRF token not found from /templates/oobe/d-device-pick.handlebars
2024-10-12 19:54:02.753 DEBUG (MainThread) [alexapy.alexalogin] No csrf token found
2024-10-12 19:54:02.918 DEBUG (MainThread) [alexapy.alexalogin] GET:
https://alexa.amazon.com/api/bootstrap returned 401:Unauthorized with response <CIMultiDictProxy('Content-Length': '0', 'Connection': 'keep-alive', 'Server': 'Server', 'Date': 'Sat, 12 Oct 2024 16:54:02 GMT', 'Vary': 'Content-Type,Accept-Encoding,User-Agent', 'x-amz-rid': 'B4D9MEN38YDQCG5V8308', 'loginUrl': 'https://www.amazon.com/ap/signin?showRmrMe=1&openid.return_to=https%3A%2F%2Falexa.amazon.com%2Flogin&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.assoc_handle=amzn_dp_project_dee&openid.mode=checkid_setup&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&', 'x-amzn-RequestId': 'B4D9MEN38YDQCG5V8308', 'X-Cache': 'Error from cloudfront', 'Via': '1.1 7e0d8fe3a1927ce16863bca92fb950e4.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'OTP50-P2', 'X-Amz-Cf-Id': 'ej9Lfxbxa4M7dOKS6S_uCsINhw1-EzyUqDdVjBAtrbQojBxgCJX5WQ==')>
2024-10-12 19:54:02.918 DEBUG (MainThread) [alexapy.alexalogin] Not logged in: An exception of type ContentTypeError occurred. Arguments:
(RequestInfo(url=URL('https://alexa.amazon.com/api/bootstrap'), method='GET', headers=<CIMultiDictProxy('Host': 'alexa.amazon.com', 'User-Agent': 'AmazonWebView/Amazon Alexa/2.2.556530.0/iOS/16.6/iPhone', 'Accept': '
/
', 'Accept-Language': '
', 'DNT': '1', 'Upgrade-Insecure-Requests': '1', 'Accept-Encoding': 'gzip, deflate, br', 'Cookie': 'session-id=136-4620224-9711024; session-id-time=2359472042l; session-token=a0RR+3f63Ah85DfUshOddBRyTykHuvY8UtdOEp6NHNYUE+4dUJEmq+5uDlz6kR0x2yrEiqzWAOmz95Y4M5CTaR7FSjzG3laowtZ2NWX9eTVJilFkJsHrnEmLMk/JgdhC7EGih17mOb8Y8tLAtHFTCdeNaYOhYac6AYtqrWbkdC7nE80hM0+qiLvlXDdg4nNompvxBDiMWb63Av4UYDWyomzy/pYcJ+BFG4kY8A0mwrnLuDHRzhU5YD07o5L2XzmmKQWQXG6KEgn/QkOdlMSfbIZesvNbvSFQUNeduoHgmoCwRjTbjCvCmM67dfDDL8chdEl5FZtHU2nC8RIL/vDewevqCf7N28Xj; ubid-main=130-7524385-0351830')>, real_url=URL('https://alexa.amazon.com/api/bootstrap')), ())
2024-10-12 19:54:02.919 DEBUG (MainThread) [alexapy.alexalogin] Login failed; check credentials
2024-10-12 19:54:02.919 DEBUG (MainThread) [alexapy.alexalogin] Found post url to /errors/validateCaptcha
2024-10-12 19:54:02.919 DEBUG (MainThread) [alexapy.alexalogin] Preparing form submission to /errors/validateCaptcha with input data: {}
2024-10-12 19:54:02.920 WARNING (MainThread) [alexapy.helpers] alexalogin.login((<alexapy.alexalogin.AlexaLogin object at 0x7fa9502fe690>,), {'cookies': {}}): An error occurred accessing AlexaAPI: An exception of type InvalidUrlClientError occurred. Arguments:
(URL('/errors/validateCaptcha'),)
2024-10-12 19:54:02.920 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry mail.account@hotmail.com - amazon.com for alexa_media
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 594, in async_setup
result = await component.async_setup_entry(hass, self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/config/custom_components/alexa_media/init.py", line 361, in async_setup_entry
await login.login(cookies=await login.load_cookie())
File "/config/deps/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
return await func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/config/deps/lib/python3.12/site-packages/alexapy/alexalogin.py", line 687, in login
post_resp = await self._session.post(
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/aiohttp/client.py", line 588, in _request
raise err_exc_cls(url)
aiohttp.client_exceptions.InvalidUrlClientError: /errors/validateCaptcha

@ik0adr
Copy link

ik0adr commented Oct 14, 2024

+1 same here
An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
Deleted pickle file, restarted and it works for a while, than error again.

UPDATE: after deleting pickle, and devices suppressing OTP, it works.

@sim-bax
Copy link

sim-bax commented Oct 18, 2024

I have deleted pickle, no device suppreing OTP and still get the error

Logger: homeassistant
Source: /usr/src/homeassistant/homeassistant/runner.py:147
First occurred: 3:30:23 PM (3 occurrences)
Last logged: 4:41:46 PM

Error doing job: Task exception was never retrieved (None)
Traceback (most recent call last):
File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
return await func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 960, in send_announcement
await self.send_sequence(
File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
return await func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 512, in send_sequence
await self.run_behavior(node_data, queue_delay=queue_delay)
File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
return await func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 434, in run_behavior
await self._post_request("/api/behaviors/preview", data=data)
File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 226, in _post_request
return await self._request("post", uri, data, query)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/backoff/_async.py", line 151, in retry
ret = await target(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 199, in _request
raise AlexapyLoginError("Login error detected; not contacting API")
alexapy.errors.AlexapyLoginError: Login error detected; not contacting API

@kompre
Copy link

kompre commented Oct 21, 2024

For several weeks the integration has not worked for me due to the issue #2515

Now after updating to v4.13.5 I am not getting the issue described in #2515, but still the integration fails, even after reconfiguring it, which seems to match the current issue.

When I try to do something with the integration, log shows 2 warning and an error:

This error originated from a custom integration.

Logger: alexapy.helpers
Source: custom_components/alexa_media/media_player.py:654
integration: Alexa Media Player (documentation, issues)
First occurred: 15:54:45 (1 occurrences)
Last logged: 15:54:45

alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0x7fe472475760>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
Logger: alexapy.helpers
Source: runner.py:189
First occurred: 15:54:46 (3 occurrences)
Last logged: 15:54:46

alexaapi.run_behavior((<alexapy.alexaapi.AlexaAPI object at 0x7fe472475760>, {'@type': 'com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode', 'type': 'Alexa.Music.PlaySearchPhrase', 'operationPayload': {'deviceType': 'A2U21SRK4QGSE1', 'deviceSerialNumber': 'G************8XA', 'locale': 'it-it', 'customerId': 'A*********OP9', 'searchPhrase': 'custom', 'sanitizedSearchPhrase': 'custom', 'musicProviderId': 'che ore sono?'}}), {'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.send_sequence((<alexapy.alexaapi.AlexaAPI object at 0x7fe472475760>, 'Alexa.Music.PlaySearchPhrase'), {'customer_id': 'ARZATHI64LOP9', 'searchPhrase': 'custom', 'sanitizedSearchPhrase': 'custom', 'musicProviderId': 'che ore sono?', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
alexaapi.play_music((<alexapy.alexaapi.AlexaAPI object at 0x7fe472475760>, 'che ore sono?', 'custom'), {'customer_id': 'ARZATHI64LOP9', 'queue_delay': 1.5, 'timer': None, 'extra': {}}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments: ('Login error detected; not contacting API',)
Logger: homeassistant
Source: /usr/src/homeassistant/homeassistant/runner.py:147
First occurred: 15:54:46 (1 occurrences)
Last logged: 15:54:46

Error doing job: Task exception was never retrieved (None)
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 724, in play_music
    await self.send_sequence(
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 512, in send_sequence
    await self.run_behavior(node_data, queue_delay=queue_delay)
  File "/usr/local/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 434, in run_behavior
    await self._post_request("/api/behaviors/preview", data=data)
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 226, in _post_request
    return await self._request("post", uri, data, query)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/backoff/_async.py", line 151, in retry
    ret = await target(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/alexapy/alexaapi.py", line 199, in _request
    raise AlexapyLoginError("Login error detected; not contacting API")
alexapy.errors.AlexapyLoginError: Login error detected; not contacting API

@srescio
Copy link
Contributor

srescio commented Oct 23, 2024

the exception is originating from here https://gitlab.com/keatontaylor/alexapy/-/blob/dev/alexapy/alexaapi.py?ref_type=heads#L199
and it happens when it does not find self._login.status['login_successful'] to be True:
https://gitlab.com/keatontaylor/alexapy/-/blob/dev/alexapy/alexaapi.py?ref_type=heads#L190

in my case, after setting conditional logging in the 3 only places where the value is being explicitly set to False (so after an unsuccessful login), it was after one call ended in 401:
https://gitlab.com/keatontaylor/alexapy/-/blob/dev/alexapy/alexaapi.py?ref_type=heads#L119-120

when in this state all subsequent calls will fail, it looks like it never reattempts automatically to login, which is the only way to end in the flow where that flag gets assigned True again (if everything goes well):
https://gitlab.com/keatontaylor/alexapy/-/blob/dev/alexapy/alexalogin.py?ref_type=heads#L1761-1770

now...just for curiosity I retried from my HA test instance to reissue a call that should fail because supposedly not loggedin, and while in breakpoint I overrode the value of login_successful to True just to see what happens if the request does not get killed there and...guess what?
The echo dot spoke correctly regardless 😄

Screenshot 2024-10-23 alle 20 35 21

Still not sure how to move from here, but IMHO killing the request because of that check done only once for all next calls does not seems correct,
in alexahttp2 there is the fn handle_login_error which as per comment attempts to relogin
https://gitlab.com/keatontaylor/alexapy/-/blob/dev/alexapy/alexahttp2.py?ref_type=heads#L189-195
which is done by login.test_loggedin()
https://gitlab.com/keatontaylor/alexapy/-/blob/dev/alexapy/alexalogin.py?ref_type=heads#L485

this one is however apparently internally called here only at initial phase so when integration is loaded into HA and not with further calls,

I think we could try replacing the static value check with the dynamic one like in alexahttp2

one disadvantage I see is that running that fn for every single request is going to be way more expensive than quickly checking a stored boolean value, still the improvement in reliability would be there...or at least it could be limited to only when the value happens to be found False

@danielbrunt57
Copy link
Collaborator

danielbrunt57 commented Oct 24, 2024

@srescio I think alexapy MR !392 might be relevant here. Could you give it a test run &/or reply with your evaluation of its effect/benefit?

image

@danielbrunt57
Copy link
Collaborator

danielbrunt57 commented Oct 24, 2024

As for you suggestion "try replacing the static value check with the dynamic one like in alexahttp2", I'm not sure how you would do that. Does this look like what you're proposing?
Existing :

        if not self._login.status.get("login_successful"):
            _LOGGER.debug(
                "%s:Login error detected; ignoring %s request to %s with %s %s",
                hide_email(self._login.email),
                method,
                uri,
                data,
                query,
            )
            raise AlexapyLoginError("Login error detected; not contacting API")

Revised:

        if not self._login.status.get("login_successful"):
            if not await self._login.test_loggedin():
                raise AlexapyLoginError(message)

@srescio
Copy link
Contributor

srescio commented Oct 24, 2024

yes thats what I though, though after checking better also the custom component code it would not be enough as there are several places where that flag is checked for the same purpose...so for a solid fix we need to find a way for repopulating it to True

yesterday I started my instance at 00:15 then did not execute any more commands and let it sit,

today I found out that the extension with the api lib did periodically some refreshing calls which all went well till 00:39 where it finally hit a 401 unauthorized when attempting to retrieve data from https://www.amazon.it/alexa-privacy/apd/rvh/customer-history-records

and that was the last one with a non 0 time execution for "Finished fetching alexa_media" (5.295), all the others happening later at roughly 10min interval (i guess some polling is happening here, hence why the hack of reloading the integration needs to be at 10min or lower) ends in 0 seconds with no other logs, because all request in alexapy are then immediately killed by the login_successful flag being False
Funny thing is those logs end with (success: True) but since they last almost nothing and no other logs call come before/after those the operation is clearly failing but not being correctly bubbled up:

2024-10-24 00:29:29.126 DEBUG (MainThread) [custom_components.alexa_media] Finished fetching alexa_media data in 6.049 seconds (success: True)
2024-10-24 00:39:29.297 DEBUG (MainThread) [alexapy.alexaapi] s***********o@g*******m: static GET: https://alexa.amazon.it/api/dnd/device-status-list returned 200:OK:application/json
2024-10-24 00:39:29.306 DEBUG (MainThread) [alexapy.alexaapi] s***********o@g*******m: static GET: https://alexa.amazon.it/api/devices-v2/device returned 200:OK:application/json
2024-10-24 00:39:29.359 DEBUG (MainThread) [alexapy.alexaapi] s***********o@g*******m: static GET: https://alexa.amazon.it/api/bluetooth?cached=false returned 200:OK:application/json
2024-10-24 00:39:29.665 DEBUG (MainThread) [alexapy.alexaapi] s***********o@g*******m: static GET: https://alexa.amazon.it/api/device-preferences returned 200:OK:application/json
2024-10-24 00:39:34.173 DEBUG (MainThread) [alexapy.alexaapi] s***********o@g*******m: static GET: https://alexa.amazon.it/api/notifications returned 200:OK:application/json
2024-10-24 00:39:34.175 DEBUG (MainThread) [custom_components.alexa_media] s***********o@g*******m: Updated 7 notifications for 4 devices at 2024-10-24 02:39:34.174925+02:00
2024-10-24 00:39:34.336 DEBUG (MainThread) [alexapy.alexaapi] s***********o@g*******m: static GET: https://www.amazon.it/alexa-privacy/apd/rvh/customer-history-records?startTime=1729643974176&endTime=1729816774176&recordType=VOICE_HISTORY&maxRecordSize=10 returned 401:Unauthorized:text/html
2024-10-24 00:39:34.337 WARNING (MainThread) [alexapy.helpers] alexaapi.get_customer_history_records((<alexapy.alexalogin.AlexaLogin object at 0xffff6183f1d0>,), {'max_record_size': 10}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Unauthorized',)
2024-10-24 00:39:34.337 WARNING (MainThread) [alexapy.helpers] alexaapi.get_last_device_serial((<alexapy.alexalogin.AlexaLogin object at 0xffff6183f1d0>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Unauthorized',)
2024-10-24 00:39:34.338 DEBUG (MainThread) [custom_components.alexa_media] Simone's Ultimate Alexa: Locale it-it timezone Europe/Rome
2024-10-24 00:39:34.338 DEBUG (MainThread) [custom_components.alexa_media] Simone's Ultimate Alexa: DND False
2024-10-24 00:39:34.339 DEBUG (MainThread) [custom_components.alexa_media] Ovunque: DND False
2024-10-24 00:39:34.340 DEBUG (MainThread) [custom_components.alexa_media.media_player] s***********o@g*******m: Refreshing <entity media_player.ovunque=standby>
2024-10-24 00:39:34.340 DEBUG (MainThread) [custom_components.alexa_media.media_player] s***********o@g*******m: Ovunque: Last_called check: self: 9****************************c68 reported: G************62Q
2024-10-24 00:39:34.340 DEBUG (MainThread) [custom_components.alexa_media] Echo notte: Locale it-it timezone Europe/Rome
2024-10-24 00:39:34.340 DEBUG (MainThread) [custom_components.alexa_media] Echo notte: DND True
2024-10-24 00:39:34.340 DEBUG (MainThread) [custom_components.alexa_media.media_player] s***********o@g*******m: Refreshing <entity media_player.echo_notte=standby>
2024-10-24 00:39:34.340 DEBUG (MainThread) [custom_components.alexa_media.media_player] s***********o@g*******m: Echo notte: Last_called check: self: G************62Q reported: G************62Q
2024-10-24 00:39:34.341 DEBUG (MainThread) [custom_components.alexa_media] Sonos Arc: Locale it-it timezone Europe/Rome
2024-10-24 00:39:34.341 DEBUG (MainThread) [custom_components.alexa_media] Sonos Arc: DND False
2024-10-24 00:39:34.341 DEBUG (MainThread) [custom_components.alexa_media.media_player] s***********o@g*******m: Refreshing <entity media_player.sonos_arc=standby>
2024-10-24 00:39:34.341 DEBUG (MainThread) [custom_components.alexa_media.media_player] s***********o@g*******m: Sonos Arc: Last_called check: self: 2****************************8f9 reported: G************62Q
2024-10-24 00:39:34.341 DEBUG (MainThread) [custom_components.alexa_media] Sonos System: Locale en-us timezone None
2024-10-24 00:39:34.341 DEBUG (MainThread) [custom_components.alexa_media] Sonos System: DND False
2024-10-24 00:39:34.342 DEBUG (MainThread) [custom_components.alexa_media] Echo giorno: Locale it-it timezone Europe/Rome
2024-10-24 00:39:34.342 DEBUG (MainThread) [custom_components.alexa_media] Echo giorno: DND False
2024-10-24 00:39:34.342 DEBUG (MainThread) [custom_components.alexa_media.media_player] s***********o@g*******m: Refreshing <entity media_player.echo_giorno=standby>
2024-10-24 00:39:34.342 DEBUG (MainThread) [custom_components.alexa_media.media_player] s***********o@g*******m: Echo giorno: Last_called check: self: G************E0Q reported: G************62Q
2024-10-24 00:39:34.343 DEBUG (MainThread) [custom_components.alexa_media] Simone's Jabra Elite 7 Pro: Locale en-us timezone None
2024-10-24 00:39:34.343 DEBUG (MainThread) [custom_components.alexa_media] Simone's Jabra Elite 7 Pro: DND False
2024-10-24 00:39:34.343 DEBUG (MainThread) [custom_components.alexa_media] This Device: Locale en-us timezone None
2024-10-24 00:39:34.343 DEBUG (MainThread) [custom_components.alexa_media] This Device: DND False
2024-10-24 00:39:34.343 DEBUG (MainThread) [custom_components.alexa_media.media_player] s***********o@g*******m: Refreshing <entity media_player.this_device=standby>
2024-10-24 00:39:34.343 DEBUG (MainThread) [custom_components.alexa_media.media_player] s***********o@g*******m: This Device: Last_called check: self: 8****************************bc7 reported: G************62Q
2024-10-24 00:39:34.344 DEBUG (MainThread) [custom_components.alexa_media] s***********o@g*******m: Existing: [<entity media_player.simone_s_ultimate_alexa=unavailable>, <entity media_player.ovunque=standby>, <entity media_player.echo_notte=standby>, <entity media_player.sonos_arc=standby>, <entity media_player.sonos_system=unavailable>, <entity media_player.echo_giorno=standby>, <entity media_player.simone_s_jabra_elite_7_pro=unavailable>, <entity media_player.this_device=standby>] New: []; Filtered out by not being in include: [] or in exclude: []
2024-10-24 00:39:34.348 DEBUG (MainThread) [custom_components.alexa_media] Finished fetching alexa_media data in 5.295 seconds (success: True)
2024-10-24 00:49:34.049 DEBUG (MainThread) [custom_components.alexa_media] Finished fetching alexa_media data in 0.000 seconds (success: True)
2024-10-24 00:59:34.056 DEBUG (MainThread) [custom_components.alexa_media] Finished fetching alexa_media data in 0.001 seconds (success: True)
2024-10-24 01:06:53.468 DEBUG (MainThread) [custom_components.alexa_media] s***********o@g*******m: Login error; will not reconnect http2
2024-10-24 01:09:34.061 DEBUG (MainThread) [custom_components.alexa_media] Finished fetching alexa_media data in 0.000 seconds (success: True)
2024-10-24 01:19:34.087 DEBUG (MainThread) [custom_components.alexa_media] Finished fetching alexa_media data in 0.000 seconds (success: True)
2024-10-24 01:29:34.086 DEBUG (MainThread) [custom_components.alexa_media] Finished fetching alexa_media data in 0.000 seconds (success: True)
2024-10-24 01:39:34.115 DEBUG (MainThread) [custom_components.alexa_media] Finished fetching alexa_media data in 0.000 seconds (success: True)
2024-10-24 01:49:34.116 DEBUG (MainThread) [custom_components.alexa_media] Finished fetching alexa_media data in 0.000 seconds (success: True)
2024-10-24 01:59:34.130 DEBUG (MainThread) [custom_components.alexa_media] Finished fetching alexa_media data in 0.000 seconds (success: True)
2024-10-24 02:09:34.129 DEBUG (MainThread) [custom_components.alexa_media] Finished fetching alexa_media data in 0.000 seconds (success: True)
...

@srescio
Copy link
Contributor

srescio commented Oct 24, 2024

after all the above idleness I just did a speak test knowing it would fail and these are the full logs (i've enabled debug logs pretty much everywhere it seemed fit) :

2024-10-24 17:57:04.041 INFO (MainThread) [homeassistant.helpers.script.websocket_api_script] websocket_api script: Running websocket_api script
2024-10-24 17:57:04.041 INFO (MainThread) [homeassistant.helpers.script.websocket_api_script] websocket_api script: Executing step Alexa speak echo notte
2024-10-24 17:57:04.042 DEBUG (MainThread) [custom_components.alexa_media.notify] Message: prova da instanza test, kwargs: {'target': ['G09147040156062Q'], 'data': None}
2024-10-24 17:57:04.042 DEBUG (MainThread) [custom_components.alexa_media.notify] Target type: <class 'list'>
2024-10-24 17:57:04.042 DEBUG (MainThread) [custom_components.alexa_media.notify] Processing: G09147040156062Q
2024-10-24 17:57:04.042 DEBUG (MainThread) [custom_components.alexa_media.notify] Processed Target by string: ['G09147040156062Q']
2024-10-24 17:57:04.043 DEBUG (MainThread) [custom_components.alexa_media.notify] TTS by <entity media_player.echo_notte=standby> : prova da instanza test
2024-10-24 17:57:05.554 DEBUG (MainThread) [alexapy.alexaapi] s***********o@g*******m: Creating sequence for 1 items
2024-10-24 17:57:05.554 DEBUG (MainThread) [alexapy.alexaapi] s***********o@g*******m: Running behavior with data: {"behaviorId": "PREVIEW", "sequenceJson": "{\"@type\": \"com.amazon.alexa.behaviors.model.Sequence\", \"startNode\": {\"@type\": \"com.amazon.alexa.behaviors.model.SerialNode\", \"nodesToExecute\": [{\"@type\": \"com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode\", \"type\": \"Alexa.Speak\", \"operationPayload\": {\"deviceType\": \"A30YDR2MK8HMRV\", \"deviceSerialNumber\": \"G09147040156062Q\", \"locale\": \"it-it\", \"customerId\": \"A1H2UL28U6ONC4\", \"textToSpeak\": \"prova da instanza test\", \"target\": {\"customerId\": \"A1H2UL28U6ONC4\", \"devices\": [{\"deviceSerialNumber\": \"G09147040156062Q\", \"deviceTypeId\": \"A30YDR2MK8HMRV\"}]}, \"skillId\": \"amzn1.ask.1p.saysomething\"}}]}}", "status": "ENABLED"}
2024-10-24 17:57:05.554 DEBUG (MainThread) [alexapy.alexaapi] s***********o@g*******m: Detected access token expiration; refreshing
2024-10-24 17:57:05.783 DEBUG (MainThread) [alexapy.alexalogin] refresh response <ClientResponse(https://api.amazon.it/auth/token) [200 OK]>
<CIMultiDictProxy('Server': 'Server', 'Date': 'Thu, 24 Oct 2024 17:57:05 GMT', 'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': '981', 'Connection': 'keep-alive', 'x-amz-rid': 'DR1Z04ZWG77B2VGZHV4R', 'x-amzn-RequestId': '7934ec73-e09b-45e1-926d-3550feaef415', 'X-Amz-Date': 'Thu, 24 Oct 2024 17:57:05 GMT', 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Vary': 'Content-Type,Accept-Encoding,User-Agent', 'Strict-Transport-Security': 'max-age=47474747; includeSubDomains; preload')>
 with 
{"app_name": "Alexa Media Player", "app_version": "2.2.556530.0", "di.sdk.version": "6.12.4", "source_token": "Atnr|EwICIF62lXtQRCF9X46J0D_ly0PBEVQvKy3pwbjlNSm6aF1CqZrx7BmDr-TnBhILHjdW4uT657EBZKSAfGPwtYdsdeFq0_TM4z46Qiu8Fq2nYKeGj3vaPBAVxXC9BupdY_eIwCIZneSmdaXTw4-csQ9bQFAVpsvaPt6heXyLjNqj-zpoWTKnbK205XWkQtqGoZU0YGNMxDGkJBywlaOL4LEyGMwdkmWAvO_mXjWtb8kfdAQfalKXGm77XIGHfEqXhl0tJji94XshUIQ_N7qnd58ll--nHTGiWI97AE7JXUDvLjgOmYcQtn2QqpevdR2tbnejVOqPdTgL7RmHCfaqEHHzhadJxc8-vIFYo_iooblEi4Vkjg", "package_name": "com.amazon.echo", "di.hw.version": "iPhone", "platform": "iOS", "requested_token_type": "access_token", "source_token_type": "refresh_token", "di.os.name": "iOS", "di.os.version": "16.6", "current_version": "6.12.4", "previous_version": "6.12.4"}
2024-10-24 17:57:05.783 DEBUG (MainThread) [alexapy.alexalogin] Successfully refreshed access_token(396) which expires at 2024-10-24 18:57:05.783812 in 0:59:59.999982
2024-10-24 17:57:06.137 DEBUG (MainThread) [alexapy.alexalogin] updating jar with cookie Set-Cookie: session-id=262-0487447-1922101; Domain=.amazon.it; expires=19 Oct 2044 17:57:06 GMT; Path=/; Secure
2024-10-24 17:57:06.137 DEBUG (MainThread) [alexapy.alexalogin] updating jar with cookie Set-Cookie: ubid-acbit=262-1390390-7325002; Domain=.amazon.it; expires=19 Oct 2044 17:57:06 GMT; Path=/; Secure
2024-10-24 17:57:06.137 DEBUG (MainThread) [alexapy.alexalogin] updating jar with cookie Set-Cookie: x-acbit="CBchM7QD1d?Qzb08cmu3?wz9bK9l48r0"; Domain=.amazon.it; expires=19 Oct 2044 17:57:06 GMT; Path=/; Secure
2024-10-24 17:57:06.137 DEBUG (MainThread) [alexapy.alexalogin] updating jar with cookie Set-Cookie: at-acbit=Atza|IwEBIHSbr8GKGTOPEFargIlrTkDVE3FIpnJEXV7fX4A2pq_to2HFkcK8CFvtWSdA8hUu88RJNYe_eH5Xj6xl5FzcK4wWTe7I3gGgrUBhtH8rdtk-5xScT5lhpx-3t0h-cInnv-R43iRXROp9uvpF6eiVIkSb9kh25E7njhbBuhnKGNzJhjm2Mg7WxQ-C2x_yn91JNyPrx8tNH41KRH6sa3UNaciZuD1x7Bs5n0k1dc3nUyGn6qNtvO7rtk20ztp6p2HHARCtpC5tpJFCwF9fHDOF4i96OZzkY-TcGK3wcz6FlVG05ZRrM-7ucxmYoku3CymNHVJXzjhproWspsvW6QeRGrXdcyeZrAdOEW8BqFFkHAvsOfOHE_q8YPmV66Bfoeijn0z15sO-3G2hTuF9hEjhdA5k; Domain=.amazon.it; expires=25 Oct 2024 17:57:06 GMT; HttpOnly; Path=/; Secure
2024-10-24 17:57:06.137 DEBUG (MainThread) [alexapy.alexalogin] updating jar with cookie Set-Cookie: sess-at-acbit="TLMzN0t1tMCu2JONOx2GtxCpZeyVxUlDoOeH4iAt1lQ="; Domain=.amazon.it; expires=25 Oct 2024 17:57:06 GMT; HttpOnly; Path=/; Secure
2024-10-24 17:57:06.138 INFO (MainThread) [alexapy.alexalogin] Exchanged refresh token for 5 .amazon.it cookies: ['session-id', 'ubid-acbit', 'x-acbit', 'at-acbit', 'sess-at-acbit']
2024-10-24 17:57:06.138 DEBUG (MainThread) [alexapy.alexalogin] CSRF already exists; no need to discover
2024-10-24 17:57:06.141 DEBUG (MainThread) [alexapy.alexaapi] s***********o@g*******m: Trying post: https://alexa.amazon.it/api/behaviors/preview : with uri: /api/behaviors/preview data {'behaviorId': 'PREVIEW', 'sequenceJson': '{"@type": "com.amazon.alexa.behaviors.model.Sequence", "startNode": {"@type": "com.amazon.alexa.behaviors.model.SerialNode", "nodesToExecute": [{"@type": "com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode", "type": "Alexa.Speak", "operationPayload": {"deviceType": "A30YDR2MK8HMRV", "deviceSerialNumber": "G09147040156062Q", "locale": "it-it", "customerId": "A1H2UL28U6ONC4", "textToSpeak": "prova da instanza test", "target": {"customerId": "A1H2UL28U6ONC4", "devices": [{"deviceSerialNumber": "G09147040156062Q", "deviceTypeId": "A30YDR2MK8HMRV"}]}, "skillId": "amzn1.ask.1p.saysomething"}}]}}', 'status': 'ENABLED'} query None
2024-10-24 17:57:06.141 DEBUG (MainThread) [alexapy.alexaapi] s***********o@g*******m:Login error detected; ignoring post request to /api/behaviors/preview with {'behaviorId': 'PREVIEW', 'sequenceJson': '{"@type": "com.amazon.alexa.behaviors.model.Sequence", "startNode": {"@type": "com.amazon.alexa.behaviors.model.SerialNode", "nodesToExecute": [{"@type": "com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode", "type": "Alexa.Speak", "operationPayload": {"deviceType": "A30YDR2MK8HMRV", "deviceSerialNumber": "G09147040156062Q", "locale": "it-it", "customerId": "A1H2UL28U6ONC4", "textToSpeak": "prova da instanza test", "target": {"customerId": "A1H2UL28U6ONC4", "devices": [{"deviceSerialNumber": "G09147040156062Q", "deviceTypeId": "A30YDR2MK8HMRV"}]}, "skillId": "amzn1.ask.1p.saysomething"}}]}}', 'status': 'ENABLED'} None
2024-10-24 17:57:06.142 WARNING (MainThread) [alexapy.helpers] alexaapi.run_behavior((<alexapy.alexaapi.AlexaAPI object at 0xffff57f32270>, {'@type': 'com.amazon.alexa.behaviors.model.OpaquePayloadOperationNode', 'type': 'Alexa.Speak', 'operationPayload': {'deviceType': 'A30YDR2MK8HMRV', 'deviceSerialNumber': 'G************62Q', 'locale': 'it-it', 'customerId': 'A**********NC4', 'textToSpeak': 'prova da instanza test', 'target': {'customerId': 'A**********NC4', 'devices': [{'deviceSerialNumber': 'G************62Q', 'deviceTypeId': 'A30YDR2MK8HMRV'}]}, 'skillId': 'amzn1.ask.1p.saysomething'}}), {'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-10-24 17:57:06.142 WARNING (MainThread) [alexapy.helpers] alexaapi.send_sequence((<alexapy.alexaapi.AlexaAPI object at 0xffff57f32270>, 'Alexa.Speak'), {'customer_id': 'A1H2UL28U6ONC4', 'textToSpeak': 'prova da instanza test', 'target': {'customerId': 'A**********NC4', 'devices': [{'deviceSerialNumber': 'G************62Q', 'deviceTypeId': 'A30YDR2MK8HMRV'}]}, 'skillId': 'amzn1.ask.1p.saysomething', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-10-24 17:57:06.142 WARNING (MainThread) [alexapy.helpers] alexaapi.send_tts((<alexapy.alexaapi.AlexaAPI object at 0xffff57f32270>, 'prova da instanza test'), {'customer_id': 'A1H2UL28U6ONC4', 'queue_delay': 1.5}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Login error detected; not contacting API',)
2024-10-24 17:57:06.144 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved (None):   File "/usr/local/lib/python3.12/runpy.py", line 198, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/local/lib/python3.12/runpy.py", line 88, in _run_code
    exec(code, run_globals)
  File "/home/vscode/.vscode-server/extensions/ms-python.debugpy-2024.12.0-linux-arm64/bundled/libs/debugpy/adapter/../../debugpy/launcher/../../debugpy/__main__.py", line 71, in <module>
    cli.main()
  File "/home/vscode/.vscode-server/extensions/ms-python.debugpy-2024.12.0-linux-arm64/bundled/libs/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py", line 501, in main
    run()
  File "/home/vscode/.vscode-server/extensions/ms-python.debugpy-2024.12.0-linux-arm64/bundled/libs/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py", line 384, in run_module
    run_module_as_main(options.target, alter_argv=True)
  File "/home/vscode/.vscode-server/extensions/ms-python.debugpy-2024.12.0-linux-arm64/bundled/libs/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 228, in _run_module_as_main
    return _run_code(code, main_globals, None, "__main__", mod_spec)
  File "/home/vscode/.vscode-server/extensions/ms-python.debugpy-2024.12.0-linux-arm64/bundled/libs/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 118, in _run_code
    exec(code, run_globals)
  File "/workspaces/core/homeassistant/__main__.py", line 223, in <module>
    sys.exit(main())
  File "/workspaces/core/homeassistant/__main__.py", line 209, in main
    exit_code = runner.run(runtime_conf)
  File "/workspaces/core/homeassistant/runner.py", line 189, in run
    return loop.run_until_complete(setup_and_run_hass(runtime_config))
  File "/usr/local/lib/python3.12/asyncio/base_events.py", line 674, in run_until_complete
    self.run_forever()
  File "/usr/local/lib/python3.12/asyncio/base_events.py", line 641, in run_forever
    self._run_once()
  File "/usr/local/lib/python3.12/asyncio/base_events.py", line 1978, in _run_once
    handle._run()
  File "/usr/local/lib/python3.12/asyncio/events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "/workspaces/core/config/custom_components/alexa_media/helpers.py", line 158, in _catch_login_errors
    result = await func(*args, **kwargs)
  File "/workspaces/core/config/custom_components/alexa_media/media_player.py", line 1322, in async_send_tts
    self.hass.async_create_task(
  File "/workspaces/core/homeassistant/core.py", line 810, in async_create_task
    return self.async_create_task_internal(target, name, eager_start)
  File "/workspaces/core/homeassistant/core.py", line 832, in async_create_task_internal
    task = create_eager_task(target, name=name, loop=self.loop)
  File "/workspaces/core/homeassistant/util/async_.py", line 45, in create_eager_task
    return Task(coro, loop=loop, name=name, eager_start=True)
Traceback (most recent call last):
  File "/home/vscode/.local/ha-venv/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.local/ha-venv/lib/python3.12/site-packages/alexapy/alexaapi.py", line 889, in send_tts
    await self.send_sequence(
  File "/home/vscode/.local/ha-venv/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.local/ha-venv/lib/python3.12/site-packages/alexapy/alexaapi.py", line 512, in send_sequence
    await self.run_behavior(node_data, queue_delay=queue_delay)
  File "/home/vscode/.local/ha-venv/lib/python3.12/site-packages/alexapy/helpers.py", line 137, in wrapper
    return await func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.local/ha-venv/lib/python3.12/site-packages/alexapy/alexaapi.py", line 434, in run_behavior
    await self._post_request("/api/behaviors/preview", data=data)
  File "/home/vscode/.local/ha-venv/lib/python3.12/site-packages/alexapy/alexaapi.py", line 226, in _post_request
    return await self._request("post", uri, data, query)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.local/ha-venv/lib/python3.12/site-packages/backoff/_async.py", line 151, in retry
    ret = await target(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.local/ha-venv/lib/python3.12/site-packages/alexapy/alexaapi.py", line 199, in _request
    raise AlexapyLoginError("Login error detected; not contacting API")
alexapy.errors.AlexapyLoginError: Login error detected; not contacting API

the interesting one is the Successfully refreshed access_token logged from alexalogin.refresh_access_token
followed by Exchanged refresh token logged from alexalogin.exchange_token_for_cookies

at this point all necessary bits for making a request are there, only that for some reason alexalogin.finalize_login which would set the self.status["login_successful"] = True was not called along the way...

another log indicates that its not passing trough the test_loggedin as I was thinking,
Detected access token expiration; refreshing is coming from these places
these requests individually call the functions to refresh the login, but none of them includes the part of calling finalize_login

@srescio
Copy link
Contributor

srescio commented Oct 24, 2024

given that the next thing being done is to call save_cookiefile and that function is called also by finalize_login...maybe swapping them will work,

made this fix branch for alexapy: https://gitlab.com/srescio/alexapy/-/commits/fix-login_successful-not-being-set-true-after-session-refresh
and imported it in this bump branch for AMP: #2647

check it out, and hope it works 🤞🏻
just installed on my test instance, will see what happens tomorrow....

@danielbrunt57
Copy link
Collaborator

danielbrunt57 commented Oct 24, 2024

This is just a stab in the dark and I've not tested the code change but what about setting "login_seccessful" here?

    async def _request(
        self,
        method: str,
        uri: str,
        data: Optional[dict[str, str]] = None,
        query: Optional[dict[str, str]] = None,
    ) -> ClientResponse:
        async with self._login._oauth_lock:
            if self._login.expires_in and (self._login.expires_in - time.time() < 0):
                _LOGGER.debug(
                    "%s: Detected access token expiration; refreshing",
                    hide_email(self._login.email),
                )
                if (
                    # await self._login.get_tokens()
                    # and
                    await self._login.refresh_access_token()
                    and await self._login.exchange_token_for_cookies()
                    and await self._login.get_csrf()
                ):
                    await self._login.save_cookiefile()
                    login.status = "login_successful"                             # <-- Will this work?
                else:
                    _LOGGER.debug(
                        "%s: Unable to refresh oauth",
                        hide_email(self._login.email),
                    )
                    self._login.access_token = None
                    self._login.refresh_token = None
                    self._login.expires_in = None
        if method == "get":
            if query and not query.get("_"):
                query["_"] = math.floor(time.time() * 1000)
            elif query is None:
                query = {"_": math.floor(time.time() * 1000)}
        url: URL = URL(self._url + uri).update_query(query)
        _LOGGER.debug(
            "%s: Trying %s: %s : with uri: %s data %s query %s",
            hide_email(self._login.email),
            method,
            url,
            uri,
            data,
            query,
        )
        if self._login.close_requested:
            _LOGGER.debug(
                "%s: Login object has been asked to close; ignoring %s request to %s with %s %s",
                hide_email(self._login.email),
                method,
                uri,
                data,
                query,

The above stab-in-the-dark was devised before your most recent post above...

@srescio
Copy link
Contributor

srescio commented Oct 24, 2024

kinda, the syntax is a bit off, login is an object and you need to assign a boolean value to its property named login_successful so it should be done like here, would likely have the same effect, anyway the branch where i swapped the calls is working for now, will confirm tomorrow if it survives the relogin jinx

https://github.com/srescio/alexa_media_player/tree/fix-recurring-Authenication-required-by-Login-error-detected-in-alexapy

@srescio
Copy link
Contributor

srescio commented Oct 24, 2024

following @vhuynen instructions here, if you wanna test this change,

  1. go in your custom_components/alexa_media/manifest.json
  2. replace "alexapy==1.29.3" with "alexapy@git+https://gitlab.com/srescio/alexapy.git@9aeb1ff47f7fd68c8af1324f2f07b58d84f6cbcf"
  3. restart HA
    🤞🏻

@danielbrunt57
Copy link
Collaborator

so self.status["login_successful"] = True

@danielbrunt57
Copy link
Collaborator

danielbrunt57 commented Oct 24, 2024

I've not experienced the Login error detected; not contacting API here in NA but maybe I just reboot too often for my tokens to expire. That &/or maybe my tokens are longer lived than in EU...

I've made the two replacements in my alexaapi.py as I have other modified code in there I don't want to lose (again)!
Namely my relaxed @backoff strategy...

    def _min_expo_wait(min_wait: float):
        """Exponential backoff with a minimum wait time."""

        def f(*args, **kwargs):
            gen = backoff.expo(*args, **kwargs)
            v  = next(gen) # waste first one always returning None in backoff.expo
            #_LOGGER.debug(f"initial {v}")
            while True:
                v = max(min_wait, next(gen))
                #_LOGGER.debug(f"max {v}")
                yield v

        return f
    @backoff.on_exception(
        # backoff.expo,
        _min_expo_wait(2.0),
        (AlexapyTooManyRequestsError, AlexapyConnectionError, ClientConnectionError),
        max_time=120,
        max_tries=10,
        jitter=None,
        #factor=5,
        logger=__name__,
    )
    async def _request(
    @staticmethod
    @backoff.on_exception(
        # backoff.expo,
        _min_expo_wait(2.0),
        (AlexapyTooManyRequestsError, AlexapyCancelledError, AlexapyConnectionError, ClientConnectionError),
        max_time=120,
        max_tries=10,
        jitter=None,
        # factor=2,
        logger=__name__,
    )
    async def _static_request(

@srescio
Copy link
Contributor

srescio commented Oct 24, 2024

nha, saw again this after some idle

2024-10-24 23:46:40.313 DEBUG (MainThread) [alexapy.alexaapi] s***********o@g*******m: static GET: https://www.amazon.it/alexa-privacy/apd/rvh/customer-history-records?startTime=1729727200121&endTime=1729900000121&recordType=VOICE_HISTORY&maxRecordSize=10 returned 401:Unauthorized:text/html
2024-10-24 23:46:40.313 WARNING (MainThread) [alexapy.helpers] alexaapi.get_customer_history_records((<alexapy.alexalogin.AlexaLogin object at 0xffff70cdc470>,), {'max_record_size': 10}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Unauthorized',)
2024-10-24 23:46:40.314 WARNING (MainThread) [alexapy.helpers] alexaapi.get_last_device_serial((<alexapy.alexalogin.AlexaLogin object at 0xffff70cdc470>,), {}): An error occurred accessing AlexaAPI: An exception of type AlexapyLoginError occurred. Arguments:
('Unauthorized',)

I think they're two different issues, the flag should fix a speak attempt after session has expired, but why this call ends in 401 for https://www.amazon.it/alexa-privacy/apd/rvh/customer-history-records` needs to be investigated...

@danielbrunt57
Copy link
Collaborator

I see it ending in 429, not 401.

Interesting note: Alexa-Remote (Node.JS) was updated some time ago to use customer-history-records-v2...

24 Oct 16:57:46 - [debug] [alexa-remote-account:14f19d12849e6414] Alexa-Remote: Sending Request with {"host":"www.amazon.ca","path":"/alexa-privacy/apd/rvh/customer-history-records-v2?startTime=1729814202493&endTime=1729900666493","method":"POST","timeout":10000,"headers":{"Accept-Language":"en-CA","anti-csrftoken-a2z":"hDxVCUvv39jRFzai4cPVT2IeHca2u8BMkwThMsktJcdsAAAAAGca2GYAAAAB","referer":"https://www.amazon.ca/alexa-privacy/apd/activity?disableGlobalNav=true&ref=activityHistory"}} and data={"previousRequestToken": null}

@danielbrunt57
Copy link
Collaborator

It's also using a somewhat different header for the client connection that I've retrofitted into alexapy with no ill effects..

Constants.

For more details about this api, please refer to the documentation at
https://gitlab.com/keatontaylor/alexapy
"""

EXCEPTION_TEMPLATE = "An exception of type {0} occurred. Arguments:\n{1!r}"

#CALL_VERSION = "2.2.556530.0"
CALL_VERSION = "2.2.595606.0"
APP_NAME = "Alexa Media Player"
#USER_AGENT = f"AmazonWebView/Amazon Alexa/{CALL_VERSION}/iOS/16.6/iPhone"
#USER_AGENT = f"AppleWebKit PitanguiBridge/{CALL_VERSION}/iOS/17.4.1/iPhone"
USER_AGENT = f"AppleWebKit PitanguiBridge/{CALL_VERSION}-[HARDWARE=iPhone14_7][SOFTWARE=17.4.1][DEVICE=iPhone]"

@spaggio80
Copy link

Hurrah !!!
Finally from version 4.13.5 it seems to work without warnings (with polling disabled, I haven't tried to re-enable it).

@PaulBiod
Copy link

Hurrah !!! Finally from version 4.13.5 it seems to work without warnings (with polling disabled, I haven't tried to re-enable it).

@spaggio80
how do you disable polling ?

@spaggio80
Copy link

Hurrah !!! Finally from version 4.13.5 it seems to work without warnings (with polling disabled, I haven't tried to re-enable it).

@spaggio80 how do you disable polling ?

Settings > Devices & Services > Alexa Media Player > 3 Dots > System Options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests