Skip to content

Commit

Permalink
v0.4.2 Release Candidate (#16)
Browse files Browse the repository at this point in the history
- Override API default date range to always search at least 5 days into future for upcoming games
- Added native support for upcoming World Cup (WC) matches
  • Loading branch information
vasqued2 authored Oct 30, 2022
1 parent e19e1bd commit f2c219a
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 7 deletions.
64 changes: 57 additions & 7 deletions custom_components/teamtracker/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
""" TeamTracker Team Status """
import asyncio
import logging
from datetime import datetime, timedelta
from datetime import date, datetime, timedelta
import arrow
import json
import codecs
Expand Down Expand Up @@ -39,6 +39,7 @@
ISSUE_URL,
LEAGUE_LIST,
PLATFORMS,
SPORT_LIST,
URL_HEAD,
URL_TAIL,
USER_AGENT,
Expand Down Expand Up @@ -190,13 +191,14 @@ async def async_get_state(config, hass) -> dict:
"""Query API for status."""

values = {}
prev_values = {}
headers = {"User-Agent": USER_AGENT, "Accept": "application/ld+json"}
sensor_name = config[CONF_NAME]

data = None
file_override = False
first_date = "9999"
last_date = "0000"
first_date = (date.today() - timedelta(days = 1)).strftime("%Y-%m-%dT%H:%MZ")
last_date = (date.today() + timedelta(days = 5)).strftime("%Y-%m-%dT%H:%MZ")

#
# Get the language based on the locale
Expand All @@ -220,6 +222,11 @@ async def async_get_state(config, hass) -> dict:
sport_path = config[CONF_SPORT_PATH]
league_path = config[CONF_LEAGUE_PATH]
url_parms = "?lang=" + lang[:2]

d1 = (date.today() - timedelta(days = 1)).strftime("%Y%m%d")
d2 = (date.today() + timedelta(days = 5)).strftime("%Y%m%d")
url_parms = url_parms + "&dates=" + d1 + "-" + d2

if CONF_CONFERENCE_ID in config.keys():
if (len(config[CONF_CONFERENCE_ID]) > 0):
url_parms = url_parms + "&groups=" + config[CONF_CONFERENCE_ID]
Expand All @@ -240,11 +247,36 @@ async def async_get_state(config, hass) -> dict:
if r.status == 200:
data = await r.json()

num_events = 0
if data is not None:
try:
num_events = len(data["events"])
except:
num_events = 0

if num_events == 0:
url_parms = "?lang=" + lang[:2]
if CONF_CONFERENCE_ID in config.keys():
if (len(config[CONF_CONFERENCE_ID]) > 0):
url_parms = url_parms + "&groups=" + config[CONF_CONFERENCE_ID]
if (config[CONF_CONFERENCE_ID] == '9999'):
file_override = True
url = URL_HEAD + sport_path + "/" + league_path + URL_TAIL + url_parms

async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as r:
_LOGGER.debug("%s: Getting state without date constraint for '%s' from %s", sensor_name, team_id, url)
if r.status == 200:
data = await r.json()

team_id = config[CONF_TEAM_ID].upper()

values = await async_clear_states(config)
values["sport"] = sport_path
values["league"] = league_id
values["league_logo"] = DEFAULT_LOGO
values["team_abbr"] = team_id
values["state"] = "NOT_FOUND"

found_team = False
if data is not None:
Expand Down Expand Up @@ -281,8 +313,10 @@ async def async_get_state(config, hass) -> dict:

if sn.startswith(team_id + ' ') or sn.endswith(' ' + team_id) or t0 == team_id or t1 == team_id:
found_team = True
prev_values = values.copy()

_LOGGER.debug("%s: Found event for %s; parsing data.", sensor_name, team_id)

if t0 == team_id:
team_index = 0
elif t1 == team_id:
Expand Down Expand Up @@ -315,11 +349,27 @@ async def async_get_state(config, hass) -> dict:
elif sport_path in ["hockey"]:
values.update(await async_get_in_hockey_event_attributes(event, values, team_index, oppo_index))

if 'IN' in values["state"]:
if values["state"] == "IN":
break
if 'PRE' in values["state"] and "minute" in values["kickoff_in"]:

if ((values["state"] == "PRE") and (abs((arrow.get(values["date"])-arrow.now()).total_seconds()) < 1200)):
break

if prev_values["state"] == "POST":
if values["state"] == "PRE": # Use POST if PRE is more than 18 hours in future
if (abs((arrow.get(values["date"])-arrow.now()).total_seconds()) > 64800):
values = prev_values
elif values["state"] == "POST": # use POST w/ latest date
if (arrow.get(prev_values["date"]) > arrow.get(values["date"])):
values = prev_values
if prev_values["state"] == "PRE":
if values["state"] == "PRE": # use PRE w/ earliest date
if (arrow.get(prev_values["date"]) < arrow.get(values["date"])):
values = prev_values
elif values["state"] == "POST": # Use PRE if less than 18 hours in future
if (abs((arrow.get(prev_values["date"])-arrow.now()).total_seconds()) < 64800):
values = prev_values

# Never found the team. Either a bye or a post-season condition
if not found_team:
_LOGGER.debug("%s: Did not find a game for team '%s'. Checking if it's a bye week.", sensor_name, team_id)
Expand Down Expand Up @@ -354,7 +404,7 @@ async def async_get_state(config, hass) -> dict:
_LOGGER.debug("%s: Event is over, setting refresh back to 10 minutes.", sensor_name)
values["private_fast_refresh"] = False
else:
values["api_message"] = "PI error, no data returned"
values["api_message"] = "API error, no data returned"
_LOGGER.warn("%s: API did not return any data for team '%s': %s", sensor_name, team_id, url)
values["state"] = 'NOT_FOUND'
values["last_update"] = arrow.now().format(arrow.FORMAT_W3C)
Expand Down
1 change: 1 addition & 0 deletions custom_components/teamtracker/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
["MLS", "soccer", "usa.1"],
["NWSL", "soccer", "usa.nwsl"],
["SERA", "soccer", "ita.1"],
["WC", "soccer", "fifa.world"],
["NCAAVB", "volleyball", "mens-college-volleyball"],
["NCAAVBW", "volleyball", "womens-college-volleyball"],
]
Expand Down

0 comments on commit f2c219a

Please sign in to comment.