o
    iVj                     @  s  d dl mZ d dlZd dlZd dlZd dlZd dl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 ddl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) ddl*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1 ddl,m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7 G dd de8Z9G dd de8Z:G dd de8Z;G dd de8Z<G dd de8Z=G dd  d eZ>e
d!ge	eee?  ee? f f Z@ed"e
e2ge	eee?  ee? f f d#ZAG d$d% d%e>ZBG d&d' d'e>ZCdS )(    )annotationsN)	ListUnionCallableDict	AwaitableOptionalMappingcastTypeVar)abstractmethodABC   )	FfiClient	FfiHandle)ffi_pb2)participant_pb2)TrackPublishOptions)TranscriptionSegment)ParticipantTrackPermission)BroadcastQueue)
LocalTrack)LocalTrackPublicationRemoteTrackPublicationTrackPublication)Transcription)RpcError)"RpcMethodInvocationResponseRequest)logger)RpcInvocationData)TextStreamWriterByteStreamWriterByteStreamInfoSTREAM_CHUNK_SIZEc                   @     e Zd ZdddZdS )	PublishTrackErrormessagestrreturnNonec                 C  
   || _ d S Nr&   selfr&    r/   Y/var/www/html/livekit_bhavya/venv/lib/python3.10/site-packages/livekit/rtc/participant.py__init__;      
zPublishTrackError.__init__Nr&   r'   r(   r)   __name__
__module____qualname__r1   r/   r/   r/   r0   r%   :       r%   c                   @  r$   )	UnpublishTrackErrorr&   r'   r(   r)   c                 C  r*   r+   r,   r-   r/   r/   r0   r1   @   r2   zUnpublishTrackError.__init__Nr3   r4   r/   r/   r/   r0   r9   ?   r8   r9   c                   @  r$   )	PublishDataErrorr&   r'   r(   r)   c                 C  r*   r+   r,   r-   r/   r/   r0   r1   E   r2   zPublishDataError.__init__Nr3   r4   r/   r/   r/   r0   r:   D   r8   r:   c                   @  r$   )	PublishDTMFErrorr&   r'   r(   r)   c                 C  r*   r+   r,   r-   r/   r/   r0   r1   J   r2   zPublishDTMFError.__init__Nr3   r4   r/   r/   r/   r0   r;   I   r8   r;   c                   @  r$   )	PublishTranscriptionErrorr&   r'   r(   r)   c                 C  r*   r+   r,   r-   r/   r/   r0   r1   O   r2   z"PublishTranscriptionError.__init__Nr3   r4   r/   r/   r/   r0   r<   N   r8   r<   c                   @  s   e Zd Zd ddZeed!dd	Zed"ddZed"ddZed"ddZ	ed"ddZ
ed#ddZed$ddZed%ddZed&ddZdS )'Participant
owned_info"proto_participant.OwnedParticipantr(   r)   c                 C  s   |j | _t|jj| _d S r+   )info_infor   handleid_ffi_handler.   r>   r/   r/   r0   r1   T   s   zParticipant.__init__Mapping[str, TrackPublication]c                 C  s   dS )U
        A dictionary of track publications associated with the participant.
        Nr/   r.   r/   r/   r0   track_publicationsX   s   zParticipant.track_publicationsr'   c                 C     | j jS r+   )rA   sidrH   r/   r/   r0   rK   `      zParticipant.sidc                 C  rJ   r+   )rA   namerH   r/   r/   r0   rM   d   rL   zParticipant.namec                 C  rJ   r+   )rA   identityrH   r/   r/   r0   rN   h   rL   zParticipant.identityc                 C  rJ   r+   )rA   metadatarH   r/   r/   r0   rO   l   rL   zParticipant.metadatadict[str, str]c                 C  s   t | jjS )z2Custom attributes associated with the participant.)dictrA   
