feat: Add Twitch Drops Tracker application with campaign management

- Implemented models for DropCampaign, Game, Organization, DropBenefit, TimeBasedDrop, and DropBenefitEdge.
- Created views for listing and detailing drop campaigns.
- Added templates for dashboard, campaign list, and campaign detail.
- Developed management command to import drop campaigns from JSON files.
- Configured admin interface for managing campaigns and related models.
- Updated URL routing for the application.
- Enhanced README with installation instructions and project structure.
This commit is contained in:
Joakim Hellsén 2025-07-09 22:46:23 +02:00
commit 5c482c1729
15 changed files with 1145 additions and 10 deletions

View file

@ -2,6 +2,53 @@
Get notified when a new drop is available on Twitch
## Features
- Import and track Twitch drop campaigns
- View campaign details including start/end dates and rewards
- Filter campaigns by game and status
- Dashboard with active campaigns and quick stats
- Admin interface for managing campaigns and drops
## Installation
1. Clone the repository
```bash
git clone https://github.com/TheLovinator1/ttvdrops.git
cd ttvdrops
```
2. Install dependencies
```bash
uv sync
```
3. Set up environment variables by modifying the `.env` file
4. Apply migrations
```bash
uv run python manage.py migrate
```
5. Create a superuser
```bash
uv run python manage.py createsuperuser
```
## Usage
### Running the server
```bash
uv run python manage.py runserver
```
Access the application at http://127.0.0.1:8000/
### Importing drop campaigns
```bash
uv run python manage.py import_drop_campaign path/to/your/json/file.json
```
## Development
```bash
@ -12,3 +59,22 @@ uv run python manage.py collectstatic
uv run python manage.py runserver
uv run pytest
```
## Project Structure
- `twitch/` - Main app for Twitch drop campaigns
- `models.py` - Database models for campaigns, drops, and benefits
- `views.py` - Views for displaying campaign data
- `admin.py` - Admin interface configuration
- `management/commands/` - Custom management commands
- `import_drop_campaign.py` - Command for importing JSON data
- `templates/` - HTML templates
- `twitch/` - App-specific templates
- `dashboard.html` - Dashboard view
- `campaign_list.html` - List of all campaigns
- `campaign_detail.html` - Detailed view of a campaign
## License
See the [LICENSE](LICENSE) file for details.

View file

@ -5,13 +5,14 @@ from typing import TYPE_CHECKING
from debug_toolbar.toolbar import debug_toolbar_urls # pyright: ignore[reportMissingTypeStubs]
from django.conf import settings
from django.contrib import admin
from django.urls import path
from django.urls import include, path
if TYPE_CHECKING:
from django.urls.resolvers import URLResolver
urlpatterns: list[URLResolver] = [
path(route="admin/", view=admin.site.urls),
path(route="", view=include("twitch.urls", namespace="twitch")),
]
if not settings.TESTING:

View file

