U
    	hQ0                     @   s   d Z ddlmZ ddlmZ ddlmZmZmZm	Z	m
Z
 G dd dejZG dd dejZG d	d
 d
ejZG dd dejZG dd dejZG dd dejZG dd dejZG dd dejZdS )a  
REST API Serializers for Streams Application

This module contains Django REST Framework serializers for converting
complex datatypes such as model instances to native Python datatypes
that can then be easily rendered into JSON, XML or other content types.
    )serializers)User)ChannelStreamSession
HLSSegmentVideoConfigurationAudioConfigurationc                   @   s   e Zd ZdZG dd dZdS )UserSerializerz
    Serializer for User model with basic information.
    
    Provides a simple representation of user data for API responses.
    c                   @   s$   e Zd ZeZdddddgZdgZdS )zUserSerializer.Metaidusernameemail
first_name	last_nameN)__name__
__module____qualname__r   modelfieldsread_only_fields r   r   @/var/www/html/JingleDetector/src/apps/streams/api/serializers.pyMeta   s   r   N)r   r   r   __doc__r   r   r   r   r   r	      s   r	   c                   @   s&   e Zd ZdZG dd dZdd ZdS )VideoConfigurationSerializerz
    Serializer for VideoConfiguration model.
    
    Handles serialization of video encoding configuration parameters
    for API consumption and creation.
    c                   @   s8   e Zd ZeZddddddddd	d
dddgZdddgZdS )z!VideoConfigurationSerializer.Metar
   name
resolutionaspect_ratio
frame_ratemin_bitratemax_bitratecodecpresetprofilelevel
created_at
updated_atN)r   r   r   r   r   r   r   r   r   r   r   r   #   s              r   c                 C   sz   |rv| d}t|dkr$tdz2t|d t|d  }}|dksP|dkrTtW n tk
rt   tdY nX |S )a(  
        Validate resolution format (WIDTHxHEIGHT).
        
        Args:
            value (str): Resolution string to validate
            
        Returns:
            str: Validated resolution
            
        Raises:
            ValidationError: If resolution format is invalid
        x   z;Resolution must be in format WIDTHxHEIGHT (e.g., 1920x1080)r      z/Resolution dimensions must be positive integers)splitlenr   ValidationErrorint
ValueError)selfvaluepartswidthheightr   r   r   validate_resolution,   s    

z0VideoConfigurationSerializer.validate_resolutionN)r   r   r   r   r   r3   r   r   r   r   r      s   	r   c                   @   s&   e Zd ZdZG dd dZdd ZdS )AudioConfigurationSerializerz
    Serializer for AudioConfiguration model.
    
    Handles serialization of audio encoding configuration parameters
    for API consumption and creation.
    c                	   @   s0   e Zd ZeZddddddddd	g	Zddd	gZd
S )z!AudioConfigurationSerializer.Metar
   r   r    bitratesample_ratechannels	normalizer$   r%   N)r   r   r   r   r   r   r   r   r   r   r   r   T   s          r   c                 C   sl   | j d}|rh| ds(tdz t|dd }|dkrFtW n tk
rf   tdY nX |S )z
        Validate audio bitrate format.
        
        Returns:
            str: Validated bitrate
            
        Raises:
            ValidationError: If bitrate format is invalid
        r5   kz&Bitrate must end with "k" (e.g., 128k)Nr   z1Bitrate must be a positive number followed by "k")validated_datagetlowerendswithr   r+   r,   r-   )r.   r5   rater   r   r   validate_bitrate\   s    

z-AudioConfigurationSerializer.validate_bitrateN)r   r   r   r   r   r@   r   r   r   r   r4   L   s   r4   c                   @   sP   e Zd ZdZeddZe Ze Z	G dd dZ
dd Zdd	 Zd
d ZdS )ChannelSerializerz
    Serializer for Channel model.
    
    Provides complete channel information including related configurations
    and active session status for comprehensive API responses.
    T	read_onlyc                   @   s@   e Zd ZeZddddddddd	d
ddddddgZddddgZdS )zChannelSerializer.Metar
   r   slughls_urldescription	is_activeoutput_directorysegment_durationmax_segmentsretry_attemptsretry_interval
created_byactive_sessiontotal_sessionsr$   r%   N)r   r   r   r   r   r   r   r   r   r   r   r      s&               r   c                 C   s.   |  }|r*t|j|j|j|j|jdS dS )z
        Get active session information for the channel.
        
        Args:
            obj (Channel): Channel instance
            
        Returns:
            dict: Active session data or None
        )r
   status
started_atsegments_processederrors_countN)get_active_sessionstrr
   rP   rQ   rR   rS   )r.   objrN   r   r   r   rT      s    
z$ChannelSerializer.get_active_sessionc                 C   s
   |j  S )z
        Get total number of sessions for the channel.
        
        Args:
            obj (Channel): Channel instance
            
        Returns:
            int: Total session count
        )sessionscountr.   rV   r   r   r   get_total_sessions   s    
z$ChannelSerializer.get_total_sessionsc                 C   s    |r|  dstd|S )z
        Validate HLS URL format.
        
        Args:
            value (str): HLS URL to validate
            
        Returns:
            str: Validated URL
            
        Raises:
            ValidationError: If URL format is invalid
        z.m3u8zHLS URL should end with .m3u8)r=   r>   r   r+   r.   r/   r   r   r   validate_hls_url   s
    z"ChannelSerializer.validate_hls_urlN)r   r   r   r   r	   rM   r   SerializerMethodFieldrN   rO   r   rT   rZ   r\   r   r   r   r   rA   z   s   

