
    qi0                    *   d dl mZ d dlZd dlZd dlZd dlZd dlmZmZ d dl	m
Z
mZmZmZmZmZ d dlZddl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& ddl'm(Z( ddl)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z:m;Z;m<Z< ed   Z=e G d d             Z>e G d d             Z?e G d d             Z@e G d d             ZAe G d  d!             ZB G d" d#eC      ZD G d$ d%ee=         ZEy)&    )annotationsN)	dataclassfield)CallableDictLiteralOptionalcastMapping   )EventEmitter)	FfiClient	FfiHandle)ffi_pb2)participant_pb2)room_pb2)	stats_pb2)DisconnectReason)ConnectionState)	TrackKind)RpcMethodInvocationEvent)BroadcastQueue)E2EEManagerE2EEOptions)LocalParticipantParticipantRemoteParticipant)RemoteAudioTrackRemoteVideoTrack)RemoteTrackPublicationTrackPublication)TranscriptionSegment)TextStreamReaderByteStreamReaderTextStreamHandlerByteStreamHandler) participant_connectedparticipant_disconnectedlocal_track_publishedlocal_track_unpublishedlocal_track_subscribedtrack_publishedtrack_unpublishedtrack_subscribedtrack_unsubscribedtrack_subscription_failedtrack_mutedtrack_unmutedactive_speakers_changedroom_metadata_changedparticipant_metadata_changedparticipant_name_changedparticipant_attributes_changedconnection_quality_changed%participant_encryption_status_changedparticipant_permissions_changeddata_receivedsip_dtmf_receivedtranscription_receivede2ee_state_changedconnection_state_changed	connecteddisconnectedreconnectingreconnectedroom_updatedmovedtoken_refreshedc                      e Zd ZU ej                  j
                  Zded<   	 ej                  j                  Z
