Skip to content

Commit

Permalink
Update sensori e fix generali
Browse files Browse the repository at this point in the history
  • Loading branch information
Bobsilvio committed Oct 4, 2024
1 parent da930da commit 009c781
Show file tree
Hide file tree
Showing 7 changed files with 104 additions and 73 deletions.
99 changes: 68 additions & 31 deletions custom_components/calcio_live/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import logging
import requests
import aiohttp
from .const import DOMAIN, COMPETITIONS
from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -49,45 +49,80 @@ async def async_step_user(self, user_input=None):


async def async_step_campionato(self, user_input=None):
"""Schermata per selezionare il campionato (senza richiesta API)."""
"""Schermata per selezionare il campionato (recuperato tramite API, ordinato alfabeticamente e senza ricerca)."""
if user_input is not None:
competition_code = user_input.get("competition_code")
competition_name = await self._get_competition_name(competition_code) # Recupera il nome completo
self._data.update({"competition_code": competition_code})

nome_sensore = COMPETITIONS.get(competition_code, competition_code)

return self.async_create_entry(
title=f"{COMPETITIONS[competition_code]}",
title=f"{competition_name}",
data={
**self._data,
"competition_code": competition_code,
"team_id": None,
"name": nome_sensore,
"name": competition_name, # Salva il nome invece del codice
},
)

# Recupera e ordina le competizioni
competitions = await self._get_competitions()

# Ordinamento alfabetico per nome della competizione
sorted_competitions = {k: v for k, v in sorted(competitions.items(), key=lambda item: item[1])}

return self.async_show_form(
step_id="campionato",
data_schema=vol.Schema({
vol.Required("competition_code"): vol.In(COMPETITIONS),
vol.Required("competition_code"): vol.In(sorted_competitions),
}),
errors=self._errors,
)

async def _get_competitions(self):
"""Recupera e organizza le competizioni tramite API."""
url = "https://site.api.espn.com/apis/site/v2/leagues/dropdown?lang=en&region=us&calendartype=whitelist&limit=200&sport=soccer"
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response.raise_for_status()
competitions_data = await response.json()

# Estrai le competizioni e usa il nome per il selettore
competitions = {
league['slug']: league['name']
for league in competitions_data.get("leagues", [])
}
_LOGGER.debug(f"Competizioni caricate: {competitions}")
return competitions
except aiohttp.ClientError as e:
_LOGGER.error(f"Errore nel caricamento delle competizioni: {e}")
return {}

async def _get_competition_name(self, competition_code):
"""Recupera il nome della competizione dato il suo codice."""
competitions = await self._get_competitions()
return competitions.get(competition_code, "Nome Sconosciuto")



async def async_step_select_competition_for_team(self, user_input=None):
"""Schermata per selezionare il campionato per un Team (passo intermedio)."""
if user_input is not None:
competition_code = user_input.get("competition_code")
self._data.update({"competition_code": competition_code})

# Recupera le squadre in modo dinamico
await self._get_teams(competition_code)
return await self.async_step_team()

competitions = await self._get_competitions()
sorted_competitions = {k: v for k, v in sorted(competitions.items(), key=lambda item: item[1])}

return self.async_show_form(
step_id="select_competition_for_team",
data_schema=vol.Schema({
vol.Required("competition_code"): vol.In(COMPETITIONS),
vol.Required("competition_code"): vol.In(sorted_competitions),
}),
errors=self._errors,
)
Expand All @@ -112,7 +147,8 @@ async def async_step_team(self, user_input=None):
},
)

team_options = {team['id']: team['displayName'] for team in self._teams}
# Ordina le squadre in ordine alfabetico
team_options = {team['id']: team['displayName'] for team in sorted(self._teams, key=lambda t: t['displayName'])}
team_options[OPTION_MANUAL_TEAM] = OPTION_MANUAL_TEAM

return self.async_show_form(
Expand All @@ -123,6 +159,29 @@ async def async_step_team(self, user_input=None):
errors=self._errors,
)

async def _get_teams(self, competition_code):
"""Recupera la lista delle squadre dal campionato selezionato tramite API."""
url = f"https://site.api.espn.com/apis/site/v2/sports/soccer/{competition_code}/teams"
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response.raise_for_status()
teams_data = await response.json()

# Estrai le squadre e ordinale alfabeticamente
self._teams = [
{
"id": team['team']['id'],
"displayName": team['team']['displayName']
}
for team in teams_data.get("sports", [])[0].get("leagues", [])[0].get("teams", [])
]
_LOGGER.debug(f"Squadre caricate per {competition_code}: {self._teams}")
except aiohttp.ClientError as e:
_LOGGER.error(f"Errore nel caricamento delle squadre per {competition_code}: {e}")
self._teams = []


