Files
WerkoutAPI/video/views.py
Trey t c80c66c2e5 Codebase hardening: 102 fixes across 35+ files
Deep audit identified 106 findings; 102 fixed, 4 deferred. Covers 8 areas:

- Settings & deploy: env-gated DEBUG/SECRET_KEY, HTTPS headers, gunicorn, celery worker
- Auth (registered_user): password write_only, request.data fixes, transaction safety, proper HTTP status codes
- Workout app: IDOR protection, get_object_or_404, prefetch_related N+1 fixes, transaction.atomic
- Video/scripts: path traversal sanitization, HLS trigger guard, auth on cache wipe
- Models (exercise/equipment/muscle/superset): null-safe __str__, stable IDs, prefetch support
- Generator views: helper for registered_user lookup, logger.exception, bulk_update, transaction wrapping
- Generator core (rules/selector/generator): push-pull ratio, type affinity normalization, modality checks, side-pair exact match, word-boundary regex, equipment cache clearing
- Generator services (plan_builder/analyzer/normalizer): transaction.atomic, muscle cache, bulk_update, glutes classification fix

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 22:29:14 -06:00

99 lines
3.9 KiB
Python

from .models import *
from .serializers import *
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import authentication_classes
from rest_framework.decorators import permission_classes
from django.shortcuts import get_object_or_404
from datetime import datetime
import json
import os
from django.core.cache import cache
from django.http import JsonResponse
from django.conf import settings
import ffmpeg_streaming
from ffmpeg_streaming import Formats, Bitrate, Representation, Size
from django.core.files.storage import default_storage
from .tasks import create_hls_tasks
# Create your views here.
@api_view(['GET'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def nsfw_videos(request):
if 'nsfw_videos' in cache:
data = cache.get('nsfw_videos')
if len(data) > 0:
return Response(data=data, status=status.HTTP_200_OK)
users = Video.objects.all()
serializer = VideoSerializer(users, many=True)
data = serializer.data
cache.set('nsfw_videos', data, timeout=None)
return Response(data=data, status=status.HTTP_200_OK)
@api_view(['GET'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def hls_videos(request):
video_url = request.GET.get('video_name', '')
video_type = request.GET.get('video_type', '')
# Sanitize inputs to prevent path traversal
video_url = os.path.basename(video_url)
video_type = os.path.basename(video_type)
if not video_url or not video_type:
return Response({"error": "video_name and video_type are required"}, status=status.HTTP_400_BAD_REQUEST)
end_location = os.path.join(str(settings.MEDIA_ROOT), 'hls', video_url + '.m3u8')
end_file_name = '/media/hls/' + video_url + '_720p.m3u8'
# Verify the resolved path is within MEDIA_ROOT
if not os.path.realpath(end_location).startswith(os.path.realpath(str(settings.MEDIA_ROOT))):
return Response({"error": "Invalid path"}, status=status.HTTP_400_BAD_REQUEST)
if default_storage.exists(end_location):
return JsonResponse({'file_location': end_file_name})
media_location = os.path.join(str(settings.MEDIA_ROOT), video_type, video_url)
# Verify media_location is within MEDIA_ROOT
if not os.path.realpath(media_location).startswith(os.path.realpath(str(settings.MEDIA_ROOT))):
return Response({"error": "Invalid path"}, status=status.HTTP_400_BAD_REQUEST)
video = ffmpeg_streaming.input(media_location)
hls = video.hls(Formats.h264())
#_720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024))
hls.auto_generate_representations()
hls.output(end_location)
# {{url}}/videos/hls_video?video_name=Spiderman_Stretch.mp4&video_type=exercise_videos
# {{url}}/videos/hls_video?video_name=Recover_24.mp4&video_type=videos
return JsonResponse({'file_location': end_file_name})
@api_view(['POST'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def create_hls(request):
filename = request.data.get('filename', '')
if not filename:
return Response({"error": "filename is required"}, status=status.HTTP_400_BAD_REQUEST)
# Sanitize to prevent path traversal
filename = os.path.basename(filename)
full_path = os.path.join(str(settings.MEDIA_ROOT), 'videos', filename)
if not os.path.realpath(full_path).startswith(os.path.realpath(str(settings.MEDIA_ROOT))):
return Response({"error": "Invalid path"}, status=status.HTTP_400_BAD_REQUEST)
create_hls_tasks.delay(os.path.join('videos', filename))
return JsonResponse({'running': "running"})