@ -32,12 +32,13 @@ lint.pydocstyle.convention = "google"
lint.isort.required-imports = ["from __future__ import annotations"]
lint.ignore = [
"CPY001", # Checks for the absence of copyright notices within Python files.
"D100", # Checks for undocumented public module definitions.
"D104", # Checks for undocumented public package definitions.
"D106", # Checks for undocumented public class definitions, for nested classes.
"ERA001", # Checks for commented-out Python code.
"FIX002", # Checks for "TODO" comments.
"CPY001", # Checks for the absence of copyright notices within Python files.
"D100", # Checks for undocumented public module definitions.
"D104", # Checks for undocumented public package definitions.
"D106", # Checks for undocumented public class definitions, for nested classes.
"ERA001", # Checks for commented-out Python code.
"FIX002", # Checks for "TODO" comments.
"PLR6301", # Checks for the presence of unused self parameter in methods definitions.
# Conflicting lint rules when using Ruff's formatter
# https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules

114
templates/base.html Normal file
View file

@ -0,0 +1,114 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Twitch Drops Tracker{% endblock %}</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- FontAwesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
<style>
/* Custom styles */
.campaign-card {
transition: transform 0.3s;
height: 100%;
}
.campaign-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}
.campaign-active {
border-left: 4px solid #9147ff;
}
.campaign-upcoming {
border-left: 4px solid #1d9bf0;
}
.campaign-expired {
border-left: 4px solid #6c757d;
}
.drop-item {
border-left: 4px solid #9147ff;
}
.twitch-color {
color: #9147ff;
}
.bg-twitch {
background-color: #9147ff;
color: white;
}
.benefit-img {
max-width: 120px;
max-height: 120px;
}
</style>
{% block extra_css %}{% endblock %}
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-4">
<div class="container">
<a class="navbar-brand" href="{% url 'twitch:dashboard' %}">
<i class="fa-brands fa-twitch me-2"></i>Twitch Drops Tracker
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link {% if request.path == '/' %}active{% endif %}"
href="{% url 'twitch:dashboard' %}">
<i class="fas fa-home me-1"></i> Dashboard
</a>
</li>
<li class="nav-item">
<a class="nav-link {% if '/campaigns/' in request.path %}active{% endif %}"
href="{% url 'twitch:campaign_list' %}">
<i class="fas fa-gift me-1"></i> Campaigns
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'admin:index' %}">
<i class="fas fa-cog me-1"></i> Admin
</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container mb-5">
{% block content %}{% endblock %}
</div>
<footer class="bg-dark text-white py-4 mt-auto">
<div class="container">
<div class="row">
<div class="col-md-6">
<h5><i class="fa-brands fa-twitch me-2"></i>Twitch Drops Tracker</h5>
<p>Track and manage Twitch drops campaigns for your favorite games</p>
</div>
<div class="col-md-6 text-md-end">
<p class="mb-0">&copy; {% now "Y" %} Twitch Drops Tracker</p>
<p class="mb-0 small">Not affiliated with Twitch Interactive, Inc.</p>
</div>
</div>
</div>
</footer>
<!-- Bootstrap JS Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
{% block extra_js %}{% endblock %}
</body>
</html>

View file

@ -0,0 +1,150 @@
{% extends "base.html" %}
{% block title %}{{ campaign.name }} - Twitch Drops Tracker{% endblock %}
{% block content %}
<div class="row mb-4">
<div class="col-12">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="{% url 'twitch:dashboard' %}">Dashboard</a></li>
<li class="breadcrumb-item"><a href="{% url 'twitch:campaign_list' %}">Campaigns</a></li>
<li class="breadcrumb-item active" aria-current="page">{{ campaign.name }}</li>
</ol>
</nav>
</div>
</div>
<div class="row mb-4">
<div class="col-md-8">
<h1 class="mb-3">{{ campaign.name }}</h1>
<div class="d-flex flex-wrap gap-2 mb-3">
<span class="badge bg-primary">{{ campaign.game.display_name }}</span>
{% if campaign.start_at <= now and campaign.end_at >= now %}
{% if campaign.status == 'ACTIVE' %}
<span class="badge bg-success">Active</span>
{% else %}
<span class="badge bg-warning text-dark">{{ campaign.status|title }}</span>
{% endif %}
{% elif campaign.start_at > now %}
<span class="badge bg-info text-dark">Upcoming</span>
{% else %}
<span class="badge bg-secondary">Expired</span>
{% endif %}
</div>
<p>{{ campaign.description }}</p>
<div class="row mb-3">
<div class="col-md-6">
<p><strong><i class="far fa-calendar-alt me-2"></i>Start Date:</strong>
{{ campaign.start_at|date:"F j, Y, g:i a" }}</p>
</div>
<div class="col-md-6">
<p><strong><i class="far fa-calendar-alt me-2"></i>End Date:</strong>
{{ campaign.end_at|date:"F j, Y, g:i a" }}</p>
</div>
</div>
{% if campaign.details_url %}
<p>
<a href="{{ campaign.details_url }}" target="_blank" class="btn btn-outline-primary">
<i class="fas fa-external-link-alt me-2"></i>Official Details
</a>
</p>
{% endif %}
{% if campaign.account_link_url %}
<p>
<a href="{{ campaign.account_link_url }}" target="_blank" class="btn btn-success">
<i class="fas fa-link me-2"></i>Connect Account
</a>
</p>
{% endif %}
</div>
<div class="col-md-4">
{% if campaign.image_url %}
<img src="{{ campaign.image_url }}" class="img-fluid rounded shadow-sm" alt="{{ campaign.name }}">
{% else %}
<div class="bg-light rounded shadow-sm p-4 text-center">
<i class="fas fa-image fa-5x text-muted mb-3"></i>
<p class="text-muted">No image available</p>
</div>
{% endif %}
<div class="card mt-3 border-0 shadow-sm">
<div class="card-header bg-dark text-white">
<h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>Campaign Info</h5>
</div>
<div class="card-body">
<p><strong>Owner:</strong> {{ campaign.owner.name }}</p>
<p><strong>Status:</strong> {{ campaign.status }}</p>
<p><strong>Account Connected:</strong> {% if campaign.is_account_connected %}<span
class="text-success">Yes</span>{% else %}<span class="text-danger">No</span>{% endif %}</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="card border-0 shadow-sm">
<div class="card-header bg-twitch">
<h5 class="mb-0"><i class="fas fa-gift me-2"></i>Rewards</h5>
</div>
<div class="card-body">
{% if drops %}
<div class="timeline-container">
{% for drop in drops %}
<div class="card mb-4 drop-item">
<div class="card-body">
<div class="row">
<div class="col-md-8">
<h4>{{ drop.name }}</h4>
<p class="mb-2">
<span class="badge bg-primary">{{ drop.required_minutes_watched }} minutes
watched</span>
{% if drop.required_subs > 0 %}
<span class="badge bg-info">{{ drop.required_subs }} subscriptions
required</span>
{% endif %}
</p>
<p class="mb-2">
<small class="text-muted">
<i class="far fa-clock me-1"></i>Available:
{{ drop.start_at|date:"M d, Y" }} - {{ drop.end_at|date:"M d, Y" }}
</small>
</p>
<div class="progress mb-3" style="height: 25px;">
<div class="progress-bar bg-twitch" role="progressbar" style="width: 0%;"
aria-valuenow="0" aria-valuemin="0"
aria-valuemax="{{ drop.required_minutes_watched }}">
0 / {{ drop.required_minutes_watched }} minutes
</div>
</div>
</div>
<div class="col-md-4 text-center">
{% for benefit in drop.benefits.all %}
<div class="mb-2">
{% if benefit.image_asset_url %}
<img src="{{ benefit.image_asset_url }}" class="benefit-img mb-2"
alt="{{ benefit.name }}">
{% else %}
<div class="bg-light rounded p-3 mb-2">
<i class="fas fa-gift fa-3x text-muted"></i>
</div>
{% endif %}
<p class="mb-0"><strong>{{ benefit.name }}</strong></p>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% else %}
<div class="alert alert-info">
<i class="fas fa-info-circle me-2"></i>No drops found for this campaign.
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock %}

