feat: Add endpoint and service method to retrieve top sounds by play count with filtering options
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
"""Dashboard service for statistics and analytics."""
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.core.logging import get_logger
|
||||
@@ -43,4 +44,65 @@ class DashboardService:
|
||||
}
|
||||
except Exception:
|
||||
logger.exception("Failed to get track statistics")
|
||||
raise
|
||||
raise
|
||||
|
||||
async def get_top_sounds(
|
||||
self,
|
||||
sound_type: str,
|
||||
period: str = "all_time",
|
||||
limit: int = 10,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Get top sounds by play count for a specific period."""
|
||||
try:
|
||||
# Calculate the date filter based on period
|
||||
date_filter = self._get_date_filter(period)
|
||||
|
||||
# Get top sounds from repository
|
||||
top_sounds = await self.sound_repository.get_top_sounds(
|
||||
sound_type=sound_type,
|
||||
date_filter=date_filter,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
return [
|
||||
{
|
||||
"id": sound["id"],
|
||||
"name": sound["name"],
|
||||
"type": sound["type"],
|
||||
"play_count": sound["play_count"],
|
||||
"duration": sound["duration"],
|
||||
"created_at": (
|
||||
sound["created_at"].isoformat()
|
||||
if sound["created_at"]
|
||||
else None
|
||||
),
|
||||
}
|
||||
for sound in top_sounds
|
||||
]
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Failed to get top sounds for type=%s, period=%s",
|
||||
sound_type,
|
||||
period,
|
||||
)
|
||||
raise
|
||||
|
||||
def _get_date_filter(self, period: str) -> datetime | None:
|
||||
"""Calculate the date filter based on the period."""
|
||||
now = datetime.now(UTC)
|
||||
|
||||
match period:
|
||||
case "today":
|
||||
return now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
case "1_day":
|
||||
return now - timedelta(days=1)
|
||||
case "1_week":
|
||||
return now - timedelta(weeks=1)
|
||||
case "1_month":
|
||||
return now - timedelta(days=30)
|
||||
case "1_year":
|
||||
return now - timedelta(days=365)
|
||||
case "all_time":
|
||||
return None
|
||||
case _:
|
||||
return None # Default to all time for unknown periods
|
||||
|
||||
Reference in New Issue
Block a user