attributesrH   r/   r/   r0   rR   p   s   zParticipant.attributes+proto_participant.ParticipantKind.ValueTypec                 C  rJ   )zLParticipant's kind (e.g., regular participant, ingress, egress, sip, agent).)rA   kindrH   r/   r/   r0   rT   u      zParticipant.kind'proto_participant.ParticipantPermissionc                 C  rJ   )z.The participant's permissions within the room.)rA   
permissionrH   r/   r/   r0   permissionsz   rU   zParticipant.permissions6Optional[proto_participant.DisconnectReason.ValueType]c                 C  s   | j jtjjkr
dS | j jS )a  Reason for the participant's disconnection.

        Returns one of DisconnectReasons or None if the participant isn't disconnected. Common reasons are:
        - CLIENT_INITIATED - the client initiated the disconnect
        - DUPLICATE_IDENTITY - another participant with the same identity has joined the room
        - SERVER_SHUTDOWN - the server instance is shutting down
        - PARTICIPANT_REMOVED - RoomService.RemoveParticipant was called
        - ROOM_DELETED - RoomService.DeleteRoom was called
        - STATE_MISMATCH - the client is attempting to resume a session, but server is not aware of it
        - JOIN_FAILURE - client was unable to connect fully

        When dialing a participant via SIP, you may see the following reasons:
        - USER_UNAVAILABLE - SIP callee did not respond in time
        - USER_REJECTED - SIP callee rejected the call (busy)
        - SIP_TRUNK_FAILURE - SIP protocol failure or unexpected response
        N)rA   disconnect_reasonproto_participantDisconnectReasonUNKNOWN_REASONrH   r/   r/   r0   rZ      s   zParticipant.disconnect_reasonNr>   r?   r(   r)   )r(   rF   r(   r'   )r(   rP   )r(   rS   )r(   rV   )r(   rY   )r5   r6   r7   r1   propertyr   rI   rK   rM   rN   rO   rR   rT   rX   rZ   r/   r/   r/   r0   r=   S   s*    
r=   r   F)boundc                      s>  e Zd ZdZdp fdd	ZedqddZdg dddrddZdsddZdtd!d"Z	d#d$dud)d*Z
	#dvdwd/d0Zdxd1d2Zd#d3dyd7d8Zdzd=d>Zd{d@dAZd|dCdDZd}dGdHZd#dd#d#d#d#d#dId~dSdTZd#dd#d#dUddWdXZd#dYd#d#d#ddZdd]d^Zdd#d#d#d_ddbdcZe fddidjZddldmZddndoZ  ZS )LocalParticipantz+Represents the local participant in a room.
room_queue"BroadcastQueue[proto_ffi.FfiEvent]r>   r?   r(   r)   c                   s"   t  | || _i | _i | _d S r+   )superr1   _room_queue_track_publications_rpc_handlers)r.   rd   r>   	__class__r/   r0   r1      s   
zLocalParticipant.__init__#Mapping[str, LocalTrackPublication]c                 C     | j S rG   rh   rH   r/   r/   r0   rI         z#LocalParticipant.track_publicationsT )reliabledestination_identitiestopicpayloadUnion[bytes, str]rr   boolrs   	List[str]rt   r'   c          
   	     s   t |tr|d}t|}tj| | }t }| jj	|j
_t||j
_||j
_||j
_||j
_|j
j| tjj }ztj| | fddI dH }	W tjj| ntjj| w |	j
jrnt|	j
jdS )a  
        Publish arbitrary data to the room.

        Args:
            payload (Union[bytes, str]): The data to publish.
            reliable (bool, optional): Whether to send reliably or not. Defaults to True.
            destination_identities (List[str], optional): List of participant identities to send to. Defaults to [].
            topic (str, optional): The topic under which to publish the data. Defaults to "".

        Raises:
            PublishDataError: If there is an error in publishing data.
        zutf-8c                      | j j j jkS r+   )publish_dataasync_iderespr/   r0   <lambda>       z/LocalParticipant.publish_data.<locals>.<lambda>N)
