o
    i;                     @   s   d Z ddlZddlmZmZmZmZmZ ddlm	Z	 ddl
Z
ddlmZmZmZmZ G dd deZG dd	 d	eZG d
d deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd dZdS )zoDaily REST Helpers.

Methods that wrap the Daily API to create rooms, check room URLs, and get meeting tokens.
    N)AnyDictListLiteralOptional)urlparse)	BaseModel
ConfigDictFieldValidationErrorc                   @   sn   e Zd ZU dZdZeed< dZeed< dZ	eed< dZ
eed	< d
Zeeeee f  ed< d
Zee ed< d
S )DailyRoomSipParamsa  SIP configuration parameters for Daily rooms.

    Parameters:
        display_name: Name shown for the SIP endpoint.
        video: Whether video is enabled for SIP.
        sip_mode: SIP connection mode, typically 'dial-in'.
        num_endpoints: Number of allowed SIP endpoints.
        codecs: Codecs to support for audio and video. If None, uses Daily defaults.
            Example: {"audio": ["OPUS"], "video": ["H264"]}
        provider: Optional SIP provider name (defaults to None).
            Example: "daily"
    zsw-sip-dialindisplay_nameFvideozdial-insip_mode   num_endpointsNcodecsprovider)__name__
__module____qualname____doc__r   str__annotations__r   boolr   r   intr   r   r   r   r    r   r   R/home/ubuntu/.local/lib/python3.10/site-packages/pipecat/transports/daily/utils.pyr      s   
 r   c                   @   6   e Zd ZU dZeed< eed< eed< dZeed< dS )RecordingsBucketConfiga  Configuration for storing Daily recordings in a custom S3 bucket.

    Refer to the Daily API documentation for more information:
    https://docs.daily.co/guides/products/live-streaming-recording/storing-recordings-in-a-custom-s3-bucket

    Parameters:
        bucket_name: Name of the S3 bucket for storing recordings.
        bucket_region: AWS region where the S3 bucket is located.
        assume_role_arn: ARN of the IAM role to assume for S3 access.
        allow_api_access: Whether to allow API access to the recordings.
    bucket_namebucket_regionassume_role_arnFallow_api_accessNr   r   r   r   r   r   r#   r   r   r   r   r   r   *      
 r   c                   @   r   )TranscriptionBucketConfiga   Configuration for storing Daily transcription in a custom S3 bucket.

    Refer to the Daily API documentation for more information:
    https://docs.daily.co/guides/products/live-streaming-recording/storing-recordings-in-a-custom-s3-bucket

    Parameters:
        bucket_name: Name of the S3 bucket for storing transcription.
        bucket_region: AWS region where the S3 bucket is located.
        assume_role_arn: ARN of the IAM role to assume for S3 access.
        allow_api_access: Whether to allow API access to the transcription.
    r    r!   r"   Fr#   Nr$   r   r   r   r   r&   =   r%   r&   c                   @   s  e Zd ZU dZeddZdZee e	d< dZ
ee	d< dZee	d< dZee	d	< dZee	d
< dZee e	d< dZeed  e	d< dZee e	d< dZee e	d< dZee e	d< dZee e	d< dZee e	d< dZee e	d< dZeeeef  e	d< dZ ee	d< e!defddZ"dS )DailyRoomPropertiesa  Properties for configuring a Daily room.

    Reference: https://docs.daily.co/reference/rest-api/rooms/create-room#properties

    Parameters:
        exp: Optional Unix epoch timestamp for room expiration (e.g., time.time() + 300 for 5 minutes).
        enable_chat: Whether chat is enabled in the room.
        enable_prejoin_ui: Whether the pre-join UI is enabled.
        enable_emoji_reactions: Whether emoji reactions are enabled.
        eject_at_room_exp: Whether to remove participants when room expires.
        enable_dialout: Whether SIP dial-out is enabled.
        enable_recording: Recording settings ('cloud', 'cloud-audio-only', 'local', 'raw-tracks').
        enable_transcription_storage: Whether transcription storage is enabled.
        geo: Geographic region for room.
        max_participants: Maximum number of participants allowed in the room.
        recordings_bucket: Configuration for custom S3 bucket recordings.
        transcription_bucket: Configuration for custom S3 bucket transcription.
        sip: SIP configuration parameters.
        sip_uri: SIP URI information returned by Daily.
        start_video_off: Whether video is off by default.
    allow)extraNexpFenable_chatenable_prejoin_uienable_emoji_reactionseject_at_room_expenable_dialoutcloudzcloud-audio-onlylocalz
