Compare commits

...

3 Commits

Author SHA1 Message Date
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
12 changed files with 225 additions and 10 deletions

View File

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

View File

@ -10,3 +10,10 @@ def has_permission(self, request, view):
or request.user or request.user
and get_object_user(view.get_object()) == 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): class ListSongSerializer(SetUserModelSerializer):
album = serializers.CharField(source="album.name", read_only=True) 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: class Meta:
model = Song model = Song

View File

@ -1,13 +1,28 @@
from rest_framework import generics, permissions 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 ( from akarpov.music.api.serializers import (
FullPlaylistSerializer, FullPlaylistSerializer,
ListSongSerializer, ListSongSerializer,
PlaylistSerializer, PlaylistSerializer,
SongSerializer, 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): class ListCreatePlaylistAPIView(generics.ListCreateAPIView):
@ -18,7 +33,9 @@ def get_queryset(self):
return Playlist.objects.filter(creator=self.request.user) return Playlist.objects.filter(creator=self.request.user)
class RetrieveUpdateDestroyPlaylistAPIView(generics.RetrieveUpdateDestroyAPIView): class RetrieveUpdateDestroyPlaylistAPIView(
LikedSongsContextMixin, generics.RetrieveUpdateDestroyAPIView
):
lookup_field = "slug" lookup_field = "slug"
lookup_url_kwarg = "slug" lookup_url_kwarg = "slug"
permission_classes = [IsCreatorOrReadOnly] permission_classes = [IsCreatorOrReadOnly]
@ -34,12 +51,23 @@ def get_object(self):
return self.object return self.object
class ListCreateSongAPIView(generics.ListCreateAPIView): class ListCreateSongAPIView(LikedSongsContextMixin, generics.ListCreateAPIView):
serializer_class = ListSongSerializer serializer_class = ListSongSerializer
permission_classes = [IsCreatorOrReadOnly] permission_classes = [IsAdminOrReadOnly]
pagination_class = StandardResultsSetPagination
def get_queryset(self): 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): class RetrieveUpdateDestroySongAPIView(generics.RetrieveUpdateDestroyAPIView):
@ -56,3 +84,21 @@ def get_object(self):
if not self.object: if not self.object:
self.object = super().get_object() self.object = super().get_object()
return self.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 "users.User", related_name="songs", on_delete=models.SET_NULL, null=True
) )
meta = models.JSONField(blank=True, null=True) meta = models.JSONField(blank=True, null=True)
likes = models.IntegerField(default=0)
def get_absolute_url(self): def get_absolute_url(self):
return reverse("music:song", kwargs={"slug": self.slug}) return reverse("music:song", kwargs={"slug": self.slug})
@ -128,3 +129,21 @@ class RadioSong(models.Model):
start = models.DateTimeField(auto_now=True) start = models.DateTimeField(auto_now=True)
slug = models.SlugField(unique=True) slug = models.SlugField(unique=True)
song = models.ForeignKey("Song", related_name="radio", on_delete=models.CASCADE) 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 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 django.dispatch import receiver
from akarpov.music.models import Song from akarpov.music.models import Song, SongUserRating
@receiver(post_delete, sender=Song) @receiver(post_delete, sender=Song)
@ -16,3 +16,21 @@ def auto_delete_file_on_delete(sender, instance, **kwargs):
@receiver(post_save) @receiver(post_save)
def send_que_status(sender, instance, created, **kwargs): 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

@ -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.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): 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 \ RUN mkdir -p /etc/traefik/acme \
&& touch /etc/traefik/acme/acme.json \ && touch /etc/traefik/acme/acme.json \
&& chmod 600 /etc/traefik/acme/acme.json && chmod 600 /etc/traefik/acme/acme.json

View File

@ -76,6 +76,7 @@
"gallery.*": {"ops": "all", "timeout": 60 * 15}, "gallery.*": {"ops": "all", "timeout": 60 * 15},
"files.*": {"ops": ("fetch", "get"), "timeout": 60}, "files.*": {"ops": ("fetch", "get"), "timeout": 60},
"auth.permission": {"ops": "all", "timeout": 60 * 15}, "auth.permission": {"ops": "all", "timeout": 60 * 15},
"music.*": {"ops": "all", "timeout": 60 * 15},
} }
CACHEOPS_REDIS = env.str("REDIS_URL") CACHEOPS_REDIS = env.str("REDIS_URL")
@ -639,3 +640,6 @@
ELASTICSEARCH_DSL = { ELASTICSEARCH_DSL = {
"default": {"hosts": env("ELASTIC_SEARCH", default="http://127.0.0.1:9200/")}, "default": {"hosts": env("ELASTIC_SEARCH", default="http://127.0.0.1:9200/")},
} }
USE_DEBUG_TOOLBAR = False