ded<   	  ee      Zded<   y)	RtcConfigurationz%proto_room.IceTransportType.ValueTypeice_transport_typez-proto_room.ContinualGatheringPolicy.ValueTypecontinual_gathering_policy)default_factoryzlist[proto_room.IceServer]ice_serversN)__name__
__module____qualname__
proto_roomIceTransportTypeTRANSPORT_ALLrI   __annotations__ContinualGatheringPolicyGATHER_CONTINUALLYrJ   r   listrL        B/opt/pipecat/venv/lib/python3.12/site-packages/livekit/rtc/room.pyrH   rH   T   s\     	##11 =  S++>>  M  <.3D.IK+IrX   rH   c                  z    e Zd ZU dZded<   	 dZded<   dZded<   	 dZded	<   	 dZd
ed<   	 dZ	ded<   	 dZ
ded<   y)RoomOptionsTboolauto_subscribeFdynacastNzE2EEOptions | Nonee2ee
encryptionzRtcConfiguration | None
rtc_configzfloat | Noneconnect_timeoutzbool | Nonesingle_peer_connection)rM   rN   rO   r]   rS   r^   r_   r`   ra   rb   rc   rW   rX   rY   r[   r[   c   s^    NDCHd#D
#4%)J"),*.J'.'$(O\(b*.K.krX   r[   c                  @    e Zd ZU ded<   	 ded<   	 ded<   	 dZded	<   y)

DataPacketbytesdataz#proto_room.DataPacketKind.ValueTypekindRemoteParticipant | NoneparticipantNz
str | Nonetopic)rM   rN   rO   rS   rk   rW   rX   rY   re   re   t   s)    
K)
--:))HE:0rX   re   c                  4    e Zd ZU ded<   	 ded<   	 dZded<   y)SipDTMFintcodestrdigitNri   rj   )rM   rN   rO   rS   rj   rW   rX   rY   rm   rm      s     
I/J,0K)0NrX   rm   c                  "    e Zd ZU ded<   ded<   y)RtcStatszlist[proto_stats.RtcStats]publisher_statssubscriber_statsN)rM   rN   rO   rS   rW   rX   rY   rs   rs      s    //00rX   rs   c                      e Zd ZddZy)ConnectErrorc                    || _         y N)message)selfrz   s     rY   __init__zConnectError.__init__   s	    rX   N)rz   rp   )rM   rN   rO   r|   rW   rX   rY   rw   rw      s    rX   rw   c                      e Zd Z	 d%	 	 	 d& fdZd'dZed(d       Zed)d       Zed*d       Zed+d       Z	ed(d       Z
ed(d       Zed,d	       Zed-d
       Zed-d       Zed.d       Zed/d       Zed0d       Zed0d       Zd/dZd%d1 fdZ e       fd2dZd3dZd4dZd5dZd6dZd5dZd'dZd'dZd7dZd8dZ	 	 	 	 d9dZ d:dZ!d;dZ"d'dZ#d'd Z$d<d!Z%d=d"Z&	 	 	 	 d>d#Z'd(d$Z( xZ)S )?Roomc                   t         |           d| _        |xs t        j                         | _        t        t        j                            | _	        t        j                         | _        t               | _        t               | _        i | _        t"        j$                  | _        t        j(                  t*                  | _        d| _        i | _        i | _        i | _        i | _        d| _        d| _        y)zInitializes a new Room instance.

        Parameters:
            loop (Optional[asyncio.AbstractEventLoop]): The event loop to use. If not provided, the default event loop is used.
        N)superr|   _ffi_handleasyncioget_event_loop_loopr   	proto_ffiFfiEvent_room_queuerP   RoomInfo_infoset_rpc_invocation_tasks_data_stream_tasks_remote_participantsr   CONN_DISCONNECTED_connection_stateFuturerp   _first_sid_future_local_participant_text_stream_readers_byte_stream_readers_text_stream_handlers_byte_stream_handlers_token_server_url)r{   loop	__class__s     rY   r|   zRoom.__init__   s     	045W335
))*<*<=?((*
8;"58UBD!!0!B!B!(!4!6;?AC!AC!CE"CE""&'+rX   c                    | j                   4t        j                  j                  j	                  | j
                         y y ry   )r   r   instancequeueunsubscribe
_ffi_queuer{   s    rY   __del__zRoom.__del__   s1    '$$00A (rX   c                   K   | j                   j                  r| j                   j                  S | j                   d{   S 7 w)zAsynchronously retrieves the session ID (SID) of the room.

        Returns:
            str: The session ID of the room.
        N)r   sidr   r   s    rY   r   zRoom.sid   s3      ::>>::>>!+++++s   <AAAc                H    | j                   t        d      | j                   S )zGets the local participant in the room.

        Returns:
            LocalParticipant: The local participant in the room.
        z1cannot access local participant before connecting)r   	Exceptionr   s    rY   local_participantzRoom.local_participant   s(     ""*OPP&&&rX   c                    | j                   S )zGets the connection state of the room.

        Returns:
            ConnectionState: The connection state of the room.
        )r   r   s    rY   connection_statezRoom.connection_state   s     %%%rX   c                    | j                   S )zGets the remote participants in the room.

        Returns:
            dict[str, RemoteParticipant]: A dictionary of remote participants indexed by their
            identity.
        )r   r   s    rY   remote_participantszRoom.remote_participants   s     (((rX   c                .    | j                   j                  S )z\Gets the name of the room.

        Returns:
            str: The name of the room.
        )r   namer   s    rY   r   z	Room.name   s     zzrX   c                .    | j                   j                  S )zqGets the metadata associated with the room.

        Returns:
            str: The metadata of the room.
        )r   metadatar   s    rY   r   zRoom.metadata   s     zz"""rX   c                    | j                   S )zGets the end-to-end encryption (E2EE) manager for the room.

        Returns:
            E2EEManager: The E2EE manager instance.
        )_e2ee_managerr   s    rY   e2ee_managerzRoom.e2ee_manager   s     !!!rX   c                .    | j                   j                  S )zGets the number of participants in the room.
        This value is updated periodically, and is eventually consistent.

        Returns:
            int: The number of participants in the room.
        )r   num_participantsr   s    rY   r   zRoom.num_participants   s     zz***rX   c                .    | j                   j                  S )zGets the number of publishers in the room.
        This value is updated periodically, and is eventually consistent.

        Returns:
            int: The number of publishers in the room.
        )r   num_publishersr   s    rY   r   zRoom.num_publishers	  s     zz(((rX   c                    t         j                   j                  | j                  j                  dz  t         j                  j
                        S )zxTime when the room was created.

        Returns:
            datetime.datetime: The creation time of the room.
          )datetimefromtimestampr   creation_timetimezoneutcr   s    rY   r   zRoom.creation_time  s=       ..JJ$$t+X->->-B-B
 	
rX   c                .    | j                   j                  S )zWhether the room is actively recording.

        Returns:
            bool: True if actively recording, False otherwise.
        )r   active_recordingr   s    rY   is_recordingzRoom.is_recording  s     zz***rX   c                @    t        | j                  j                        S )zAmount of time to hold the room open after the last standard participant leaves.

        Returns:
            float: The departure timeout of the room.
        )floatr   departure_timeoutr   s    rY   r   zRoom.departure_timeout'  s     TZZ1122rX   c                @    t        | j                  j                        S )zAmount of time to keep the room open if no participants join.

        Returns:
            float: The empty timeout of the room.
        )r   r   empty_timeoutr   s    rY   r   zRoom.empty_timeout0  s     TZZ--..rX   c                \    | j                   duxr | j                  t        j                  k7  S )z{Checks if the room is currently connected.

        Returns:
            bool: True if connected, False otherwise.
        N)r   r   r   r   r   s    rY   isconnectedzRoom.isconnected9  s1     D( L&&/*K*KK	
rX   c                $    t         |   ||      S )a  Registers an event handler for a specific event type.

        Parameters:
            event (EventTypes): The name of the event to listen for.
            callback (Callable): The function to call when the event occurs.

        Returns:
            Callable: The registered callback function.

        Available events:
            - **"participant_connected"**: Called when a new participant joins the room.
                - Arguments: `participant` (RemoteParticipant)
            - **"participant_disconnected"**: Called when a participant leaves the room.
                - Arguments: `participant` (RemoteParticipant)
            - **"local_track_published"**: Called when a local track is published.
                - Arguments: `publication` (LocalTrackPublication), `track` (Track)
            - **"local_track_unpublished"**: Called when a local track is unpublished.
                - Arguments: `publication` (LocalTrackPublication)
            - **"local_track_subscribed"**: Called when a local track is subscribed.
                - Arguments: `track` (Track)
            - **"track_published"**: Called when a remote participant publishes a track.
                - Arguments: `publication` (RemoteTrackPublication), `participant` (RemoteParticipant)
            - **"track_unpublished"**: Called when a remote participant unpublishes a track.
                - Arguments: `publication` (RemoteTrackPublication), `participant` (RemoteParticipant)
            - **"track_subscribed"**: Called when a track is subscribed.
                - Arguments: `track` (Track), `publication` (RemoteTrackPublication), `participant` (RemoteParticipant)
            - **"track_unsubscribed"**: Called when a track is unsubscribed.
                - Arguments: `track` (Track), `publication` (RemoteTrackPublication), `participant` (RemoteParticipant)
            - **"track_subscription_failed"**: Called when a track subscription fails.
                - Arguments: `participant` (RemoteParticipant), `track_sid` (str), `error` (str)
            - **"track_muted"**: Called when a track is muted.
                - Arguments: `participant` (Participant), `publication` (TrackPublication)
            - **"track_unmuted"**: Called when a track is unmuted.
                - Arguments: `participant` (Participant), `publication` (TrackPublication)
            - **"active_speakers_changed"**: Called when the list of active speakers changes.
                - Arguments: `speakers` (list[Participant])
            - **"room_metadata_changed"**: Called when the room's metadata is updated.
                - Arguments: `old_metadata` (str), `new_metadata` (str)
            - **"participant_metadata_changed"**: Called when a participant's metadata is updated.
                - Arguments: `participant` (Participant), `old_metadata` (str), `new_metadata` (str)
            - **"participant_name_changed"**: Called when a participant's name is changed.
                - Arguments: `participant` (Participant), `old_name` (str), `new_name` (str)
            - **"participant_attributes_changed"**: Called when a participant's attributes change.
                - Arguments: `changed_attributes` (dict), `participant` (Participant)
            - **"participant_encryption_status_changed"**: Called when a participant's encryption status changes.
                - Arguments `is_encrypted` (bool), `participant` (Participant)
            - **"connection_quality_changed"**: Called when a participant's connection quality changes.
                - Arguments: `participant` (Participant), `quality` (ConnectionQuality)
            - **"transcription_received"**: Called when a transcription is received.
                - Arguments: `segments` (list[TranscriptionSegment]), `participant` (Participant), `publication` (TrackPublication)
            - **"data_received"**: Called when data is received.
                - Arguments: `data_packet` (DataPacket)
            - **"sip_dtmf_received"**: Called when a SIP DTMF signal is received.
                - Arguments: `sip_dtmf` (SipDTMF)
            - **"e2ee_state_changed"**: Called when a participant's E2EE state changes.
                - Arguments: `participant` (Participant), `state` (EncryptionState)
            - **"connection_state_changed"**: Called when the room's connection state changes.
                - Arguments: `connection_state` (ConnectionState)
            - **"connected"**: Called when the room is successfully connected.
                - Arguments: None
            - **"disconnected"**: Called when the room is disconnected.
                - Arguments: `reason` (DisconnectReason)
            - **"reconnecting"**: Called when the room is attempting to reconnect.
                - Arguments: None
            - **"reconnected"**: Called when the room has successfully reconnected.
                - Arguments: None
            - **"room_updated"**: Called when any information about the room is updated.
                - Arguments: None
            - **"moved"**: Called when the participant has been moved to another room.
                - Arguments: None

        Example:
            ```python
            def on_participant_connected(participant):
                print(f"Participant connected: {participant.identity}")

            room.on("participant_connected", on_participant_connected)
            ```
        )r   on)r{   eventcallbackr   s      rY   r   zRoom.onD  s    ` wz%**rX   c                  K   || _         || _        t        j                         }||j                  _        ||j                  _        |j                  |j                  j                  _        |j                  |j                  j                  _	        |j                  1t        |j                  dz        |j                  j                  _        |j                  %|j                  |j                  j                  _        |j                  rt        j                   dt"        d       |j                  j$                  |j                  j                  j                  _        |j                  j&                  j(                  |j                  j                  j                  j&                  _        |j                  j&                  j*                  |j                  j                  j                  j&                  _        |j                  j&                  j,                  |j                  j                  j                  j&                  _        |j                  j&                  j.                  |j                  j                  j                  j&                  _        |j0                  rm|j0                  j$                  |j                  j                  j0                  _        |j0                  j&                  j(                  |j                  j                  j0                  j&                  _        |j0                  j&                  j*                  |j                  j                  j0                  j&                  _        |j0                  j&                  j,                  |j                  j                  j0                  j&                  _        |j0                  j&                  j.                  |j                  j                  j0                  j&                  _        |j2                  r|j2                  j4                  |j                  j                  j2                  _        |j2                  j6                  |j                  j                  j2                  _        |j                  j                  j2                  j8                  j;                  |j2                  j8                         t<        j>                  j@                  jC                  | jD                        | _#        t<        j>                  j@                  jC                         }	 t<        j>                  jI                  |      |jK                  fd       d{   }t<        j>                  j@                  jM                  |       |j                  jN                  rRt<        j>                  j@                  jM                  | jF                         tQ        |j                  jN                        tS        |j                  jT                  jV                  jX                  jZ                        | _.        t_        | j\                  jX                  |j0                  xs |j                        | _0        |j                  jT                  jV                  jb                  | _2        tf        jh                  | _5        tm        | jn                  |j                  jT                  jp                        | _9        |j                  jT                  jt                  D ]R  }| jw                  |jx                        }|jz                  D ]&  }	t}        |	      }
