Skip to content

Commit 2525f1a

Browse files
author
codingcyclist
committed
Merge branch 'dev'
2 parents d0b17f9 + e689a57 commit 2525f1a

File tree

3 files changed

+108
-101
lines changed

3 files changed

+108
-101
lines changed

custom_components/ha_strava/__init__.py

Lines changed: 102 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -80,13 +80,13 @@ class StravaWebhookView(HomeAssistantView):
8080

8181
def __init__(
8282
self,
83-
websession: config_entry_oauth2_flow.OAuth2Session,
83+
oauth_websession: config_entry_oauth2_flow.OAuth2Session,
8484
event_factory: Callable,
8585
host: str,
8686
hass: HomeAssistant,
8787
):
8888
"""Init the view."""
89-
self.websession = websession
89+
self.oauth_websession = oauth_websession
9090
self.event_factory = event_factory
9191
self.webhook_id = None
9292
self.host = host
@@ -101,7 +101,7 @@ async def fetch_strava_data(self):
101101

102102
_LOGGER.debug("Fetching Data from Strava API")
103103

104-
activities_response = await self.websession.async_request(
104+
activities_response = await self.oauth_websession.async_request(
105105
method="GET",
106106
url=f"https://www.strava.com/api/v3/athlete/activities?per_page={MAX_NB_ACTIVITIES}",
107107
)
@@ -110,7 +110,7 @@ async def fetch_strava_data(self):
110110
activities = json.loads(await activities_response.text())
111111
cities = []
112112
for activity in activities:
113-
geo_location_response = await self.websession.async_request(
113+
geo_location_response = await self.oauth_websession.async_request(
114114
method="GET",
115115
url=f'https://geocode.xyz/{activity.get("start_latitude", 0)},{activity.get("start_longitude", 0)}?geoit=json',
116116
)
@@ -218,86 +218,86 @@ async def renew_webhook_subscription(
218218

219219
config_data[CONF_CALLBACK_URL] = f"{ha_host}/api/strava/webhook"
220220

221-
async with ClientSession() as websession:
222-
callback_response = await websession.get(url=config_data[CONF_CALLBACK_URL])
221+
websession = async_get_clientsession(hass, verify_ssl=False)
222+
callback_response = await websession.get(url=config_data[CONF_CALLBACK_URL])
223223

224-
if callback_response.status != 200:
225-
_LOGGER.error(
226-
f"HA Callback URL for Strava Webhook not available: {await callback_response.text()}"
227-
)
228-
return
229-
230-
existing_webhook_subscriptions_response = await websession.get(
231-
url=WEBHOOK_SUBSCRIPTION_URL,
232-
params={
233-
"client_id": entry.data[CONF_CLIENT_ID],
234-
"client_secret": entry.data[CONF_CLIENT_SECRET],
235-
},
236-
)
237-
238-
existing_webhook_subscriptions = json.loads(
239-
await existing_webhook_subscriptions_response.text()
224+
if callback_response.status != 200:
225+
_LOGGER.error(
226+
f"HA Callback URL for Strava Webhook not available: {await callback_response.text()}"
240227
)
228+
return
241229

242-
if len(existing_webhook_subscriptions) == 1:
243-
244-
config_data[CONF_WEBHOOK_ID] = existing_webhook_subscriptions[0]["id"]
230+
existing_webhook_subscriptions_response = await websession.get(
231+
url=WEBHOOK_SUBSCRIPTION_URL,
232+
params={
233+
"client_id": entry.data[CONF_CLIENT_ID],
234+
"client_secret": entry.data[CONF_CLIENT_SECRET],
235+
},
236+
)
245237

246-
if (
247-
config_data[CONF_CALLBACK_URL]
248-
!= existing_webhook_subscriptions[0][CONF_CALLBACK_URL]
249-
):
250-
_LOGGER.debug(
251-
f"Deleting outdated Strava Webhook Subscription for {existing_webhook_subscriptions[0][CONF_CALLBACK_URL]}"
252-
)
238+
existing_webhook_subscriptions = json.loads(
239+
await existing_webhook_subscriptions_response.text()
240+
)
253241

254-
delete_response = await websession.delete(
255-
url=WEBHOOK_SUBSCRIPTION_URL + f"/{config_data[CONF_WEBHOOK_ID]}",
256-
data={
257-
"client_id": config_data[CONF_CLIENT_ID],
258-
"client_secret": config_data[CONF_CLIENT_SECRET],
259-
},
260-
)
242+
if len(existing_webhook_subscriptions) == 1:
261243

262-
if delete_response.status == 204:
263-
_LOGGER.debug(
264-
"Successfully deleted outdated Strava Webhook Subscription"
265-
)
266-
existing_webhook_subscriptions = []
267-
else:
268-
_LOGGER.error(
269-
f"Unexpected response (status code: {delete_response.status}) while deleting Strava Webhook Subscription: {await delete_response.text()}"
270-
)
271-
return
244+
config_data[CONF_WEBHOOK_ID] = existing_webhook_subscriptions[0]["id"]
272245

273-
elif len(existing_webhook_subscriptions) == 0:
246+
if (
247+
config_data[CONF_CALLBACK_URL]
248+
!= existing_webhook_subscriptions[0][CONF_CALLBACK_URL]
249+
):
274250
_LOGGER.debug(
275-
f"Creating a new Strava Webhook subscription for {config_data[CONF_CALLBACK_URL]}"
251+
f"Deleting outdated Strava Webhook Subscription for {existing_webhook_subscriptions[0][CONF_CALLBACK_URL]}"
276252
)
277-
post_response = await websession.post(
278-
url=WEBHOOK_SUBSCRIPTION_URL,
253+
254+
delete_response = await websession.delete(
255+
url=WEBHOOK_SUBSCRIPTION_URL + f"/{config_data[CONF_WEBHOOK_ID]}",
279256
data={
280-
CONF_CLIENT_ID: config_data[CONF_CLIENT_ID],
281-
CONF_CLIENT_SECRET: config_data[CONF_CLIENT_SECRET],
282-
CONF_CALLBACK_URL: config_data[CONF_CALLBACK_URL],
283-
"verify_token": "HA_STRAVA",
257+
"client_id": config_data[CONF_CLIENT_ID],
258+
"client_secret": config_data[CONF_CLIENT_SECRET],
284259
},
285260
)
286-
if post_response.status == 201:
287-
post_response_content = json.loads(await post_response.text())
288-
config_data[CONF_WEBHOOK_ID] = post_response_content["id"]
261+
262+
if delete_response.status == 204:
263+
_LOGGER.debug(
264+
"Successfully deleted outdated Strava Webhook Subscription"
265+
)
266+
existing_webhook_subscriptions = []
289267
else:
290268
_LOGGER.error(
291-
f"Unexpected response (status code: {post_response.status}) while creating Strava Webhook Subscription: {await post_response.text()}"
269+
f"Unexpected response (status code: {delete_response.status}) while deleting Strava Webhook Subscription: {await delete_response.text()}"
292270
)
293271
return
294272

273+
elif len(existing_webhook_subscriptions) == 0:
274+
_LOGGER.debug(
275+
f"Creating a new Strava Webhook subscription for {config_data[CONF_CALLBACK_URL]}"
276+
)
277+
post_response = await websession.post(
278+
url=WEBHOOK_SUBSCRIPTION_URL,
279+
data={
280+
CONF_CLIENT_ID: config_data[CONF_CLIENT_ID],
281+
CONF_CLIENT_SECRET: config_data[CONF_CLIENT_SECRET],
282+
CONF_CALLBACK_URL: config_data[CONF_CALLBACK_URL],
283+
"verify_token": "HA_STRAVA",
284+
},
285+
)
286+
if post_response.status == 201:
287+
post_response_content = json.loads(await post_response.text())
288+
config_data[CONF_WEBHOOK_ID] = post_response_content["id"]
295289
else:
296290
_LOGGER.error(
297-
f"Expected 1 existing Strava Webhook subscription for {config_data[CONF_CALLBACK_URL]}: Found {len(existing_webhook_subscriptions)}"
291+
f"Unexpected response (status code: {post_response.status}) while creating Strava Webhook Subscription: {await post_response.text()}"
298292
)
299293
return
300294

295+
else:
296+
_LOGGER.error(
297+
f"Expected 1 existing Strava Webhook subscription for {config_data[CONF_CALLBACK_URL]}: Found {len(existing_webhook_subscriptions)}"
298+
)
299+
return
300+
301301
hass.config_entries.async_update_entry(entry=entry, data=config_data)
302302

303303
return True
@@ -341,16 +341,18 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
341341

342342
OAuth2FlowHandler.async_register_implementation(hass, implementation)
343343

344-
session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
344+
oauth_websession = config_entry_oauth2_flow.OAuth2Session(
345+
hass, entry, implementation
346+
)
345347

346-
await session.async_ensure_token_valid()
348+
await oauth_websession.async_ensure_token_valid()
347349

348350
# webhook view to get notifications for strava activity updates
349351
def strava_update_event_factory(data):
350352
hass.bus.fire(CONF_STRAVA_DATA_UPDATE_EVENT, data)
351353

352354
strava_webhook_view = StravaWebhookView(
353-
websession=session,
355+
oauth_websession=oauth_websession,
354356
event_factory=strava_update_event_factory,
355357
host=get_url(hass, allow_internal=False, allow_ip=False),
356358
hass=hass,
@@ -402,15 +404,15 @@ def core_config_update_handler(event):
402404
# register event listeners
403405
hass.data[DOMAIN]["remove_update_listener"] = []
404406

405-
if hass.bus.async_listeners().get(EVENT_HOMEASSISTANT_START, 0) < 1:
406-
hass.data[DOMAIN]["remove_update_listener"].append(
407-
hass.bus.async_listen(EVENT_HOMEASSISTANT_START, ha_start_handler)
408-
)
407+
# if hass.bus.async_listeners().get(EVENT_HOMEASSISTANT_START, 0) < 1:
408+
hass.data[DOMAIN]["remove_update_listener"].append(
409+
hass.bus.async_listen(EVENT_HOMEASSISTANT_START, ha_start_handler)
410+
)
409411

410-
if hass.bus.async_listeners().get(EVENT_CORE_CONFIG_UPDATE, 0) < 1:
411-
hass.data[DOMAIN]["remove_update_listener"].append(
412-
hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, core_config_update_handler)
413-
)
412+
# if hass.bus.async_listeners().get(EVENT_CORE_CONFIG_UPDATE, 0) < 1:
413+
hass.data[DOMAIN]["remove_update_listener"].append(
414+
hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, core_config_update_handler)
415+
)
414416

415417
if hass.bus.async_listeners().get(CONF_STRAVA_RELOAD_EVENT, 0) < 1:
416418
hass.data[DOMAIN]["remove_update_listener"].append(
@@ -447,43 +449,43 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
447449
remove_listener()
448450

449451
# delete strava webhook subscription
450-
async with ClientSession() as websession:
451-
existing_webhook_subscriptions_response = await websession.get(
452-
url=WEBHOOK_SUBSCRIPTION_URL,
453-
params={
452+
websession = async_get_clientsession(hass, verify_ssl=False)
453+
existing_webhook_subscriptions_response = await websession.get(
454+
url=WEBHOOK_SUBSCRIPTION_URL,
455+
params={
456+
"client_id": entry.data[CONF_CLIENT_ID],
457+
"client_secret": entry.data[CONF_CLIENT_SECRET],
458+
},
459+
)
460+
461+
existing_webhook_subscriptions = json.loads(
462+
await existing_webhook_subscriptions_response.text()
463+
)
464+
465+
if len(existing_webhook_subscriptions) == 1:
466+
delete_response = await websession.delete(
467+
url=WEBHOOK_SUBSCRIPTION_URL
468+
+ f"/{existing_webhook_subscriptions[0]['id']}",
469+
data={
454470
"client_id": entry.data[CONF_CLIENT_ID],
455471
"client_secret": entry.data[CONF_CLIENT_SECRET],
456472
},
457473
)
458474

459-
existing_webhook_subscriptions = json.loads(
460-
await existing_webhook_subscriptions_response.text()
461-
)
462-
463-
if len(existing_webhook_subscriptions) == 1:
464-
delete_response = await websession.delete(
465-
url=WEBHOOK_SUBSCRIPTION_URL
466-
+ f"/{existing_webhook_subscriptions[0]['id']}",
467-
data={
468-
"client_id": entry.data[CONF_CLIENT_ID],
469-
"client_secret": entry.data[CONF_CLIENT_SECRET],
470-
},
475+
if delete_response.status == 204:
476+
_LOGGER.debug(
477+
f"Successfully deleted strava webhook subscription for {entry.data[CONF_CALLBACK_URL]}"
471478
)
472-
473-
if delete_response.status == 204:
474-
_LOGGER.debug(
475-
f"Successfully deleted strava webhook subscription for {entry.data[CONF_CALLBACK_URL]}"
476-
)
477-
else:
478-
_LOGGER.error(
479-
f"Strava webhook for {entry.data[CONF_CALLBACK_URL]} could not be deleted: {await delete_response.text()}"
480-
)
481-
return False
482479
else:
483480
_LOGGER.error(
484-
f"Expected 1 webhook subscription for {entry.data[CONF_CALLBACK_URL]}; found: {len(existing_webhook_subscriptions)}"
481+
f"Strava webhook for {entry.data[CONF_CALLBACK_URL]} could not be deleted: {await delete_response.text()}"
485482
)
486483
return False
484+
else:
485+
_LOGGER.error(
486+
f"Expected 1 webhook subscription for {entry.data[CONF_CALLBACK_URL]}; found: {len(existing_webhook_subscriptions)}"
487+
)
488+
return False
487489

488490
unload_ok = all(
489491
await asyncio.gather(

custom_components/ha_strava/config_flow.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,11 @@ async def show_form_init(self):
8080
"""
8181
Show form to customize the number of Strava activities to track in HASS
8282
"""
83+
ha_strava_config_entries = self.hass.config_entries.async_entries(domain=DOMAIN)
84+
85+
if len(ha_strava_config_entries) != 1:
86+
return self.async_abort(reason="no_config")
87+
8388
return self.async_show_form(
8489
step_id="init",
8590
data_schema=vol.Schema(

custom_components/ha_strava/const.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
CONF_CALLBACK_URL = "callback_url"
1313
WEBHOOK_SUBSCRIPTION_URL = "https://www.strava.com/api/v3/push_subscriptions"
1414
CONF_NB_ACTIVITIES = "nb_activities"
15-
DEFAULT_NB_ACTIVITIES = 1
15+
DEFAULT_NB_ACTIVITIES = 2
1616
MAX_NB_ACTIVITIES = 10
1717

1818
# Event Specs

0 commit comments

Comments
 (0)