Newer
Older
#
# steering, Programme/schedule management for AURA
#
# Copyright (C) 2011-2017, 2020, Ernesto Rico Schmidt
# Copyright (C) 2017-2019, Ingo Leindecker
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from datetime import datetime
from functools import cached_property
from zoneinfo import ZoneInfo
from drf_jsonschema_serializer import JSONSchemaField
from rest_framework.permissions import exceptions
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist

Ernesto Rico Schmidt
committed
from django.db import IntegrityError, transaction
from django.db.models import Q
from django.utils import text, timezone
Playlist,
ProgramEntry,
from program.typing import (
Logo,
MicroProgram,
ProgramFallback,
RadioCBASettings,
RadioImageRequirementsSettings,
RadioPlayoutSettings,
RadioProgramSettings,
RadioStationSettings,
)
from program.utils import update_links
SOLUTION_CHOICES = {
"theirs": "Discard projected timeslot. Keep existing timeslot(s).",
"ours": "Create projected timeslot. Delete existing timeslot(s).",
"theirs-start": (
"Keep existing timeslot. Create projected timeslot with start time of existing end."
),
"ours-start": (
"Create projected timeslot. Change end of existing timeslot to projected start time."
),
"theirs-end": (
"Keep existing timeslot. Create projected timeslot with end of existing start time."
),
"ours-end": (
"Create projected timeslot. Change start of existing timeslot to projected end time."
),
"theirs-both": (
"Keep existing timeslot. "
"Create two projected timeslots with end of existing start and start of existing end."
),
"ours-both": (
"Create projected timeslot. Split existing timeslot into two: \n\n"
"* set existing end time to projected start,\n"
"* create another timeslot with start = projected end and end = existing end."
),
}
class ErrorSerializer(serializers.Serializer):
message = serializers.CharField()
code = serializers.CharField(allow_null=True)
class CBASerializer(serializers.ModelSerializer):
read_only_fields = (
"created_at",
"created_by",
"updated_at",
"updated_by",
)
fields = (
"username",
"user_token",
) + read_only_fields
def to_representation(self, instance):
if not self.parent.context.get("request").user.is_authenticated:
return None
return super().to_representation(instance)
class UserSerializer(serializers.ModelSerializer):
is_privileged = serializers.SerializerMethodField()
permissions = serializers.SerializerMethodField()
cba = CBASerializer(required=False)
profile_ids = serializers.PrimaryKeyRelatedField(
many=True, queryset=Profile.objects.all(), required=False, source="profiles"
class Meta:
extra_kwargs = {
"password": {"write_only": True},
}
model = User
) + read_only_fields
@staticmethod
def get_permissions(obj: User) -> list[str]:
return sorted(
[p for p in obj.get_all_permissions() if p.split(".", 1)[0] in ["auth", "program"]]
)
@staticmethod
def get_is_privileged(obj: User) -> bool:
return obj.is_superuser
def create(self, validated_data):
"""
Create and return a new User instance, given the validated data.
"""
cba_data = validated_data.pop("cba") if "cba" in validated_data else None
user = super(UserSerializer, self).create(validated_data)
user.date_joined = timezone.now()
user.set_password(validated_data["password"])
if cba_data:
CBA.objects.create(
username=cba_data.get("username").strip(),
user_token=cba_data.get("user_token").strip(),
created_by=self.context.get("request").user.username,
user=user,
def update(self, instance, validated_data):
"""
Update and return an existing User instance, given the validated data.
"""
if "first_name" in validated_data:
instance.first_name = validated_data.get("first_name")
if "last_name" in validated_data:
instance.last_name = validated_data.get("last_name")
if "email" in validated_data:
instance.email = validated_data.get("email")
if "is_active" in validated_data:
instance.is_active = validated_data.get("is_active")
if "is_staff" in validated_data:
instance.is_staff = validated_data.get("is_staff")
if "is_superuser" in validated_data:
instance.is_superuser = validated_data.get("is_superuser")
cba_data = validated_data.pop("cba") if "cba" in validated_data else None
except ObjectDoesNotExist:
user = self.context.get("request").user
if cba:
# having the update_cba permission overrides being the user
if not (user.has_perm("program.update_cba") or user.id == instance.id):
raise exceptions.PermissionDenied(
detail="You do not have permission to update this user CBA profile."
if "username" in cba_data:
cba.username = cba_data.get("username")
if "user_token" in cba_data:
cba.user_token = cba_data.get("user_token")
cba.updated_by = self.context.get("request").user.username
cba.save()
else:
# having the create_cba permission overrides being the user
if not (user.has_perm("program.create_cba") or user.id == instance.id):
raise exceptions.PermissionDenied(
detail="You do not have permission to create this user CBA profile."
created_by=self.context.get("request").user.username,
user=instance,
instance.save()
return instance
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ("description", "id", "is_active", "name", "slug", "subtitle")
class LinkTypeSerializer(serializers.ModelSerializer):
class Meta:
model = LinkType
fields = ("id", "is_active", "name")
class LicenseSerializer(serializers.ModelSerializer):
fields = (
"id",
"identifier",
"name",
"needs_author",
"requires_express_permission_for_publication",
"url",
)
class ProfileLinkSerializer(serializers.ModelSerializer):
type_id = serializers.PrimaryKeyRelatedField(queryset=LinkType.objects.all(), source="type")
class Meta:
fields = ("type_id", "url")
class PPOIField(serializers.CharField):
def validate_format(self, value: str):
if not re.match(r"\d(?:\.\d+)?x\d(?:\.\d+)?", value):
raise serializers.ValidationError("PPOI must match format: ${float}x${float}")
def __init__(self, **kwargs):
kwargs["max_length"] = 20
kwargs.setdefault("validators", [])
kwargs["validators"].append(self.validate_format)
super().__init__(**kwargs)
def to_representation(self, value: tuple[float, float]):
[left, top] = value
return f"{left}x{top}"
class ImageSerializer(serializers.ModelSerializer):
license_id = serializers.PrimaryKeyRelatedField(
allow_null=True,
queryset=License.objects.all(),
required=False,
source="license",
help_text="`License` ID of this image.",
ppoi = PPOIField(required=False, help_text="PPOI specifies the crop centerpoint of the image.")

Ernesto Rico Schmidt
committed
url = serializers.SerializerMethodField()

Ernesto Rico Schmidt
committed
@staticmethod
def get_url(instance: Image) -> str:
"""Returns the image URL, using settings.SITE_URL to include the protocol and avoid mixed
media warnings."""
return f"{settings.SITE_URL}{instance.image.url}"
extra_kwargs = {"image": {"write_only": True}}
model = Image
read_only_fields = (
"height",
"id",
Loading
Loading full blame...