Compare commits

...

10 Commits

Author SHA1 Message Date
dependabot[bot]
3d70be0de2
Merge 5fd8d7a217 into aff1cc0591 2023-12-08 01:45:17 +03:00
dependabot[bot]
aff1cc0591
Bump actions/setup-python from 4 to 5 (#214)
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 4 to 5.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-08 01:43:00 +03:00
dependabot[bot]
b52366d9a8
Bump traefik from 2.10.1 to 2.10.7 in /compose/production/traefik (#215)
Bumps traefik from 2.10.1 to 2.10.7.

---
updated-dependencies:
- dependency-name: traefik
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-08 01:42:48 +03:00
80a1b2b554 added like songs updated tests 2023-12-08 01:38:39 +03:00
8fd1d55f08 minor fixes and updates 2023-12-07 17:55:23 +03:00
43aeb2290d updated allauth login 2023-12-07 12:49:58 +03:00
e38888e411 updated allauth 2023-12-07 12:07:33 +03:00
957d748647 updated allauth 2023-12-07 03:36:49 +03:00
b9302f16a8 updated mail 2023-12-07 03:13:40 +03:00
f57472f1f3 updated mail 2023-12-07 02:52:24 +03:00
19 changed files with 370 additions and 74 deletions

View File

@ -7,6 +7,7 @@ DJANGO_READ_DOT_ENV_FILE=no
# ------------------------------------------------------------------------------
REDIS_URL=redis://redis:6379/1
REDIS_CACHE=rediscache://redis:6379/1
REDIS_CACHE_URL=redis://redis:6379/1
CELERY_BROKER_URL=redis://redis:6379/0
# Celery

View File

@ -49,7 +49,7 @@ jobs:
- name: Install poetry
run: pipx install poetry
- uses: actions/setup-python@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
cache: 'poetry'

View File

@ -10,3 +10,10 @@ def has_permission(self, request, view):
or request.user
and get_object_user(view.get_object()) == request.user
)
class IsAdminOrReadOnly(BasePermission):
def has_permission(self, request, view):
return bool(
request.method in SAFE_METHODS or request.user and request.user.is_staff
)

View File

@ -56,6 +56,10 @@ class Meta:
class ListSongSerializer(SetUserModelSerializer):
album = serializers.CharField(source="album.name", read_only=True)
liked = serializers.SerializerMethodField(method_name="get_liked")
def get_liked(self, obj):
return obj.id in self.context["likes_ids"]
class Meta:
model = Song

View File

@ -1,13 +1,28 @@
from rest_framework import generics, permissions
from akarpov.common.api.permissions import IsCreatorOrReadOnly
from akarpov.common.api.pagination import StandardResultsSetPagination
from akarpov.common.api.permissions import IsAdminOrReadOnly, IsCreatorOrReadOnly
from akarpov.music.api.serializers import (
FullPlaylistSerializer,
ListSongSerializer,
PlaylistSerializer,
SongSerializer,
)
from akarpov.music.models import Playlist, Song
from akarpov.music.models import Playlist, Song, SongUserRating
class LikedSongsContextMixin(generics.GenericAPIView):
def get_serializer_context(self):
context = super().get_serializer_context()
if self.request.user.is_authenticated:
context["likes_ids"] = (
SongUserRating.objects.cache()
.filter(user=self.request.user, like=True)
.values_list("song_id", flat=True)
)
else:
context["likes_ids"] = []
return context
class ListCreatePlaylistAPIView(generics.ListCreateAPIView):
@ -18,7 +33,9 @@ def get_queryset(self):
return Playlist.objects.filter(creator=self.request.user)
class RetrieveUpdateDestroyPlaylistAPIView(generics.RetrieveUpdateDestroyAPIView):
class RetrieveUpdateDestroyPlaylistAPIView(
LikedSongsContextMixin, generics.RetrieveUpdateDestroyAPIView
):
lookup_field = "slug"
lookup_url_kwarg = "slug"
permission_classes = [IsCreatorOrReadOnly]
@ -34,12 +51,23 @@ def get_object(self):
return self.object
class ListCreateSongAPIView(generics.ListCreateAPIView):
class ListCreateSongAPIView(LikedSongsContextMixin, generics.ListCreateAPIView):
serializer_class = ListSongSerializer
permission_classes = [IsCreatorOrReadOnly]
permission_classes = [IsAdminOrReadOnly]
pagination_class = StandardResultsSetPagination
def get_queryset(self):
return Song.objects.all()
if self.request.user.is_authenticated:
return (
Song.objects.exclude(
id__in=SongUserRating.objects.filter(
user=self.request.user
).values_list("song_id", flat=True)
)
.prefetch_related("authors")
.select_related("album")
)
return Song.objects.all().prefetch_related("authors").select_related("album")
class RetrieveUpdateDestroySongAPIView(generics.RetrieveUpdateDestroyAPIView):
@ -56,3 +84,21 @@ def get_object(self):
if not self.object:
self.object = super().get_object()
return self.object
class ListLikedSongsAPIView(generics.ListAPIView):
serializer_class = ListSongSerializer
pagination_class = StandardResultsSetPagination
authentication_classes = [permissions.IsAuthenticated]
def get_queryset(self):
return (
Song.objects.cache()
.filter(
id__in=self.request.user.song_likes.objects.cache()
.all()
.values_list("song_id", flat=True)
)
.prefetch_related("authors")
.select_related("album")
)

View File

@ -0,0 +1,56 @@
# Generated by Django 4.2.7 on 2023-12-07 22:36
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("music", "0009_alter_songinque_name_alter_songinque_status"),
]
operations = [
migrations.AddField(
model_name="song",
name="likes",
field=models.IntegerField(default=0),
),
migrations.CreateModel(
name="SongUserRating",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("like", models.BooleanField(default=True)),
("created", models.DateTimeField(auto_now_add=True)),
(
"song",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="user_likes",
to="music.song",
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="song_likes",
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"ordering": ["-created"],
"unique_together": {("song", "user")},
},
),
]