raw-tracksenable_recordingenable_transcription_storagegeomax_participantsrecordings_buckettranscription_bucketsipsip_uristart_video_offreturnc                 C   s   | j sdS d| j d  S )zGet the SIP endpoint URI if available.

        Returns:
            SIP endpoint URI or empty string if not available.
         zsip:%sendpoint)r:   )selfr   r   r   sip_endpointy   s   z DailyRoomProperties.sip_endpoint)#r   r   r   r   r	   model_configr*   r   floatr   r+   r   r,   r-   r.   r/   r3   r   r4   r5   r   r6   r   r7   r   r8   r&   r9   r   r:   r   r   r;   propertyr@   r   r   r   r   r'   P   s(   
 
r'   c                   @   sD   e Zd ZU dZdZee ed< dZe	d ed< e
edZeed< dS )	DailyRoomParamszParameters for creating a Daily room.

    Parameters:
        name: Optional custom name for the room.
        privacy: Room privacy setting ('private' or 'public').
        properties: Room configuration properties.
    Nnamepublic)privaterF   privacydefault_factory
properties)r   r   r   r   rE   r   r   r   rH   r   r
   r'   rK   r   r   r   r   rD      s
   
 rD   c                   @   sJ   e Zd ZU dZeed< eed< eed< eed< eed< eed< eed< d	S )
DailyRoomObjecta  Represents a Daily room returned by the API.

    Parameters:
        id: Unique room identifier.
        name: Room name.
        api_created: Whether room was created via API.
        privacy: Room privacy setting ('private' or 'public').
        url: Full URL for joining the room.
        created_at: Timestamp of room creation in ISO 8601 format (e.g., "2019-01-26T09:01:22.000Z").
        config: Room configuration properties.
    idrE   api_createdrH   url
created_atconfigN)r   r   r   r   r   r   r   r'   r   r   r   r   rL      s   
 rL   c                   @   s  e Zd ZU dZdZee ed< dZee	 ed< dZ
ee ed< dZee ed< dZee ed< dZee	 ed< dZee ed	< dZee ed
< dZee	 ed< dZee	 ed< dZee	 ed< dZeed  ed< dZee	 ed< dZee	 ed< dZeeeef  ed< dS )DailyMeetingTokenPropertiesa}  Properties for configuring a Daily meeting token.

    Refer to the Daily API documentation for more information:
    https://docs.daily.co/reference/rest-api/meeting-tokens/create-meeting-token#properties

    Parameters:
        room_name: The room for which this token is valid. If not set, the token is valid for all rooms in your domain.
        eject_at_token_exp: If True, the user will be ejected from the room when the token expires.
        eject_after_elapsed: The number of seconds after which the user will be ejected from the room.
        nbf: Not before timestamp - users cannot join with this token before this time.
        exp: Expiration time (unix timestamp in seconds). Strongly recommended for security.
        is_owner: If True, the token will grant owner privileges in the room.
        user_name: The name of the user. This will be added to the token payload.
        user_id: A unique identifier for the user. This will be added to the token payload.
        enable_screenshare: If True, the user will be able to share their screen.
        start_video_off: If True, the user's video will be turned off when they join the room.
        start_audio_off: If True, the user's audio will be turned off when they join the room.
        enable_recording: Recording settings for the token. Must be one of 'cloud', 'cloud-audio-only', 'local' or 'raw-tracks'.
        enable_prejoin_ui: If True, the user will see the prejoin UI before joining the room.
        start_cloud_recording: Start cloud recording when the user joins the room.
        permissions: Specifies the initial default permissions for a non-meeting-owner participant.
    N	room_nameeject_at_token_expeject_after_elapsednbfr*   is_owner	user_nameuser_idenable_screensharer;   start_audio_offr0   r3   r,   start_cloud_recordingpermissions)r   r   r   r   rS   r   r   r   rT   r   rU   r   rV   r*   rW   rX   rY   rZ   r;   r[   r3   r   r,   r\   r]   r   r   r   r   r   r   rR      s"   
 rR   c                   @   s$   e Zd ZU dZeedZeed< dS )DailyMeetingTokenParamsa  Parameters for creating a Daily meeting token.

    Refer to the Daily API documentation for more information:
    https://docs.daily.co/reference/rest-api/meeting-tokens/create-meeting-token#body-params

    Parameters:
        properties: Meeting token configuration properties.
    rI   rK   N)r   r   r   r   r
   rR   rK   r   r   r   r   r   r^      s   
 	r^   c                   @   s   e Zd ZdZdddededejfddZd	ed
efddZd	ed
e	fddZ
ded
e	fddZ				d"d	ededededee d
efddZd	ed
efddZded
efddZded
e	fd d!ZdS )#DailyRESTHelperzHelper class for interacting with Daily's REST API.

    Provides methods for creating, managing, and accessing Daily rooms.
    zhttps://api.daily.co/v1)daily_api_urldaily_api_keyr`   aiohttp_sessionc                C   s   || _ || _|| _dS )zInitialize the Daily REST helper.

        Args:
            daily_api_key: Your Daily API key.
            daily_api_url: Daily API base URL (e.g. "https://api.daily.co/v1").
            aiohttp_session: Async HTTP session for making requests.
        N)ra   r`   rb   )r?   ra   r`   rb   r   r   r   __init__   s   