rA   c                   @   s>   e Zd ZdZe Ze ZG dd dZdd Z	dd Z
dS )	HLSSegmentSerializerz
    Serializer for HLSSegment model.
    
    Provides segment information with file status and metadata
    for monitoring and debugging purposes.
    c                   @   s:   e Zd ZeZddddddddd	d
dgZdddd	d
dgZdS )zHLSSegmentSerializer.Metar
   filenamesequence_numberduration	file_sizefile_size_humanis_availablefile_existsprocessed_atr$   r%   N)r   r   r   r   r   r   r   r   r   r   r   r      s(                r   c                 C   s   |  S )z
        Check if the segment file exists on disk.
        
        Args:
            obj (HLSSegment): Segment instance
            
        Returns:
            bool: True if file exists, False otherwise
        )re   rY   r   r   r   get_file_exists   s    
z$HLSSegmentSerializer.get_file_existsc                 C   sJ   |j rF|j }dD ](}|dk r0|dd|   S |d }q|ddS dS )z
        Get human-readable file size.
        
        Args:
            obj (HLSSegment): Segment instance
            
        Returns:
            str: Human-readable file size
        )BKBMBGBg      @z.1f z TBUnknown)rb   )r.   rV   sizeunitr   r   r   get_file_size_human   s    

z(HLSSegmentSerializer.get_file_size_humanN)r   r   r   r   r   r]   re   rc   r   rg   rp   r   r   r   r   r^      s   r^   c                   @   sl   e Zd ZdZeddZeddZeddZ	e
 Ze
 Ze
 ZG dd dZdd Zdd	 Zd
d ZdS )StreamSessionSerializerz
    Serializer for StreamSession model.
    
    Provides comprehensive session information including channel details,
    configurations, statistics, and recent segments.
    TrB   c                   @   sH   e Zd ZeZddddddddd	d
dddddddgZdd
dddddgZdS )zStreamSessionSerializer.Metar
   channelvideo_configaudio_configrP   rQ   ended_atra   
is_runningrR   rS   
last_error
process_id
statisticsrecent_segmentsr$   r%   N)r   r   r   r   r   r   r   r   r   r   r   r     s6                    r   c                 C   s   |  }|rt| S dS )z
        Get session duration in seconds.
        
        Args:
            obj (StreamSession): Session instance
            
        Returns:
            int: Duration in seconds or None
        N)ra   r,   total_seconds)r.   rV   ra   r   r   r   get_duration  s    
z$StreamSessionSerializer.get_durationc                 C   s   |  S )z
        Check if session is currently running.
        
        Args:
            obj (StreamSession): Session instance
            
        Returns:
            bool: True if running, False otherwise
        )rv   rY   r   r   r   get_is_running*  s    
z&StreamSessionSerializer.get_is_runningc                 C   s"   |j ddd }t|ddjS )z
        Get recent segments for the session.
        
        Args:
            obj (StreamSession): Session instance
            
        Returns:
            list: Recent segment data
        z-processed_atN   T)many)segmentsorder_byr^   data)r.   rV   rz   r   r   r   get_recent_segments6  s    
z+StreamSessionSerializer.get_recent_segmentsN)r   r   r   r   rA   rr   r   rs   r4   rt   r   r]   ra   rv   rz   r   r|   r}   r   r   r   r   r   rq      s   


rq   c                   @   s<   e Zd ZdZejdddZejdddZdd Zdd Z	d	S )
StreamStartSerializerz
    Serializer for stream start operation parameters.
    
    Handles validation and serialization of parameters needed
    to start a new stream session.
    FT)required
allow_nullc                 C   s$   |r t jj|d s td|S )a  
        Validate video configuration exists.
        
        Args:
            value (UUID): Video configuration ID
            
        Returns:
            UUID: Validated ID
            
        Raises:
            ValidationError: If configuration doesn't exist
        r
   zVideo configuration not found)r   objectsfilterexistsr   r+   r[   r   r   r   validate_video_config_idO  s    z.StreamStartSerializer.validate_video_config_idc                 C   s$   |r t jj|d s td|S )a  
        Validate audio configuration exists.
        
        Args:
            value (UUID): Audio configuration ID
            
        Returns:
            UUID: Validated ID
            
        Raises:
            ValidationError: If configuration doesn't exist
        r   zAudio configuration not found)r   r   r   r   r   r+   r[   r   r   r   validate_audio_config_idc  s    z.StreamStartSerializer.validate_audio_config_idN)
r   r   r   r   r   	UUIDFieldvideo_config_idaudio_config_idr   r   r   r   r   r   r   D  s
   r   c                   @   sL   e Zd ZdZe Ze Ze Ze Z	e
 Ze ZejddZdS )ChannelStatsSerializerz
    Serializer for channel statistics data.
    
    Provides aggregated statistics for channel performance
    and usage metrics.
    T)r   N)r   r   r   r   r   IntegerFieldrO   active_sessionstotal_segmentstotal_duration
FloatFieldsuccess_rateavg_session_durationDateTimeFieldlast_session_atr   r   r   r   r   x  s   r   N)r   rest_frameworkr   django.contrib.auth.modelsr   apps.streams.modelsr   r   r   r   r   ModelSerializerr	   r   r4   rA   r^   rq   
Serializerr   r   r   r   r   r   <module>   s   1.L7G4