|
|j~                  |
j                  <   ( T | jD                  j                  | j                               | _C        y7 6# t<        j>                  j@                  jM                  |       w xY ww)a  Connects to a LiveKit room using the specified URL and token.

        Parameters:
            url (str): The WebSocket URL of the LiveKit server to connect to.
            token (str): The access token for authentication and authorization.
            options (RoomOptions, optional): Additional options for the room connection.

        Raises:
            ConnectError: If the connection fails.

        Example:
            ```python
            room = Room()

            # Listen for events before connecting to the room
            @room.on("participant_connected")
            def on_participant_connected(participant):
                print(f"Participant connected: {participant.identity}")

            await room.connect("ws://localhost:7880", "your_token")
            ```
        Nr   z:options.e2ee is deprecated, use options.encryption instead   )
stacklevelc                ^    | j                   j                  j                   j                  k(  S ry   )connectasync_ideresps    rY   <lambda>zRoom.connect.<locals>.<lambda>  s     !)),,0E0EE rX   )Dr   r   r   
FfiRequestr   urltokenr]   optionsr^   rb   rn   connect_timeout_msrc   r_   warningswarnDeprecationWarningencryption_typekey_provider_options
shared_keyratchet_saltfailure_toleranceratchet_window_sizer`   ra   rI   rJ   rL   extendr   r   r   	subscriber   r   requestwait_forr   errorrw   r   resultroomhandleidr   r   r   infor   r   CONN_CONNECTEDr   r   r   r   r   participants_create_remote_participantrj   publicationsr    _track_publicationsr   create_task_listen_task_task)r{   r   r   r   reqr   cbptrpowned_publication_infopublicationr   s              @rY   r   zRoom.connect  s    . ""$! .5-C-C*'.'7'7$"".589P9PSW9W5XCKK2))59@9W9WCKK6<<MML" 8?||7S7SCKK$$411<< KK$$99D 11>> KK$$99F 11CC KK$$99K 11EE KK$$99M =D=O=O=_=_CKK**:""77BB KK**??J ""77DD KK**??L ""77II KK**??Q ""77KK KK**??S ""55 KK**= ""== KK**E KK**66==g>P>P>\>\] $,,22<<TZZH""((224	8%%--c2D+0>>E, &B $$007::$$00Arzz//00$RZZ%6%6%;%;%B%B%E%EF(##W%7%7%G7<<
 ZZ&&++00
!0!?!?"2bjj//AA#
 **##00 	FB00@B +-// F&45KL:E&&{7F		F ZZ++D,=,=,?@
A& $$007s1   T8_<6^+ 2^(3^+ 7H1_(^+ ++__c                V  K   | j                         st        d      t        j                         }| j                  j
                  |j                  _        t        j                  j                  j                         }	 t        j                  j                  |      |j                  fd       d {   }t        j                  j                  j                  |       |j                  j                  rt        |j                  j                        t!        |j                  j"                  j$                        }t!        |j                  j"                  j&                        }t)        ||      S 7 # t        j                  j                  j                  |       w xY ww)Nzthe room isn't connectedc                ^    | j                   j                  j                   j                  k(  S ry   )get_session_statsr   r   s    rY   r   z$Room.get_rtc_stats.<locals>.<lambda>  s$    !--66$:P:P:Y:YY rX   )rt   ru   )r   RuntimeErrorr   r   r   r   r   room_handler   r   r   r   r   r   r   r   rV   r   rt   ru   rs   )r{   r   r   r   rt   ru   r   s         @rY   get_rtc_statszRoom.get_rtc_stats  s=    !9::""$,0,<,<,C,C)""((224	8%%--c2D+0>>Y, &B $$007%%r3399::r33::JJK 4 4 ; ; L LMJZ[[& $$007s1   A=F)6E; 7E98E; <B=F)9E; ;+F&&F)c                x    | j                   j                  |      }||| j                   |<   y t        d|z        )Nz.byte stream handler for topic '%s' already set)r   get
ValueErrorr{   rk   handlerexisting_handlers       rY   register_byte_stream_handlerz!Room.register_byte_stream_handler*  A    5599%@#07D&&u-MPUUVVrX   c                r    | j                   j                  |      r| j                   j                  |       y y ry   )r   r  popr{   rk   s     rY   unregister_byte_stream_handlerz#Room.unregister_byte_stream_handler1  /    %%))%0&&**51 1rX   c                x    | j                   j                  |      }||| j                   |<   y t        d|z        )Nz.text stream handler for topic '%s' already set)r   r  r  r  s       rY   register_text_stream_handlerz!Room.register_text_stream_handler5  r  rX   c                r    | j                   j                  |      r| j                   j                  |       y y ry   )r   r  r
  r  s     rY   unregister_text_stream_handlerz#Room.unregister_text_stream_handler<  r  rX   c                N  K   | j                         sy| j                          d{    | j                          d{    t        j                         }| j
                  j                  |j                  _        t        j                  j                  j                         }	 t        j                  j                  |      |j                  fd       d{    t        j                  j                  j                  |       | j                    d{    t        j                  j                  j                  | j"                         | j$                  t&        j(                  k7  r{t*        j,                  | j.                  j0                  _        t&        j(                  | _        | j5                  d| j$                         | j5                  dt*        j,                         yy7 7 7 # t        j                  j                  j                  |       w xY w7 w)zDisconnects from the room.Nc                ^    | j                   j                  j                   j                  k(  S ry   )
disconnectr   r   s    rY   r   z!Room.disconnect.<locals>.<lambda>M  s     1<<+@+@DOOD\D\+\ rX   r?   rA   )r   _drain_rpc_invocation_tasks_drain_data_stream_tasksr   r   r   r   r  r   r   r   r   r   r   r   r   r   r   r   r   r   r   CLIENT_INITIATEDr   r   disconnect_reasonemit)r{   r   r   r   s      @rY   r  zRoom.disconnect@  s    !..000++---""$%)%5%5%<%<"""((224	8%%--c2D..!\]]]$$007jj  ,,T__= !!_%F%FF=M=^=^D""((:%4%F%FD"II0$2H2HIIIn&6&G&GH	 G# 	1- ^$$007sY   %H%G+H% G.A%H%'6G4 G1G4 "8H%H"CH%.H%1G4 4+HH%c                  K   	 | j                   j                          d {   }|j                  d      dk(  r| j                  |j                         ne|j
                  j                  | j                  j                  k(  r8|j
                  j                  d      rnZ	 | j                  |j
                         | j                  j                  |       | j                  j!                          d {    | j#                          d {    | j%                          d {    y 7 	# t        $ r= t        j                  d|j
                  j                  d      |j
                         Y w xY w7 7 k7 Uw)Nrz   rpc_method_invocationeosz&error running user callback for %s: %s)r   r  
WhichOneof_on_rpc_method_invocationr  
room_eventr   r   r   HasField_on_room_eventr   logging	exceptionr   
put_nowaitjoinr  r  )r{   r   s     rY   r   zRoom._listen_task\  sB    //--//E	*.EE..u/J/JK!!--1A1A1H1HH##,,U3''(8(89 ''.""'')))) . ..000++---/ 0 ! %%@((33I>(( * 	1-se   E<D*A=E< D- ;8E<3E64E<E8E<$E:%E<-AE30E<2E33E<8E<:E<c                   | j                   y |j                  | j                   j                  j                  k(  r| j                  j                  | j                   j                  |j                  |j                  |j                  |j                  |j                  |j                  dz              }| j                  j                  |       |j                  | j                  j                          y y )Ng     @@)r   local_participant_handler   r   r   r   _handle_rpc_method_invocationinvocation_idmethod
request_idcaller_identitypayloadresponse_timeout_msr   addadd_done_callbackdiscard)r{   rpc_invocationtasks      rY   r  zRoom._on_rpc_method_invocationx  s    ""*22d6M6M6Y6Y6`6``::))''EE"00"))"--"22"**"66?	D &&**40""4#=#=#E#EF arX   c                Z   |j                  d      }|dk(  r8| j                  |j                  j                        }| j	                  d|       y |dk(  ri|j
                  j                  }| j                  j                  |      }|j
                  j                  |j                  _	        | j	                  d|       y |dk(  rO|j                  j                  }| j                  j                  |   }|j                  }| j	                  d||       y |dk(  rB|j                   j"                  }| j                  j                  |   }| j	                  d|       y |dk(  rg|j$                  j                  }| j                  j                  |   }|j&                  j)                  d        | j	                  d|j                         y |dk(  ro| j                  |j*                  j                     }t-        |j*                  j.                        }||j0                  |j2                  <   | j	                  d||       y |dk(  rf| j                  |j4                  j                     }|j0                  j                  |j4                  j"                        }| j	                  d||       y |d	k(  r|j6                  j                  }	|	j                  }
