Merge remote-tracking branch 'origin/master'

This commit is contained in:
Stepan Fedyanin 2024-06-14 17:34:35 +05:00
commit 4e3ceb30ce
35 changed files with 77 additions and 52 deletions

1
.gitignore vendored
View File

@ -17,3 +17,4 @@ server/proj/conf/settings/__init__.py
__pycache__ __pycache__
media/ media/
env/ env/
db.sqlite3

View File

@ -10,7 +10,7 @@ from rest_framework.permissions import AllowAny
class FetchAndServeFile(ViewSet): class FetchAndServeFile(ViewSet):
#http://82.97.242.49:10084/api/station/it-radio/file/5196269acd9d54e86297557a6d9a7aab/ #http://82.97.242.49:10084/api/station/it-radio/file/5196269acd9d54e86297557a6d9a7aab/
def list(self, request): def list(self, request):
file_url = f"http://82.97.242.49:10084/api/station/it-radio/file/fc6377b2dae75d29358783bc/play" file_url = f"http://82.97.242.49:10084/api/station/it-radio/file/fc6377b2dae75d29358783bc"
api_key = "49226d3488aac3f5:18d88659c6c1c5e131a0ce0a94d55235" api_key = "49226d3488aac3f5:18d88659c6c1c5e131a0ce0a94d55235"
headers = { headers = {
@ -19,8 +19,9 @@ class FetchAndServeFile(ViewSet):
try: try:
response = requests.get(file_url, headers=headers) response = requests.get(file_url, headers=headers)
response.raise_for_status()
response.raise_for_status()
print(response.content)
# Create a response with the appropriate content type and headers # Create a response with the appropriate content type and headers
file_response = HttpResponse(response.content, content_type='audio/mpeg') file_response = HttpResponse(response.content, content_type='audio/mpeg')
file_response['Content-Disposition'] = 'attachment; filename="output.mp3"' file_response['Content-Disposition'] = 'attachment; filename="output.mp3"'

View File

@ -20,9 +20,19 @@ class Song(models.Model):
def __str__(self): def __str__(self):
return f"{self.artist} - {self.title}" return f"{self.artist} - {self.title}"
class Meta:
verbose_name = 'Треки'
verbose_name_plural = 'Треки'
class FavoriteSong(models.Model): class FavoriteSong(models.Model):
song = models.ForeignKey(Song, verbose_name='Трек', on_delete=models.CASCADE, null=True, blank=True) song = models.ForeignKey(Song, verbose_name='Трек', on_delete=models.CASCADE, null=True, blank=True)
user = models.ForeignKey(MyUser, verbose_name='Пользователь', on_delete=models.CASCADE, blank=True, null=True) user = models.ForeignKey(MyUser, verbose_name='Пользователь', on_delete=models.CASCADE, blank=True, null=True)
def __str__(self): def __str__(self):
return f"{self.song.title}" return f"{self.song.title}"
class Meta:
verbose_name = 'Избранные Треки'
unique_together = ('song', 'user')
verbose_name_plural = 'Избранные Треки'

View File

@ -47,7 +47,7 @@ class DeleteSongSchema(AutoSchema):
def get_serializer_fields(self, path, method): def get_serializer_fields(self, path, method):
return [ return [
coreapi.Field( coreapi.Field(
name='song_id', name='azura_id',
location='form', location='form',
required=False, required=False,
schema=coreschema.String(description='ID трека') schema=coreschema.String(description='ID трека')

View File

@ -7,6 +7,7 @@ from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.shortcuts import get_object_or_404, get_list_or_404 from django.shortcuts import get_object_or_404, get_list_or_404
from rest_framework.permissions import IsAuthenticated from rest_framework.permissions import IsAuthenticated
import requests import requests
from django.http import HttpResponse
from .schemas import SongSchema, DeleteSongSchema from .schemas import SongSchema, DeleteSongSchema
from .models import Song, FavoriteSong from .models import Song, FavoriteSong
@ -39,6 +40,33 @@ class SongViewSet(GenericViewSet):
return Response(serializer.data) return Response(serializer.data)
@action(
detail=False,
methods=['get'],
url_path='get_audio/(?P<azura_id>[a-zA-Z0-9_]+)',
url_name='get_audio',
)
def get_audio(self, request, azura_id):
try:
song_obj = Song.objects.get(azura_id=azura_id)
file_url = f"http://82.97.242.49:10084/api/station/it-radio/file/{song_obj.azura_id}/play"
API_KEY = "49226d3488aac3f5:18d88659c6c1c5e131a0ce0a94d55235"
headers = {
"Authorization": f"Bearer {API_KEY}"
}
response = requests.get(file_url, headers=headers)
response.raise_for_status()
file_response = HttpResponse(response.content, content_type='audio/mpeg')
file = f'{song_obj.title}-{song_obj.artist}.mp3'
file_response['Content-Disposition'] = f'attachment; filename={file}'
return file_response
except ObjectDoesNotExist:
return Response({"error": 'Объекта не существует'}, status=status.HTTP_404_NOT_FOUND)
@action(detail=False, methods=['post'], schema=SongSchema()) @action(detail=False, methods=['post'], schema=SongSchema())
def add_favorite(self, request): def add_favorite(self, request):
data = None data = None
@ -75,7 +103,7 @@ class SongViewSet(GenericViewSet):
@action(detail=False, methods=['post'], schema=DeleteSongSchema()) @action(detail=False, methods=['post'], schema=DeleteSongSchema())
def delete_song(self, request): def delete_song(self, request):
try: try:
item = FavoriteSong.objects.get(user=request.user, song=request.data.get('song_id')) item = FavoriteSong.objects.get(user=request.user, song=request.data.get('azura_id'))
item.delete() item.delete()
return Response(status=status.HTTP_202_ACCEPTED) return Response(status=status.HTTP_202_ACCEPTED)
except ObjectDoesNotExist: except ObjectDoesNotExist:

View File

@ -6,7 +6,7 @@ ALLOWED_HOSTS = ['*']
# Database # Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases # https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = { """ DATABASES = {
'default': { 'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', 'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'it_radio', 'NAME': 'it_radio',
@ -15,6 +15,12 @@ DATABASES = {
'HOST': 'localhost', 'HOST': 'localhost',
'PORT': '5433', 'PORT': '5433',
}, },
} """
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
} }
REST_FRAMEWORK['DEFAULT_PERMISSION_CLASSES'] = ('rest_framework.permissions.AllowAny',) REST_FRAMEWORK['DEFAULT_PERMISSION_CLASSES'] = ('rest_framework.permissions.AllowAny',)

View File

@ -7,7 +7,6 @@ from rest_framework_simplejwt.views import (
TokenVerifyView, TokenVerifyView,
) )
from django.conf.urls.static import static from django.conf.urls.static import static
from news import views as newsViews
from rest_framework import routers from rest_framework import routers
from userProfile.views import TeamViewSet from userProfile.views import TeamViewSet
from django.conf import settings from django.conf import settings
@ -17,7 +16,6 @@ from audio.views import SongViewSet
router = routers.DefaultRouter() router = routers.DefaultRouter()
router.register(r'news', newsViews.NewsViewSet)
router.register(r'teams', TeamViewSet, basename='teams') router.register(r'teams', TeamViewSet, basename='teams')
router.register(r'rubriks', RubricViewSet, basename='rubriks') router.register(r'rubriks', RubricViewSet, basename='rubriks')
router.register(r'song', SongViewSet, basename='song') router.register(r'song', SongViewSet, basename='song')

View File

@ -1,6 +0,0 @@
from django.contrib import admin
from .models import ConfigSite
@admin.register(ConfigSite)
class ConfigSiteAdmin(admin.ModelAdmin):
list_display = ('id', 'social_name', 'social_url')

View File

@ -1,12 +1,13 @@
from django.db import models from django.db import models
class ConfigSite(models.Model): class Page(models.Model):
social_name = models.CharField('Название социальной сети', max_length=100) name = models.CharField('Название страницы', max_length=50)
social_url = models.CharField('Социальная сеть', max_length=100) title_1 = models.TextField('Главный заголовок на странице', null=True, blank=True, max_length=300)
title_2 = models.TextField('Второй заголовок на странице', null=True, blank=True, max_length=300)
def __str__(self): title_3 = models.TextField('Третий заголовок на странице', null=True, blank=True, max_length=300)
return self.social_name video = models.FileField('Видео', upload_to='videos/', null=True, blank=True)
img = models.ImageField('Изображение', blank=True, null=True, upload_to="images/")
title_4 = models.TextField('Заголовок "Поддержи нас" ', null=True, blank=True, max_length=200)
class Meta: def __str__(self):
verbose_name = 'Настройки сайта' return self.name
verbose_name_plural = 'Настройки сайта'

View File

View File

@ -1,3 +1,11 @@
from django.shortcuts import render from django.shortcuts import render
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework import status
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.shortcuts import get_object_or_404, get_list_or_404
from rest_framework.permissions import IsAuthenticated
import requests
from .models import Page
# Create your views here.

View File

@ -1,8 +0,0 @@
from django.contrib import admin
from .models import News
class NewsAdmin(admin.ModelAdmin):
list_display = ('name', 'date') # поля, которые будут отображаться
ordering = ('-date',) # сортировка по дате в обратном порядке
admin.site.register(News, NewsAdmin)

View File

@ -1,8 +1,8 @@
from django.db import models from django.db import models
from django.utils import timezone
class HistoryRadio(models.Model):
class News(models.Model): description = models.CharField('Описание события кратко', max_length=50)
name = models.CharField(max_length=255) date = models.DateField('Дата события', default=timezone.now, null=True)
description = models.TextField() def __str__(self):
date = models.DateTimeField(blank=True) return f"{self.date}: {self.description}"
author = models.CharField(max_length=255, blank=True)

View File

@ -1,7 +0,0 @@
from rest_framework import serializers
from .models import News
class NewsSerializer(serializers.ModelSerializer):
class Meta:
model = News
fields = ['id', 'name', 'description', 'date', 'author']

View File

@ -1,8 +1 @@
from rest_framework import viewsets from .models import HistoryRadio
from .models import News
from news.serializers import NewsSerializer
class NewsViewSet(viewsets.ModelViewSet):
queryset = News.objects.all()
serializer_class = NewsSerializer