Don't use users
This commit is contained in:
@ -74,10 +74,6 @@ INSTALLED_APPS: list[str] = [
|
|||||||
"django.contrib.messages",
|
"django.contrib.messages",
|
||||||
"django.contrib.staticfiles",
|
"django.contrib.staticfiles",
|
||||||
"ninja",
|
"ninja",
|
||||||
"allauth",
|
|
||||||
"allauth.account",
|
|
||||||
"allauth.socialaccount",
|
|
||||||
"allauth.socialaccount.providers.twitch",
|
|
||||||
"simple_history",
|
"simple_history",
|
||||||
]
|
]
|
||||||
|
|
||||||
@ -90,7 +86,6 @@ MIDDLEWARE: list[str] = [
|
|||||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||||
"django.contrib.messages.middleware.MessageMiddleware",
|
"django.contrib.messages.middleware.MessageMiddleware",
|
||||||
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||||
"allauth.account.middleware.AccountMiddleware",
|
|
||||||
"simple_history.middleware.HistoryRequestMiddleware",
|
"simple_history.middleware.HistoryRequestMiddleware",
|
||||||
]
|
]
|
||||||
|
|
||||||
@ -165,26 +160,6 @@ LOGGING = {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
LOGIN_URL = "/login/"
|
|
||||||
LOGIN_REDIRECT_URL = "/"
|
|
||||||
LOGOUT_REDIRECT_URL = "/"
|
|
||||||
SOCIALACCOUNT_ONLY = True
|
|
||||||
ACCOUNT_EMAIL_VERIFICATION = "none"
|
|
||||||
SOCIALACCOUNT_STORE_TOKENS = True
|
|
||||||
|
|
||||||
AUTHENTICATION_BACKENDS: list[str] = [
|
|
||||||
"django.contrib.auth.backends.ModelBackend",
|
|
||||||
"allauth.account.auth_backends.AuthenticationBackend",
|
|
||||||
]
|
|
||||||
|
|
||||||
SOCIALACCOUNT_PROVIDERS = {
|
|
||||||
"twitch": {
|
|
||||||
"SCOPE": ["user:read:email"],
|
|
||||||
"AUTH_PARAMS": {"force_verify": True},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
MESSAGE_TAGS: dict[int, str] = {
|
MESSAGE_TAGS: dict[int, str] = {
|
||||||
messages.DEBUG: "alert-info",
|
messages.DEBUG: "alert-info",
|
||||||
messages.INFO: "alert-info",
|
messages.INFO: "alert-info",
|
||||||
|
@ -21,7 +21,6 @@ app_name: str = "config"
|
|||||||
|
|
||||||
urlpatterns: list[URLPattern | URLResolver] = [
|
urlpatterns: list[URLPattern | URLResolver] = [
|
||||||
path(route="admin/", view=admin.site.urls),
|
path(route="admin/", view=admin.site.urls),
|
||||||
path(route="accounts/", view=include(arg="allauth.urls")),
|
|
||||||
path(route="", view=include(arg="core.urls")),
|
path(route="", view=include(arg="core.urls")),
|
||||||
path(route="api/", view=api.urls),
|
path(route="api/", view=api.urls),
|
||||||
]
|
]
|
||||||
|
@ -1,8 +1,7 @@
|
|||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
from simple_history.admin import SimpleHistoryAdmin
|
from simple_history.admin import SimpleHistoryAdmin
|
||||||
|
|
||||||
from .models import DiscordSetting, Subscription
|
from .models import Webhook
|
||||||
|
|
||||||
# https://django-simple-history.readthedocs.io/en/latest/admin.html
|
# https://django-simple-history.readthedocs.io/en/latest/admin.html
|
||||||
admin.site.register(DiscordSetting, SimpleHistoryAdmin)
|
admin.site.register(Webhook, SimpleHistoryAdmin)
|
||||||
admin.site.register(Subscription, SimpleHistoryAdmin)
|
|
||||||
|
@ -1,15 +1,24 @@
|
|||||||
from django import forms
|
from django import forms
|
||||||
|
from django.core.validators import URLValidator
|
||||||
|
|
||||||
|
|
||||||
class DiscordSettingForm(forms.Form):
|
class DiscordSettingForm(forms.Form):
|
||||||
name = forms.CharField(
|
|
||||||
max_length=255,
|
|
||||||
label="Name",
|
|
||||||
required=True,
|
|
||||||
help_text="Friendly name for knowing where the notification goes to.",
|
|
||||||
)
|
|
||||||
webhook_url = forms.URLField(
|
webhook_url = forms.URLField(
|
||||||
label="Webhook URL",
|
label="Webhook URL",
|
||||||
required=True,
|
required=True,
|
||||||
help_text="The URL to the Discord webhook. The URL can be found by right-clicking on the channel and selecting 'Edit Channel', then 'Integrations', and 'Webhooks'.", # noqa: E501
|
validators=[
|
||||||
|
URLValidator(
|
||||||
|
schemes=["https"],
|
||||||
|
message="The URL must be a valid HTTPS URL.",
|
||||||
|
),
|
||||||
|
URLValidator(
|
||||||
|
regex=r"https://discord.com/api/webhooks/\d{18}/[a-zA-Z0-9_-]{68}",
|
||||||
|
message="The URL must be a valid Discord webhook URL.",
|
||||||
|
),
|
||||||
|
URLValidator(
|
||||||
|
regex=r"https://discordapp.com/api/webhooks/\d{18}/[a-zA-Z0-9_-]{68}",
|
||||||
|
message="The URL must be a valid Discord webhook URL.",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
help_text="The URL can be found by right-clicking on the channel and selecting 'Edit Channel', then 'Integrations', and 'Webhooks'.", # noqa: E501
|
||||||
)
|
)
|
||||||
|
@ -1,28 +1,26 @@
|
|||||||
from django.contrib.auth.models import User
|
from typing import Literal
|
||||||
|
|
||||||
|
import auto_prefetch
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from simple_history.models import HistoricalRecords
|
from simple_history.models import HistoricalRecords
|
||||||
|
|
||||||
from twitch_app.models import Game
|
from twitch_app.models import Game
|
||||||
|
|
||||||
|
|
||||||
class DiscordSetting(models.Model):
|
class Webhook(auto_prefetch.Model):
|
||||||
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
"""Webhooks to send notifications to."""
|
||||||
name = models.CharField(max_length=255)
|
|
||||||
webhook_url = models.URLField()
|
|
||||||
history = HistoricalRecords()
|
|
||||||
disabled = models.BooleanField(default=False)
|
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
|
||||||
|
|
||||||
def __str__(self) -> str:
|
url = models.URLField(unique=True)
|
||||||
return f"Discord: {self.user.username} - {self.name}"
|
|
||||||
|
|
||||||
|
|
||||||
class Subscription(models.Model):
|
|
||||||
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
|
||||||
game = models.ForeignKey(Game, on_delete=models.CASCADE)
|
game = models.ForeignKey(Game, on_delete=models.CASCADE)
|
||||||
created_at = models.DateTimeField(auto_now_add=True)
|
disabled = models.BooleanField(default=False)
|
||||||
|
added_at = models.DateTimeField(blank=True, null=True, auto_now_add=True)
|
||||||
|
modified_at = models.DateTimeField(blank=True, null=True, auto_now=True)
|
||||||
history = HistoricalRecords()
|
history = HistoricalRecords()
|
||||||
discord_webhook = models.ForeignKey(DiscordSetting, on_delete=models.CASCADE)
|
|
||||||
|
class Meta(auto_prefetch.Model.Meta):
|
||||||
|
verbose_name: str = "Webhook"
|
||||||
|
verbose_name_plural: str = "Webhooks"
|
||||||
|
ordering: tuple[Literal["url"]] = ("url",)
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def __str__(self) -> str:
|
||||||
return f"Subscription: {self.user.username} - {self.game.display_name} - {self.discord_webhook.name}"
|
return self.url
|
||||||
|
@ -1,54 +0,0 @@
|
|||||||
{% extends "base.html" %}
|
|
||||||
{% block content %}
|
|
||||||
<div class="container">
|
|
||||||
<h1 class="my-4">Add Discord Webhook</h1>
|
|
||||||
<form method="post" class="needs-validation" novalidate>
|
|
||||||
{% csrf_token %}
|
|
||||||
{{ form.non_field_errors }}
|
|
||||||
<div class="mb-3">
|
|
||||||
{{ form.name.errors }}
|
|
||||||
<label for="{{ form.name.id_for_label }}" class="form-label">{{ form.name.label }}</label>
|
|
||||||
<input type="text"
|
|
||||||
name="name"
|
|
||||||
maxlength="255"
|
|
||||||
required=""
|
|
||||||
class="form-control"
|
|
||||||
aria-describedby="id_name_helptext"
|
|
||||||
id="id_name">
|
|
||||||
<div class="form-text text-muted">{{ form.name.help_text }}</div>
|
|
||||||
</div>
|
|
||||||
<div class="mb-3">
|
|
||||||
{{ form.webhook_url.errors }}
|
|
||||||
<label for="{{ form.webhook_url.id_for_label }}" class="form-label">{{ form.webhook_url.label }}</label>
|
|
||||||
<input type="url"
|
|
||||||
name="webhook_url"
|
|
||||||
required=""
|
|
||||||
class="form-control"
|
|
||||||
aria-describedby="id_webhook_url_helptext"
|
|
||||||
id="id_webhook_url">
|
|
||||||
<div class="form-text text-muted">{{ form.webhook_url.help_text }}</div>
|
|
||||||
</div>
|
|
||||||
<button type="submit" class="btn btn-primary">Add Webhook</button>
|
|
||||||
</form>
|
|
||||||
<h2 class="mt-5">Webhooks</h2>
|
|
||||||
<ul class="list-group mt-3">
|
|
||||||
{% for webhook in webhooks %}
|
|
||||||
<li class="list-group-item d-flex justify-content-between align-items-center">
|
|
||||||
<div>
|
|
||||||
<a href="{{ webhook.webhook_url }}" target="_blank">{{ webhook.name }}</a>
|
|
||||||
<small class="text-muted">added on {{ webhook.created_at|date:"F j, Y, g:i a" }}</small>
|
|
||||||
</div>
|
|
||||||
<form method="post"
|
|
||||||
action="{% url 'core:delete_discord_webhook' %}"
|
|
||||||
class="mb-0">
|
|
||||||
{% csrf_token %}
|
|
||||||
<input type="hidden" name="webhook_id" value="{{ webhook.id }}">
|
|
||||||
<input type="hidden" name="webhook_name" value="{{ webhook.name }}">
|
|
||||||
<input type="hidden" name="webhook_url" value="{{ webhook.webhook_url }}">
|
|
||||||
<button type="submit" class="btn btn-sm btn-danger">Delete</button>
|
|
||||||
</form>
|
|
||||||
</li>
|
|
||||||
{% endfor %}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
{% endblock content %}
|
|
@ -1,5 +1,9 @@
|
|||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
|
<body data-bs-spy="scroll"
|
||||||
|
data-bs-target=".toc"
|
||||||
|
data-bs-offset="-200"
|
||||||
|
tabindex="0">
|
||||||
<div class="container mt-4">
|
<div class="container mt-4">
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col-lg-3">
|
<div class="col-lg-3">
|
||||||
@ -7,13 +11,12 @@
|
|||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<h5 class="card-title">Games</h5>
|
<h5 class="card-title">Games</h5>
|
||||||
<ul class="list-unstyled">
|
<div id="toc-list" class="list-group">
|
||||||
{% for game in games %}
|
{% for game in games %}
|
||||||
<li>
|
<a class="list-group-item list-group-item-action plain-text-item"
|
||||||
<a href="#game-{{ game.game_id }}" class="text-decoration-none">{{ game.display_name }}</a>
|
href="#game-{{ game.game_id }}">{{ game.display_name }}</a>
|
||||||
</li>
|
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</ul>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -37,23 +40,31 @@
|
|||||||
</h2>
|
</h2>
|
||||||
<div class="mt-auto">
|
<div class="mt-auto">
|
||||||
<div class="form-check form-switch">
|
<div class="form-check form-switch">
|
||||||
<input class="form-check-input" type="checkbox" role="switch" id="new">
|
<input class="form-check-input"
|
||||||
<label class="form-check-label" for="new">
|
type="checkbox"
|
||||||
|
role="switch"
|
||||||
|
id="new-{{ game.game_id }}">
|
||||||
|
<label class="form-check-label" for="new-{{ game.game_id }}">
|
||||||
Notify when new drop is found on <a href="https://www.twitch.tv/drops/campaigns">Twitch</a>
|
Notify when new drop is found on <a href="https://www.twitch.tv/drops/campaigns">Twitch</a>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-check form-switch">
|
<div class="form-check form-switch">
|
||||||
<input class="form-check-input" type="checkbox" role="switch" id="live">
|
<input class="form-check-input"
|
||||||
<label class="form-check-label" for="live">Notify when a drop starts</label>
|
type="checkbox"
|
||||||
|
role="switch"
|
||||||
|
id="live-{{ game.game_id }}">
|
||||||
|
<label class="form-check-label" for="live-{{ game.game_id }}">Notify when a drop starts</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{% for campaign in game.campaigns %}
|
{% for campaign in game.campaigns %}
|
||||||
{% if not forloop.first %}<br>{% endif %}
|
{% if not forloop.first %}<br>{% endif %}
|
||||||
<div class="mt-3">
|
<div class="mt-3">
|
||||||
<h3 class="h6">{{ campaign.name }}</h3>
|
<h3 class="h6">{{ campaign.name }}</h3>
|
||||||
<p class="mb-2 text-muted">Ends in: {{ campaign.end_at|timeuntil }}</p>
|
<p class="mb-2 text-muted">
|
||||||
|
Ends in: <abbr title="{{ campaign.start_at|date:'l d F H:i' }} - {{ campaign.end_at|date:'l d F H:i e' }}">{{ campaign.end_at|timeuntil }}</abbr>
|
||||||
|
</p>
|
||||||
{% if campaign.description != campaign.name %}
|
{% if campaign.description != campaign.name %}
|
||||||
{% if campaign.description|length|get_digit:"-1" > 100 %}
|
{% if campaign.description|length > 100 %}
|
||||||
<p>
|
<p>
|
||||||
<a class="btn btn-link p-0 text-muted"
|
<a class="btn btn-link p-0 text-muted"
|
||||||
data-bs-toggle="collapse"
|
data-bs-toggle="collapse"
|
||||||
@ -95,4 +106,17 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<script type="module">
|
||||||
|
const scrollSpy = new bootstrap.ScrollSpy(document.body, {
|
||||||
|
target: '.toc'
|
||||||
|
})
|
||||||
|
|
||||||
|
document.body.addEventListener('activate.bs.scrollspy', function (event) {
|
||||||
|
const activeItem = document.querySelector('.toc .active');
|
||||||
|
if (activeItem) {
|
||||||
|
activeItem.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
{% endblock content %}
|
{% endblock content %}
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
{% load socialaccount %}
|
|
||||||
<header class="d-flex justify-content-between align-items-center py-3 border-bottom">
|
<header class="d-flex justify-content-between align-items-center py-3 border-bottom">
|
||||||
<h1 class="h2">
|
<h1 class="h2">
|
||||||
<a href='{% url "core:index" %}' class="text-decoration-none nav-title">Twitch drops</a>
|
<a href='{% url "core:index" %}' class="text-decoration-none nav-title">Twitch drops</a>
|
||||||
@ -15,17 +14,8 @@
|
|||||||
<a class="nav-link" href="https://github.com/sponsors/TheLovinator1">Donate</a>
|
<a class="nav-link" href="https://github.com/sponsors/TheLovinator1">Donate</a>
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<a class="nav-link" href='{% url "core:add_discord_webhook" %}'>Webhooks</a>
|
<a class="nav-link" href='{% url "core:webhooks" %}'>Webhooks</a>
|
||||||
</li>
|
</li>
|
||||||
{% if user.is_authenticated %}
|
|
||||||
<li class="nav-item">
|
|
||||||
<a class="nav-link" href='{% url "account_logout" %}'>Logout</a>
|
|
||||||
</li>
|
|
||||||
{% else %}
|
|
||||||
<li class="nav-item">
|
|
||||||
<a class="nav-link" href='{% provider_login_url "twitch" %}'>Login</a>
|
|
||||||
</li>
|
|
||||||
{% endif %}
|
|
||||||
</ul>
|
</ul>
|
||||||
</nav>
|
</nav>
|
||||||
</header>
|
</header>
|
||||||
|
47
core/templates/webhooks.html
Normal file
47
core/templates/webhooks.html
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% block content %}
|
||||||
|
<div class="container">
|
||||||
|
<h1 class="my-4">Add Discord Webhook</h1>
|
||||||
|
<form method="post"
|
||||||
|
action="{% url 'core:add_webhook' %}"
|
||||||
|
class="needs-validation"
|
||||||
|
novalidate>
|
||||||
|
{% csrf_token %}
|
||||||
|
{{ form.non_field_errors }}
|
||||||
|
<div class="mb-3">
|
||||||
|
{{ form.webhook_url.errors }}
|
||||||
|
<label for="{{ form.webhook_url.id_for_label }}" class="form-label">{{ form.webhook_url.label }}</label>
|
||||||
|
<input type="url"
|
||||||
|
name="webhook_url"
|
||||||
|
required=""
|
||||||
|
class="form-control"
|
||||||
|
aria-describedby="id_webhook_url_helptext"
|
||||||
|
id="id_webhook_url">
|
||||||
|
<div class="form-text text-muted">{{ form.webhook_url.help_text }}</div>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-primary">Add Webhook</button>
|
||||||
|
</form>
|
||||||
|
<h2 class="mt-5">Webhooks</h2>
|
||||||
|
{% if webhooks %}
|
||||||
|
<ul class="list-group mt-3">
|
||||||
|
{% for webhook in webhooks %}
|
||||||
|
<li class="list-group-item d-flex justify-content-between align-items-center">
|
||||||
|
<div>
|
||||||
|
<a href="{{ webhook.webhook_url }}" target="_blank">{{ webhook.name }}</a>
|
||||||
|
<small class="text-muted">added on {{ webhook.created_at|date:"F j, Y, g:i a" }}</small>
|
||||||
|
</div>
|
||||||
|
<form method="post" action="" class="mb-0">
|
||||||
|
{% csrf_token %}
|
||||||
|
<input type="hidden" name="webhook_id" value="{{ webhook.id }}">
|
||||||
|
<input type="hidden" name="webhook_name" value="{{ webhook.name }}">
|
||||||
|
<input type="hidden" name="webhook_url" value="{{ webhook.webhook_url }}">
|
||||||
|
<button type="submit" class="btn btn-sm btn-danger">Delete</button>
|
||||||
|
</form>
|
||||||
|
</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
{% else %}
|
||||||
|
<p class="text-muted">No webhooks added yet.</p>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endblock content %}
|
26
core/urls.py
26
core/urls.py
@ -9,25 +9,19 @@ app_name: str = "core"
|
|||||||
|
|
||||||
urlpatterns: list[URLPattern | URLResolver] = [
|
urlpatterns: list[URLPattern | URLResolver] = [
|
||||||
path(route="", view=views.index, name="index"),
|
path(route="", view=views.index, name="index"),
|
||||||
path(route="test/", view=views.test_webhook, name="test"),
|
|
||||||
path(
|
|
||||||
route="add-discord-webhook/",
|
|
||||||
view=views.add_discord_webhook,
|
|
||||||
name="add_discord_webhook",
|
|
||||||
),
|
|
||||||
path(
|
|
||||||
route="delete_discord_webhook/",
|
|
||||||
view=views.delete_discord_webhook,
|
|
||||||
name="delete_discord_webhook",
|
|
||||||
),
|
|
||||||
path(
|
|
||||||
route="subscribe/",
|
|
||||||
view=views.subscription_create,
|
|
||||||
name="subscription_create",
|
|
||||||
),
|
|
||||||
path(
|
path(
|
||||||
route="games/",
|
route="games/",
|
||||||
view=views.GameView.as_view(),
|
view=views.GameView.as_view(),
|
||||||
name="games",
|
name="games",
|
||||||
),
|
),
|
||||||
|
path(
|
||||||
|
route="webhooks/",
|
||||||
|
view=views.Webhooks.as_view(),
|
||||||
|
name="webhooks",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
route="webhooks/add/",
|
||||||
|
view=views.add_webhook,
|
||||||
|
name="add_webhook",
|
||||||
|
),
|
||||||
]
|
]
|
||||||
|
298
core/views.py
298
core/views.py
@ -1,21 +1,17 @@
|
|||||||
import datetime
|
import datetime
|
||||||
import logging
|
import logging
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import TYPE_CHECKING
|
|
||||||
|
|
||||||
|
import httpx
|
||||||
from django.contrib import messages
|
from django.contrib import messages
|
||||||
from django.contrib.auth.decorators import login_required
|
|
||||||
from django.db.models.manager import BaseManager
|
|
||||||
from django.http import (
|
from django.http import (
|
||||||
HttpRequest,
|
HttpRequest,
|
||||||
HttpResponse,
|
HttpResponse,
|
||||||
)
|
)
|
||||||
from django.shortcuts import redirect, render
|
|
||||||
from django.template.response import TemplateResponse
|
from django.template.response import TemplateResponse
|
||||||
from django.views.generic import ListView
|
from django.views.decorators.http import require_POST
|
||||||
|
from django.views.generic import ListView, TemplateView
|
||||||
|
|
||||||
from core.discord import send
|
|
||||||
from core.models import DiscordSetting
|
|
||||||
from twitch_app.models import (
|
from twitch_app.models import (
|
||||||
DropBenefit,
|
DropBenefit,
|
||||||
DropCampaign,
|
DropCampaign,
|
||||||
@ -25,12 +21,6 @@ from twitch_app.models import (
|
|||||||
|
|
||||||
from .forms import DiscordSettingForm
|
from .forms import DiscordSettingForm
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from django.contrib.auth.base_user import AbstractBaseUser
|
|
||||||
from django.contrib.auth.models import AnonymousUser
|
|
||||||
from django.db.models.manager import BaseManager
|
|
||||||
from django.views.decorators.http import require_POST
|
|
||||||
|
|
||||||
logger: logging.Logger = logging.getLogger(__name__)
|
logger: logging.Logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -75,18 +65,13 @@ class GameContext:
|
|||||||
slug: str | None = None
|
slug: str | None = None
|
||||||
|
|
||||||
|
|
||||||
def index(request: HttpRequest) -> HttpResponse:
|
def fetch_games() -> list[Game]:
|
||||||
"""/ index page.
|
"""Fetch all games with necessary fields."""
|
||||||
|
return list(Game.objects.all().only("id", "image_url", "display_name", "slug"))
|
||||||
|
|
||||||
Args:
|
|
||||||
request: The request.
|
|
||||||
|
|
||||||
Returns:
|
def fetch_campaigns(game: Game) -> list[CampaignContext]:
|
||||||
HttpResponse: Returns the index page.
|
"""Fetch active campaigns for a given game."""
|
||||||
"""
|
|
||||||
list_of_games: list[GameContext] = []
|
|
||||||
|
|
||||||
for game in Game.objects.all().only("id", "image_url", "display_name", "slug"):
|
|
||||||
campaigns: list[CampaignContext] = []
|
campaigns: list[CampaignContext] = []
|
||||||
for campaign in DropCampaign.objects.filter(
|
for campaign in DropCampaign.objects.filter(
|
||||||
game=game,
|
game=game,
|
||||||
@ -103,30 +88,7 @@ def index(request: HttpRequest) -> HttpResponse:
|
|||||||
"start_at",
|
"start_at",
|
||||||
"end_at",
|
"end_at",
|
||||||
):
|
):
|
||||||
drops: list[DropContext] = []
|
drops = fetch_drops(campaign)
|
||||||
drop: TimeBasedDrop
|
|
||||||
for drop in campaign.time_based_drops.all().only(
|
|
||||||
"id",
|
|
||||||
"name",
|
|
||||||
"required_minutes_watched",
|
|
||||||
"required_subs",
|
|
||||||
):
|
|
||||||
benefit: DropBenefit | None = drop.benefits.first()
|
|
||||||
image_asset_url: str = (
|
|
||||||
benefit.image_asset_url
|
|
||||||
if benefit
|
|
||||||
else "https://static-cdn.jtvnw.net/twitch-quests-assets/CAMPAIGN/default.png"
|
|
||||||
)
|
|
||||||
drops.append(
|
|
||||||
DropContext(
|
|
||||||
drops_id=drop.id,
|
|
||||||
image_url=image_asset_url,
|
|
||||||
name=drop.name,
|
|
||||||
required_minutes_watched=drop.required_minutes_watched,
|
|
||||||
required_subs=drop.required_subs,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
if not drops:
|
if not drops:
|
||||||
logger.info("No drops found for %s", campaign.name)
|
logger.info("No drops found for %s", campaign.name)
|
||||||
continue
|
continue
|
||||||
@ -145,11 +107,44 @@ def index(request: HttpRequest) -> HttpResponse:
|
|||||||
drops=drops,
|
drops=drops,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
return campaigns
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_drops(campaign: DropCampaign) -> list[DropContext]:
|
||||||
|
"""Fetch drops for a given campaign."""
|
||||||
|
drops: list[DropContext] = []
|
||||||
|
drop: TimeBasedDrop
|
||||||
|
for drop in campaign.time_based_drops.all().only(
|
||||||
|
"id",
|
||||||
|
"name",
|
||||||
|
"required_minutes_watched",
|
||||||
|
"required_subs",
|
||||||
|
):
|
||||||
|
benefit: DropBenefit | None = drop.benefits.first()
|
||||||
|
|
||||||
|
image_asset_url: str = "https://static-cdn.jtvnw.net/twitch-quests-assets/CAMPAIGN/default.png"
|
||||||
|
if benefit and benefit.image_asset_url:
|
||||||
|
image_asset_url = benefit.image_asset_url
|
||||||
|
|
||||||
|
drops.append(
|
||||||
|
DropContext(
|
||||||
|
drops_id=drop.id,
|
||||||
|
image_url=image_asset_url,
|
||||||
|
name=drop.name,
|
||||||
|
required_minutes_watched=drop.required_minutes_watched,
|
||||||
|
required_subs=drop.required_subs,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return drops
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_game_contexts() -> list[GameContext]:
|
||||||
|
"""Prepare game contexts with their respective campaigns and drops."""
|
||||||
|
list_of_games: list[GameContext] = []
|
||||||
|
for game in fetch_games():
|
||||||
|
campaigns: list[CampaignContext] = fetch_campaigns(game)
|
||||||
if not campaigns:
|
if not campaigns:
|
||||||
logger.info("No campaigns found for %s", game.display_name)
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
list_of_games.append(
|
list_of_games.append(
|
||||||
GameContext(
|
GameContext(
|
||||||
game_id=game.id,
|
game_id=game.id,
|
||||||
@ -159,131 +154,106 @@ def index(request: HttpRequest) -> HttpResponse:
|
|||||||
twitch_url=game.twitch_url,
|
twitch_url=game.twitch_url,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
return list_of_games
|
||||||
|
|
||||||
context: dict[str, list[GameContext]] = {"games": list_of_games}
|
|
||||||
|
def sort_games_by_campaign_start(list_of_games: list[GameContext]) -> list[GameContext]:
|
||||||
|
"""Sort games by the start date of the first campaign and reverse the list so the latest games are first."""
|
||||||
|
if list_of_games and list_of_games[0].campaigns:
|
||||||
|
list_of_games.sort(
|
||||||
|
key=lambda x: x.campaigns[0].start_at
|
||||||
|
if x.campaigns and x.campaigns[0].start_at is not None
|
||||||
|
else datetime.datetime.min,
|
||||||
|
)
|
||||||
|
list_of_games.reverse()
|
||||||
|
return list_of_games
|
||||||
|
|
||||||
|
|
||||||
|
def index(request: HttpRequest) -> HttpResponse:
|
||||||
|
"""Render the index page."""
|
||||||
|
list_of_games: list[GameContext] = prepare_game_contexts()
|
||||||
|
sorted_list_of_games: list[GameContext] = sort_games_by_campaign_start(list_of_games)
|
||||||
|
|
||||||
return TemplateResponse(
|
return TemplateResponse(
|
||||||
request=request,
|
request=request,
|
||||||
template="index.html",
|
template="index.html",
|
||||||
context=context,
|
context={"games": sorted_list_of_games},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@require_POST
|
|
||||||
def test_webhook(request: HttpRequest) -> HttpResponse:
|
|
||||||
"""Test webhook.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
request: The request.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
HttpResponse: Returns a response.
|
|
||||||
"""
|
|
||||||
org_id: str | None = request.POST.get("org_id")
|
|
||||||
if not org_id:
|
|
||||||
return HttpResponse(status=400)
|
|
||||||
|
|
||||||
campaign: DropCampaign = DropCampaign.objects.get(id=org_id)
|
|
||||||
|
|
||||||
msg: str = f"Found new drop for {campaign.game.display_name}:\n{campaign.name}\n{campaign.description}"
|
|
||||||
send(msg.strip())
|
|
||||||
|
|
||||||
return HttpResponse(status=200)
|
|
||||||
|
|
||||||
|
|
||||||
@login_required
|
|
||||||
def add_discord_webhook(request: HttpRequest) -> HttpResponse:
|
|
||||||
"""Add Discord webhook."""
|
|
||||||
if request.method == "POST":
|
|
||||||
form = DiscordSettingForm(request.POST)
|
|
||||||
if form.is_valid():
|
|
||||||
DiscordSetting.objects.create(
|
|
||||||
user=request.user,
|
|
||||||
name=form.cleaned_data["name"],
|
|
||||||
webhook_url=form.cleaned_data["webhook_url"],
|
|
||||||
disabled=False,
|
|
||||||
)
|
|
||||||
|
|
||||||
messages.success(
|
|
||||||
request=request,
|
|
||||||
message=f"Webhook '{form.cleaned_data["name"]}' added ({form.cleaned_data["webhook_url"]})",
|
|
||||||
)
|
|
||||||
|
|
||||||
return redirect("core:add_discord_webhook")
|
|
||||||
else:
|
|
||||||
form = DiscordSettingForm()
|
|
||||||
|
|
||||||
webhooks: BaseManager[DiscordSetting] = DiscordSetting.objects.filter(
|
|
||||||
user=request.user,
|
|
||||||
)
|
|
||||||
|
|
||||||
return render(
|
|
||||||
request,
|
|
||||||
"add_discord_webhook.html",
|
|
||||||
{"form": form, "webhooks": webhooks},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@login_required
|
|
||||||
def delete_discord_webhook(request: HttpRequest) -> HttpResponse:
|
|
||||||
"""Delete Discord webhook."""
|
|
||||||
if request.method == "POST":
|
|
||||||
DiscordSetting.objects.filter(
|
|
||||||
id=request.POST.get("webhook_id"),
|
|
||||||
name=request.POST.get("webhook_name"),
|
|
||||||
webhook_url=request.POST.get("webhook_url"),
|
|
||||||
user=request.user,
|
|
||||||
).delete()
|
|
||||||
messages.success(
|
|
||||||
request=request,
|
|
||||||
message=f"Webhook '{request.POST.get("webhook_name")}' deleted ({request.POST.get("webhook_url")})",
|
|
||||||
)
|
|
||||||
|
|
||||||
return redirect("core:add_discord_webhook")
|
|
||||||
|
|
||||||
|
|
||||||
@login_required
|
|
||||||
def subscription_create(request: HttpRequest) -> HttpResponse:
|
|
||||||
"""Create subscription."""
|
|
||||||
if request.method == "POST":
|
|
||||||
game: Game = Game.objects.get(id=request.POST.get("game_id"))
|
|
||||||
user: AbstractBaseUser | AnonymousUser = request.user
|
|
||||||
webhook_id: str | None = request.POST.get("webhook_id")
|
|
||||||
if not webhook_id:
|
|
||||||
messages.error(request, "No webhook ID provided.")
|
|
||||||
return redirect("core:index")
|
|
||||||
|
|
||||||
if not user.is_authenticated:
|
|
||||||
messages.error(
|
|
||||||
request,
|
|
||||||
"You need to be logged in to create a subscription.",
|
|
||||||
)
|
|
||||||
return redirect("core:index")
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"Current webhooks: %s",
|
|
||||||
DiscordSetting.objects.filter(user=user).values_list("id", flat=True),
|
|
||||||
)
|
|
||||||
discord_webhook: DiscordSetting = DiscordSetting.objects.get(
|
|
||||||
id=int(webhook_id),
|
|
||||||
user=user,
|
|
||||||
)
|
|
||||||
|
|
||||||
messages.success(request, "Subscription created")
|
|
||||||
|
|
||||||
send(
|
|
||||||
message=f"This channel will now receive a notification when a new Twitch drop for **{game}** is available.", # noqa: E501
|
|
||||||
webhook_url=discord_webhook.webhook_url,
|
|
||||||
)
|
|
||||||
|
|
||||||
return redirect("core:index")
|
|
||||||
|
|
||||||
messages.error(request, "Failed to create subscription")
|
|
||||||
return redirect("core:index")
|
|
||||||
|
|
||||||
|
|
||||||
class GameView(ListView):
|
class GameView(ListView):
|
||||||
model = Game
|
model = Game
|
||||||
template_name: str = "games.html"
|
template_name: str = "games.html"
|
||||||
context_object_name: str = "games"
|
context_object_name: str = "games"
|
||||||
paginate_by = 100
|
paginate_by = 100
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class WebhookData:
|
||||||
|
"""The webhook data."""
|
||||||
|
|
||||||
|
name: str | None = None
|
||||||
|
url: str | None = None
|
||||||
|
status: str | None = None
|
||||||
|
response: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class Webhooks(TemplateView):
|
||||||
|
model = Game
|
||||||
|
template_name: str = "webhooks.html"
|
||||||
|
context_object_name: str = "webhooks"
|
||||||
|
paginate_by = 100
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs) -> dict[str, list[WebhookData] | DiscordSettingForm]: # noqa: ANN003, ARG002
|
||||||
|
"""Get the context data for the view."""
|
||||||
|
cookie: str = self.request.COOKIES.get("webhooks", "")
|
||||||
|
webhooks: list[str] = cookie.split(",")
|
||||||
|
webhooks = list(filter(None, webhooks))
|
||||||
|
|
||||||
|
webhook_respones: list[WebhookData] = []
|
||||||
|
|
||||||
|
# Use httpx to connect to webhook url and get the response
|
||||||
|
# Use the response to get name of the webhook
|
||||||
|
with httpx.Client() as client:
|
||||||
|
for webhook in webhooks:
|
||||||
|
our_webhook = WebhookData(name="Unknown", url=webhook, status="Failed", response="No response")
|
||||||
|
response: httpx.Response = client.get(url=webhook)
|
||||||
|
if response.is_success:
|
||||||
|
our_webhook.name = response.json()["name"]
|
||||||
|
our_webhook.status = "Success"
|
||||||
|
our_webhook.response = response.text
|
||||||
|
else:
|
||||||
|
our_webhook.status = "Failed"
|
||||||
|
our_webhook.response = response.text
|
||||||
|
|
||||||
|
# Add to the list of webhooks
|
||||||
|
webhook_respones.append(our_webhook)
|
||||||
|
|
||||||
|
return {"webhooks": webhook_respones, "form": DiscordSettingForm()}
|
||||||
|
|
||||||
|
|
||||||
|
@require_POST
|
||||||
|
def add_webhook(request: HttpRequest) -> HttpResponse:
|
||||||
|
"""Add a webhook to the list of webhooks."""
|
||||||
|
form = DiscordSettingForm(request.POST)
|
||||||
|
|
||||||
|
if form.is_valid():
|
||||||
|
webhook = str(form.cleaned_data["webhook"])
|
||||||
|
response = HttpResponse()
|
||||||
|
|
||||||
|
if "webhooks" in request.COOKIES:
|
||||||
|
cookie: str = request.COOKIES["webhooks"]
|
||||||
|
webhooks: list[str] = cookie.split(",")
|
||||||
|
webhooks = list(filter(None, webhooks))
|
||||||
|
if webhook in webhooks:
|
||||||
|
messages.error(request, "Webhook already exists.")
|
||||||
|
return response
|
||||||
|
webhooks.append(webhook)
|
||||||
|
webhook: str = ",".join(webhooks)
|
||||||
|
|
||||||
|
response.set_cookie(key="webhooks", value=webhook, max_age=60 * 60 * 24 * 365)
|
||||||
|
|
||||||
|
messages.info(request, "Webhook successfully added.")
|
||||||
|
return response
|
||||||
|
|
||||||
|
return HttpResponse(status=400, content="Invalid form data.")
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
discord-webhook
|
discord-webhook
|
||||||
django-allauth[socialaccount]
|
|
||||||
django-auto-prefetch
|
django-auto-prefetch
|
||||||
django-ninja
|
django-ninja
|
||||||
django-simple-history
|
django-simple-history
|
||||||
django>=0.0.0.dev0
|
django>=0.0.0.dev0
|
||||||
|
hishel
|
||||||
|
httpx
|
||||||
pillow
|
pillow
|
||||||
platformdirs
|
platformdirs
|
||||||
playwright
|
playwright
|
||||||
playwright
|
|
||||||
psycopg[binary]
|
psycopg[binary]
|
||||||
python-dotenv
|
python-dotenv
|
||||||
sentry-sdk[django]
|
sentry-sdk[django]
|
||||||
|
@ -59,17 +59,37 @@ a:hover {
|
|||||||
/* Table of games to the left */
|
/* Table of games to the left */
|
||||||
.toc {
|
.toc {
|
||||||
top: 1rem;
|
top: 1rem;
|
||||||
|
|
||||||
|
max-height: 80vh;
|
||||||
|
/* Adjust this value as needed */
|
||||||
|
overflow-y: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Checkboxes for subscribing to notifications */
|
/* Checkboxes for subscribing to notifications */
|
||||||
/* Checked */
|
/* Checked */
|
||||||
.form-check-input:checked {
|
.form-check-input:checked {
|
||||||
background-color: #af1548;
|
background-color: #af1548;
|
||||||
border-color: #111111;
|
border: 1px solid #af1548;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Unchecked */
|
/* Unchecked */
|
||||||
.form-check-input {
|
.form-check-input {
|
||||||
background-color: #0c0c0c;
|
background-color: #1b1b1b;
|
||||||
border-color: #111111;
|
}
|
||||||
|
|
||||||
|
.plain-text-item {
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
background-color: transparent;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.plain-text-item:hover {
|
||||||
|
color: inherit;
|
||||||
|
background-color: #af1548;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
.plain-text-item.active {
|
||||||
|
background-color: #af1548;
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,9 @@
|
|||||||
import auto_prefetch
|
import auto_prefetch
|
||||||
from django.contrib.humanize.templatetags.humanize import naturaltime
|
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.db.models import Value
|
from django.db.models import Value
|
||||||
from django.db.models.functions import (
|
from django.db.models.functions import (
|
||||||
Concat,
|
Concat,
|
||||||
)
|
)
|
||||||
from django.utils import timezone
|
|
||||||
from simple_history.models import HistoricalRecords
|
from simple_history.models import HistoricalRecords
|
||||||
|
|
||||||
|
|
||||||
@ -113,10 +111,6 @@ class TimeBasedDrop(auto_prefetch.Model):
|
|||||||
ordering = ("name",)
|
ordering = ("name",)
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def __str__(self) -> str:
|
||||||
if self.end_at:
|
|
||||||
if self.end_at < timezone.now():
|
|
||||||
return f"{self.benefits.first()} - {self.name} - Ended {naturaltime(self.end_at)}"
|
|
||||||
return f"{self.benefits.first()} - {self.name} - Ends in {naturaltime(self.end_at)}"
|
|
||||||
return f"{self.benefits.first()} - {self.name}"
|
return f"{self.benefits.first()} - {self.name}"
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user