View file

@ -0,0 +1,125 @@
{% extends "base.html" %}
{% block title %}Drop Campaigns - Twitch Drops Tracker{% endblock %}
{% block content %}
<div class="row mb-4">
<div class="col">
<h1 class="mb-4"><i class="fas fa-gift me-2 twitch-color"></i>Drop Campaigns</h1>
<p class="lead">Browse all Twitch drop campaigns.</p>
</div>
</div>
<div class="row mb-4">
<div class="col-12">
<div class="card border-0 shadow-sm">
<div class="card-header bg-dark text-white">
<h5 class="mb-0"><i class="fas fa-filter me-2"></i>Filter Campaigns</h5>
</div>
<div class="card-body">
<form method="get" action="{% url 'twitch:campaign_list' %}" class="row g-3">
<div class="col-md-5">
<label for="game" class="form-label">Game</label>
<select class="form-select" id="game" name="game">
<option value="">All Games</option>
{% for game in games %}
<option value="{{ game.id }}" {% if selected_game == game.id %}selected{% endif %}>
{{ game.display_name }}
</option>
{% endfor %}
</select>
</div>
<div class="col-md-5">
<label for="status" class="form-label">Status</label>
<select class="form-select" id="status" name="status">
<option value="">All Statuses</option>
{% for status in status_options %}
<option value="{{ status }}" {% if selected_status == status %}selected{% endif %}>
{{ status|title }}
</option>
{% endfor %}
</select>
</div>
<div class="col-md-2 d-flex align-items-end">
<button type="submit" class="btn btn-primary w-100">
<i class="fas fa-search me-2"></i>Apply Filters
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="card border-0 shadow-sm">
<div class="card-header bg-twitch">
<h5 class="mb-0"><i class="fas fa-list me-2"></i>Campaign List</h5>
</div>
<div class="card-body">
{% if campaigns %}
<div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
{% for campaign in campaigns %}
<div class="col">
{% if campaign.start_at <= now and campaign.end_at >= now %}
{% if campaign.status == 'ACTIVE' %}
<div class="card h-100 campaign-card campaign-active">
{% else %}
<div class="card h-100 campaign-card">
{% endif %}
{% elif campaign.start_at > now %}
<div class="card h-100 campaign-card campaign-upcoming">
{% else %}
<div class="card h-100 campaign-card campaign-expired">
{% endif %}
{% if campaign.image_url %}
<img src="{{ campaign.image_url }}" class="card-img-top"
alt="{{ campaign.name }}">
{% endif %}
<div class="card-body">
<h5 class="card-title">{{ campaign.name }}</h5>
<h6 class="card-subtitle mb-2 text-muted">{{ campaign.game.display_name }}
</h6>
<p class="card-text small">{{ campaign.description|truncatewords:20 }}</p>
<p class="card-text">
<small class="text-muted">
<i
class="far fa-calendar-alt me-1"></i>{{ campaign.start_at|date:"M d, Y" }}
- {{ campaign.end_at|date:"M d, Y" }}
</small>
</p>
</div>
<div class="card-footer bg-transparent">
<div class="d-flex justify-content-between align-items-center">
{% if campaign.start_at <= now and campaign.end_at >= now %}
{% if campaign.status == 'ACTIVE' %}
<span class="badge bg-success">Active</span>
{% else %}
<span
class="badge bg-warning text-dark">{{ campaign.status|title }}</span>
{% endif %}
{% elif campaign.start_at > now %}
<span class="badge bg-info text-dark">Upcoming</span>
{% else %}
<span class="badge bg-secondary">Expired</span>
{% endif %}
<a href="{% url 'twitch:campaign_detail' campaign.id %}"
class="btn btn-sm btn-outline-primary">View Details</a>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% else %}
<div class="alert alert-info">
<i class="fas fa-info-circle me-2"></i>No campaigns found with the current filters.
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock %}

