From 8b5e6a3373d7e898e8ac66512847e5fb235e8b78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Coze?= <96086580+SebastienCozeDev@users.noreply.github.com> Date: Mon, 15 Apr 2024 13:47:25 +0200 Subject: [PATCH] [DONE] Clean code (#1100) * Simplify video_chapter_save & video_chapter_import function * Remove unused variable * Simplify video_completion_track_save & video_completion_track_delete function * Rename captFile variable * Rename enrichModelQueue variable * Rename FFMPEG_DRESSING_INPUT params * Update pydoc * Set some variable to lowercase * bump docker version to bullseye --------- Co-authored-by: Ptitloup --- .env.dev-exemple | 2 +- pod/chapter/views.py | 88 +++++++++++++--------------------- pod/completion/admin.py | 36 +++++++------- pod/completion/views.py | 77 +++++++++++++---------------- pod/dressing/utils.py | 10 ++-- pod/enrichment/models.py | 22 ++++----- pod/enrichment/views.py | 1 + pod/main/context_processors.py | 4 +- pod/main/forms_utils.py | 34 ++++++------- pod/main/views.py | 18 +++---- pod/meeting/models.py | 4 +- pod/meeting/webinar.py | 6 +-- pod/recorder/utils.py | 72 ++++++++++++++-------------- pod/recorder/views.py | 80 +++++++++++++++---------------- 14 files changed, 210 insertions(+), 244 deletions(-) diff --git a/.env.dev-exemple b/.env.dev-exemple index 0f17d94e9c..1174b5ccdf 100644 --- a/.env.dev-exemple +++ b/.env.dev-exemple @@ -4,7 +4,7 @@ DJANGO_SUPERUSER_EMAIL= ### You can use internal registry ELASTICSEARCH_TAG=elasticsearch:8.13.0 NODE_TAG=node:19 -PYTHON_TAG=python:3.9-buster +PYTHON_TAG=python:3.9-bullseye REDIS_TAG=redis:alpine3.16 ### DOCKER_ENV : You can specify light or full. ### In case of value changing, you have to rebuild and restart your container. diff --git a/pod/chapter/views.py b/pod/chapter/views.py index a67010ab32..9e062764f3 100644 --- a/pod/chapter/views.py +++ b/pod/chapter/views.py @@ -81,6 +81,37 @@ def video_chapter_new(request, video): ) +def toggle_valid_form__video_chapter(request, video): + """Toggle the form validity.""" + list_chapter = video.chapter_set.all() + if is_ajax(request): + csrf_token_value = get_token(request) + some_data_to_dump = { + "list_chapter": render_to_string( + "chapter/list_chapter.html", + { + "list_chapter": list_chapter, + "video": video, + "csrf_token_value": csrf_token_value, + }, + request=request, + ), + "video-elem": render_to_string( + "videos/video-element.html", + {"video": video}, + request=request, + ), + } + data = json.dumps(some_data_to_dump) + return HttpResponse(data, content_type="application/json") + else: + return render( + request, + "video_chapter.html", + {"video": video, "list_chapter": list_chapter}, + ) + + def video_chapter_save(request, video): """Save a video chapter form request.""" list_chapter = video.chapter_set.all() @@ -94,33 +125,7 @@ def video_chapter_save(request, video): form_chapter = ChapterForm(request.POST) if form_chapter.is_valid(): form_chapter.save() - list_chapter = video.chapter_set.all() - if is_ajax(request): - csrf_token_value = get_token(request) - some_data_to_dump = { - "list_chapter": render_to_string( - "chapter/list_chapter.html", - { - "list_chapter": list_chapter, - "video": video, - "csrf_token_value": csrf_token_value, - }, - request=request, - ), - "video-elem": render_to_string( - "videos/video-element.html", - {"video": video}, - request=request, - ), - } - data = json.dumps(some_data_to_dump) - return HttpResponse(data, content_type="application/json") - else: - return render( - request, - "video_chapter.html", - {"video": video, "list_chapter": list_chapter}, - ) + return toggle_valid_form__video_chapter(request, video) else: if is_ajax(request): csrf_token_value = get_token(request) @@ -175,7 +180,6 @@ def video_chapter_modify(request, video): def video_chapter_delete(request, video): - list_chapter = video.chapter_set.all() chapter = get_object_or_404(Chapter, id=request.POST.get("id")) chapter.delete() list_chapter = video.chapter_set.all() @@ -220,33 +224,7 @@ def video_chapter_import(request, video): form_chapter = ChapterForm(initial={"video": video}) form_import = ChapterImportForm(request.POST, user=request.user, video=video) if form_import.is_valid(): - list_chapter = video.chapter_set.all() - if is_ajax(request): - csrf_token_value = get_token(request) - some_data_to_dump = { - "list_chapter": render_to_string( - "chapter/list_chapter.html", - { - "list_chapter": list_chapter, - "video": video, - "csrf_token_value": csrf_token_value, - }, - request=request, - ), - "video-elem": render_to_string( - "videos/video-element.html", - {"video": video}, - request=request, - ), - } - data = json.dumps(some_data_to_dump) - return HttpResponse(data, content_type="application/json") - else: - return render( - request, - "video_chapter.html", - {"video": video, "list_chapter": list_chapter}, - ) + return toggle_valid_form__video_chapter(request, video) else: if is_ajax(request): some_data_to_dump = { diff --git a/pod/completion/admin.py b/pod/completion/admin.py index 830b993f92..696de04ff2 100644 --- a/pod/completion/admin.py +++ b/pod/completion/admin.py @@ -161,11 +161,11 @@ def debug(text): def check_if_treatment_in_progress() -> bool: return EnrichModelQueue.objects.filter(in_treatment=True).exists() - def write_into_kaldi_file(enrichModelQueue: EnrichModelQueue): + def write_into_kaldi_file(enrich_model_queue: EnrichModelQueue): with open( - MODEL_COMPILE_DIR + "/" + enrichModelQueue.lang + "/db/extra.txt", "w" + MODEL_COMPILE_DIR + "/" + enrich_model_queue.lang + "/db/extra.txt", "w" ) as f: - f.write(enrichModelQueue.text) + f.write(enrich_model_queue.text) subprocess.call( [ "docker", @@ -174,16 +174,16 @@ def write_into_kaldi_file(enrichModelQueue: EnrichModelQueue): MODEL_COMPILE_DIR + ":/kaldi/compile-model", "-it", "kaldi", - enrichModelQueue.lang, + enrich_model_queue.lang, ] ) - def copy_result_into_current_model(enrichModelQueue: EnrichModelQueue): + def copy_result_into_current_model(enrich_model_queue: EnrichModelQueue): from_path: str = ( - MODEL_COMPILE_DIR + "/" + enrichModelQueue.lang + "/exp/chain/tdnn/graph" + MODEL_COMPILE_DIR + "/" + enrich_model_queue.lang + "/exp/chain/tdnn/graph" ) to_path: str = ( - TRANSCRIPTION_MODEL_PARAM[enrichModelQueue.model_type][enrichModelQueue.lang][ + TRANSCRIPTION_MODEL_PARAM[enrich_model_queue.model_type][enrich_model_queue.lang][ "model" ] + "/graph" @@ -193,10 +193,10 @@ def copy_result_into_current_model(enrichModelQueue: EnrichModelQueue): shutil.copytree(from_path, to_path) from_path: str = ( - MODEL_COMPILE_DIR + "/" + enrichModelQueue.lang + "/data/lang_test_rescore" + MODEL_COMPILE_DIR + "/" + enrich_model_queue.lang + "/data/lang_test_rescore" ) to_path: str = ( - TRANSCRIPTION_MODEL_PARAM[enrichModelQueue.model_type][enrichModelQueue.lang][ + TRANSCRIPTION_MODEL_PARAM[enrich_model_queue.model_type][enrich_model_queue.lang][ "model" ] + "/rescore/" @@ -208,10 +208,10 @@ def copy_result_into_current_model(enrichModelQueue: EnrichModelQueue): shutil.copy(from_path + "/G.carpa", to_path) from_path: str = ( - MODEL_COMPILE_DIR + "/" + enrichModelQueue.lang + "/exp/rnnlm_out" + MODEL_COMPILE_DIR + "/" + enrich_model_queue.lang + "/exp/rnnlm_out" ) to_path: str = ( - TRANSCRIPTION_MODEL_PARAM[enrichModelQueue.model_type][enrichModelQueue.lang][ + TRANSCRIPTION_MODEL_PARAM[enrich_model_queue.model_type][enrich_model_queue.lang][ "model" ] + "/rnnlm/" @@ -221,17 +221,17 @@ def copy_result_into_current_model(enrichModelQueue: EnrichModelQueue): def enrich_kaldi_model_launch(): TrackAdmin.debug("enrich_kaldi_model") - enrichModelQueue = EnrichModelQueue.objects.filter(model_type="VOSK").first() - if enrichModelQueue is not None: - enrichModelQueue.in_treatment = True - enrichModelQueue.save() + enrich_model_queue = EnrichModelQueue.objects.filter(model_type="VOSK").first() + if enrich_model_queue is not None: + enrich_model_queue.in_treatment = True + enrich_model_queue.save() TrackAdmin.debug("start subprocess") - TrackAdmin.write_into_kaldi_file(enrichModelQueue) + TrackAdmin.write_into_kaldi_file(enrich_model_queue) TrackAdmin.debug("finish subprocess") TrackAdmin.debug("start copy result") - TrackAdmin.copy_result_into_current_model(enrichModelQueue) + TrackAdmin.copy_result_into_current_model(enrich_model_queue) TrackAdmin.debug("finish copy result") - enrichModelQueue.delete() + enrich_model_queue.delete() TrackAdmin.enrich_kaldi_model_launch() return else: diff --git a/pod/completion/views.py b/pod/completion/views.py index c77aa8969d..c14d1f5e20 100644 --- a/pod/completion/views.py +++ b/pod/completion/views.py @@ -75,11 +75,11 @@ def video_caption_maker(request, slug): else: track_language = LANGUAGE_CODE track_kind = "captions" - captionFileId = request.GET.get("src") - if captionFileId: - captionFile = CustomFileModel.objects.filter(id=captionFileId).first() - if captionFile: - track = Track.objects.filter(video=video, src=captionFile).first() + caption_file_id = request.GET.get("src") + if caption_file_id: + caption_file = CustomFileModel.objects.filter(id=caption_file_id).first() + if caption_file: + track = Track.objects.filter(video=video, src=caption_file).first() if track: track_language = track.lang track_kind = track.kind @@ -119,12 +119,12 @@ def video_caption_maker_save(request, video): response = file_edit_save(request, cur_folder) response_data = json.loads(response.content) if ("list_element" in response_data) and (lang in __LANG_CHOICES_DICT__): - captFile = get_object_or_404(CustomFileModel, id=response_data["file_id"]) + capt_file = get_object_or_404(CustomFileModel, id=response_data["file_id"]) # immediately assign the newly created captions file to the video - desired = Track.objects.filter(video=video, src=captFile) + desired = Track.objects.filter(video=video, src=capt_file) if desired.exists(): desired.update( - lang=lang, kind=kind, src=captFile, enrich_ready=enrich_ready + lang=lang, kind=kind, src=capt_file, enrich_ready=enrich_ready ) else: # check if the same combination of lang and kind exists @@ -133,7 +133,7 @@ def video_caption_maker_save(request, video): video=video, kind=kind, lang=lang, - src=captFile, + src=capt_file, enrich_ready=enrich_ready, ) track.save() @@ -587,6 +587,27 @@ def video_completion_get_form_track(request): return form_track +def toggle_form_track_is_valid__video_completion_track(request, video, list_track): + """Toggle form_track is valid.""" + if request.is_ajax(): + some_data_to_dump = { + "list_data": render_to_string( + "track/list_track.html", + {"list_track": list_track, "video": video}, + request=request, + ) + } + data = json.dumps(some_data_to_dump) + return HttpResponse(data, content_type="application/json") + else: + context = get_video_completion_context(video, list_track=list_track) + return render( + request, + "video_completion.html", + context, + ) + + def video_completion_track_save(request, video): """View to save a track associated to a video.""" form_track = video_completion_get_form_track(request) @@ -594,24 +615,7 @@ def video_completion_track_save(request, video): if form_track.is_valid(): form_track.save() - - if request.is_ajax(): - some_data_to_dump = { - "list_data": render_to_string( - "track/list_track.html", - {"list_track": list_track, "video": video}, - request=request, - ) - } - data = json.dumps(some_data_to_dump) - return HttpResponse(data, content_type="application/json") - else: - context = get_video_completion_context(video, list_track=list_track) - return render( - request, - "video_completion.html", - context, - ) + return toggle_form_track_is_valid__video_completion_track(request, video, list_track) else: if request.is_ajax(): some_data_to_dump = { @@ -659,24 +663,7 @@ def video_completion_track_delete(request, video): track = get_object_or_404(Track, id=request.POST["id"]) track.delete() list_track = video.track_set.all() - - if request.is_ajax(): - some_data_to_dump = { - "list_data": render_to_string( - "track/list_track.html", - {"list_track": list_track, "video": video}, - request=request, - ) - } - data = json.dumps(some_data_to_dump) - return HttpResponse(data, content_type="application/json") - else: - context = get_video_completion_context(video, list_track=list_track) - return render( - request, - "video_completion.html", - context, - ) + return toggle_form_track_is_valid__video_completion_track(request, video, list_track) def is_already_link(url, text): diff --git a/pod/dressing/utils.py b/pod/dressing/utils.py index bcd6728dda..8b179eed64 100644 --- a/pod/dressing/utils.py +++ b/pod/dressing/utils.py @@ -6,28 +6,28 @@ from django.db.models import Q -def get_dressing_input(dressing: Dressing, FFMPEG_DRESSING_INPUT: str) -> str: +def get_dressing_input(dressing: Dressing, ffmpeg_dressing_input: str) -> str: """ Obtain the files necessary for encoding a dressed video. Args: dressing (:class:`pod.dressing.models.Dressing`): The dressing object. - FFMPEG_DRESSING_INPUT (str): Source file for encoding. + ffmpeg_dressing_input (str): Source file for encoding. Returns: command (str): params for the ffmpeg command. """ command = "" if dressing.watermark: - command += FFMPEG_DRESSING_INPUT % {"input": dressing.watermark.file.path} + command += ffmpeg_dressing_input % {"input": dressing.watermark.file.path} if dressing.opening_credits: - command += FFMPEG_DRESSING_INPUT % { + command += ffmpeg_dressing_input % { "input": os.path.join( settings.MEDIA_ROOT, str(dressing.opening_credits.video) ) } if dressing.ending_credits: - command += FFMPEG_DRESSING_INPUT % { + command += ffmpeg_dressing_input % { "input": os.path.join(settings.MEDIA_ROOT, str(dressing.ending_credits.video)) } return command diff --git a/pod/enrichment/models.py b/pod/enrichment/models.py index 6f28383cdb..1051746710 100755 --- a/pod/enrichment/models.py +++ b/pod/enrichment/models.py @@ -62,26 +62,26 @@ def enrichment_to_vtt(list_enrichment, video): videodir, created = UserFolder.objects.get_or_create( name="%s" % video.slug, owner=video.owner ) - previousEnrichmentFile = CustomFileModel.objects.filter( + previous_enrichment_file = CustomFileModel.objects.filter( name__startswith="enrichment", folder=videodir, created_by=video.owner, ) - for enr in previousEnrichmentFile: + for enr in previous_enrichment_file: enr.delete() # do it like this to delete file - enrichmentFile, created = CustomFileModel.objects.get_or_create( + enrichment_file, created = CustomFileModel.objects.get_or_create( name="enrichment", folder=videodir, created_by=video.owner ) - if enrichmentFile.file and os.path.isfile(enrichmentFile.file.path): - os.remove(enrichmentFile.file.path) + if enrichment_file.file and os.path.isfile(enrichment_file.file.path): + os.remove(enrichment_file.file.path) else: - enrichmentFile, created = CustomFileModel.objects.get_or_create() - enrichmentFile.file.save("enrichment.vtt", File(temp_vtt_file)) - enrichmentVtt, created = EnrichmentVtt.objects.get_or_create(video=video) - enrichmentVtt.src = enrichmentFile - enrichmentVtt.save() - return enrichmentFile.file.path + enrichment_file, created = CustomFileModel.objects.get_or_create() + enrichment_file.file.save("enrichment.vtt", File(temp_vtt_file)) + enrichment_vtt, created = EnrichmentVtt.objects.get_or_create(video=video) + enrichment_vtt.src = enrichment_file + enrichment_vtt.save() + return enrichment_file.file.path def enrichment_to_vtt_type(enrich): diff --git a/pod/enrichment/views.py b/pod/enrichment/views.py index a09f81572d..0c91e45a96 100644 --- a/pod/enrichment/views.py +++ b/pod/enrichment/views.py @@ -256,6 +256,7 @@ def video_enrichment( slug (`str`): The video slug. slug_c (`str`): The channel slug. slug_t (`str`): The theme slug. + slug_private (`str`): The private slug. Returns: :class:`django.http.HttpResponse`: The HTTP response. diff --git a/pod/main/context_processors.py b/pod/main/context_processors.py index b26f19c48c..b4aa95530d 100644 --- a/pod/main/context_processors.py +++ b/pod/main/context_processors.py @@ -150,9 +150,9 @@ def context_settings(request): def context_footer(request): - linkFooter = LinkFooter.objects.all().filter(sites=get_current_site(request)) + link_footer = LinkFooter.objects.all().filter(sites=get_current_site(request)) return { - "LINK_FOOTER": linkFooter, + "LINK_FOOTER": link_footer, } diff --git a/pod/main/forms_utils.py b/pod/main/forms_utils.py index 5bc269d65e..b28be2f74e 100644 --- a/pod/main/forms_utils.py +++ b/pod/main/forms_utils.py @@ -56,37 +56,37 @@ def decompress(self, value): def add_describedby_attr(fields): """Add aria-describedby attribute to specified fields.""" for fieldName in fields: - myField = fields[fieldName] - if myField.widget.__class__.__name__ != "HiddenInput" and myField.help_text: - myField.widget.attrs["aria-describedby"] = "id_%sHelp" % fieldName + my_field = fields[fieldName] + if my_field.widget.__class__.__name__ != "HiddenInput" and my_field.help_text: + my_field.widget.attrs["aria-describedby"] = "id_%sHelp" % fieldName return fields def add_placeholder_and_asterisk(fields): """Add placeholder and asterisk to specified fields.""" for fieldName in fields: - myField = fields[fieldName] - classname = myField.widget.__class__.__name__ + my_field = fields[fieldName] + classname = my_field.widget.__class__.__name__ if classname == "PasswordInput" or classname == "TextInput": - myField.widget.attrs["placeholder"] = myField.label + my_field.widget.attrs["placeholder"] = my_field.label if classname == "CheckboxInput" or classname == "CheckboxSelectMultiple": - bsClass = "form-check-input" + bs_class = "form-check-input" elif classname == "Select": - bsClass = "form-select" + bs_class = "form-select" else: - bsClass = "form-control" + bs_class = "form-control" - init_class = myField.widget.attrs.get("class", "") - bsClass = bsClass + " " + init_class - if myField.required: - myField.label = mark_safe( - '%s *' % myField.label + init_class = my_field.widget.attrs.get("class", "") + bs_class = bs_class + " " + init_class + if my_field.required: + my_field.label = mark_safe( + '%s *' % my_field.label ) - myField.widget.attrs["required"] = "" - myField.widget.attrs["class"] = "required " + bsClass + my_field.widget.attrs["required"] = "" + my_field.widget.attrs["class"] = "required " + bs_class else: - myField.widget.attrs["class"] = bsClass + my_field.widget.attrs["class"] = bs_class return fields diff --git a/pod/main/views.py b/pod/main/views.py index cc04ddae0e..ccc65f1074 100644 --- a/pod/main/views.py +++ b/pod/main/views.py @@ -391,12 +391,12 @@ def info_pod(request): @login_required(redirect_field_name="referrer") def userpicture(request): """Render the user picture.""" - frontOwnerForm = FrontOwnerForm(instance=request.user.owner) + front_owner_form = FrontOwnerForm(instance=request.user.owner) if request.method == "POST": - frontOwnerForm = FrontOwnerForm(request.POST, instance=request.user.owner) - if frontOwnerForm.is_valid(): - frontOwnerForm.save() + front_owner_form = FrontOwnerForm(request.POST, instance=request.user.owner) + if front_owner_form.is_valid(): + front_owner_form.save() # messages.add_message( # request, messages.INFO, _('Your picture has been saved.')) else: @@ -409,7 +409,7 @@ def userpicture(request): return render( request, "userpicture/userpicture.html", - {"frontOwnerForm": frontOwnerForm}, + {"frontOwnerForm": front_owner_form}, ) @@ -417,14 +417,14 @@ def userpicture(request): @login_required(redirect_field_name="referrer") def set_notifications(request): """Set 'accepts_notifications' attribute on owner instance.""" - setNotificationForm = SetNotificationForm(instance=request.user.owner) + set_notification_form = SetNotificationForm(instance=request.user.owner) if request.method == "POST": - setNotificationForm = SetNotificationForm( + set_notification_form = SetNotificationForm( request.POST, instance=request.user.owner ) - if setNotificationForm.is_valid(): - setNotificationForm.save() + if set_notification_form.is_valid(): + set_notification_form.save() return JsonResponse( { "success": True, diff --git a/pod/meeting/models.py b/pod/meeting/models.py index 6ac1bf891b..3743ecc9e9 100644 --- a/pod/meeting/models.py +++ b/pod/meeting/models.py @@ -671,14 +671,14 @@ def create(self, request=None): if (BBB_LOGOUT_URL != "") else "".join(["https://", get_current_site(None).domain]) ) - endCallbackUrl = "".join( + end_callback_url = "".join( [ "https://", get_current_site(None).domain, reverse("meeting:end_callback", kwargs={"meeting_id": self.meeting_id}), ] ) - parameters["meta_endCallbackUrl"] = endCallbackUrl + parameters["meta_endCallbackUrl"] = end_callback_url if not MEETING_DISABLE_RECORD: recordingReadyUrl = "".join( [ diff --git a/pod/meeting/webinar.py b/pod/meeting/webinar.py index 72dce57145..3f0685389a 100644 --- a/pod/meeting/webinar.py +++ b/pod/meeting/webinar.py @@ -35,9 +35,9 @@ def start_webinar(request: WSGIRequest, meet_id: int): start_webinar_livestream(request.get_host(), meet_id) # Thread for stop the webinar - tStop = threading.Thread(target=stop_webinar_livestream, args=[meet_id, False]) - tStop.setDaemon(True) - tStop.start() + t_stop = threading.Thread(target=stop_webinar_livestream, args=[meet_id, False]) + t_stop.setDaemon(True) + t_stop.start() display_message_with_icon( request, messages.INFO, diff --git a/pod/recorder/utils.py b/pod/recorder/utils.py index 8419b835a7..880c4ae450 100644 --- a/pod/recorder/utils.py +++ b/pod/recorder/utils.py @@ -53,19 +53,19 @@ def handle_upload_file(request, element_name, mimetype, tag_name): Returns: HttpResponse: The HTTP response containing the generated XML content. """ - idMedia = "" + id_media = "" type_name = "" opencast_filename = None # tags = "" # not use actually - idMedia = get_id_media(request) + id_media = get_id_media(request) if request.POST.get("flavor") and request.POST.get("flavor") != "": type_name = request.POST.get("flavor") - mediaPackage_dir = os.path.join( - settings.MEDIA_ROOT, OPENCAST_FILES_DIR, "%s" % idMedia + media_package_dir = os.path.join( + settings.MEDIA_ROOT, OPENCAST_FILES_DIR, "%s" % id_media ) - mediaPackage_content, mediaPackage_file = get_media_package_content( - mediaPackage_dir, idMedia + media_package_content, media_package_file = get_media_package_content( + media_package_dir, id_media ) if element_name != "attachment": @@ -75,39 +75,39 @@ def handle_upload_file(request, element_name, mimetype, tag_name): elif element_name == "catalog": filename = request.FILES["BODY"].name - opencastMediaFile = os.path.join(mediaPackage_dir, filename) + opencastMediaFile = os.path.join(media_package_dir, filename) with open(opencastMediaFile, "wb+") as destination: for chunk in request.FILES["BODY"].chunks(): destination.write(chunk) - url_text = "%(http)s://%(host)s%(media)sopencast-files/%(idMedia)s/%(fn)s" % { + url_text = "%(http)s://%(host)s%(media)sopencast-files/%(id_media)s/%(fn)s" % { "http": "https" if request.is_secure() else "http", "host": request.get_host(), "media": MEDIA_URL, - "idMedia": "%s" % idMedia, + "id_media": "%s" % id_media, "fn": filename, } else: url_text = "" element = create_xml_element( - mediaPackage_content, + media_package_content, element_name, type_name, mimetype, url_text, opencast_filename, ) - media = mediaPackage_content.getElementsByTagName(tag_name)[0] + media = media_package_content.getElementsByTagName(tag_name)[0] media.appendChild(element) - with open(mediaPackage_file, "w+") as f: - f.write(mediaPackage_content.toxml()) + with open(media_package_file, "w+") as f: + f.write(media_package_content.toxml()) - return HttpResponse(mediaPackage_content.toxml(), content_type="application/xml") + return HttpResponse(media_package_content.toxml(), content_type="application/xml") def get_id_media(request): - """Extract and returns idMedia from the mediaPackage in the request.""" + """Extract and returns id_media from the mediaPackage in the request.""" if ( request.POST.get("mediaPackage") != "" and request.POST.get("mediaPackage") != "{}" @@ -115,25 +115,25 @@ def get_id_media(request): mediaPackage = request.POST.get("mediaPackage") # XML result to parse xmldoc = minidom.parseString(mediaPackage) - # Get the idMedia - idMedia = xmldoc.getElementsByTagName("mediapackage")[0].getAttribute("id") - return idMedia + # Get the id_media + id_media = xmldoc.getElementsByTagName("mediapackage")[0].getAttribute("id") + return id_media return None -def get_media_package_content(mediaPackage_dir, idMedia): +def get_media_package_content(media_package_dir, id_media): """Retrieve media package content & media package file by parsing an XML file.""" - mediaPackage_file = os.path.join(mediaPackage_dir, "%s.xml" % idMedia) - mediaPackage_content = minidom.parse(mediaPackage_file) # parse an open file - mediapackage = mediaPackage_content.getElementsByTagName("mediapackage")[0] - if mediapackage.getAttribute("id") != idMedia: + media_package_file = os.path.join(media_package_dir, "%s.xml" % id_media) + media_package_content = minidom.parse(media_package_file) # parse an open file + mediapackage = media_package_content.getElementsByTagName("mediapackage")[0] + if mediapackage.getAttribute("id") != id_media: raise PermissionDenied("Access denied: ID mismatch.") - return mediaPackage_content, mediaPackage_file + return media_package_content, media_package_file def create_xml_element( - mediaPackage_content, + media_package_content, element_name, type_name, mimetype, @@ -144,7 +144,7 @@ def create_xml_element( Create an XML element with the specified attributes. Args: - mediaPackage_content: The media package content. + media_package_content: The media package content. element_name (str): The name of the XML element. type_name (str): The type of the XML element. mimetype (str): The mimetype of the XML element. @@ -154,23 +154,23 @@ def create_xml_element( Returns: element : The created XML element. """ - element = mediaPackage_content.createElement(element_name) - element.setAttributeNode(mediaPackage_content.createAttribute("id")) - element.setAttributeNode(mediaPackage_content.createAttribute("type")) + element = media_package_content.createElement(element_name) + element.setAttributeNode(media_package_content.createAttribute("id")) + element.setAttributeNode(media_package_content.createAttribute("type")) element.setAttribute("id", "%s" % uuid.uuid4()) element.setAttribute("type", type_name) if element_name == "track": - element.setAttributeNode(mediaPackage_content.createAttribute("filename")) + element.setAttributeNode(media_package_content.createAttribute("filename")) element.setAttribute("filename", opencast_filename) - mimetype_element = mediaPackage_content.createElement("mimetype") - mimetype_element.appendChild(mediaPackage_content.createTextNode(mimetype)) + mimetype_element = media_package_content.createElement("mimetype") + mimetype_element.appendChild(media_package_content.createTextNode(mimetype)) element.appendChild(mimetype_element) - url = mediaPackage_content.createElement("url") - url.appendChild(mediaPackage_content.createTextNode(url_text)) + url = media_package_content.createElement("url") + url.appendChild(media_package_content.createTextNode(url_text)) element.appendChild(url) if element_name == "track": - live = mediaPackage_content.createElement("live") - live.appendChild(mediaPackage_content.createTextNode("false")) + live = media_package_content.createElement("live") + live.appendChild(media_package_content.createTextNode("false")) element.appendChild(live) return element diff --git a/pod/recorder/views.py b/pod/recorder/views.py index f5a421451c..6707bf50ba 100644 --- a/pod/recorder/views.py +++ b/pod/recorder/views.py @@ -494,19 +494,19 @@ def info_me_json(request): def ingest_createMediaPackage(request): # URI createMediaPackage useful for OpenCast Studio # Necessary id. Example format : a3d9e9f3-66d0-403b-a775-acb3f79196d4 - idMedia = uuid.uuid4() + id_media = uuid.uuid4() # Necessary start date. Example format : 2021-12-08T08:52:28Z start = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%dT%H:%M:%S%zZ") - mediaPackage_dir = os.path.join( - settings.MEDIA_ROOT, OPENCAST_FILES_DIR, "%s" % idMedia + media_package_dir = os.path.join( + settings.MEDIA_ROOT, OPENCAST_FILES_DIR, "%s" % id_media ) - mediaPackage_file = os.path.join(mediaPackage_dir, "%s.xml" % idMedia) + media_package_file = os.path.join(media_package_dir, "%s.xml" % id_media) # create directory to store all the data. - os.makedirs(mediaPackage_dir, exist_ok=True) + os.makedirs(media_package_dir, exist_ok=True) - mediaPackage_content = minidom.parseString(OPENCAST_MEDIAPACKAGE) - mediapackage = mediaPackage_content.getElementsByTagName("mediapackage")[0] - mediapackage.setAttribute("id", "%s" % idMedia) + media_package_content = minidom.parseString(OPENCAST_MEDIAPACKAGE) + mediapackage = media_package_content.getElementsByTagName("mediapackage")[0] + mediapackage.setAttribute("id", "%s" % id_media) mediapackage.setAttribute("start", start) presenter = OPENCAST_DEFAULT_PRESENTER @@ -515,17 +515,17 @@ def ingest_createMediaPackage(request): del request.session["presenter"] mediapackage.setAttribute("presenter", presenter) - with open(mediaPackage_file, "w") as f: - f.write(mediaPackage_content.toxml()) - return HttpResponse(mediaPackage_content.toxml(), content_type="application/xml") + with open(media_package_file, "w") as f: + f.write(media_package_content.toxml()) + return HttpResponse(media_package_content.toxml(), content_type="application/xml") @login_required(redirect_field_name="referrer") @csrf_exempt def ingest_addDCCatalog(request): # URI addDCCatalog useful for OpenCast Studio - # Form management with 3 parameters : mediaPackage, dublinCore, flavor - # For Pod, management of dublinCore is useless + # Form management with 3 parameters : mediaPackage, dublin_core, flavor + # For Pod, management of dublin_core is useless if ( request.POST.get("mediaPackage") and request.POST.get("flavor") @@ -535,49 +535,49 @@ def ingest_addDCCatalog(request): # Id catalog. Example format: 798017b1-2c45-42b1-85b0-41ce804fa527 # idCatalog = uuid.uuid4() # Id media package - idMedia = "" + id_media = "" # dublinCore - dublinCore = "" - idMedia = get_id_media(request) + dublin_core = "" + id_media = get_id_media(request) if request.POST.get("flavor") and request.POST.get("flavor") != "": typeCatalog = request.POST.get("flavor") if request.POST.get("dublinCore") and request.POST.get("dublinCore") != "": - dublinCore = request.POST.get("dublinCore") + dublin_core = request.POST.get("dublinCore") - mediaPackage_dir = os.path.join( - settings.MEDIA_ROOT, OPENCAST_FILES_DIR, "%s" % idMedia + media_package_dir = os.path.join( + settings.MEDIA_ROOT, OPENCAST_FILES_DIR, "%s" % id_media ) # create directory to store the dublincore file. - os.makedirs(mediaPackage_dir, exist_ok=True) + os.makedirs(media_package_dir, exist_ok=True) # store the dublin core file - dublinCore_file = os.path.join(mediaPackage_dir, "dublincore.xml") - with open(dublinCore_file, "w+") as f: - f.write(unquote(dublinCore)) + dublin_core_file = os.path.join(media_package_dir, "dublincore.xml") + with open(dublin_core_file, "w+") as f: + f.write(unquote(dublin_core)) - mediaPackage_content, mediaPackage_file = get_media_package_content( - mediaPackage_dir, idMedia + media_package_content, media_package_file = get_media_package_content( + media_package_dir, id_media ) dc_url = str( - "%(http)s://%(host)s%(media)sopencast-files/%(idMedia)s/dublincore.xml" + "%(http)s://%(host)s%(media)sopencast-files/%(id_media)s/dublincore.xml" % { "http": "https" if request.is_secure() else "http", "host": request.get_host(), "media": MEDIA_URL, - "idMedia": "%s" % idMedia, + "id_media": "%s" % id_media, } ) catalog = create_xml_element( - mediaPackage_content, "catalog", typeCatalog, "text/xml", dc_url + media_package_content, "catalog", typeCatalog, "text/xml", dc_url ) - metadata = mediaPackage_content.getElementsByTagName("metadata")[0] + metadata = media_package_content.getElementsByTagName("metadata")[0] metadata.appendChild(catalog) - with open(mediaPackage_file, "w+") as f: - f.write(mediaPackage_content.toxml()) + with open(media_package_file, "w+") as f: + f.write(media_package_content.toxml()) - return HttpResponse(mediaPackage_content.toxml(), content_type="application/xml") + return HttpResponse(media_package_content.toxml(), content_type="application/xml") return HttpResponseBadRequest() @@ -632,12 +632,12 @@ def ingest_ingest(request): # Form management with 1 parameter : mediaPackage # Management of the mediaPackage (XML) if request.POST.get("mediaPackage"): - idMedia = get_id_media(request) - mediaPackage_dir = os.path.join( - settings.MEDIA_ROOT, OPENCAST_FILES_DIR, "%s" % idMedia + id_media = get_id_media(request) + media_package_dir = os.path.join( + settings.MEDIA_ROOT, OPENCAST_FILES_DIR, "%s" % id_media ) - mediaPackage_content, mediaPackage_file = get_media_package_content( - mediaPackage_dir, idMedia + media_package_content, media_package_file = get_media_package_content( + media_package_dir, id_media ) # Create the recording # Search for the recorder corresponding to the Studio @@ -647,10 +647,10 @@ def ingest_ingest(request): if recorder: recording = Recording.objects.create( user=request.user, - title=idMedia, + title=id_media, type="studio", # Source file corresponds to Pod XML file - source_file=mediaPackage_file, + source_file=media_package_file, recorder=recorder, ) recording.save() @@ -660,6 +660,6 @@ def ingest_ingest(request): ) raise PermissionDenied - return HttpResponse(mediaPackage_content.toxml(), content_type="application/xml") + return HttpResponse(media_package_content.toxml(), content_type="application/xml") return HttpResponseBadRequest()