View File

@ -43,6 +43,7 @@ class Song(BaseImageModel, ShortLinkModel):
"users.User", related_name="songs", on_delete=models.SET_NULL, null=True
)
meta = models.JSONField(blank=True, null=True)
likes = models.IntegerField(default=0)
def get_absolute_url(self):
return reverse("music:song", kwargs={"slug": self.slug})
@ -128,3 +129,21 @@ class RadioSong(models.Model):
start = models.DateTimeField(auto_now=True)
slug = models.SlugField(unique=True)
song = models.ForeignKey("Song", related_name="radio", on_delete=models.CASCADE)
class SongUserRating(models.Model):
song = models.ForeignKey(
"Song", related_name="user_likes", on_delete=models.PROTECT
)
user = models.ForeignKey(
"users.User", related_name="song_likes", on_delete=models.CASCADE
)
like = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.user} {self.song} {'like' if self.like else 'dislike'}"
class Meta:
unique_together = ["song", "user"]
ordering = ["-created"]

View File

@ -1,9 +1,9 @@
import os
from django.db.models.signals import post_delete, post_save
from django.db.models.signals import post_delete, post_save, pre_save
from django.dispatch import receiver
from akarpov.music.models import Song
from akarpov.music.models import Song, SongUserRating
@receiver(post_delete, sender=Song)
@ -16,3 +16,21 @@ def auto_delete_file_on_delete(sender, instance, **kwargs):
@receiver(post_save)
def send_que_status(sender, instance, created, **kwargs):
...
@receiver(pre_save, sender=SongUserRating)
def create_or_update_rating(sender, instance: SongUserRating, **kwargs):
song = instance.song
if instance.pk:
previous = SongUserRating.objects.get(pk=instance.pk)
if previous.like != instance.like:
if instance.like:
song.likes += 2
else:
song.likes -= 2
else:
if instance.like:
song.likes += 1
else:
song.likes -= 1
song.save(update_fields=["likes"])

View File

