U
    	h5U                     @   sz  d Z ddlmZmZmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZmZ ddlmZ ddlmZmZmZmZ ddlm Z  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6m7Z7 ddl8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z? G dd de
Z@eedde"e#e$e%g e(dgdedde(dgdedddgdedd dgded!d"dgded#d$dgdd%G d&d' d'ejAZBeed(d)e"e#e&e'g d*gd+ed,d-d*gded.d/d*gded0d1d*gded2d3d*gded4d5d*gdd%G d6d7 d7ejAZCeed8d9e"e#g d:gd+ed;d<d:gdd=G d>d? d?ejDZEeed@dAe"e#g dBgd+edCdDdBgdedEdFdBgdedGdHdBgdedIdJdBgdedKdLdBgdd%G dMdN dNejAZFeedOdPe"e#g dBgd+edQdRdBgdedSdTdBgdedUdVdBgdedWdXdBgdedYdZdBgdd%G d[d\ d\ejAZGd]S )^z
REST API Views for Streams Application

This module contains Django REST Framework views for managing
streaming channels, sessions, configurations, and related operations
through a RESTful API interface.
    )viewsetsstatuspermissions)action)Response)PageNumberPagination)UserRateThrottle)DjangoFilterBackend)get_object_or_404)timezone)CountSumAvgQ)	timedelta)extend_schemaextend_schema_viewOpenApiParameterOpenApiExample)OpenApiTypes)	PAGINATION_PARAMETERSORDERING_PARAMETERSEARCH_PARAMETERCHANNEL_STATUS_PARAMETERSESSION_STATUS_PARAMETERCHANNEL_FILTER_PARAMETERCHANNEL_EXAMPLESSUCCESS_EXAMPLESERROR_EXAMPLES)ChannelStreamSession
HLSSegmentVideoConfigurationAudioConfiguration)start_stream_capturestop_stream_capturecreate_playlist_for_channel)StreamControlThrottleDetectionAPIThrottle)ChannelSerializerStreamSessionSerializerHLSSegmentSerializerVideoConfigurationSerializerAudioConfigurationSerializerChannelStatsSerializerStreamStartSerializerc                   @   s   e Zd ZdZdZdZdZdS )StandardResultsSetPaginationz
    Standard pagination configuration for API responses.
    
    Provides consistent pagination across all API endpoints
    with configurable page sizes and metadata.
       	page_sized   N)__name__
__module____qualname____doc__r2   page_size_query_parammax_page_size r:   r:   :/var/www/html/JingleDetector/src/apps/streams/api/views.pyr0   %   s   r0   zList channelsz/Retrieve a paginated list of streaming channelsChannels)summarydescription
parametersexamplestagszCreate channelzCreate a new streaming channel)r=   r>   r@   rA   zGet channelz!Retrieve a specific channel by ID)r=   r>   rA   zUpdate channelzUpdate an existing channelzPartially update channelz$Partially update an existing channelzDelete channelz(Delete a channel and all associated data)listcreateretrieveupdatepartial_updatedestroyc                   @   sZ  e Zd ZdZej dZe	Z
ejgZeZegZddgZdddgZdddgZd	gZd
d Zeddeeddddddded ed ddgdeddgegdd3ddZedd ed! ed ed ddgd"eddgegdd4d#d$Zed%d&e ed d'dgd"edd(gd)d5d*d+Z!ed,d-d.e	dd/idgd"ed0d(gd)d1d2 Z"dS )6ChannelViewSetz
    ViewSet for managing streaming channels via REST API.
    
    Provides CRUD operations for channels along with custom actions
    for starting/stopping streams and retrieving statistics.
    
created_by	is_activenameslugr>   
created_at
updated_atz-created_atc                 C   s   |j | jjd dS )z
        Set the current user as the channel creator.
        
        Args:
            serializer: Channel serializer instance
        )rI   N)saverequestuser)self
serializerr:   r:   r;   perform_createf   s    zChannelViewSet.perform_createzStart stream capturezTStart stream capture for a specific channel with optional video/audio configurationszStream StartedTzStream started for News Channelzabc123-def456-ghi789z$f47ac10b-58cc-4372-a567-0e02b2c3d479successmessagetask_id
channel_id)valuevalidation_error	not_found   i  i  r<   )r=   r>   rP   	responsesrA   post)detailmethodsthrottle_classesNc              
   C   s  |   }| r"tdditjdS t|jd}| sFt|jtjdS zxt	j
t|j|jdrpt|jdnd|jdrt|jdndd}td	d
|j |jt|jdtjdW S  tk
 r } ztdt|itjd W Y S d}~X Y nX dS )a  
        Start stream capture for a specific channel.
        
        Args:
            request: HTTP request with optional configuration IDs
            pk: Channel primary key
            
        Returns:
            Response: Success/error response with task information
        errorz,Channel already has an active stream sessionr   )datavideo_config_idNaudio_config_id)rY   rg   rh   TzStream started for rU   )
