From 24f6f06da58f11ca0c78abb4a6c540b82975a971 Mon Sep 17 00:00:00 2001 From: Konrad Mohrfeldt <konrad.mohrfeldt@farbdev.org> Date: Thu, 17 Mar 2022 13:02:24 +0100 Subject: [PATCH] fix: fix audio_url generation for notes There were some problems during audio_url generation for notes: 1. the cba_id was never part of the Note serializer so getting values from the validated data needed to fail. 2. the get_audio_url utililty function returned None if no cba_id was provided if a the CBA_API_KEY was missing, but None but the respective model field is not nullable on the note. 3. Request or JSON decoder errors would bubble unhandled, even though audio_url generation seems to be optional and should not necessarily interfere with note creation. --- program/serializers.py | 3 ++- program/utils.py | 15 +++++++++------ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/program/serializers.py b/program/serializers.py index a8b85bba..7e9e8af4 100644 --- a/program/serializers.py +++ b/program/serializers.py @@ -453,6 +453,7 @@ class NoteSerializer(serializers.ModelSerializer): timeslot = serializers.PrimaryKeyRelatedField(queryset=TimeSlot.objects.all()) host = serializers.PrimaryKeyRelatedField(queryset=Host.objects.all()) thumbnails = serializers.SerializerMethodField() # Read-only + cba_id = serializers.IntegerField(required=False, write_only=True) @staticmethod def get_thumbnails(note): @@ -476,7 +477,7 @@ class NoteSerializer(serializers.ModelSerializer): validated_data["user_id"] = self.context["user_id"] # Try to retrieve audio URL from CBA - validated_data["audio_url"] = get_audio_url(validated_data["cba_id"]) + validated_data["audio_url"] = get_audio_url(validated_data.get("cba_id", None)) note = Note.objects.create(**validated_data) diff --git a/program/utils.py b/program/utils.py index 6d30c207..53b6420d 100644 --- a/program/utils.py +++ b/program/utils.py @@ -18,6 +18,7 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # +import json from datetime import date, datetime, time from typing import Dict, Optional, Tuple, Union @@ -57,7 +58,7 @@ def parse_time(date_string: str) -> time: return datetime.strptime(date_string, "%H:%M:%S").time() -def get_audio_url(cba_id): +def get_audio_url(cba_id: Optional[int]) -> str: """ Retrieve the direct URL to the mp3 in CBA In order to retrieve the URL, stations need @@ -67,8 +68,8 @@ def get_audio_url(cba_id): For these contact cba@fro.at """ - if cba_id is None or cba_id == "" or CBA_API_KEY == "": - return None + if not cba_id or CBA_API_KEY == "": + return "" else: if DEBUG: url = ( @@ -85,9 +86,11 @@ def get_audio_url(cba_id): + CBA_API_KEY ) - audio_url = requests.get(url).json() - - return audio_url + try: + return requests.get(url).json() + except (requests.RequestException, json.JSONDecodeError): + # TODO: we might want to add some logging + return "" def get_values( -- GitLab