View file

@ -0,0 +1,86 @@
{% extends "base.html" %}
{% block title %}Dashboard - Twitch Drops Tracker{% endblock %}
{% block content %}
<div class="row mb-4">
<div class="col">
<h1 class="mb-4"><i class="fas fa-tachometer-alt me-2 twitch-color"></i>Dashboard</h1>
<p class="lead">Track your active Twitch drop campaigns and progress.</p>
</div>
</div>
<div class="row mb-4">
<div class="col-12">
<div class="card border-0 shadow-sm">
<div class="card-header bg-twitch">
<h5 class="mb-0"><i class="fas fa-fire me-2"></i>Active Campaigns</h5>
</div>
<div class="card-body">
{% if active_campaigns %}
<div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
{% for campaign in active_campaigns %}
<div class="col">
<div class="card h-100 campaign-card campaign-active">
{% if campaign.image_url %}
<img src="{{ campaign.image_url }}" class="card-img-top" alt="{{ campaign.name }}">
{% endif %}
<div class="card-body">
<h5 class="card-title">{{ campaign.name }}</h5>
<h6 class="card-subtitle mb-2 text-muted">{{ campaign.game.display_name }}</h6>
<p class="card-text small">{{ campaign.description|truncatewords:20 }}</p>
</div>
<div class="card-footer bg-transparent">
<div class="d-flex justify-content-between align-items-center">
<span class="badge bg-success">Active</span>
<a href="{% url 'twitch:campaign_detail' campaign.id %}"
class="btn btn-sm btn-outline-primary">View Details</a>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% else %}
<div class="alert alert-info">
<i class="fas fa-info-circle me-2"></i>No active campaigns at the moment.
</div>
{% endif %}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="card border-0 shadow-sm">
<div class="card-header bg-dark text-white">
<h5 class="mb-0"><i class="fas fa-chart-bar me-2"></i>Quick Stats</h5>
</div>
<div class="card-body">
<div class="row text-center">
<div class="col-md-4 mb-3 mb-md-0">
<div class="p-3 border rounded">
<h2 class="twitch-color">{{ active_campaigns.count }}</h2>
<p class="mb-0 text-muted">Active Campaigns</p>
</div>
</div>
<div class="col-md-4 mb-3 mb-md-0">
<div class="p-3 border rounded">
<h2 class="text-primary">{{ now|date:"F j, Y" }}</h2>
<p class="mb-0 text-muted">Current Date</p>
</div>
</div>
<div class="col-md-4">
<div class="p-3 border rounded">
<a href="{% url 'twitch:campaign_list' %}" class="btn btn-primary btn-lg w-100">
<i class="fas fa-list me-2"></i>View All Campaigns
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