isinstancer'   encodelenctypesc_byte	proto_ffi
FfiRequestrD   rB   rz   local_participant_handle	addressofdata_ptrdata_lenrr   rt   rs   extendr   instancequeue	subscriberequestwait_forunsubscribeerrorr:   )
r.   ru   rr   rs   rt   r   cdatareqr   cbr/   r~   r0   rz      s,   


 zLocalParticipant.publish_datacodeintdigitc             	     s   t  }| jj|j_||j_||j_tj	j
 }ztj	| | fddI dH }W tj	j
| ntj	j
| w |jjrGt|jjdS )z
        Publish SIP DTMF message.

        Args:
            code (int): DTMF code.
            digit (str): DTMF digit.

        Raises:
            PublishDTMFError: If there is an error in publishing SIP DTMF message.
        c                   ry   r+   )publish_sip_dtmfr{   r|   r~   r/   r0   r      r   z/LocalParticipant.publish_dtmf.<locals>.<lambda>N)r   r   rD   rB   r   r   r   r   r   r   r   r   r   r   r   r   r;   )r.   r   r   r   r   r   r/   r~   r0   publish_dtmf   s   
 zLocalParticipant.publish_dtmftranscriptionr   c              	     s   t  }dd |jD }| jj|j_|j|j_|jj| |j	|j_
tjj }ztj| | fddI dH }W tjj| ntjj| w |jjrXt|jjdS )a   
        Publish transcription data to the room.

        Args:
            transcription (Transcription): The transcription data to publish.

        Raises:
            PublishTranscriptionError: If there is an error in publishing transcription.
        c              
   S  s,   g | ]}t |j|j|j|j|j|jd qS ))rC   text
start_timeend_timefinallanguage)ProtoTranscriptionSegmentrC   r   r   r   r   r   ).0sr/   r/   r0   
<listcomp>  s    	z:LocalParticipant.publish_transcription.<locals>.<listcomp>c                   ry   r+   )publish_transcriptionr{   r|   r~   r/   r0   r     r   z8LocalParticipant.publish_transcription.<locals>.<lambda>N)r   r   segmentsrD   rB   r   r   participant_identityr   	track_sidtrack_idr   r   r   r   r   r   r   r   r<   )r.   r   r   proto_segmentsr   r   r/   r~   r0   r      s&   
	


 z&LocalParticipant.publish_transcriptionN)response_timeoutdestination_identitymethodr   Optional[float]c             	     s   t  }| jj|j_||j_||j_||j_|dur#t	|d |j_
tjj }ztj| | fddI dH }W tjj| ntjj| w |jdrZt|jj|jjS )a  
        Initiate an RPC call to a remote participant.

        Args:
            destination_identity (str): The `identity` of the destination participant
            method (str): The method name to call
            payload (str): The method payload
            response_timeout (Optional[float]): Timeout for receiving a response after initial connection

        Returns:
            str: The response payload

        Raises:
            RpcError: On failure. Details in `message`.
        Ni  c                   ry   r+   )perform_rpcr{   r|   r~   r/   r0   r   F  r   z.LocalParticipant.perform_rpc.<locals>.<lambda>r   )r   r   rD   rB   r   r   r   r   ru   r   response_timeout_msr   r   r   r   r   r   r   HasFieldr   _from_protor   )r.   r   r   ru   r   r   r   r   r/   r~   r0   r   $  s     zLocalParticipant.perform_rpcmethod_namehandlerOptional[F]Union[F, Callable[[F], F]]c                   s$   d fdd}|dur||S |S )a  
        Establishes the participant as a receiver for calls of the specified RPC method.
        Can be used either as a decorator or a regular method.

        The handler will receive one argument of type `RpcInvocationData` and should return a string response which will be forwarded back to the caller.

        The handler may be synchronous or asynchronous.

        If unable to respond within `response_timeout`, the caller will hang up and receive an error on their side.

        You may raise errors of type `RpcError` in the handler, and they will be forwarded to the caller.

        Other errors raised in your handler will be caught and forwarded to the caller as "1500 Application Error".

        Args:
            method_name (str): The name of the indicated RPC method.
            handler (Optional[Callable]): Handler to be invoked whenever an RPC request for this method is received.  Omit this argument to use the decorator syntax.

        Returns:
            None (when used as a decorator it returns the decorator function)

        Example:
            # As a decorator:
            @room.local_participant.register_rpc_method("greet")
            async def greet_handler(data: RpcInvocationData) -> str:
                print(f"Received greeting from {data.caller_identity}: {data.payload}")
                return f"Hello, {data.caller_identity}!"

            # As a regular method:
            async def greet_handler(data: RpcInvocationData) -> str:
                print(f"Received greeting from {data.caller_identity}: {data.payload}")
                return f"Hello, {data.caller_identity}!"

            room.local_participant.register_rpc_method('greet', greet_handler)
        handler_funcra   r(   c                   s6   | j  < t }jj|j_ |j_tj	