async def async_step_manual_team(self, user_input=None):
"""Schermata per inserire manualmente l'ID del team."""
if user_input is not None:
Expand All @@ -147,25 +206,3 @@ async def async_step_manual_team(self, user_input=None):
}),
errors=self._errors,
)

async def _get_teams(self, competition_code):
"""Recupera la lista delle squadre dal campionato selezionato tramite API."""
url = f"https://site.api.espn.com/apis/site/v2/sports/soccer/{competition_code}/teams"
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response.raise_for_status()
teams_data = await response.json()

# Estrai le squadre
self._teams = [
{
"id": team['team']['id'],
"displayName": team['team']['displayName']
}
for team in teams_data.get("sports", [])[0].get("leagues", [])[0].get("teams", [])
]
_LOGGER.debug(f"Squadre caricate per {competition_code}: {self._teams}")
except aiohttp.ClientError as e:
_LOGGER.error(f"Errore nel caricamento delle squadre per {competition_code}: {e}")
self._teams = []
28 changes: 0 additions & 28 deletions custom_components/calcio_live/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,3 @@

DOMAIN = "calcio_live"
CONF_COMPETITION_CODE = "competition_code"

COMPETITIONS = {
'ita.1': 'Serie A',
'ger.1': 'Bundesliga',
'esp.1': 'La Liga',
'por.1': 'Primeira Liga',
'uefa.europa_qual': 'UEFA Europa League Qualifying',
'uefa.champions_qual': 'UEFA Champions League Qualifying',
'fifa.intercontinental.cup': 'FIFA Intercontinental Cup',
'mex.2': 'Liga de Expansión MX',
'arg.5': 'Primera C Metropolitana',
'wal.1': 'Cymru Premier',
'ven.2': 'Segunda División Venezolana',
'arg.4': 'Primera D Metropolitana',
'irl.1': 'League of Ireland Premier Division',
'uru.2': 'Segunda División Uruguaya',
'aut.promotion.relegation': 'Austrian Promotion/Relegation Playoff',
'arg.3': 'Primera B Metropolitana',
'den.promotion.relegation': 'Danish Promotion/Relegation Playoff',
'chi.2': 'Primera B de Chile',
'ned.1': 'Eredivisie',
'nor.1': 'Eliteserien',
'swe.1': 'Allsvenskan',
'sui.1': 'Swiss Super League',
'tur.1': 'Super Lig',
'usa.1': 'Major League Soccer (MLS)',
'arg.copa': 'Copa Argentina',
}
17 changes: 10 additions & 7 deletions custom_components/calcio_live/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,29 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
hass.data[DOMAIN] = {}

if team_id:
team_name = competition_name.replace(" ", "_").lower()
team_name = competition_name.replace(" ", "_").replace(".", "_").lower()
competition_name = competition_code.replace(" ", "_").replace(".", "_").lower()

sensors += [
CalcioLiveSensor(
hass, f"calciolive_{team_name}_next".lower(), competition_code, "team_match", base_scan_interval, team_id=team_id, config_entry_id=entry.entry_id
hass, f"calciolive_{competition_name}_{team_name}_next", competition_code, "team_match", base_scan_interval, team_id=team_id, config_entry_id=entry.entry_id
),
CalcioLiveSensor(
hass, f"calciolive_{team_name}".lower(), competition_code, "team_matches", base_scan_interval, team_id=team_id, config_entry_id=entry.entry_id
hass, f"calciolive_{competition_name}_{team_name}", competition_code, "team_matches", base_scan_interval, team_id=team_id, config_entry_id=entry.entry_id
)
]


# Se c'è il competition_code, creiamo solo i sensori "classifica" e "match_day"
elif competition_code:
competition_name = competition_name.replace(" ", "_").replace(".", "_").lower()

sensors += [
CalcioLiveSensor(
hass, f"calciolive_{competition_name}_classifica".replace(" ", "_").lower(), competition_code, "standings", base_scan_interval + timedelta(seconds=random.randint(0, 30)), config_entry_id=entry.entry_id
hass, f"calciolive_{competition_name}_classifica", competition_code, "standings", base_scan_interval + timedelta(seconds=random.randint(0, 30)), config_entry_id=entry.entry_id
),
CalcioLiveSensor(
hass, f"calciolive_{competition_name}_match_day".replace(" ", "_").lower(), competition_code, "match_day", base_scan_interval + timedelta(seconds=random.randint(0, 30)), config_entry_id=entry.entry_id
hass, f"calciolive_{competition_name}_match_day", competition_code, "match_day", base_scan_interval + timedelta(seconds=random.randint(0, 30)), config_entry_id=entry.entry_id
)
]