View file

@ -1 +1,81 @@
# Register your models here.
from __future__ import annotations
from django.contrib import admin
from twitch.models import DropBenefit, DropBenefitEdge, DropCampaign, Game, Organization, TimeBasedDrop
@admin.register(Game)
class GameAdmin(admin.ModelAdmin):
"""Admin configuration for Game model."""
list_display = ("id", "display_name", "slug")
search_fields = ("id", "display_name", "slug")
@admin.register(Organization)
class OrganizationAdmin(admin.ModelAdmin):
"""Admin configuration for Organization model."""
list_display = ("id", "name")
search_fields = ("id", "name")
class TimeBasedDropInline(admin.TabularInline):
"""Inline admin for TimeBasedDrop model."""
model = TimeBasedDrop
extra = 0
@admin.register(DropCampaign)
class DropCampaignAdmin(admin.ModelAdmin):
"""Admin configuration for DropCampaign model."""
list_display = ("id", "name", "game", "owner", "status", "start_at", "end_at", "is_active")
list_filter = ("status", "game", "owner")
search_fields = ("id", "name", "description")
inlines = [TimeBasedDropInline]
readonly_fields = ("created_at", "updated_at")
class DropBenefitEdgeInline(admin.TabularInline):
"""Inline admin for DropBenefitEdge model."""
model = DropBenefitEdge
extra = 0
@admin.register(TimeBasedDrop)
class TimeBasedDropAdmin(admin.ModelAdmin):
"""Admin configuration for TimeBasedDrop model."""
list_display = (
"id",
"name",
"campaign",
"required_minutes_watched",
"required_subs",
"start_at",
"end_at",
)
list_filter = ("campaign__game", "campaign")
search_fields = ("id", "name")
inlines = [DropBenefitEdgeInline]
@admin.register(DropBenefit)
class DropBenefitAdmin(admin.ModelAdmin):
"""Admin configuration for DropBenefit model."""
list_display = (
"id",
"name",
"game",
"owner_organization",
"distribution_type",
"entitlement_limit",
"created_at",
)
list_filter = ("game", "owner_organization", "distribution_type")
search_fields = ("id", "name")

View file

View file

View file