| j                  |j6                  j                     }|j                  |
j2                     }d
|_        |
j:                  t<        j>                  k(  r'tA        |	      }||_!        | j	                  d	|||       y |
j:                  t<        jD                  k(  r'tG        |	      }||_!        | j	                  d	|||       y y |dk(  rw|jH                  j                  }| j                  |   }|j                  |jH                  j                     }|j                  }d |_!        d|_        | j	                  d|||       y |dk(  rd|jJ                  j                  }| j                  |   }|jJ                  jL                  }| j	                  d||jJ                  j                  |       y |dk(  r|jN                  j                  }| jQ                  |      }tS        |tT              sJ |j                  |jN                  j                     }d
|j                  _+        |j                  rd
|j                  j                  _+        | j	                  d||       y |dk(  r|jX                  j                  }| jQ                  |      }tS        |tT              sJ |j                  |jX                  j                     }d|j                  _+        |j                  rd|j                  j                  _+        | j	                  d||       y |dk(  rdg }|jZ                  j\                  D ]6  }| jQ                  |      }tS        |tT              sJ |j_                  |       8 | j	                  d|       y |dk(  rO| j`                  }|jb                  j`                  | j                  _0        | j	                  d|| j`                         y |dk(  rk| j                  j2                  s/| jd                  j)                  |jf                  j2                         |jf                  j2                  | j                  _        y |dk(  r|jh                  j                  }| jQ                  |      }tS        |tT              sJ |j`                  }|jh                  j`                  |j                  _0        | j	                  d|||j`                         y |dk(  r|jj                  j                  }| jQ                  |      }tS        |tT              sJ |jl                  }|jj                  jl                  |j                  _6        | j	                  d|||jl                         y |dk(  r|jn                  j                  }|jn                  jp                  }ts        d |jn                  jt                  D              }| jQ                  |      }tS        |tT              sJ |j                  jp                  jw                          |j                  jp                  jy                  d |D               | j	                  d||       y |dk(  rO|jz                  j                  }| jQ                  |      }| j	                  d||jz                  j|                         y |dk(  r|j~                  j                  }| jQ                  |      }tS        |tT              sJ |j                  j                  j                  |j~                  j                         | j	                  d||j                         y |dk(  rO|j                  j                  }| jQ                  |      }| j	                  d||j                  j                         y |dk(  r|j                  }|j                  D cg c]O  }t        |j                  |j                  |j                  |j                  |j                  |j                        Q }}| jQ                  |j                        }d }|r%|j                  j                  |j                        }| j	                  d|||       y |dk(  r|j                  }|j                  d      }|dk(  r|j                  j                  }|j                  }t        j                  |j                  t        j                  t        j                  |j                  z              j                  }t        |      } t        |j                  j                        j                          t        t        | j                  |j                              }| j	                  d t        | |j:                  ||j                  j                  !             y |d"k(  rpt        t        | j                  |j                              }| j	                  d#t        |j                  j                  |j                  j                  |$             y y |d%k(  rO|j                  j                  }|j                  j                  }!| j	                  d%| jQ                  |      |!       y |d&k(  r0|j                  j                  }"|"| _h        | j	                  d&|"       y |d'k(  r'| j	                  d'|j                  j                         y |d(k(  r| j	                  d(       y |d)k(  r| j	                  d)       y |d*k(  r;| j                  |j                  j                  |j                  j                         y |d+k(  ryt        j                  | j                  |j                  j                              }#| j                  j                  |#       |#j                  | j                  j                         y |d,k(  ryt        j                  | j                  |j                  j                              }#| j                  j                  |#       |#j                  | j                  j                         y |d-k(  r#|j                  | _
        | j	                  d-       y |d.k(  r#|j                  | _
        | j	                  d.       y |d/k(  rA|j                  j                  D ]'  }$| jQ                  |$j                        }|s!|$|_
        ) y |d0k(  r.|j                  j                   | _        | j	                  d0       y y c c}w )1Nrz   r'   r(   r)   r*   r+   r,   r-   r.   Tr/   Fr0   r1   r2   r3   r4   room_sid_changedr5   r6   r7   c              3  L   K   | ]  }|j                   |j                  f  y wry   keyvalue.0entrys     rY   	<genexpr>z&Room._on_room_event.<locals>.<genexpr>  s%      & EKK(&   "$c              3  L   K   | ]  }|j                   |j                  f  y wry   r7  r:  s     rY   r=  z&Room._on_room_event.<locals>.<genexpr>  s     /aUEKK0H/ar>  r9   r:   r8   r=   )r   textfinal
