clean code & bugfixes

This commit is contained in:
Chneemann 2024-08-29 09:48:37 +02:00
parent 0d7b669cf6
commit 3f2d4afc06
9 changed files with 29 additions and 26 deletions

View file

@ -18,7 +18,7 @@ def video_post_save(sender, instance, created, **kwargs):
create_thumbnails(instance, instance.id) create_thumbnails(instance, instance.id)
#Convert video #Convert video
for resolution in ["720", "480", "1080"]: for resolution in ["1280x720", "640x360", "1920x1080"]:
queue.enqueue(convert_video_to_hls, instance.video_file.path, resolution, instance.id) queue.enqueue(convert_video_to_hls, instance.video_file.path, resolution, instance.id)
#Delete the original video file #Delete the original video file
@ -51,7 +51,7 @@ def delete_converted_files(video_file_path):
""" """
Delete all converted video files related to the original video file. Delete all converted video files related to the original video file.
""" """
resolutions = ["480", "720", "1080"] resolutions = ["360", "720", "1080"]
for resolution in resolutions: for resolution in resolutions:
converted_video_path = video_file_path + f'_{resolution}p.mp4' converted_video_path = video_file_path + f'_{resolution}p.mp4'
converted_video_path = remove_first_mp4(converted_video_path) converted_video_path = remove_first_mp4(converted_video_path)

View file

@ -8,24 +8,26 @@ def convert_video_to_hls(source, resolution, model_id):
""" """
Converts a video to the HLS format Converts a video to the HLS format
""" """
resolution_after_x = resolution.split('x')[1] if 'x' in resolution else resolution
target_dir = os.path.join(os.path.dirname(source), str(model_id)) target_dir = os.path.join(os.path.dirname(source), str(model_id))
os.makedirs(target_dir, exist_ok=True) os.makedirs(target_dir, exist_ok=True)
base_filename = os.path.basename(source).split(".")[0] base_filename = os.path.basename(source).split(".")[0]
target = os.path.join(target_dir, f'{base_filename}_{resolution}p') target = os.path.join(target_dir, f'{base_filename}_{resolution_after_x}p')
ffmpeg_path = shutil.which("ffmpeg") ffmpeg_path = shutil.which("ffmpeg")
cmd = [ cmd = [
ffmpeg_path, ffmpeg_path,
'-i', source, '-i', source,
'-s', f'hd{resolution}', '-s', resolution,
'-c:v', 'libx264', '-c:v', 'libx264',
'-crf', '23', '-crf', '23',
'-c:a', 'aac', '-c:a', 'aac',
'-strict', '-2', '-strict', '-2',
'-hls_time', '10', '-hls_time', '10',
'-hls_playlist_type', 'vod', '-hls_playlist_type', 'vod',
'-hls_segment_filename', os.path.join(target_dir, f'{base_filename}_{resolution}p_%03d.ts'), '-hls_segment_filename', os.path.join(target_dir, f'{base_filename}_{resolution_after_x}p_%03d.ts'),
f'{target}.m3u8' f'{target}.m3u8'
] ]

View file

@ -12,12 +12,12 @@ from rest_framework.parsers import MultiPartParser, FormParser
from django.http import JsonResponse from django.http import JsonResponse
import os import os
CACHETTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT) CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT)
# Create your views here. # Create your views here.
@api_view(['GET']) @api_view(['GET'])
@permission_classes([IsAuthenticated]) @permission_classes([IsAuthenticated])
@cache_page(CACHETTL) #@cache_page(CACHE_TTL)
def video_list(request): def video_list(request):
""" """
List all videos. List all videos.
@ -28,11 +28,11 @@ def video_list(request):
@api_view(['GET']) @api_view(['GET'])
@permission_classes([IsAuthenticated]) @permission_classes([IsAuthenticated])
def check_video(request, id): def check_video_resolutions(request, id):
""" """
Check if a specific video exists in different resolutions (480p, 720p, 1080p). Check if a specific video exists in different resolutions (360p, 720p, 1080p).
""" """
resolutions = ['480', '720', '1080'] resolutions = ['360', '720', '1080']
result = {} result = {}
try: try:
@ -59,6 +59,7 @@ def video_upload(request):
if request.method == 'POST': if request.method == 'POST':
serializer = VideoSerializer(data=request.data) serializer = VideoSerializer(data=request.data)
if serializer.is_valid(): if serializer.is_valid():
serializer.save() creator = request.user
serializer.save(creator=creator)
return Response(serializer.data, status=201) return Response(serializer.data, status=201)
return Response({"error": "Invalid data", "details": serializer.errors}, status=400) return Response({"error": "Invalid data", "details": serializer.errors}, status=400)

View file

