Skip to content

Commit

Permalink
feat: add week selector for weekly top uploaders metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
mhdzumair committed Feb 20, 2025
1 parent ec20fec commit 185f015
Show file tree
Hide file tree
Showing 4 changed files with 539 additions and 483 deletions.
173 changes: 96 additions & 77 deletions metrics/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,92 +186,111 @@ async def get_torrents_by_uploaders(response: Response):
return uploader_stats


@metrics_router.get("/torrents/uploaders/weekly", tags=["metrics"])
async def get_weekly_top_uploaders(response: Response):
@metrics_router.get("/torrents/uploaders/weekly/{week_date}", tags=["metrics"])
async def get_weekly_top_uploaders(week_date: str, response: Response):
response.headers.update(const.NO_CACHE_HEADERS)

# Calculate the start of the current week (Monday)
today = datetime.now(tz=timezone.utc)
start_of_week = today - timedelta(days=today.weekday())
start_of_week = start_of_week.replace(hour=0, minute=0, second=0, microsecond=0)
try:
# Parse the input date
selected_date = datetime.strptime(week_date, "%Y-%m-%d")
selected_date = selected_date.replace(tzinfo=timezone.utc)

# Get raw aggregation results
raw_results = await TorrentStreams.aggregate(
[
{
"$match": {
"source": "Contribution Stream",
"$or": [
{"created_at": {"$gte": start_of_week}},
{"uploaded_at": {"$gte": start_of_week}},
],
"is_blocked": {"$ne": True},
}
},
{
"$group": {
"_id": "$uploader",
"count": {"$sum": 1},
"latest_upload": {"$max": "$created_at"},
}
},
]
).to_list()
# Calculate the start of the week (Monday) for the selected date
start_of_week = selected_date - timedelta(days=selected_date.weekday())
start_of_week = start_of_week.replace(hour=0, minute=0, second=0, microsecond=0)

# Calculate end of week
end_of_week = start_of_week + timedelta(days=7)

# Process and clean the results
processed_results = []
anonymous_total = 0
anonymous_latest = None

for stat in raw_results:
uploader_name = stat["_id"]
count = stat["count"]
latest_upload = stat["latest_upload"]

# Skip invalid entries
if count <= 0:
continue