get_objectget_active_sessionr   r   HTTP_400_BAD_REQUESTr/   rf   is_validerrorsr$   delaystridvalidated_datagetrK   HTTP_202_ACCEPTED	ExceptionHTTP_500_INTERNAL_SERVER_ERROR)rR   rP   pkchannelrS   tasker:   r:   r;   start_streamo   s>    

zChannelViewSet.start_streamzStop stream capturez1Stop active stream capture for a specific channeltask_startedr=   r>   r_   rA   c              
   C   s   |   }| }|s&tdditjdS z:tt|j}tdd|j	 |jt|jdtj
dW S  tk
r } ztdt|itjd W Y S d}~X Y nX dS )z
        Stop active stream for a specific channel.
        
        Args:
            request: HTTP request
            pk: Channel primary key
            
        Returns:
            Response: Success/error response with task information
        rd   z/No active stream session found for this channelre   TStream stopped for )rV   rW   rX   
session_idN)ri   rj   r   r   rk   r%   rn   ro   rp   rK   rs   rt   ru   )rR   rP   rv   rw   active_sessionrx   ry   r:   r:   r;   stop_stream   s,    

zChannelViewSet.stop_streamzGet channel statisticszjRetrieve detailed statistics for a specific channel including session counts, durations, and success rates)   i  rr   ra   rb   c              	   C   s  |   }|j }tjj|d}| }|jddgd }|dkrP|| d nd}|jdd}	d}
g }|	D ].}| rlt| 	 }|
|7 }
|
| ql|rt|t| nd}||jddgd | |
t|d	t|| r|d
 jndd}t|}t|jS )z
        Get detailed statistics for a specific channel.
        
        Args:
            request: HTTP request
            pk: Channel primary key
            
        Returns:
            Response: Channel statistics data
        )session__channel	completedactive
status__inr   r3   re   
processing   -started_atN)total_sessionsactive_sessionstotal_segmentstotal_durationsuccess_rateavg_session_durationZlast_session_at)ri   sessionsallr!   objectsfiltercountdurationinttotal_secondsappendsumlenroundexistsorder_byfirst
started_atr.   r   rf   )rR   rP   rv   rw   r   segmentsr   Zsuccessful_sessionsr   Zcompleted_sessionsr   Zsession_durationssessionduration_secondsr   
stats_datarS   r:   r:   r;   
statistics   s6    


zChannelViewSet.statisticszGet active channelsz@Retrieve all channels that currently have active stream sessionsr   manyFc                 C   s.   | j jddgd }| j|dd}t|jS )z
        Get all channels with active streams.
        
        Args:
            request: HTTP request
            
        Returns:
            Response: List of channels with active sessions
        r   r   )Zsessions__status__inTr   )querysetr   distinctget_serializerr   rf   )rR   rP   Zactive_channelsrS   r:   r:   r;   r      s
    
zChannelViewSet.active)N)N)N)#r4   r5   r6   r7   r   r   r   select_relatedr   r)   serializer_classr   IsAuthenticatedpermission_classesr0   pagination_classr	   filter_backendsfilterset_fieldssearch_fieldsordering_fieldsorderingrT   r   r/   r   r   r   r'   rz   r   r   r.   r   r   r:   r:   r:   r;   rH   1   sv   $

		1