@ -0,0 +1,151 @@
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
from django.core.management.base import BaseCommand, CommandError, CommandParser
from twitch.models import DropBenefit, DropBenefitEdge, DropCampaign, Game, Organization, TimeBasedDrop
class Command(BaseCommand):
"""Import Twitch drop campaign data from a JSON file."""
help = "Import Twitch drop campaign data from a JSON file"
def add_arguments(self, parser: CommandParser) -> None:
"""Add command arguments.
Args:
parser: The command argument parser.
"""
parser.add_argument(
"json_file",
type=str,
help="Path to the JSON file containing the drop campaign data",
)
def handle(self, **options: str) -> None:
"""Execute the command.
Args:
**options: Arbitrary keyword arguments.
Raises:
CommandError: If the file doesn't exist, isn't a JSON file,
or has an invalid JSON structure.
"""
json_file_path: str = options["json_file"]
file_path = Path(json_file_path)
# Validate file exists and is a JSON file
if not file_path.exists():
msg = f"File {json_file_path} does not exist"
raise CommandError(msg)
if not json_file_path.endswith(".json"):
msg = f"File {json_file_path} is not a JSON file"
raise CommandError(msg)
# Load JSON data
try:
with file_path.open(encoding="utf-8") as f:
data = json.load(f)
except json.JSONDecodeError as e:
msg = f"Error decoding JSON: {e}"
raise CommandError(msg) from e
# Check if the JSON has the expected structure
if "data" not in data or "user" not in data["data"] or "dropCampaign" not in data["data"]["user"]:
msg = "Invalid JSON structure: Missing data.user.dropCampaign"
raise CommandError(msg)
# Extract drop campaign data
drop_campaign_data = data["data"]["user"]["dropCampaign"]
# Process the data
self._import_drop_campaign(drop_campaign_data)
self.stdout.write(self.style.SUCCESS(f"Successfully imported drop campaign: {drop_campaign_data['name']}"))
def _import_drop_campaign(self, campaign_data: dict[str, Any]) -> None:
"""Import drop campaign data into the database.
Args:
campaign_data: The drop campaign data to import.
"""
# First, create or update the game
game_data = campaign_data["game"]
game, _ = Game.objects.update_or_create(
id=game_data["id"],
defaults={
"slug": game_data.get("slug", ""),
"display_name": game_data["displayName"],
},
)
# Create or update the organization
org_data = campaign_data["owner"]
organization, _ = Organization.objects.update_or_create(
id=org_data["id"],
defaults={"name": org_data["name"]},
)
# Create or update the drop campaign
drop_campaign, _ = DropCampaign.objects.update_or_create(
id=campaign_data["id"],
defaults={
"name": campaign_data["name"],
"description": campaign_data["description"],
"details_url": campaign_data.get("detailsURL", ""),
"account_link_url": campaign_data.get("accountLinkURL", ""),
"image_url": campaign_data.get("imageURL", ""),
"start_at": campaign_data["startAt"],
"end_at": campaign_data["endAt"],
"status": campaign_data["status"],
"is_account_connected": campaign_data["self"]["isAccountConnected"],
"game": game,
"owner": organization,
},
)
# Process time-based drops
for drop_data in campaign_data.get("timeBasedDrops", []):
time_based_drop, _ = TimeBasedDrop.objects.update_or_create(
id=drop_data["id"],
defaults={
"name": drop_data["name"],
"required_minutes_watched": drop_data["requiredMinutesWatched"],
"required_subs": drop_data.get("requiredSubs", 0),
"start_at": drop_data["startAt"],
"end_at": drop_data["endAt"],
"campaign": drop_campaign,
},
)
# Process benefits
for benefit_edge in drop_data.get("benefitEdges", []):
benefit_data = benefit_edge["benefit"]
benefit, _ = DropBenefit.objects.update_or_create(
id=benefit_data["id"],
defaults={
"name": benefit_data["name"],
"image_asset_url": benefit_data.get("imageAssetURL", ""),
"created_at": benefit_data["createdAt"],
"entitlement_limit": benefit_data.get("entitlementLimit", 1),
"is_ios_available": benefit_data.get("isIosAvailable", False),
"distribution_type": benefit_data["distributionType"],
"game": game,
"owner_organization": organization,
},
)
# Create the relationship between drop and benefit
DropBenefitEdge.objects.update_or_create(
drop=time_based_drop,
benefit=benefit,
defaults={
"entitlement_limit": benefit_edge.get("entitlementLimit", 1),
},
)

View file