| | S r+   )ri   r   r   rD   rB   register_rpc_methodr   r   r   r   r   )r   r   r   r.   r/   r0   registerx  s   
z6LocalParticipant.register_rpc_method.<locals>.registerN)r   ra   r(   ra   r/   )r.   r   r   r   r/   r   r0   r   O  s   )z$LocalParticipant.register_rpc_methodc                 C  s:   | j |d t }| jj|j_||j_t	j
| dS )z
        Unregisters a previously registered RPC method.

        Args:
            method (str): The name of the RPC method to unregister
        N)ri   popr   r   rD   rB   unregister_rpc_methodr   r   r   r   r   )r.   r   r   r/   r/   r0   r     s
   z&LocalParticipant.unregister_rpc_method)participant_permissionsallow_all_participantsr   *Optional[List[ParticipantTrackPermission]]c                C  sF   |du rg }t  }| jj|j_||j_|jj| t	j
| dS )a  
        Set the track subscription permissions for the local participant.

        Args:
            allow_all_participants (bool): Whether to allow all participants to subscribe to this participant's tracks.
            participant_permissions (List[ParticipantTrackPermission]): Participant-specific track subscription permissions, ignored if `allow_all_participants` is True.
        N)r   r   rD   rB   "set_track_subscription_permissionsr   all_participants_allowedrX   r   r   r   r   )r.   r   r   r   r/   r/   r0   r     s   z3LocalParticipant.set_track_subscription_permissionsinvocation_id
request_idcaller_identityfloatc              
     sf  d }d }t ||||}	| j|}
|
sttjj}niz<t|
rNztj	|
|	|dI d H }W n& tj
y?   ttjj tjyM   ttjjw ttt |
|	}W n, tyl } z|}W Y d }~nd }~w ty   td| d ttjj}Y nw tjt| jj||r| nd |dd}tj|}|jjr|jj}td|  d S d S )N)timeoutz+Uncaught error returned by RPC handler for z'. Returning APPLICATION_ERROR instead. )r   r   r   ru   )rpc_method_invocation_responsez.error sending rpc method invocation response: ) r   ri   getr   	_built_in	ErrorCodeUNSUPPORTED_METHODasyncioiscoroutinefunctionr   TimeoutErrorRESPONSE_TIMEOUTCancelledErrorRECIPIENT_DISCONNECTEDr
   r   r'   	Exceptionr   	exceptionAPPLICATION_ERRORr   r   r   rD   rB   	_to_protor   r   r   r   r   )r.   r   r   r   r   ru   r   response_errorresponse_payloadparamsr   r   r   reserrr/   r/   r0   _handle_rpc_method_invocation  sT   	

	z.LocalParticipant._handle_rpc_method_invocationrO   c              	     t   t  }| jj|j_||j_tjj	
 }ztj| | fddI dH  W tjj	| dS tjj	| w )z
        Set the metadata for the local participant.

        Note: this requires `canUpdateOwnMetadata` permission.

        Args:
            metadata (str): The new metadata.
        c                   ry   r+   )set_local_metadatar{   r|   r~   r/   r0   r     r   z/LocalParticipant.set_metadata.<locals>.<lambda>N)r   r   rD   rB   r   r   rO   r   r   r   r   r   r   r   )r.   rO   r   r   r/   r~   r0   set_metadata     	