zDailyRESTHelper.__init__room_urlr<   c                 C   s   t |jdd S )zExtract room name from a Daily room URL.

        Args:
            room_url: Full Daily room URL.

        Returns:
            Room name portion of the URL.
        r   N)r   path)r?   rd   r   r   r   get_name_from_url   s   	z!DailyRESTHelper.get_name_from_urlc                       |  |}| |I dH S )zGet room details from a Daily room URL.

        Args:
            room_url: Full Daily room URL.

        Returns:
            DailyRoomObject instance for the room.
        N)rf   _get_room_from_namer?   rd   rS   r   r   r   get_room_from_url     
	z!DailyRESTHelper.get_room_from_urlparamsc           	   
      s   dd| j  i}|jdd}| jj| j d||d4 I dH )}|jdkr8| I dH }td	|j d
| | I dH }W d  I dH  n1 I dH sOw   Y  z
t	di |}W |S  t
yq } ztd| d}~ww )a  Create a new Daily room.

        Args:
            params: Room configuration parameters.

        Returns:
            DailyRoomObject instance for the created room.

        Raises:
            Exception: If room creation fails or response is invalid.
        AuthorizationBearer Texclude_nonez/roomsheadersjsonN   zUnable to create room (status: ): Invalid response: r   )ra   
model_dumprb   postr`   statustext	Exceptionrs   rL   r   )	r?   rl   rr   rs   rrz   dataroomer   r   r   create_room  s&   
(	zDailyRESTHelper.create_room  FTNexpiry_timerT   ownerc              	      s  |st dtt | }| |}dd| j i}|du r,tt||||dd}n||j_||j_	||j_
||j_|jdd}	| jj| j d	||	d
4 I dH ,}
|
jdkrk|
 I dH }t d|
j d| |
 I dH }W d  I dH  |d S 1 I dH sw   Y  |d S )a  Generate a meeting token for user to join a Daily room.

        Args:
            room_url: Daily room URL.
            expiry_time: Token validity duration in seconds (default: 1 hour).
            eject_at_token_exp: Whether to eject user when token expires.
            owner: Whether token has owner privileges.
            params: Optional additional token properties. Note that room_name,
                exp, and is_owner will be set based on the other function
                parameters regardless of values in params.

        Returns:
            Meeting token.

        Raises:
            Exception: If token generation fails or room URL is missing.
        zXNo Daily room specified. You must specify a Daily room in order a token to be generated.rm   rn   N)rS   rW   r*   rT   )rK   Tro   z/meeting-tokensrq   rt   z(Failed to create meeting token (status: ru   token)r{   r   timerf   ra   r^   rR   rK   rS   r*   rT   rW   rw   rb   rx   r`   ry   rz   rs   )r?   rd   r   rT   r   rl   
expirationrS   rr   rs   r|   rz   r}   r   r   r   	get_token-  sD   
	
		zDailyRESTHelper.get_tokenc                    rg   )zDelete a room using its URL.

        Args:
            room_url: Daily room URL.

        Returns:
            True if deletion was successful.
        N)rf   delete_room_by_nameri   r   r   r   delete_room_by_urlm  rk   z"DailyRESTHelper.delete_room_by_urlrS   c              	      s   dd| j  i}| jj| j d| |d4 I dH +}|jdkr;|jdkr;| I dH }td| d	|j d
| W d  I dH  dS 1 I dH sLw   Y  dS )zDelete a room using its name.

        Args:
            room_name: Name of the room to delete.

        Returns:
            True if deletion was successful.

        Raises:
            Exception: If deletion fails (excluding 404 Not Found).
        rm   rn   /rooms/rr   Nrt   i  zFailed to delete room [z] (status: ru   T)ra   rb   deleter`   ry   rz   r{   )r?   rS   rr   r|   rz   r   r   r   r   y  s   z#DailyRESTHelper.delete_room_by_namec              
      s   dd| j  i}| jj| j d| |d4 I dH }|jdkr(td| | I dH }W d  I dH  n1 I dH s?w   Y  z
td	i |}W |S  tya } ztd| d}~ww )
z,Internal method to get room details by name.rm   rn   r   r   Nrt   zRoom not found: rv   r   )	ra   rb   getr`   ry   r{   rs   rL   r   )r?   rS   rr   r|   r}   r~   r   r   r   r   rh     s"   
(z#DailyRESTHelper._get_room_from_name)r   FTN)r   r   r   r   r   aiohttpClientSessionrc   rf   rL   rj   rD   r   rB   r   r   r^   r   r   r   rh   r   r   r   r   r_      sB    	
!
@r_   )r   r   typingr   r   r   r   r   urllib.parser   r   pydanticr   r	   r
   r   r   r   r&   r'   rD   rL   rR   r^   r_   r   r   r   r   <module>   s   6)