From 80a1b2b554baf7133b7ac6ad0ffb79441f9c9ef8 Mon Sep 17 00:00:00 2001 From: Alexander-D-Karpov Date: Fri, 8 Dec 2023 01:38:39 +0300 Subject: [PATCH] added like songs updated tests --- akarpov/common/api/permissions.py | 7 +++ akarpov/music/api/serializers.py | 4 ++ akarpov/music/api/views.py | 58 +++++++++++++++++-- .../0010_song_likes_songuserrating.py | 56 ++++++++++++++++++ akarpov/music/models.py | 19 ++++++ akarpov/music/signals.py | 22 ++++++- akarpov/users/tests/test_forms.py | 36 ++++++++++++ akarpov/users/tests/test_models.py | 7 +++ akarpov/users/tests/test_views.py | 18 ++++++ config/settings/base.py | 4 ++ 10 files changed, 223 insertions(+), 8 deletions(-) create mode 100644 akarpov/music/migrations/0010_song_likes_songuserrating.py create mode 100644 akarpov/users/tests/test_forms.py create mode 100644 akarpov/users/tests/test_views.py diff --git a/akarpov/common/api/permissions.py b/akarpov/common/api/permissions.py index 31c34ff..dfc1836 100644 --- a/akarpov/common/api/permissions.py +++ b/akarpov/common/api/permissions.py @@ -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 + ) diff --git a/akarpov/music/api/serializers.py b/akarpov/music/api/serializers.py index 95548bd..336dde1 100644 --- a/akarpov/music/api/serializers.py +++ b/akarpov/music/api/serializers.py @@ -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 diff --git a/akarpov/music/api/views.py b/akarpov/music/api/views.py index a3f0f50..b9d3de3 100644 --- a/akarpov/music/api/views.py +++ b/akarpov/music/api/views.py @@ -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") + ) diff --git a/akarpov/music/migrations/0010_song_likes_songuserrating.py b/akarpov/music/migrations/0010_song_likes_songuserrating.py new file mode 100644 index 0000000..eb154ef --- /dev/null +++ b/akarpov/music/migrations/0010_song_likes_songuserrating.py @@ -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")}, + }, + ), + ] diff --git a/akarpov/music/models.py b/akarpov/music/models.py index ace73fc..aa8d9e7 100644 --- a/akarpov/music/models.py +++ b/akarpov/music/models.py @@ -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"] diff --git a/akarpov/music/signals.py b/akarpov/music/signals.py index 006232e..95cb866 100644 --- a/akarpov/music/signals.py +++ b/akarpov/music/signals.py @@ -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"]) diff --git a/akarpov/users/tests/test_forms.py b/akarpov/users/tests/test_forms.py new file mode 100644 index 0000000..6bfd3fa --- /dev/null +++ b/akarpov/users/tests/test_forms.py @@ -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."]) diff --git a/akarpov/users/tests/test_models.py b/akarpov/users/tests/test_models.py index dbb31ac..4b72dd4 100644 --- a/akarpov/users/tests/test_models.py +++ b/akarpov/users/tests/test_models.py @@ -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): diff --git a/akarpov/users/tests/test_views.py b/akarpov/users/tests/test_views.py new file mode 100644 index 0000000..6deae53 --- /dev/null +++ b/akarpov/users/tests/test_views.py @@ -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) diff --git a/config/settings/base.py b/config/settings/base.py index e42c4d1..a825c11 100644 --- a/config/settings/base.py +++ b/config/settings/base.py @@ -76,6 +76,7 @@ "gallery.*": {"ops": "all", "timeout": 60 * 15}, "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") @@ -639,3 +640,6 @@ ELASTICSEARCH_DSL = { "default": {"hosts": env("ELASTIC_SEARCH", default="http://127.0.0.1:9200/")}, } + + +USE_DEBUG_TOOLBAR = False