%	2rH   zList stream sessionsz,Retrieve a paginated list of stream sessionsSessions)r=   r>   r?   rA   zCreate stream sessionzCreate a new stream sessionzGet stream sessionz(Retrieve a specific stream session by IDzUpdate stream sessionz!Update an existing stream sessionzPartially update stream sessionz+Partially update an existing stream sessionzDelete stream sessionz/Delete a stream session and all associated datac                   @   s   e Zd ZdZej dddZe	Z
ejgZeZegZddgZdddgZdgZed	d
ed ed ed ddgdeddgdd"ddZeddededdidgdeddgdd#ddZeddgdd d! ZdS )$StreamSessionViewSetz
    ViewSet for managing stream sessions via REST API.
    
    Provides CRUD operations for sessions along with custom actions
    for stopping sessions and retrieving segments.
    rw   video_configaudio_configr   r   ended_atr   zStop stream sessionz%Stop a specific active stream sessionr{   r[   r\   r]   r   r|   Tr`   r   Nc              
   C   s   |   }| s"tdditjdS z4tt|j}tdd|j	j
 |jdtjdW S  tk
r } ztdt|itjd W Y S d}~X Y nX dS )z
        Stop a specific stream session.
        
        Args:
            request: HTTP request
            pk: Session primary key
            
        Returns:
            Response: Success/error response with task information
        rd   z Session is not currently runningre   Tr}   )rV   rW   rX   N)ri   
is_runningr   r   rk   r%   rn   ro   rp   rw   rK   rs   rt   ru   )rR   rP   rv   r   rx   ry   r:   r:   r;   stopm  s(    
zStreamSessionViewSet.stopzGet session segmentsz3Retrieve HLS segments for a specific stream sessionr   r   )r=   r>   r?   r_   rA   rr   c                 C   s^   |   }|jd}|  }|||}|dk	rHt|dd}||jS t|dd}t|jS )a  
        Get segments for a specific session.
        
        Args:
            request: HTTP request with optional pagination
            pk: Session primary key
            
        Returns:
            Response: Paginated list of session segments
        -processed_atNTr   )	ri   r   r   r   paginate_querysetr+   get_paginated_responserf   r   )rR   rP   rv   r   r   	paginatorpagerS   r:   r:   r;   r     s    zStreamSessionViewSet.segmentsFc                 C   s*   | j jddgd}| j|dd}t|jS )z
        Get all active stream sessions.
        
        Args:
            request: HTTP request
            
        Returns:
            Response: List of active sessions
        r   r   r   Tr   )r   r   r   r   rf   )rR   rP   r   rS   r:   r:   r;   r     s
    zStreamSessionViewSet.active)N)N)r4   r5   r6   r7   r    r   r   r   r   r*   r   r   r   r   r0   r   r	   r   r   r   r   r   r   r   r   r   r   r+   r   r   r:   r:   r:   r;   r   9  sF   "
  

#r   zList HLS segmentsz=Retrieve a paginated list of HLS segments across all sessionsSegmentszGet HLS segmentz%Retrieve a specific HLS segment by ID)rB   rD   c                   @   s~   e Zd ZdZej dZe	Z
ejgZeZegZddgZddgZdgZedd	d
e	ddidgdeddgddd ZdS )HLSSegmentViewSetz
    ViewSet for HLS segments (read-only).
    
    Provides read-only access to segment information for monitoring
    and debugging purposes.
    r   r   is_availableprocessed_atsequence_numberr   zGet recent segmentszHRetrieve the 50 most recently processed HLS segments across all sessionsr   Tr   r   r|   Frr   r   c                 C   s,   | j ddd }| j|dd}t|jS )z
        Get recently processed segments across all sessions.
        
        Args:
            request: HTTP request
            
        Returns:
            Response: List of recent segments
        r   N2   Tr   )r   r   r   r   rf   )rR   rP   recent_segmentsrS   r:   r:   r;   recent  s    zHLSSegmentViewSet.recentN)r4   r5   r6   r7   r!   r   r   r   r   r+   r   r   r   r   r0   r   r	   r   r   r   r   r   r   r   r:   r:   r:   r;   r     s"   r   zList video configurationsz0Retrieve a list of video encoding configurationsConfigurationszCreate video configurationz)Create a new video encoding configurationzGet video configurationz-Retrieve a specific video configuration by IDzUpdate video configurationz&Update an existing video configurationz$Partially update video configurationz0Partially update an existing video configurationzDelete video configurationzDelete a video configurationc                   @   s8   e Zd ZdZej ZeZ	e
jgZeZddgZdgZdS )VideoConfigurationViewSetz
    ViewSet for video encoding configurations.
    
    Provides CRUD operations for video encoding presets
    that can be used with stream sessions.
    rK   rM   N)r4   r5   r6   r7   r"   r   r   r   r,   r   r   r   r   r0   r   r   r   r:   r:   r:   r;   r     s   "
r   zList audio configurationsz0Retrieve a list of audio encoding configurationszCreate audio configurationz)Create a new audio encoding configurationzGet audio configurationz-Retrieve a specific audio configuration by IDzUpdate audio configurationz&Update an existing audio configurationz$Partially update audio configurationz0Partially update an existing audio configurationzDelete audio configurationzDelete an audio configurationc                   @   s8   e Zd ZdZej ZeZ	e
jgZeZddgZdgZdS )AudioConfigurationViewSetz
    ViewSet for audio encoding configurations.
    
    Provides CRUD operations for audio encoding presets
    that can be used with stream sessions.
    rK   rM   N)r4   r5   r6   r7   r#   r   r   r   r-   r   r   r   r   r0   r   r   r   r:   r:   r:   r;   r   4  s   "
r   N)Hr7   rest_frameworkr   r   r   rest_framework.decoratorsr   rest_framework.responser   Zrest_framework.paginationr   Zrest_framework.throttlingr   Zdjango_filters.rest_frameworkr	   django.shortcutsr
   django.utilsr   django.db.modelsr   r   r   r   datetimer   drf_spectacular.utilsr   r   r   r   drf_spectacular.typesr   Zcore.schemar   r   r   r   r   r   r   r   r   Zapps.streams.modelsr   r    r!   r"   r#   apps.streams.tasksr$   r%   r&   apps.core.throttlingr'   r(   Zapps.streams.api.serializersr)   r*   r+   r,   r-   r.   r/   r0   ModelViewSetrH   r   ReadOnlyModelViewSetr   r   r   r:   r:   r:   r;   <module>   sV  ,$# f!u'!!