Skip to content

Commit

Permalink
feat: add API endpoint for retrieving playlists and improve section U…
Browse files Browse the repository at this point in the history
…RL handling
  • Loading branch information
drikusroor committed Jan 7, 2025
1 parent 2b34e47 commit efd5a61
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
7 changes: 3 additions & 4 deletions backend/section/urls.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
from django.urls import path
from .views import get_section, playlists

from .views import get_section

app_name = 'section'
app_name = "section"

urlpatterns = [
# Section
path("<int:section_id>/", get_section, name="section"),
path("api/playlists/", playlists, name="playlists"),
]
21 changes: 16 additions & 5 deletions backend/section/views.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
from os.path import join

from django.http import Http404, HttpRequest, FileResponse
from django.http import Http404, HttpRequest, FileResponse, HttpResponsePermanentRedirect, HttpResponseRedirect
from django.conf import settings
from django.shortcuts import redirect

from .models import Section
from .models import Playlist, Section
from rest_framework.decorators import api_view
from rest_framework.response import Response


def get_section(request: HttpRequest, section_id: int) -> Section:
def get_section(
request: HttpRequest, section_id: int
) -> Section | HttpResponsePermanentRedirect | HttpResponseRedirect | FileResponse:
"""Get section by given id"""
try:
section = Section.objects.get(pk=section_id)
Expand All @@ -23,7 +27,7 @@ def get_section(request: HttpRequest, section_id: int) -> Section:
# Advantage: low server load
# Disadvantage: exposes url

if str(section.filename).startswith('http'):
if str(section.filename).startswith("http"):
# external link, redirect
return redirect(str(section.filename))

Expand Down Expand Up @@ -51,11 +55,18 @@ def get_section(request: HttpRequest, section_id: int) -> Section:
response = FileResponse(open(filepath, "rb"))

# Header is required to make seeking work in Chrome
response['Accept-Ranges'] = 'bytes'
response["Accept-Ranges"] = "bytes"

# Response may log a ConnectionResetError on the development server
# This has no effect on serving the file
return response

except Section.DoesNotExist:
raise Http404("Section does not exist")


@api_view(["GET"])
def playlists(request):
"""Return a list of all playlists"""
playlists = [{"id": playlist.id, "name": playlist.name} for playlist in Playlist.objects.all()]
return Response(playlists)

0 comments on commit efd5a61

Please sign in to comment.