Skip to content
Snippets Groups Projects
serializers.py 37 KiB
Newer Older
  • Learn to ignore specific revisions
  •         ) + read_only_fields
    
            """Create and return a new Note instance, given the validated data."""
    
            links_data = validated_data.pop("links", [])
    
            show = validated_data["timeslot"].schedule.show
    
            user = self.context.get("request").user
            user_is_owner = user in show.owners.all()
    
    
            # Having the create_note permission overrides the ownership
    
            if not (
                user.has_perm("program.create_note")
                or (user.has_perm("program.add_note") and user_is_owner)
            ):
    
                raise exceptions.PermissionDenied(detail="You are not allowed to create this note.")
    
            # we derive `contributors`, `language` and `topic` from the Show's values if not set
    
            contributors = validated_data.pop("contributors", show.hosts.values_list("id", flat=True))
    
            language = validated_data.pop("language", show.language.values_list("id", flat=True))
            topic = validated_data.pop("topic", show.topic.values_list("id", flat=True))
    
            # optional foreign key
    
            validated_data["image"] = validated_data.pop("image", None)
    
            try:
                note = Note.objects.create(
                    created_by=self.context.get("request").user.username,
                    **validated_data,
                )
            except IntegrityError:
                raise exceptions.ValidationError(
                    code="duplicate", detail="note for this timeslot already exists."
                )
            else:
                note.contributors.set(contributors)
                note.language.set(language)
                note.topic.set(topic)
    
                # optional nested objects
                for link_data in links_data:
                    NoteLink.objects.create(note=note, **link_data)
    
    
        def update(self, instance, validated_data):
    
            """Update and return an existing Note instance, given the validated data."""
    
    
            user = self.context.get("request").user
    
            user_is_owner = user in instance.timeslot.schedule.show.owners.all()
    
            # Having the update_note permission overrides the ownership
    
            if not (
                user.has_perm("program.update_note")
                or (user.has_perm("program.change_note") and user_is_owner)
            ):
    
                raise exceptions.PermissionDenied(detail="You are not allowed to update this note.")
    
            if "cba_id" in validated_data:
                instance.cba_id = validated_data.get("cba_id")
    
            if "content" in validated_data:
                instance.content = validated_data.get("content")
    
            if "image" in validated_data:
                instance.image = validated_data.get("image")
    
            if "summary" in validated_data:
                instance.summary = validated_data.get("summary")
    
            if "timeslot" in validated_data:
                instance.timeslot = validated_data.get("timeslot")
    
            if "tags" in validated_data:
                instance.tags = validated_data.get("tags")
    
            if "title" in validated_data:
                instance.title = validated_data.get("title")
    
            if "contributors" in validated_data:
                instance.contributors.set(validated_data.get("contributors", []))
    
            if "language" in validated_data:
                instance.language.set(validated_data.get("language", []))
    
            # Only update this field if the user has the update_note permission, ignore otherwise
            if "topic" in validated_data and user.has_perm("program.update_note"):
    
                instance.topic.set(validated_data.get("topic", []))
    
            # optional nested objects
    
            if "links" in validated_data:
    
                instance = delete_links(instance)
    
    
                for link_data in validated_data.get("links"):
    
                    NoteLink.objects.create(note=instance, **link_data)
    
            instance.updated_by = self.context.get("request").user.username
    
    
    
    class RadioSettingsSerializer(serializers.ModelSerializer):
        cba = serializers.SerializerMethodField()
    
    Ernesto Rico Schmidt's avatar
    Ernesto Rico Schmidt committed
        line_in = serializers.SerializerMethodField()
        programme = serializers.SerializerMethodField()
    
        station = serializers.SerializerMethodField()
    
        class Meta:
    
    Ernesto Rico Schmidt's avatar
    Ernesto Rico Schmidt committed
            read_only_fields = ("cba", "line_in", "programme", "station")
    
            fields = read_only_fields
            model = RadioSettings
    
        def get_cba(self, obj) -> dict[str, str] | dict[str, list[str]]:
            if self.context.get("request").user.is_authenticated:
                return {
                    "api_key": obj.cba_api_key,
                    "domain": obj.cba_domains,
                }
            else:
                return {"domains": obj.cba_domains}
    
        @staticmethod
    
    Ernesto Rico Schmidt's avatar
    Ernesto Rico Schmidt committed
        def get_programme(obj) -> dict[str, int]:
            return {"fallbackShowId": obj.fallback_show.id if obj.fallback_show else None}
    
    Ernesto Rico Schmidt's avatar
    Ernesto Rico Schmidt committed
        def get_line_in(obj) -> dict[str, dict[str, str]]:
            return {"channels": obj.line_in_channels}
    
    
        @staticmethod
        def get_station(obj) -> dict[str, int | str]:
            return {
                "name": obj.station_name,
    
    Ernesto Rico Schmidt's avatar
    Ernesto Rico Schmidt committed
                "logoId": obj.station_logo.id if obj.station_logo else None,
    
                "website": obj.station_website,
            }