@ -0,0 +1,101 @@
# Generated by Django 5.2.4 on 2025-07-09 20:44
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DropBenefit',
fields=[
('id', models.TextField(primary_key=True, serialize=False)),
('name', models.TextField()),
('image_asset_url', models.URLField(blank=True, default='', max_length=500)),
('created_at', models.DateTimeField()),
('entitlement_limit', models.PositiveIntegerField(default=1)),
('is_ios_available', models.BooleanField(default=False)),
('distribution_type', models.TextField(choices=[('DIRECT_ENTITLEMENT', 'Direct Entitlement'), ('CODE', 'Code')])),
],
),
migrations.CreateModel(
name='Game',
fields=[
('id', models.TextField(primary_key=True, serialize=False)),
('slug', models.TextField(blank=True, default='')),
('display_name', models.TextField()),
],
),
migrations.CreateModel(
name='Organization',
fields=[
('id', models.TextField(primary_key=True, serialize=False)),
('name', models.TextField()),
],
),
migrations.CreateModel(
name='DropBenefitEdge',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('entitlement_limit', models.PositiveIntegerField(default=1)),
('benefit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='twitch.dropbenefit')),
],
),
migrations.AddField(
model_name='dropbenefit',
name='game',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='drop_benefits', to='twitch.game'),
),
migrations.CreateModel(
name='DropCampaign',
fields=[
('id', models.TextField(primary_key=True, serialize=False)),
('name', models.TextField()),
('description', models.TextField(blank=True)),
('details_url', models.URLField(blank=True, default='', max_length=500)),
('account_link_url', models.URLField(blank=True, default='', max_length=500)),
('image_url', models.URLField(blank=True, default='', max_length=500)),
('start_at', models.DateTimeField()),
('end_at', models.DateTimeField()),
('status', models.TextField(choices=[('ACTIVE', 'Active'), ('UPCOMING', 'Upcoming'), ('EXPIRED', 'Expired')])),
('is_account_connected', models.BooleanField(default=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('game', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='drop_campaigns', to='twitch.game')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='drop_campaigns', to='twitch.organization')),
],
),
migrations.AddField(
model_name='dropbenefit',
name='owner_organization',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='drop_benefits', to='twitch.organization'),
),
migrations.CreateModel(
name='TimeBasedDrop',
fields=[
('id', models.TextField(primary_key=True, serialize=False)),
('name', models.TextField()),
('required_minutes_watched', models.PositiveIntegerField()),
('required_subs', models.PositiveIntegerField(default=0)),
('start_at', models.DateTimeField()),
('end_at', models.DateTimeField()),
('benefits', models.ManyToManyField(related_name='drops', through='twitch.DropBenefitEdge', to='twitch.dropbenefit')),
('campaign', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='time_based_drops', to='twitch.dropcampaign')),
],
),
migrations.AddField(
model_name='dropbenefitedge',
name='drop',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='twitch.timebaseddrop'),
),
migrations.AlterUniqueTogether(
name='dropbenefitedge',
unique_together={('drop', 'benefit')},
),
]

View file

@ -1 +1,127 @@
# Create your models here.
from __future__ import annotations
from typing import ClassVar
from django.db import models
from django.utils import timezone
class Game(models.Model):
"""Represents a game on Twitch."""
id = models.TextField(primary_key=True)
slug = models.TextField(blank=True, default="")
display_name = models.TextField()
def __str__(self) -> str:
"""Return a string representation of the game."""
return self.display_name
class Organization(models.Model):
"""Represents an organization on Twitch that can own drop campaigns."""
id = models.TextField(primary_key=True)
name = models.TextField()
def __str__(self) -> str:
"""Return a string representation of the organization."""
return self.name
class DropCampaign(models.Model):
"""Represents a Twitch drop campaign."""
STATUS_CHOICES: ClassVar[list[tuple[str, str]]] = [
("ACTIVE", "Active"),
("UPCOMING", "Upcoming"),
("EXPIRED", "Expired"),
]
id = models.TextField(primary_key=True)
name = models.TextField()
description = models.TextField(blank=True)
details_url = models.URLField(max_length=500, blank=True, default="")
account_link_url = models.URLField(max_length=500, blank=True, default="")
image_url = models.URLField(max_length=500, blank=True, default="")
start_at = models.DateTimeField()
end_at = models.DateTimeField()
status = models.TextField(choices=STATUS_CHOICES)
is_account_connected = models.BooleanField(default=False)
# Foreign keys
game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name="drop_campaigns")
owner = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="drop_campaigns")
# Tracking fields
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self) -> str:
"""Return a string representation of the drop campaign."""
return self.name
@property
def is_active(self) -> bool:
"""Check if the campaign is currently active."""
now = timezone.now()
return self.start_at <= now <= self.end_at and self.status == "ACTIVE"
class DropBenefit(models.Model):
"""Represents a benefit that can be earned from a drop."""
DISTRIBUTION_TYPES: ClassVar[list[tuple[str, str]]] = [
("DIRECT_ENTITLEMENT", "Direct Entitlement"),
("CODE", "Code"),
]
id = models.TextField(primary_key=True)
name = models.TextField()
image_asset_url = models.URLField(max_length=500, blank=True, default="")
created_at = models.DateTimeField()
entitlement_limit = models.PositiveIntegerField(default=1)
is_ios_available = models.BooleanField(default=False)
distribution_type = models.TextField(choices=DISTRIBUTION_TYPES)
# Foreign keys
game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name="drop_benefits")
owner_organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="drop_benefits")
def __str__(self) -> str:
"""Return a string representation of the drop benefit."""
return self.name
class TimeBasedDrop(models.Model):
"""Represents a time-based drop in a drop campaign."""
id = models.TextField(primary_key=True)
name = models.TextField()
required_minutes_watched = models.PositiveIntegerField()
required_subs = models.PositiveIntegerField(default=0)
start_at = models.DateTimeField()
end_at = models.DateTimeField()
# Foreign keys
campaign = models.ForeignKey(DropCampaign, on_delete=models.CASCADE, related_name="time_based_drops")
benefits = models.ManyToManyField(DropBenefit, through="DropBenefitEdge", related_name="drops")
def __str__(self) -> str:
"""Return a string representation of the time-based drop."""
return self.name
class DropBenefitEdge(models.Model):
"""Represents the relationship between a TimeBasedDrop and a DropBenefit."""
drop = models.ForeignKey(TimeBasedDrop, on_delete=models.CASCADE)
benefit = models.ForeignKey(DropBenefit, on_delete=models.CASCADE)
entitlement_limit = models.PositiveIntegerField(default=1)
class Meta:
unique_together = ("drop", "benefit")
def __str__(self) -> str:
"""Return a string representation of the drop benefit edge."""
return f"{self.drop.name} - {self.benefit.name}"