"zLocalParticipant.set_metadatarM   c              	     r   )z
        Set the name for the local participant.

        Note: this requires `canUpdateOwnMetadata` permission.

        Args:
            name (str): The new name.
        c                   ry   r+   )set_local_namer{   r|   r~   r/   r0   r     r   z+LocalParticipant.set_name.<locals>.<lambda>N)r   r   rD   rB   r   r   rM   r   r   r   r   r   r   r   )r.   rM   r   r   r/   r~   r0   set_name  r   zLocalParticipant.set_namerR   rP   c              	     s   t  }| jj|j_dd |jjD }|| | D ]\}}|jj	 }||_
||_qtjj }ztj| | fddI dH  W tjj| dS tjj| w )z
        Set custom attributes for the local participant.

        Note: this requires `canUpdateOwnMetadata` permission.

        Args:
            attributes (dict[str, str]): A dictionary of attributes to set.
        c                 S  s   i | ]}|j |jqS r/   )keyvalue)r   entryr/   r/   r0   
<dictcomp>  s    
z3LocalParticipant.set_attributes.<locals>.<dictcomp>c                   ry   r+   )set_local_attributesr{   r|   r~   r/   r0   r   &  r   z1LocalParticipant.set_attributes.<locals>.<lambda>N)r   r   rD   rB   r   r   rR   updateitemsaddr   r   r   r   r   r   r   r   r   )r.   rR   r   existing_attributesr   r   r   r   r/   r~   r0   set_attributes  s$   	

"zLocalParticipant.set_attributes)rs   rt   rR   	stream_idreply_to_id
total_sizesender_identityOptional[List[str]]Optional[Dict[str, str]]r   
str | Noner   r   
int | Noner   r    c          	   
     s,   t | |||||||d}| I dH  |S )z
        Returns a TextStreamWriter that allows to write individual chunks of text to a text stream.
        In most cases where you want to simply send a text message use send_text() instead.
        )rt   rR   r   rs   r   r   r   N)r    _send_header)	r.   rs   rt   rR   r   r   r   r   writerr/   r/   r0   stream_text+     zLocalParticipant.stream_text)rs   rt   rR   r   r   c                  sL   t | }| j|||||dI d H }||I d H  | I d H  |jS )N)rs   rt   rR   r   r   )r   r   r   writeacloser@   )r.   r   rs   rt   rR   r   r   r   r/   r/   r0   	send_textI  s   	zLocalParticipant.send_textapplication/octet-stream)r   	mime_typerR   r   rs   rt   r   r!   c          	   
     s,   t | |||||||d}| I dH  |S )z
        Returns a ByteStreamWriter that allows to write individual chunks of bytes to a byte stream.
        In cases where you want to simply send a file from the file system use send_file() instead.
        )rM   rR   r   r   r   rs   rt   N)r!   r   )	r.   rM   r   r   rR   r   rs   rt   r   r/   r/   r0   stream_bytes`  r   zLocalParticipant.stream_bytes)rt   rs   rR   r   	file_pathr"   c             	     s   t j|}t j|}t|\}}	|d u rd}| j|||||||dI d H }
t|d4 I d H '}|	t
I d H  }rP|
|I d H  |	t
I d H  }s>W d   I d H  n1 I d H s`w   Y  |
 I d H  |