Expand Down Expand Up @@ -165,7 +168,7 @@ def _process_data(self, data):
from .sensori.classifica import classifica_data

processed_data = classifica_data(data)
self._state = f"Classifica Serie A"
self._state = f"Classifica"
self._attributes = processed_data

elif self._sensor_type == "match_day":
Expand All @@ -179,7 +182,7 @@ def _process_data(self, data):
from .sensori.team_matches import team_matches_data

match_data = team_matches_data(data)
self._state = f"Prossime {len(match_data['matches'])} partite"
self._state = f"Concluse {len(match_data['matches'])} partite"
self._attributes = {
"team_name": match_data["team_name"],
"team_logo": match_data["team_logo"],
Expand Down
2 changes: 0 additions & 2 deletions custom_components/calcio_live/sensori/classifica.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from .const import _LOGGER

from dateutil import parser
from datetime import datetime, timedelta

def classifica_data(data):
try:
Expand Down
14 changes: 13 additions & 1 deletion custom_components/calcio_live/sensori/match_day.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from .const import _LOGGER
from dateutil import parser

def match_day_data(data):
try:
matches_data = data.get("events", [])
matches = []

for match in matches_data:
match_date = match.get("date", "N/A")
match_date = _parse_date(match.get("date", "N/A"))

competitions = match.get("competitions", [])

if not competitions or len(competitions[0].get("competitors", [])) < 2:
Expand Down Expand Up @@ -113,3 +115,13 @@ def _get_odds(odds_info):
over_under = odd.get("total", {}).get("displayName", "Total") + ": " + odd.get("total", {}).get("over", {}).get("line", "N/A")

return home_odds, away_odds, draw_odds, over_under


def _parse_date(date_str):
"""Funzione per convertire la data da stringa ISO a formato leggibile."""
try:
parsed_date = parser.isoparse(date_str)
return parsed_date.strftime("%d/%m/%Y %H:%M")
except (ValueError, TypeError) as e:
_LOGGER.error(f"Errore nel parsing della data {date_str}: {e}")
return "N/A"
2 changes: 1 addition & 1 deletion custom_components/calcio_live/sensori/team_match.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def _parse_date(date_str):
"""Funzione per convertire la data da stringa ISO a formato leggibile."""
try:
parsed_date = parser.isoparse(date_str)
return parsed_date.strftime("%d-%m-%Y %H:%M")
return parsed_date.strftime("%d/%m/%Y %H:%M")
except (ValueError, TypeError) as e:
_LOGGER.error(f"Errore nel parsing della data {date_str}: {e}")
return "N/A"
15 changes: 12 additions & 3 deletions custom_components/calcio_live/sensori/team_matches.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from .const import _LOGGER
from datetime import datetime
from dateutil import parser

def team_matches_data(data):
try:
team_data = data.get("team", {})
team_name = team_data.get("displayName", "N/A")
team_logo = team_data.get("logos", [{}])[0].get("href", "N/A")
team_logo = team_data.get("logo", [{}])[0].get("href", "N/A")

events = data.get("events", [])
matches = []
Expand All @@ -27,7 +27,7 @@ def team_matches_data(data):
def _extract_match_data(event):
try:
event_name = event.get("name", "N/A")
event_date = event.get("date", "N/A")
event_date = _parse_date(event.get("date", "N/A"))
venue = event.get("competitions", [])[0].get("venue", {}).get("fullName", "N/A")

home_team_data = event.get("competitions", [])[0].get("competitors", [])[0].get("team", {})
Expand Down Expand Up @@ -82,3 +82,12 @@ def _extract_match_data(event):
except Exception as e:
_LOGGER.error(f"Errore nell'estrazione dei dati della partita: {e}")
return {}

def _parse_date(date_str):
"""Funzione per convertire la data da stringa ISO a formato leggibile."""
try:
parsed_date = parser.isoparse(date_str)
return parsed_date.strftime("%d/%m/%Y %H:%M")
except (ValueError, TypeError) as e:
_LOGGER.error(f"Errore nel parsing della data {date_str}: {e}")
return "N/A"

0 comments on commit 009c781

Please sign in to comment.