start_timeend_timelanguagedata_packet_receivedr9  userr;   )rg   rh   rj   rk   sip_dtmfr<   )ro   rq   rj   r>   r?   rA   rB   rC   stream_header_receivedstream_chunk_receivedstream_trailer_receivedrD   rE   participants_updatedrF   )r  r   r'   r   r  r(   participant_identityr   r
  r  r   r)   	track_sidr   track_publicationstrackr*   publication_sidr+   _first_subscription
set_resultr,   r    r   r   r   r-   r.   _subscribedrh   r   
KIND_VIDEOr   _track
KIND_AUDIOr   r/   r0   r   r1   _retrieve_participant
isinstancer   mutedr2   r3   participant_identitiesappendr   r4   r   r5  r5   r6   r   r7   
attributesdictchanged_attributesclearupdater9   is_encryptedparticipant_permission_changed
permissionCopyFrompermissionsr8   qualityr=   segmentsr"   r   r@  rA  rB  rC  rD  r  rE  rF  rg   ctypesr
   data_ptrPOINTERc_bytedata_lencontentsrf   r   r   disposer   _retrieve_remote_participantre   rk   rm   rG  ro   rq   r>   stater?   r   rA   reason_handle_stream_headerrH  headerr   r   _handle_stream_chunkrI  chunkr   r/  r0  r1  _handle_stream_trailerrJ  trailerrD   rE   rK  r   identityrF   r   r   )%r{   r   whichrparticipantrx  r   lpublicationltrackrpublicationowned_track_info
track_inforemote_video_trackremote_audio_trackrtrackr   rj   r   speakersold_metadataold_namer\  r^  transcriptionsrg  partpubpacket	which_valowned_buffer_infobuffer_infonative_datarg   
e2ee_stater   r3  r   s%                                        rY   r!  zRoom._on_room_event  si     +++::5;V;V;[;[\LII-|<0055JJH4488BL383Q3Q3c3cL0II0,?----77C11DDSIL!''FII-|VD////??C11DDSILII/>....88C11DDSIL,,77=II.0B0BC''44U5J5J5_5_`L1%2G2G2S2STLAML,,\-=-=>II'|D))44U5L5L5a5abL';;??''77L II)<F(($55;;)..J44U5K5K5`5`aL':::>>JL'+L$)"6"66%56F%G"&8#		,.@,P\]I$8$88%56F%G"&8#		,.@,P\] 9 **//DDH44X>L'::5;S;S;];]^L!''F"&L',L$II*FL,O1166KKH44X>L3399EII+//99	 m#((==H44X>Kk;777%889J9J9T9TUK&*K#  04!!''-IIm[+>o%**??H44X>Kk;777%889L9L9V9VWK&+K#  05!!''-IIo{K@//*,H!99PP -"88B!+{;;;,-
 II/:--==L"'"="="F"FDJJII-|T]]K((::>>&&11%2H2H2L2LM"3377DJJN4499NNH44X>Kk;777&//L).)K)K)T)TK&II.$$	 0055JJH44X>Kk;777"''H%*%C%C%H%HK"II0+xIYIYZ66;;PPH==HHJ!% &"AATT& " 44X>Kk;777((..0((///aV`/aaII0"
 ==BBWWH44X>KII7;;HH
 77;;PPH44X>Kk;777((11%2V2V2a2abII1''
 2277LLH44X>KII,0088
 ..!88M '//
  %tt'' ||ZZZZ
H 
 --m.P.PQD+/C--11-2I2IJII.$D,,//F))'2IF"$*KK$4$4!/44$kk((NN6==;3G3G#GH ( 
 [)+22556>>@#%55f6Q6QR  		#!#[[$0$kk//	 j(#%55f6Q6QR  		'#__11$oo33$0 ) **//DDH1177JII*D,F,Fx,PR\]00$==CC%5D"II02BCn$IIne&8&8&?&?@n$IIn%m#IIm$..&&,,33,,AA --&&t'@'@A\A\AbAb'cdD##''-""4#:#:#B#BC//&&++E,I,I,Q,QRD ##''-""4#:#:#B#BCn$++DJIIn%gDJIIg,,22?? -"88G(,K%-
 ''//55DKII'( (K
s   A~(c                >   |j                  d      }|dk(  rv| j                  j                  |j                        }|!t	        j
                  d|j                         y t        |      }|| j                  |j                  <    |||       y |dk(  rv| j                  j                  |j                        }|!t	        j
                  d|j                         y t        |      }|| j                  |j                  <    |||       y t	        j                  d|       y )Ncontent_headertext_headerz:ignoring text stream with topic '%s', no callback attachedbyte_headerz:ignoring byte stream with topic '%s', no callback attachedz received unknown header type, %s)r  r   r  rk   r"  r   r#   r   	stream_idr   r$   r   warning)r{   rs  rL  stream_typetext_stream_handlertext_readerbyte_stream_handlerbyte_readers           rY   rr  zRoom._handle_stream_header  s    ''(89-'"&"<"<"@"@"N"*PLL *62K:ED%%f&6&67-AB 	 M)"&"<"<"@"@"N"*PLL *62K:ED%%f&6&67-AB 	 OO>LrX   c                  K   | j                   j                  |j                        }| j                  j                  |j                        }|r|j	                  |       d {    y |r|j	                  |       d {    y y 7 "7 wry   )r   r  r  r   _on_chunk_update)r{   ru  r  file_readers       rY   rt  zRoom._handle_stream_chunk  sv     //33EOOD//33EOOD..u555..u555  65s$   A!B
#B$B
?B B
B
c                  K   | j                   j                  |j                        }| j                  j                  |j                        }|r?|j	                  |       d {    | j                   j                  |j                         y |r?|j	                  |       d {    | j                  j                  |j                         y y 7 l7 -wry   )r   r  r  r   _on_stream_closer
  )r{   rw  r  r  s       rY   rv  zRoom._handle_stream_trailer  s     //33G4E4EF//33G4E4EF..w777%%))'*;*;<..w777%%))'*;*;<  8 8s%   A!C#C$A C$C%,CCc                   K   | j                   rI| j                   D ]  }|j                           t        j                  | j                   ddi d {    y y 7 wNreturn_exceptionsT)r   cancelr   gatherr{   r3  s     rY   r  z Room._drain_rpc_invocation_tasks  sV     %%22 ..$"<"<UPTUUU & V   AAAAc                   K   | j                   rI| j                   D ]  }|j                           t        j                  | j                   ddi d {    y y 7 wr  )r   r  r   r  r  s     rY   r  zRoom._drain_data_stream_tasks  sU     ""// ..$"9"9RTRRR # Sr  c                :    | j                   j                  |d      S )z)Retrieve a remote participant by identityN)r   r  r{   rx  s     rY   ro  z!Room._retrieve_remote_participant  s    ((,,Xt<<rX   c                r    |r%|| j                   j                  k(  r| j                   S | j                  |      S )z2Retrieve a local or remote participant by identity)r   rx  ro  r  s     rY   rW  zRoom._retrieve_participant  s5    D$:$:$C$CC)))00::rX   c                    |j                   j                  | j                  v rt        d      t	        |      }|| j                  |j                  <   |S )Nzparticipant already exists)r   rx  r   r   r   )r{   
owned_inforj   s      rY   r   zRoom._create_remote_participant  sN     ??##t'@'@@899'
3:E!!+"6"67rX   c           
         d}| j                   j                         r| j                   j                         }d| d| j                   d| j                   dt        j                  | j                         d	S )Nunknownzrtc.Room(sid=z, name=z, metadata=z, connection_state=))r   doner   r   r   r   Namer   )r{   r   s     rY   __repr__zRoom.__repr__  s    !!&&(((//1Cse7499+[Obcrcwcwx|  yO  yO  dP  cQ  QR  S  	SrX   ry   )r   z#Optional[asyncio.AbstractEventLoop]returnNone)r  r  )r  rp   )r  r   )r  zConnectionState.ValueType)r  zMapping[str, RemoteParticipant])r  r   )r  rn   )r  zdatetime.datetime)r  r\   )r  r   )r   
EventTypesr   zOptional[Callable]r  r   )r   rp   r   rp   r   r[   r  r  )r  rs   )rk   rp   r  r&   )rk   rp   )rk   rp   r  r%   )r2  r   )r   zproto_room.RoomEvent)rs  zproto_room.DataStream.HeaderrL  rp   )ru  zproto_room.DataStream.Chunk)rw  zproto_room.DataStream.Trailer)rx  rp   r  zOptional[RemoteParticipant])rx  rp   r  zOptional[Participant])r  z"proto_participant.OwnedParticipantr  r   )*rM   rN   rO   r|   r   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r[   r   r   r  r  r  r  r  r   r  r!  rr  rt  rv  r  r  ro  rW  r   r  __classcell__)r   s   @rY   r~   r~      s    59,1, 
,>B 	, 	, 	' 	' & & ) )   # # " " + + ) ) 
 
 + + 3 3 / /	
P+d JU zAx\0W2W2I8.8G$S)j2JM@6	=VS=;<	SrX   r~   )F
__future__r   r   r   rh  r"  dataclassesr   r   typingr   r   r   r	   r
   r   r   event_emitterr   _ffi_clientr   r   _protor   r   r   proto_participantr   rP   r   proto_stats_proto.participant_pb2r   _proto.room_pb2r   _proto.track_pb2r   _proto.rpc_pb2r   _utilsr   r_   r   r   rj   r   r   r   rO  r   r   track_publicationr    r!   r  r"   data_streamr#   r$   r%   r&   r  rH   r[   re   rm   rs   r   rw   r~   rW   rX   rY   <module>r     s   #     ( C C  ' - ( 8 * , 4 , ' 4 " * I I 5 G /  !
H    l l l  1 1 1 O O O 1 1 1
9 
dS<
# dSrX   