@ -38,7 +38,7 @@ urlpatterns = [
# Content URLs # Content URLs
path('content/', content_views.video_list, name='video_list'), path('content/', content_views.video_list, name='video_list'),
path('content/upload/', content_views.video_upload, name='video_upload'), path('content/upload/', content_views.video_upload, name='video_upload'),
path('content/movie/<int:id>/', content_views.check_video, name='check_video'), path('content/movie/<int:id>/', content_views.check_video_resolutions, name='check_video_resolutions'),
# Users URLs # Users URLs
path('users/', user_views.user_list, name='user_list'), path('users/', user_views.user_list, name='user_list'),

View file

@ -43,13 +43,13 @@
<button <button
[ngClass]="{ [ngClass]="{
'resolution-btn': true, 'resolution-btn': true,
active: currentResolution === '480p', active: currentResolution === '360p',
'not-available': !movieIsUploaded['480'] 'not-available': !movieIsUploaded['360']
}" }"
[disabled]="!movieIsUploaded['480'] || currentResolution === '480p'" [disabled]="!movieIsUploaded['360'] || currentResolution === '360p'"
(click)="changeResolution('480p')" (click)="changeResolution('360p')"
> >
480p 360p
</button> </button>
<button <button
[ngClass]="{ [ngClass]="{

View file

@ -33,9 +33,9 @@ export class BrowseComponent implements OnInit {
playMovie: string = ''; playMovie: string = '';
isWideScreen: boolean = false; isWideScreen: boolean = false;
uploadMovieOverview: boolean = false; uploadMovieOverview: boolean = false;
currentResolution: '480p' | '720p' | '1080p' = '720p'; currentResolution: '360p' | '720p' | '1080p' = '720p';
movieIsUploaded: { [resolution: string]: boolean } = { movieIsUploaded: { [resolution: string]: boolean } = {
'480': false, '360': false,
'720': false, '720': false,
'1080': false, '1080': false,
}; };
@ -91,7 +91,7 @@ export class BrowseComponent implements OnInit {
this.updateLikeMovies(); this.updateLikeMovies();
} }
changeResolution(resolution: '480p' | '720p' | '1080p') { changeResolution(resolution: '360p' | '720p' | '1080p') {
if (this.videoPlayer && this.movieIsUploaded[resolution.replace('p', '')]) { if (this.videoPlayer && this.movieIsUploaded[resolution.replace('p', '')]) {
this.videoPlayer.switchResolution(resolution); this.videoPlayer.switchResolution(resolution);
this.currentResolution = resolution; this.currentResolution = resolution;

View file

@ -33,7 +33,7 @@ export class HeroBannerComponent {
environmentBaseUrl: string = environment.baseUrl; environmentBaseUrl: string = environment.baseUrl;
movieIsUploaded: { [resolution: string]: boolean } = { movieIsUploaded: { [resolution: string]: boolean } = {
'480': false, '320': false,
'720': false, '720': false,
'1080': false, '1080': false,
}; };
@ -72,7 +72,7 @@ export class HeroBannerComponent {
isAnyResolutionUploaded(): boolean { isAnyResolutionUploaded(): boolean {
return ( return (
this.movieIsUploaded['480'] || this.movieIsUploaded['320'] ||
this.movieIsUploaded['720'] || this.movieIsUploaded['720'] ||
this.movieIsUploaded['1080'] this.movieIsUploaded['1080']
); );

View file

@ -22,7 +22,7 @@ export class VideoPlayerComponent implements OnInit, OnDestroy {
if (this.playMovie) { if (this.playMovie) {
this.resolutionUrls = { this.resolutionUrls = {
'480p': `${this.playMovie}_480p.m3u8`, '360p': `${this.playMovie}_360p.m3u8`,
'720p': `${this.playMovie}_720p.m3u8`, '720p': `${this.playMovie}_720p.m3u8`,
'1080p': `${this.playMovie}_1080p.m3u8`, '1080p': `${this.playMovie}_1080p.m3u8`,
}; };
@ -63,7 +63,7 @@ export class VideoPlayerComponent implements OnInit, OnDestroy {
} }
// Method to switch resolution // Method to switch resolution
public switchResolution(resolution: '480p' | '720p' | '1080p') { public switchResolution(resolution: '360p' | '720p' | '1080p') {
if (this.resolutionUrls[resolution]) { if (this.resolutionUrls[resolution]) {
if (this.hls) { if (this.hls) {
this.hls.loadSource(this.resolutionUrls[resolution]); this.hls.loadSource(this.resolutionUrls[resolution]);

View file

@ -81,7 +81,7 @@ export class MovieService {
this.http.get(url, { headers }).subscribe( this.http.get(url, { headers }).subscribe(
(response: any) => { (response: any) => {
const resolutions = { const resolutions = {
'480': response['480'] || false, '360': response['360'] || false,
'720': response['720'] || false, '720': response['720'] || false,
'1080': response['1080'] || false, '1080': response['1080'] || false,
}; };
@ -92,7 +92,7 @@ export class MovieService {
(error) => { (error) => {
observer.next( observer.next(
this.movieCache[videoID] || { this.movieCache[videoID] || {
'480': false, '360': false,
'720': false, '720': false,
'1080': false, '1080': false,
} }