jS )Nr   )rM   r   r   rR   r   rs   rt   rb)ospathgetsizebasename	mimetypes
guess_typer   aiofilesopenreadr#   r   r   r@   )r.   r   rt   rs   rR   r   	file_size	file_namer   _r   fbytesr/   r/   r0   	send_file~  s,   	
(zLocalParticipant.send_filetrackr   optionsr   r   c              	     s   t  }|jj|j_| jj|j_|jj| | j	
 }z=tj| | fddI dH }|jjr:t|jjt|jj}||_|j|j_|| j|j< |  |W | j	| S | j	| w )a  
        Publish a local track to the room.

        Args:
            track (LocalTrack): The track to publish.
            options (TrackPublishOptions, optional): Options for publishing the track.

        Returns:
            LocalTrackPublication: The publication of the published track.

        Raises:
            PublishTrackError: If there is an error in publishing the track.
        c                   ry   r+   )publish_trackr{   r|   r~   r/   r0   r     r   z0LocalParticipant.publish_track.<locals>.<lambda>N)r   r   rD   rB   r  track_handler   r  CopyFromrg   r   r   r   r   r   r   r%   r   publication_trackrK   rA   rh   	task_doner   )r.   r  r  r   r   r   track_publicationr/   r~   r0   r    s(   



zLocalParticipant.publish_trackr   c              	     s   t  }| jj|j_||j_d|j_| j	 }z2t
j| | fddI dH }|jjr5t|jj| j|}d|_|  W | j| dS | j| w )z
        Unpublish a track from the room.

        Args:
            track_sid (str): The SID of the track to unpublish.

        Raises:
            UnpublishTrackError: If there is an error in unpublishing the track.
        Tc                   ry   r+   )unpublish_trackr{   r|   r~   r/   r0   r     r   z2LocalParticipant.unpublish_track.<locals>.<lambda>N)r   r   rD   rB   r  r   r   stop_on_unpublishrg   r   r   r   r   r   r   r9   rh   r   r  r  r   )r.   r   r   r   r   r  r/   r~   r0   r    s"   




z LocalParticipant.unpublish_trackc                 C     d| j  d| j d| j dS )Nzrtc.LocalParticipant(sid=, identity=, name=)rK   rN   rM   rH   r/   r/   r0   __repr__     zLocalParticipant.__repr__)rd   re   r>   r?   r(   r)   )r(   rl   )
ru   rv   rr   rw   rs   rx   rt   r'   r(   r)   )r   r   r   r'   r(   r)   )r   r   r(   r)   )
r   r'   r   r'   ru   r'   r   r   r(   r'   r+   )r   r'   r   r   r(   r   )r   r'   r(   r)   )r   rw   r   r   r(   r)   )r   r   r   r'   r   r'   r   r'   ru   r'   r   r   r(   r)   )rO   r'   r(   r)   )rM   r'   r(   r)   )rR   rP   r(   r)   )rs   r   rt   r'   rR   r   r   r   r   r   r   r   r   r   r(   r    )
r   r'   rs   r   rt   r'   rR   r   r   r   )rM   r'   r   r   r   r'   rR   r   r   r   rs   r   rt   r'   r(   r!   )r   r'   rt   r'   rs   r   rR   r   r   r   r(   r"   )r  r   r  r   r(   r   )r   r'   r(   r)   r_   )r5   r6   r7   __doc__r1   r`   rI   rz   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r  r  r!  __classcell__r/   r/   rj   r0   rc      sf    


.
..
6

7

!""!
)rc   c                      s6   e Zd Zd fddZeddd	ZdddZ  ZS )RemoteParticipantr>   r?   r(   r)   c                   s   t  | i | _d S r+   )rf   r1   rh   rE   rj   r/   r0   r1     s   
zRemoteParticipant.__init__$Mapping[str, RemoteTrackPublication]c                 C  rm   rn   ro   rH   r/   r/   r0   rI     rp   z$RemoteParticipant.track_publicationsr'   c                 C  r  )Nzrtc.RemoteParticipant(sid=r  r  r  r   rH   r/   r/   r0   r!    r"  zRemoteParticipant.__repr__r^   )r(   r&  r_   )r5   r6   r7   r1   r`   rI   r!  r$  r/   r/   rj   r0   r%    s
    r%  )D
__future__r   r   r   r  r  r  typingr   r   r   r   r   r   r	   r
   r   abcr   r   _ffi_clientr   r   _protor   r   r   r[   _proto.room_pb2r   r   r   _proto.track_pb2r   _utilsr   r  r   r  r   r   r   r   r   rpcr   _proto.rpc_pb2r   logr   r   data_streamr    r!   r"   r#   r   r%   r9   r:   r;   r<   r=   r'   
RpcHandlerra   rc   r%  r/   r/   r/   r0   <module>   sN   ,"E"    P