Compare commits
5 Commits
14f2cdc9f9
...
master
Author | SHA1 | Date | |
---|---|---|---|
abab9b359f
|
|||
f5a874c6df
|
|||
4e40bc032c
|
|||
ef02f7878e
|
|||
ebed72f5fa
|
@ -1,112 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import datetime
|
|
||||||
from typing import TYPE_CHECKING, Any
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from django.db import models
|
|
||||||
|
|
||||||
logger: logging.Logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def wrong_typename(data: dict, expected: str) -> bool:
|
|
||||||
"""Check if the data is the expected type.
|
|
||||||
|
|
||||||
# TODO(TheLovinator): Double check this. # noqa: TD003
|
|
||||||
Type name examples:
|
|
||||||
- Game
|
|
||||||
- DropCampaign
|
|
||||||
- TimeBasedDrop
|
|
||||||
- DropBenefit
|
|
||||||
- RewardCampaign
|
|
||||||
- Reward
|
|
||||||
|
|
||||||
Args:
|
|
||||||
data (dict): The data to check.
|
|
||||||
expected (str): The expected type.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
bool: True if the data is not the expected type.
|
|
||||||
"""
|
|
||||||
is_unexpected_type: bool = data.get("__typename", "") != expected
|
|
||||||
if is_unexpected_type:
|
|
||||||
logger.error("Not a %s? %s", expected, data)
|
|
||||||
|
|
||||||
return is_unexpected_type
|
|
||||||
|
|
||||||
|
|
||||||
def update_field(instance: models.Model, django_field_name: str, new_value: str | datetime | None) -> int:
|
|
||||||
"""Update a field on an instance if the new value is different from the current value.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
instance (models.Model): The Django model instance.
|
|
||||||
django_field_name (str): The name of the field to update.
|
|
||||||
new_value (str | datetime | None): The new value to update the field with.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
int: If the field was updated, returns 1. Otherwise, returns 0.
|
|
||||||
"""
|
|
||||||
# Get the current value of the field.
|
|
||||||
try:
|
|
||||||
current_value = getattr(instance, django_field_name)
|
|
||||||
except AttributeError:
|
|
||||||
logger.exception("Field %s does not exist on %s", django_field_name, instance)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
# Only update the field if the new value is different from the current value.
|
|
||||||
if new_value and new_value != current_value:
|
|
||||||
setattr(instance, django_field_name, new_value)
|
|
||||||
return 1
|
|
||||||
|
|
||||||
# 0 fields updated.
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
def get_value(data: dict, key: str) -> datetime | str | None:
|
|
||||||
"""Get a value from a dictionary.
|
|
||||||
|
|
||||||
We have this function so we can handle values that we need to convert to a different type. For example, we might
|
|
||||||
need to convert a string to a datetime object.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
data (dict): The dictionary to get the value from.
|
|
||||||
key (str): The key to get the value for.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
datetime | str | None: The value from the dictionary
|
|
||||||
"""
|
|
||||||
data_key: Any | None = data.get(key)
|
|
||||||
if not data_key:
|
|
||||||
logger.warning("Key %s not found in %s", key, data)
|
|
||||||
return None
|
|
||||||
|
|
||||||
# Dates are in the format "2024-08-12T05:59:59.999Z"
|
|
||||||
dates: list[str] = ["endAt", "endsAt,", "startAt", "startsAt", "createdAt", "earnableUntil"]
|
|
||||||
if key in dates:
|
|
||||||
logger.debug("Converting %s to datetime", data_key)
|
|
||||||
return datetime.fromisoformat(data_key)
|
|
||||||
|
|
||||||
return data_key
|
|
||||||
|
|
||||||
|
|
||||||
def update_fields(instance: models.Model, data: dict, field_mapping: dict[str, str]) -> int:
|
|
||||||
"""Update multiple fields on an instance using a mapping from external field names to model field names.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
instance (models.Model): The Django model instance.
|
|
||||||
data (dict): The new data to update the fields with.
|
|
||||||
field_mapping (dict[str, str]): A dictionary mapping external field names to model field names.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
int: The number of fields updated. Used for only saving the instance if there were changes.
|
|
||||||
"""
|
|
||||||
dirty = 0
|
|
||||||
for json_field, django_field_name in field_mapping.items():
|
|
||||||
data_key: datetime | str | None = get_value(data, json_field)
|
|
||||||
dirty += update_field(instance=instance, django_field_name=django_field_name, new_value=data_key)
|
|
||||||
|
|
||||||
if dirty > 0:
|
|
||||||
instance.save()
|
|
||||||
|
|
||||||
return dirty
|
|
14
core/templates/404.html
Normal file
14
core/templates/404.html
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="row justify-content-center">
|
||||||
|
<div class="col-md-8 text-center">
|
||||||
|
<div class="alert-danger mt-5">
|
||||||
|
<h1 class="display-1">404</h1>
|
||||||
|
<h2>Page Not Found</h2>
|
||||||
|
<p class="lead">The page you're looking for doesn't exist or has been moved.</p>
|
||||||
|
<p>Check the URL or return to the <a href="{% url 'index' %}" class="alert-link">homepage</a>.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock content %}
|
14
core/templates/500.html
Normal file
14
core/templates/500.html
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="row justify-content-center">
|
||||||
|
<div class="col-md-8 text-center">
|
||||||
|
<div class="alert-danger mt-5">
|
||||||
|
<h1 class="display-1">500</h1>
|
||||||
|
<h2>Internal Server Error</h2>
|
||||||
|
<p class="lead">An unexpected error occurred while processing your request.</p>
|
||||||
|
<p>Check the URL or return to the <a href="{% url 'index' %}" class="alert-link">homepage</a>.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock content %}
|
@ -10,8 +10,7 @@
|
|||||||
<span class="d-inline text-muted">{{ grouped_drops|length }} game{{ grouped_drops|length|pluralize }}</span>
|
<span class="d-inline text-muted">{{ grouped_drops|length }} game{{ grouped_drops|length|pluralize }}</span>
|
||||||
</h2>
|
</h2>
|
||||||
{% if grouped_drops %}
|
{% if grouped_drops %}
|
||||||
{% for game, drops_list in grouped_drops.items %}
|
{% for game, campaigns in grouped_drops.items %}
|
||||||
{# Retain card structure for layout, replace table with list #}
|
|
||||||
<div class="card mb-4 shadow-sm">
|
<div class="card mb-4 shadow-sm">
|
||||||
<div class="row g-0">
|
<div class="row g-0">
|
||||||
<!-- Game Box Art -->
|
<!-- Game Box Art -->
|
||||||
@ -20,7 +19,7 @@
|
|||||||
<img src="{{ game.box_art_url }}" alt="{{ game.display_name|default:'Game name unknown' }} box art"
|
<img src="{{ game.box_art_url }}" alt="{{ game.display_name|default:'Game name unknown' }} box art"
|
||||||
class="img-fluid rounded-start" height="283" width="212" loading="lazy" />
|
class="img-fluid rounded-start" height="283" width="212" loading="lazy" />
|
||||||
{% else %}
|
{% else %}
|
||||||
<img src="{% static 'images/404_boxart.jpg' %}"
|
<img src="https://static-cdn.jtvnw.net/ttv-static/404_boxart.jpg"
|
||||||
alt="{% if game %}{{ game.display_name }}{% else %}Unknown Game{% endif %} box art"
|
alt="{% if game %}{{ game.display_name }}{% else %}Unknown Game{% endif %} box art"
|
||||||
class="img-fluid rounded-start" height="283" width="212" loading="lazy" />
|
class="img-fluid rounded-start" height="283" width="212" loading="lazy" />
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@ -41,54 +40,78 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
</h2>
|
</h2>
|
||||||
|
|
||||||
{% if drops_list %}
|
{% if campaigns %}
|
||||||
<!-- NEW Drop List Structure -->
|
<div class="mt-4">
|
||||||
<ul class="list-unstyled mt-3">
|
{% for campaign, drops_list in campaigns.items %}
|
||||||
{% for drop in drops_list %}
|
<div class="card mb-3">
|
||||||
<li class="mb-3"> {# Add margin between list items #}
|
<div class="card-header bg-secondary bg-opacity-25">
|
||||||
<strong>{{ drop.name|default:'Unknown Drop' }}</strong>
|
<h4 class="h6 mb-0"><a
|
||||||
(Requires {{ drop.required_minutes_watched|minutes_to_hours }})
|
href="{{ campaign.details_url|default:'#' }}">{{ campaign.name|default:"Unknown Campaign" }}</a>
|
||||||
<br>
|
</h4>
|
||||||
<em>Campaign:
|
<div class="mt-1">
|
||||||
<a href="{{ drop.campaign.details_url|default:'#' }}" class="text-decoration-none"
|
{% if campaign.details_url != campaign.account_link_url and campaign.account_link_url %}
|
||||||
title="{{ drop.campaign.name|default:'Unknown Campaign' }}">
|
<a href="{{ campaign.account_link_url }}" class="text-decoration-none">Link
|
||||||
{{ drop.campaign.name|truncatechars:40|default:'N/A' }} {# Adjusted truncate #}
|
Account</a>
|
||||||
</a>
|
|
||||||
{% if drop.campaign.details_url != drop.campaign.account_link_url and drop.campaign.account_link_url %}
|
|
||||||
| <a href="{{ drop.campaign.account_link_url }}" class="text-decoration-none"
|
|
||||||
title="Link Account for {{ drop.campaign.name }}">Link</a>
|
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</em>
|
</div>
|
||||||
<br>
|
<p class="mb-0 mt-1 text-muted small">
|
||||||
Ends in: <abbr
|
{{ campaign.start_at|date:'l d F H:i' }} -
|
||||||
title="{{ drop.campaign.start_at|date:'l d F H:i' }} - {{ drop.campaign.end_at|date:'l d F H:i' }}">
|
{{ campaign.end_at|date:'l d F H:i' }} | {{ campaign.end_at|timeuntil }}
|
||||||
{{ drop.campaign.end_at|timeuntil }}
|
</p>
|
||||||
</abbr>
|
</div>
|
||||||
|
<div class="card-body p-0">
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped table-hover align-middle mb-0">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Benefit Image</th>
|
||||||
|
<th>Drop Name</th>
|
||||||
|
<th>Benefit Name</th>
|
||||||
|
<th>Required Minutes Watched</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for drop in drops_list %}
|
||||||
{% if drop.benefits.exists %}
|
{% if drop.benefits.exists %}
|
||||||
<br>
|
|
||||||
Benefits:
|
|
||||||
<ul class="list-inline">
|
|
||||||
{% for benefit in drop.benefits.all %}
|
{% for benefit in drop.benefits.all %}
|
||||||
<li class="list-inline-item">
|
<tr>
|
||||||
<abbr title="{{ benefit.name|default:'Unknown Benefit' }}">
|
<td>
|
||||||
{% if benefit.image_asset_url %}
|
|
||||||
<img src="{{ benefit.image_asset_url|default:'https://static-cdn.jtvnw.net/ttv-static/404_boxart.jpg' }}"
|
<img src="{{ benefit.image_asset_url|default:'https://static-cdn.jtvnw.net/ttv-static/404_boxart.jpg' }}"
|
||||||
alt="{{ benefit.name|default:'Unknown Benefit' }}"
|
alt="{{ benefit.name|default:'Unknown Benefit' }}"
|
||||||
class="img-fluid rounded me-1 align-middle" {# Added align-middle #}
|
class="img-fluid rounded" height="50" width="50"
|
||||||
height="20" width="20" loading="lazy" />
|
loading="lazy" />
|
||||||
{% endif %}
|
</td>
|
||||||
<small>{{ benefit.name|truncatechars:25|default:'Unknown Benefit' }}</small>
|
<td>{{ drop.name|default:'Unknown Drop' }}</td>
|
||||||
{# Wrap text in small #}
|
<td>
|
||||||
</abbr>
|
{{ benefit.name|default:'Unknown Benefit' }}
|
||||||
</li>
|
</td>
|
||||||
|
<td>
|
||||||
|
{{ drop.required_minutes_watched|minutes_to_hours }}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</ul>
|
{% else %}
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<img src="https://static-cdn.jtvnw.net/ttv-static/404_boxart.jpg"
|
||||||
|
alt="{{ drop.name|default:'Unknown Drop' }}"
|
||||||
|
class="img-fluid rounded" height="50" width="50"
|
||||||
|
loading="lazy" />
|
||||||
|
</td>
|
||||||
|
<td>{{ drop.name|default:'Unknown Drop' }}</td>
|
||||||
|
<td>N/A</td>
|
||||||
|
<td>{{ drop.required_minutes_watched|minutes_to_hours|default:'N/A' }}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{# Removed hr, using li margin instead #}
|
|
||||||
</li>
|
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</ul>
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
{% else %}
|
{% else %}
|
||||||
<p class="mt-3 text-muted">No active drops found for this game currently.</p>
|
<p class="mt-3 text-muted">No active drops found for this game currently.</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
@ -8,8 +8,8 @@ from core.views import get_game, get_games, get_home
|
|||||||
|
|
||||||
app_name: str = "core"
|
app_name: str = "core"
|
||||||
|
|
||||||
# TODO(TheLovinator): Add a 404 page and a 500 page.
|
handler404 = "core.views.handler404"
|
||||||
# https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
|
handler500 = "core.views.handler500"
|
||||||
|
|
||||||
# TODO(TheLovinator): Add a robots.txt file.
|
# TODO(TheLovinator): Add a robots.txt file.
|
||||||
# https://developers.google.com/search/docs/crawling-indexing/robots/intro
|
# https://developers.google.com/search/docs/crawling-indexing/robots/intro
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from collections import defaultdict
|
|
||||||
from typing import TYPE_CHECKING, Any
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
from django.db.models import Prefetch
|
from django.db.models import Prefetch
|
||||||
@ -20,36 +19,112 @@ if TYPE_CHECKING:
|
|||||||
logger: logging.Logger = logging.getLogger(__name__)
|
logger: logging.Logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def handler404(request: HttpRequest, exception: Exception | None = None) -> HttpResponse:
|
||||||
|
"""Custom 404 error handler.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
request (HttpRequest): The request object that caused the 404.
|
||||||
|
exception (Exception, optional): The exception that caused the 404. Defaults to None.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
HttpResponse: The rendered 404 template.
|
||||||
|
"""
|
||||||
|
logger.warning(
|
||||||
|
"404 error occurred",
|
||||||
|
extra={"path": request.path, "exception": str(exception) if exception else None},
|
||||||
|
)
|
||||||
|
return render(request=request, template_name="404.html", status=404)
|
||||||
|
|
||||||
|
|
||||||
|
def handler500(request: HttpRequest) -> HttpResponse:
|
||||||
|
"""Custom 500 error handler.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
request (HttpRequest): The request object that caused the 500.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
HttpResponse: The rendered 500 template.
|
||||||
|
"""
|
||||||
|
logger.error("500 error occurred", extra={"path": request.path})
|
||||||
|
return render(request=request, template_name="500.html", status=500)
|
||||||
|
|
||||||
|
|
||||||
@require_http_methods(request_method_list=["GET", "HEAD"])
|
@require_http_methods(request_method_list=["GET", "HEAD"])
|
||||||
def get_home(request: HttpRequest) -> HttpResponse:
|
def get_home(request: HttpRequest) -> HttpResponse:
|
||||||
"""Render the index page.
|
"""Render the index page with drops grouped hierarchically by game and campaign.
|
||||||
|
|
||||||
|
This view fetches all currently active drops (where current time is between start_at and end_at),
|
||||||
|
and organizes them by game and campaign for display. Drops within each campaign are sorted by
|
||||||
|
required minutes watched.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
request (HttpRequest): The request object.
|
request (HttpRequest): The request object.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
HttpResponse: The response object
|
HttpResponse: The rendered index template with grouped drops.
|
||||||
"""
|
"""
|
||||||
now: timezone.datetime = timezone.now()
|
now: timezone.datetime = timezone.now()
|
||||||
grouped_drops = defaultdict(list)
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Dictionary structure: {Game: {Campaign: [TimeBasedDrop, ...]}}
|
||||||
|
grouped_drops: dict[Game, dict[DropCampaign, list[TimeBasedDrop]]] = {}
|
||||||
|
|
||||||
|
# Fetch all currently active drops with optimized queries
|
||||||
current_drops_qs = (
|
current_drops_qs = (
|
||||||
TimeBasedDrop.objects.filter(start_at__lte=now, end_at__gte=now)
|
TimeBasedDrop.objects.filter(start_at__lte=now, end_at__gte=now)
|
||||||
.select_related("campaign__game")
|
.select_related("campaign", "campaign__game", "campaign__owner")
|
||||||
.prefetch_related("benefits")
|
.prefetch_related("benefits")
|
||||||
.order_by("campaign__game__display_name", "name")
|
.order_by("campaign__game__display_name", "campaign__name", "required_minutes_watched")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Drops without associated games or campaigns
|
||||||
|
orphaned_drops: list[TimeBasedDrop] = []
|
||||||
|
|
||||||
for drop in current_drops_qs:
|
for drop in current_drops_qs:
|
||||||
|
# Check if drop has both campaign and game
|
||||||
if drop.campaign and drop.campaign.game:
|
if drop.campaign and drop.campaign.game:
|
||||||
game: Game = drop.campaign.game
|
game: Game = drop.campaign.game
|
||||||
grouped_drops[game].append(drop)
|
campaign: DropCampaign = drop.campaign
|
||||||
else:
|
|
||||||
logger.warning("Drop %s does not have an associated game or campaign.", drop.name)
|
# Initialize the game entry if it doesn't exist
|
||||||
|
if game not in grouped_drops:
|
||||||
|
grouped_drops[game] = {}
|
||||||
|
|
||||||
|
# Initialize the campaign entry if it doesn't exist
|
||||||
|
if campaign not in grouped_drops[game]:
|
||||||
|
grouped_drops[game][campaign] = []
|
||||||
|
|
||||||
|
# Add the drop to the appropriate campaign
|
||||||
|
grouped_drops[game][campaign].append(drop)
|
||||||
|
else:
|
||||||
|
# Store drops without proper association separately
|
||||||
|
orphaned_drops.append(drop)
|
||||||
|
logger.warning("Drop %s does not have an associated game or campaign.", drop.name or drop.drop_id)
|
||||||
|
|
||||||
|
# Make sure drops within each campaign are sorted by required_minutes_watched
|
||||||
|
for campaigns in grouped_drops.values():
|
||||||
|
for drops in campaigns.values():
|
||||||
|
drops.sort(key=lambda drop: drop.required_minutes_watched or 0)
|
||||||
|
|
||||||
|
# Also sort orphaned drops if any
|
||||||
|
if orphaned_drops:
|
||||||
|
orphaned_drops.sort(key=lambda drop: drop.required_minutes_watched or 0)
|
||||||
|
|
||||||
|
context: dict[str, Any] = {
|
||||||
|
"grouped_drops": grouped_drops,
|
||||||
|
"orphaned_drops": orphaned_drops,
|
||||||
|
"current_time": now,
|
||||||
|
}
|
||||||
|
|
||||||
context = {"grouped_drops": dict(grouped_drops)}
|
|
||||||
return render(request, "index.html", context)
|
return render(request, "index.html", context)
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Error in get_home view")
|
||||||
|
return HttpResponse(
|
||||||
|
status=500,
|
||||||
|
content="An error occurred while processing your request. Please try again later.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@require_http_methods(request_method_list=["GET", "HEAD"])
|
@require_http_methods(request_method_list=["GET", "HEAD"])
|
||||||
def get_game(request: HttpRequest, twitch_id: int) -> HttpResponse:
|
def get_game(request: HttpRequest, twitch_id: int) -> HttpResponse:
|
||||||
|
Reference in New Issue
Block a user