Timestamp updater adjusted.

Signed-off-by: Cliff Hill <xlorep@darkhelm.org>
This commit is contained in:
2024-04-24 15:25:03 -04:00
parent da7fc7460b
commit 5f362ad6b4
3 changed files with 64 additions and 71 deletions

View File

@@ -27,3 +27,27 @@ class Sublist(StrEnum):
yield self.LEAST_RECENTLY_ADDED
yield self.LEAST_RECENTLY_PLAYED
yield self.LEAST_OFTEN_PLAYED
class TimedEvent(StrEnum):
"""Enumerates the start/end for timed processes like updater.
Attributes:
START: Represents the start of the event.
END: Represents the end of the event.
"""
START = auto()
END = auto()
class Event(StrEnum):
"""Enumerates the major backend events that are run.
Attributes:
UPDATER: Represents the track updater process.
GENERATOR: Represents the playlist generator process.
"""
UPDATER: auto()
GENERATOR: auto()

View File

@@ -106,14 +106,15 @@ async def cleanup_unused_genres(session: AsyncSession) -> None:
await session.rollback()
async def update_statistics_timestamps(
session: AsyncSession, operation: str
async def set_timestamp(
session: AsyncSession, event: enums.Event, operation: enums.TimedEvent
) -> datetime:
"""Update the start or end timestamps in the statistics model based on the specified operation.
"""Mark the start or end timestamps in the statistics model.
Args:
session (AsyncSession): The database session.
operation (str): A string to specify whether to update 'start' or 'end' timestamp.
event (enums.Event): Identifies what event is being affected.
operation (enums.EventTime): Identifies if it is the start or end of the event.
Returns:
datetime: The datetime of the last update.
@@ -123,79 +124,42 @@ async def update_statistics_timestamps(
stats = await session.get(models.Statistics, 1)
stats_obj = stats.scalars().first()
if operation == "start":
stats_obj.start_update = datetime.now()
log_message = "Statistics start timestamp updated."
elif operation == "end":
stats_obj.end_update = datetime.now()
log_message = "Statistics end timestamp updated."
else:
raise ValueError(
"Invalid operation specified for statistics timestamp update."
)
match [event, operation]:
case [enums.Event.UPDATER, enums.EventTime.START]:
stats_obj.start_update = datetime.now()
log_message = "Updater start timestamp updated."
case [enums.Event.UPDATER, enums.EventTime.END]:
stats_obj.end_update = datetime.now()
log_message = "Updater end timestamp updated."
case [enums.Event.GENERATOR, enums.EventTime.START]:
stats_obj.start_playlist_gen = datetime.now()
log_message = "Generator start timestamp updated."
case [enums.Event.GENERATOR, enums.EventTime.END]:
stats_obj.end_playlist_gen = datetime.now()
log_message = "Generator end timestamp updated."
case _:
raise ValueError(
f"Invalid event {event} or operation {operation} specified."
)
match event:
case enums.Event.UPDATER:
last_updated = stats_obj.end_update
case enums.Event.GENERATOR:
last_updated = stats_obj.end_playlist_gen
case _:
raise ValueError(f"Invalid event {event} specified.")
await session.commit()
await logger.info(log_message)
return stats_obj.end_update
return last_updated
except SQLAlchemyError as e:
await logger.error(f"Database error during statistics timestamp update: {e}")
await logger.error(f"Database error during updater timestamp update: {e}")
await session.rollback()
except Exception as e:
await logger.error(f"Unexpected error during statistics timestamp update: {e}")
await session.rollback()
async def add_new_holiday(
session: AsyncSession, name: str, start_date: datetime, end_date: datetime
) -> None:
"""Insert a new holiday into the database.
Handles exceptions specifically related to the database.
"""
try:
new_holiday = models.Holiday(
name=name, start_date=start_date, end_date=end_date
)
session.add(new_holiday)
await session.commit()
except SQLAlchemyError as e:
await logger.error(f"SQLAlchemyError when adding a new holiday: {e}")
await session.rollback()
except Exception as e:
await logger.error(f"Unexpected error when adding a new holiday: {e}")
await session.rollback()
async def update_holiday(
session: AsyncSession,
holiday_id: int,
name: str = None,
start_date: datetime = None,
end_date: datetime = None,
) -> None:
"""Update a holiday's details in the database.
Handles SQL-specific errors and other exceptions separately.
"""
try:
holiday = await session.get(models.Holiday, holiday_id)
if holiday:
if name:
holiday.name = name
if start_date:
holiday.start_date = start_date
if end_date:
holiday.end_date = end_date
await session.commit()
else:
await logger.warning(f"No holiday found with ID: {holiday_id}")
except SQLAlchemyError as e:
await logger.error(f"SQLAlchemyError during updating holiday: {e}")
await session.rollback()
except Exception as e:
await logger.error(f"Unexpected error during updating holiday: {e}")
await logger.error(f"Unexpected error during updater timestamp update: {e}")
await session.rollback()

View File

@@ -1,5 +1,6 @@
"""Handles updating the tracks stored in the database from plex."""
import enums
import env
import numpy as np
import plex
@@ -23,7 +24,9 @@ async def process_tracks(server_url: str, token: str) -> None:
durations: list[float] = []
try:
with sql.async_session_maker() as session:
last_updated = await sql.update_statistics_timestamps(session, start=True)
last_updated = await sql.update_timestamp(
session, enums.Event.UPDATER, enums.Event.START
)
async for track_data in plex.fetch_tracks_from_plex(server_url, token):
if track_data["date_last_played"] > last_updated:
@@ -51,7 +54,7 @@ async def process_tracks(server_url: str, token: str) -> None:
await calculate_statistics(session, durations)
await sql.update_statistics_timestamps(session, start=False)
await sql.update_timestamp(session, enums.Event.UPDATER, enums.Event.END)
await logger.info("Track processing completed successfully.")
except Exception as e:
await logger.error(f"An error occurred during track processing: {e}")
@@ -118,5 +121,7 @@ async def calculate_statistics(durations: list[float]) -> None:
max_holiday_favorite_base,
max_holiday_general_base,
)
# TODO: Remove any tracks that exceed a sublist's limit for the playlist after these adjustments.
else:
logger.warning("No valid track durations retrieved, statistics not updated.")