# Combine all anonymous-like entries
if (
uploader_name is None
or uploader_name.strip() == ""
or uploader_name.lower() == "anonymous"
):
anonymous_total += count
if anonymous_latest is None or (
latest_upload and latest_upload > anonymous_latest
# Get raw aggregation results
raw_results = await TorrentStreams.aggregate(
[
{
"$match": {
"source": "Contribution Stream",
"$or": [
{
"uploaded_at": {
"$gte": start_of_week,
"$lt": end_of_week,
}
},
],
"is_blocked": {"$ne": True},
}
},
{
"$group": {
"_id": "$uploader",
"count": {"$sum": 1},
"latest_upload": {"$max": "$created_at"},
}
},
]
).to_list()

# Process and clean the results (keeping existing logic)
processed_results = []
anonymous_total = 0
anonymous_latest = None

for stat in raw_results:
uploader_name = stat["_id"]
count = stat["count"]
latest_upload = stat["latest_upload"]

if count <= 0:
continue

if (
uploader_name is None
or uploader_name.strip() == ""
or uploader_name.lower() == "anonymous"
):
anonymous_latest = latest_upload
else:
anonymous_total += count
if anonymous_latest is None or (
latest_upload and latest_upload > anonymous_latest
):
anonymous_latest = latest_upload
else:
processed_results.append(
{
"name": uploader_name.strip(),
"count": count,
"latest_upload": (
latest_upload.strftime("%Y-%m-%d")
if latest_upload
else None
),
}
)

if anonymous_total > 0:
processed_results.append(
{
"name": uploader_name.strip(),
"count": count,
"name": "Anonymous",
"count": anonymous_total,
"latest_upload": (
latest_upload.strftime("%Y-%m-%d") if latest_upload else None
anonymous_latest.strftime("%Y-%m-%d")
if anonymous_latest
else None
),
}
)

# Add anonymous entry if we have any anonymous uploads
if anonymous_total > 0:
processed_results.append(
{
"name": "Anonymous",
"count": anonymous_total,
"latest_upload": (
anonymous_latest.strftime("%Y-%m-%d") if anonymous_latest else None
),
}
)

# Sort by count and limit to top 20
final_results = sorted(processed_results, key=lambda x: x["count"], reverse=True)[
:20
]

return {
"week_start": start_of_week.strftime("%Y-%m-%d"),
"uploaders": final_results,
}
final_results = sorted(
processed_results, key=lambda x: x["count"], reverse=True
)[:20]

return {
"week_start": start_of_week.strftime("%Y-%m-%d"),
"week_end": end_of_week.strftime("%Y-%m-%d"),
"uploaders": final_results,
}

except ValueError as e:
return {
"error": f"Invalid date format. Please use YYYY-MM-DD format. Details: {str(e)}"
}
except Exception as e:
return {"error": f"An error occurred: {str(e)}"}
93 changes: 89 additions & 4 deletions resources/css/metrics.css
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,86 @@ h4 {
transform: translateY(-5px);
}

.date-info {
background: rgba(129,87,208,0.6);
.week-selector {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
margin: 20px 0;
padding: 10px;
background: rgba(74, 71, 163, 0.2);
border-radius: 8px;
}

.week-selector button {
background: #4a47a3;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
text-align: center;
border-radius: 6px;
font-size: 0.9rem;
cursor: pointer;
transition: all 0.3s ease;
min-width: 130px;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.week-selector button:hover {
background: #5b58b4;
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

.week-selector button:active {
transform: translateY(0);
}

.week-selector input[type="date"] {
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
color: white;
padding: 7px 14px;
border-radius: 6px;
font-size: 0.9rem;
min-width: 150px;
cursor: pointer;
transition: all 0.3s ease;
}

.week-selector input[type="date"]:hover {
background: rgba(255, 255, 255, 0.15);
border-color: rgba(255, 255, 255, 0.3);
}

.week-selector input[type="date"]:focus {
outline: none;
border-color: #4a47a3;
background: rgba(255, 255, 255, 0.2);
}

/* Style the calendar icon */
.week-selector input[type="date"]::-webkit-calendar-picker-indicator {
filter: invert(1);
opacity: 0.7;
cursor: pointer;
}

.week-selector input[type="date"]::-webkit-calendar-picker-indicator:hover {
opacity: 1;
}

.date-info {
background: rgba(74, 71, 163, 0.4);
color: white;
padding: 10px 20px;
border-radius: 6px;
text-align: center;
font-size: 1rem;
margin: 15px 0;
border: 1px solid rgba(255, 255, 255, 0.1);
}

.chart-wrapper {
Expand Down Expand Up @@ -229,6 +303,17 @@ h4 {
padding: 10px;
}

.week-selector {
flex-direction: column;
gap: 8px;
}

.week-selector button,
.week-selector input[type="date"] {
width: 100%;
min-width: unset;
}

h3 {
font-size: 1.2rem;
}
Expand Down
7 changes: 6 additions & 1 deletion resources/html/metrics.html
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,12 @@ <h4 class="text-left">Top 20 Torrents Uploaders</h4>
</div>

<div class="chart-section">
<h4 class="text-left">Top 20 Contribution Streams Uploaders This Week</h4>
<h4 class="text-left">Top 20 Contribution Streams Uploaders</h4>
<div class="week-selector mb-3">
<button class="btn btn-outline-light btn-sm" id="prevWeek">Previous Week</button>
<input type="date" id="weekSelector" class="form-control mx-2">
<button class="btn btn-outline-light btn-sm" id="nextWeek">Next Week</button>
</div>
<div class="date-info mb-3" id="weekDateRange"></div>
<div class="chart-wrapper">
<canvas id="weeklyUploadersChart"></canvas>
Expand Down
Loading

0 comments on commit 185f015

Please sign in to comment.