@ -531,3 +531,37 @@ p {
.nav-active {
color: white;
}
.username {
max-width: 120px; /* Adjust as needed */
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.username:hover {
text-decoration: underline;
cursor: pointer;
}
/* Tooltip CSS */
.username:hover::after {
content: attr(title);
position: absolute;
bottom: -20px;
left: 50%;
transform: translateX(-50%);
background-color: black;
color: white;
padding: 5px;
border-radius: 5px;
font-size: smaller;
white-space: nowrap;
}
/* Responsive font size */
@media (max-width: 600px) {
.username {
font-size: smaller;
}
}

View File

@ -1 +1,29 @@
/* Project specific Javascript goes here. */
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function timeSince(date) {
let seconds = Math.floor((new Date() - date) / 1000);
let interval = seconds / 31536000;
if (interval > 1) {
return Math.floor(interval) + " years";
}
interval = seconds / 2592000;
if (interval > 1) {
return Math.floor(interval) + " months";
}
interval = seconds / 86400;
if (interval > 1) {
return Math.floor(interval) + " days";
}
interval = seconds / 3600;
if (interval > 1) {
return Math.floor(interval) + " hours";
}
interval = seconds / 60;
if (interval > 1) {
return Math.floor(interval) + " minutes";
}
return Math.floor(seconds) + " seconds";
}

View File

@ -68,11 +68,11 @@
<i class="fs-5 bi-folder-fill"></i><span class="ms-1 d-none d-sm-inline">Files</span></a>
</li>
{% endif %}
<li class="dropdown">
<a href="#" class="text-muted nav-link dropdown-toggle px-sm-0 px-1" id="dropdown" data-bs-toggle="dropdown" aria-expanded="false">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle text-muted px-sm-0 px-1" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<i class="fs-5 bi-terminal-fill"></i><span class="ms-1 d-none d-sm-inline">Apps</span>
</a>
<ul class="dropdown-menu dropdown-menu-dark text-small shadow" aria-labelledby="dropdown">
<ul class="dropdown-menu dropdown-menu-dark text-small shadow" aria-labelledby="navbarDropdownMenuLink">
<li><a class="dropdown-item {% active_link 'tools:qr:create' %}" href="{% url 'tools:qr:create' %}">QR generator</a></li>
<li><a class="dropdown-item {% active_link 'tools:uuid:main' %}" href="{% url 'tools:uuid:main' %}">UUID tools</a></li>
<li><a class="dropdown-item {% active_link 'tools:shortener:create' %}" href="{% url 'tools:shortener:create' %}">URL shortcuter</a></li>
@ -88,7 +88,7 @@
{% if request.user.is_authenticated %}
<a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" id="dropdownUser1" data-bs-toggle="dropdown" aria-expanded="false">
{% if request.user.image_cropped %}<img src="{{ request.user.image_cropped.url }}" alt="hugenerd" width="28" height="28" class="rounded-circle">{% endif %}
<span class="d-none d-sm-inline mx-1">{{ request.user.username }}</span>
<span class="d-none d-sm-inline mx-1 username" title="{{ request.user.username }}">{{ request.user.username }}</span>
</a>
<ul class="dropdown-menu dropdown-menu-dark text-small shadow" aria-labelledby="dropdownUser1">
<li><a class="dropdown-item {% active_link 'users:update' %}" href="{% url 'users:update' %}">Settings</a></li>
@ -156,35 +156,6 @@
let notification_socket = new WebSocket(socketPath);
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function timeSince(date) {
let seconds = Math.floor((new Date() - date) / 1000);
let interval = seconds / 31536000;
if (interval > 1) {
return Math.floor(interval) + " years";
}
interval = seconds / 2592000;
if (interval > 1) {
return Math.floor(interval) + " months";
}
interval = seconds / 86400;
if (interval > 1) {
return Math.floor(interval) + " days";
}
interval = seconds / 3600;
if (interval > 1) {
return Math.floor(interval) + " hours";
}
interval = seconds / 60;
if (interval > 1) {
return Math.floor(interval) + " minutes";
}
return Math.floor(seconds) + " seconds";
}
const toastContainer = document.getElementById('toastContainer')

View File

@ -0,0 +1,26 @@
{% extends "socialaccount/base.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block head_title %}{% trans "Signup" %}{% endblock %}
{% block content %}
<h1>{% trans "Sign Up" %}</h1>
<p>{% blocktrans with provider_name=account.get_provider.name site_name=site.name %}You are about to use your {{provider_name}} account to login to
{{site_name}}. As a final step, please complete the following form:{% endblocktrans %}</p>
<form class="signup" id="signup_form" method="post" action="{% url 'socialaccount_signup' %}">
{% csrf_token %}
{{ form.media }}
{% for field in form %}
{{ field|as_crispy_field }}
{% endfor %}
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
{% endif %}
<button class="btn btn-success" type="submit">{% trans "Sign Up" %} &raquo;</button>
</form>
{% endblock %}

View File

@ -0,0 +1,36 @@
from django.test import TestCase
from akarpov.users.forms import UserAdminCreationForm
class UserFormTest(TestCase):
def test_valid_form(self):
form = UserAdminCreationForm(
data={
"username": "testuser",
"password1": "P4sSw0rD!",
"password2": "P4sSw0rD!",
}
)
self.assertTrue(form.is_valid())
def test_insecure_password(self):
form = UserAdminCreationForm(
data={
"username": "testuser",
"password1": "password",
"password2": "password",
}
)
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1)
self.assertEqual(
form.errors["password2"],
["This password is too common."],
)
def test_invalid_form(self):
form = UserAdminCreationForm(data={})
self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 3)
self.assertEqual(form.errors["username"], ["This field is required."])

View File

@ -1,4 +1,11 @@
from akarpov.files.consts import USER_INITIAL_FILE_UPLOAD
from akarpov.users.models import User
def test_user_creation(user_factory):
user = user_factory(username="testuser", email="test@example.com")
assert isinstance(user, User)
assert user.__str__() == user.username
def test_user_create(user_factory):

View File

@ -0,0 +1,18 @@
from django.test import Client, TestCase
from django.urls import reverse
from akarpov.users.tests.factories import UserFactory
class UserViewTest(TestCase):
def setUp(self):
self.client = Client()
self.user = UserFactory()
def test_user_detail_view(self):
self.client.force_login(self.user)
response = self.client.get(
reverse("users:detail", kwargs={"username": self.user.username})
)
self.assertEqual(response.status_code, 200)
self.assertContains(response, self.user.username)

View File

@ -1,4 +1,4 @@
FROM traefik:2.10.1
FROM traefik:2.10.7
RUN mkdir -p /etc/traefik/acme \
&& touch /etc/traefik/acme/acme.json \
&& chmod 600 /etc/traefik/acme/acme.json

View File

@ -54,7 +54,15 @@
# CACHES
# ------------------------------------------------------------------------------
CACHES = {"default": env.cache_url("REDIS_CACHE")}
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": env("REDIS_CACHE_URL", default="redis://localhost:6379/1"),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
}
}
CACHE_MIDDLEWARE_KEY_PREFIX = "cache_middleware"
CACHE_MIDDLEWARE_SECONDS = 0
CACHE_TTL = 60 * 10
@ -66,8 +74,9 @@
"blog.post": {"ops": ("fetch", "get"), "timeout": 20 * 15},
"themes.theme": {"ops": ("fetch", "get"), "timeout": 60 * 60},
"gallery.*": {"ops": "all", "timeout": 60 * 15},
"files.*": {"ops": ("fetch", "get"), "timeout": 60 * 5},
"files.*": {"ops": ("fetch", "get"), "timeout": 60},
"auth.permission": {"ops": "all", "timeout": 60 * 15},
"music.*": {"ops": "all", "timeout": 60 * 15},
}
CACHEOPS_REDIS = env.str("REDIS_URL")
@ -150,9 +159,9 @@
ALLAUTH_PROVIDERS = [
"allauth.socialaccount.providers.github",
# "allauth.socialaccount.providers.google",
# "allauth.socialaccount.providers.telegram",
# "allauth.socialaccount.providers.yandex",
"allauth.socialaccount.providers.google",
# "allauth.socialaccount.providers.telegram", TODO
# "allauth.socialaccount.providers.yandex", TODO
]
LOCAL_APPS = [
@ -308,6 +317,17 @@
# EMAIL
# ------------------------------------------------------------------------------
"""
host: EMAIL_HOST
port: EMAIL_PORT
username: EMAIL_HOST_USER
password: EMAIL_HOST_PASSWORD
use_tls: EMAIL_USE_TLS
use_ssl: EMAIL_USE_SSL
timeout: EMAIL_TIMEOUT
ssl_keyfile: EMAIL_SSL_KEYFILE
ssl_certfile: EMAIL_SSL_CERTFILE
"""
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = env(
"DJANGO_EMAIL_BACKEND",
@ -316,11 +336,11 @@
# https://docs.djangoproject.com/en/dev/ref/settings/#email-timeout
EMAIL_TIMEOUT = 5
EMAIL_HOST_PASSWORD = env(
"EMAIL_PASSWORD",
"EMAIL_HOST_PASSWORD",
default="",
)
EMAIL_HOST_USER = env(
"EMAIL_USER",
"EMAIL_HOST_USER",
default="",
)
EMAIL_USE_SSL = env(
@ -328,6 +348,13 @@
default=False,
)
EMAIL_HOST = env("EMAIL_HOST", default="mailhog")
# https://docs.djangoproject.com/en/dev/ref/settings/#email-port
EMAIL_PORT = env("EMAIL_PORT", default="1025")
EMAIL_FROM = env("EMAIL_FROM", default="noreply@akarpov.ru")
DEFAULT_FROM_EMAIL = env("EMAIL_FROM", default="noreply@akarpov.ru")
SERVER_EMAIL = env("EMAIL_FROM", default="noreply@akarpov.ru")
# ADMIN
# ------------------------------------------------------------------------------
# Django Admin URL.
@ -477,6 +504,7 @@
},
},
}
ACCOUNT_DEFAULT_HTTP_PROTOCOL = env("HTTP_PROTOCOL", default="http")
# django-rest-framework
# -------------------------------------------------------------------------------
@ -612,3 +640,6 @@
ELASTICSEARCH_DSL = {
"default": {"hosts": env("ELASTIC_SEARCH", default="http://127.0.0.1:9200/")},
}
USE_DEBUG_TOOLBAR = False