13
twitch/urls.py Normal file
View file

@ -0,0 +1,13 @@
from __future__ import annotations
from django.urls import path
from twitch import views
app_name = "twitch"
urlpatterns = [
path("", views.dashboard, name="dashboard"),
path("campaigns/", views.DropCampaignListView.as_view(), name="campaign_list"),
path("campaigns/<str:pk>/", views.DropCampaignDetailView.as_view(), name="campaign_detail"),
]

View file

@ -1 +1,122 @@
# Create your views here.
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from django.shortcuts import render
from django.utils import timezone
from django.views.generic import DetailView, ListView
from twitch.models import DropCampaign, Game, TimeBasedDrop
if TYPE_CHECKING:
from django.db.models import QuerySet
from django.http import HttpRequest, HttpResponse
class DropCampaignListView(ListView):
"""List view for drop campaigns."""
model = DropCampaign
template_name = "twitch/campaign_list.html"
context_object_name = "campaigns"
def get_queryset(self) -> QuerySet[DropCampaign]:
"""Get queryset of drop campaigns.
Returns:
QuerySet: Filtered drop campaigns.
"""
queryset = super().get_queryset()
status_filter = self.request.GET.get("status")
game_filter = self.request.GET.get("game")
# Filter by status if provided
if status_filter:
queryset = queryset.filter(status=status_filter)
# Filter by game if provided
if game_filter:
queryset = queryset.filter(game__id=game_filter)
return queryset.select_related("game", "owner").order_by("-start_at")
def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
"""Add additional context data.
Args:
**kwargs: Additional arguments.
Returns:
dict: Context data.
"""
context = super().get_context_data(**kwargs)
# Add games for filtering
context["games"] = Game.objects.all()
# Add status options for filtering
context["status_options"] = [status[0] for status in DropCampaign.STATUS_CHOICES]
# Add selected filters
context["selected_status"] = self.request.GET.get("status", "")
context["selected_game"] = self.request.GET.get("game", "")
# Current time for active campaign highlighting
context["now"] = timezone.now()
return context
class DropCampaignDetailView(DetailView):
"""Detail view for a drop campaign."""
model = DropCampaign
template_name = "twitch/campaign_detail.html"
context_object_name = "campaign"
def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
"""Add additional context data.
Args:
**kwargs: Additional arguments.
Returns:
dict: Context data.
"""
context = super().get_context_data(**kwargs)
# Add drops for this campaign with benefits preloaded
context["drops"] = (
TimeBasedDrop.objects.filter(campaign=self.get_object())
.select_related("campaign")
.prefetch_related("benefits")
.order_by("required_minutes_watched")
)
# Current time for active campaign highlighting
context["now"] = timezone.now()
return context
def dashboard(request: HttpRequest) -> HttpResponse:
"""Dashboard view showing active campaigns and progress.
Args:
request: The HTTP request.
Returns:
HttpResponse: The rendered dashboard template.
"""
# Get active campaigns
now = timezone.now()
active_campaigns = DropCampaign.objects.filter(start_at__lte=now, end_at__gte=now, status="ACTIVE").select_related("game", "owner")
return render(
request,
"twitch/dashboard.html",
{
"active_campaigns": active_campaigns,
"now": now,
},
)