View File

@ -15,14 +15,6 @@
ALLOWED_HOSTS = ["*"]
CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1", "https://*.akarpov.ru"]
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-host
EMAIL_HOST = env("EMAIL_HOST", default="mailhog")
# https://docs.djangoproject.com/en/dev/ref/settings/#email-port
EMAIL_PORT = env("EMAIL_PORT", default="1025")
EMAIL_FROM = env("EMAIL_FROM", default="noreply@akarpov.ru")
# WhiteNoise
# ------------------------------------------------------------------------------
# http://whitenoise.evans.io/en/latest/django.html#using-whitenoise-in-development
@ -32,17 +24,19 @@
# django-debug-toolbar
# ------------------------------------------------------------------------------
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#prerequisites
INSTALLED_APPS += ["debug_toolbar"] # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#middleware
MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"] # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/configuration.html#debug-toolbar-config
DEBUG_TOOLBAR_CONFIG = {
USE_DEBUG_TOOLBAR = DEBUG and not env.bool("USE_DOCKER", default=False)
if USE_DEBUG_TOOLBAR:
INSTALLED_APPS += ["debug_toolbar"] # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#middleware
MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"] # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/configuration.html#debug-toolbar-config
DEBUG_TOOLBAR_CONFIG = {
"DISABLE_PANELS": ["debug_toolbar.panels.redirects.RedirectsPanel"],
"SHOW_TEMPLATE_CONTEXT": True,
}
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#internal-ips
INTERNAL_IPS = ["127.0.0.1", "10.0.2.2"]
if env("USE_DOCKER") == "yes":
}
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#internal-ips
INTERNAL_IPS = ["127.0.0.1", "10.0.2.2"]
if env("USE_DOCKER") == "yes":
import socket
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())

View File

@ -68,7 +68,7 @@
),
]
if settings.DEBUG:
if settings.USE_DEBUG_TOOLBAR:
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [