
    qi*,                     d   d Z ddl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  G d de      Z G d d	e      Z G d
 de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d d      Zy) z;WhatsApp API.

API to communicate with WhatsApp Cloud API.
    )AnyDictListOptionalUnionN)logger)	BaseModelFieldc                   &    e Zd ZU dZeed<   eed<   y)WhatsAppSessionzWebRTC session information for WhatsApp calls.

    Parameters:
        sdp: Session Description Protocol (SDP) data for WebRTC connection
        sdp_type: Type of SDP (e.g., "offer", "answer")
    sdpsdp_typeN__name__
__module____qualname____doc__str__annotations__     Q/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/transports/whatsapp/api.pyr   r      s     
HMr   r   c                   D    e Zd ZU dZeed<   eed<   eed<   eeef   ed<   y)WhatsAppErrorzError information from WhatsApp API responses.

    Parameters:
        code: Error code number
        message: Human-readable error message
        href: URL for more information about the error
        error_data: Additional error-specific data
    codemessagehref
error_dataN)	r   r   r   r   intr   r   r   r   r   r   r   r   r   "   s&     IL
IS#Xr   r   c                   r    e Zd ZU dZeed<    edd      Zeed<   eed<   eed<   eed	<   ee   ed
<   e	ed<   y)WhatsAppConnectCallaw  Incoming call connection event data.

    Represents a user-initiated call that requires handling. This is sent
    when a WhatsApp user initiates a call to your business number.

    Parameters:
        id: Unique call identifier
        from_: Phone number of the caller (WhatsApp ID format)
        to: Your business phone number that received the call
        event: Always "connect" for incoming calls
        timestamp: ISO 8601 timestamp when the call was initiated
        direction: Optional call direction ("inbound" for user-initiated calls)
        session: WebRTC session data containing SDP offer from the caller
    id.fromaliasfrom_toevent	timestamp	directionsessionN)
r   r   r   r   r   r   r
   r&   r   r   r   r   r   r!   r!   2   s>     	Gs&)E3)GJN}r   r!   c                       e Zd ZU dZeed<    edd      Zeed<   eed<   eed<   eed	<   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<   y)WhatsAppTerminateCalla;  Call termination event data.

    Represents the end of a call session, whether completed successfully,
    failed, or was rejected by either party.

    Parameters:
        id: Unique call identifier (matches the connect event)
        from_: Phone number of the caller
        to: Your business phone number
        event: Always "terminate" for call end events
        timestamp: ISO 8601 timestamp when the call ended
        direction: Optional call direction
        biz_opaque_callback_data: Optional business-specific callback data
        status: Call completion status ("FAILED", "COMPLETED", "REJECTED")
        start_time: ISO 8601 timestamp when call actually started (after acceptance)
        end_time: ISO 8601 timestamp when call ended
        duration: Call duration in seconds (only for completed calls)
    r"   .r#   r$   r&   r'   r(   r)   r*   Nbiz_opaque_callback_datastatus
start_timeend_timeduration)r   r   r   r   r   r   r
   r&   r   r.   r/   r0   r1   r2   r   r   r   r   r-   r-   K   s    & 	Gs&)E3)GJN}.2hsm2 FHSM  $J$"Hhsm""Hhsm"r   r-   c                       e Zd ZU dZeed<   y)WhatsAppProfilez_User profile information.

    Parameters:
        name: Display name of the WhatsApp user
    nameNr   r   r   r   r4   r4   l   s     Ir   r4   c                   &    e Zd ZU dZeed<   eed<   y)WhatsAppContactzContact information for a WhatsApp user.

    Parameters:
        profile: User's profile information
        wa_id: WhatsApp ID (phone number in international format without +)
    profilewa_idN)r   r   r   r   r4   r   r   r   r   r   r7   r7   v   s     Jr   r7   c                   &    e Zd ZU dZeed<   eed<   y)WhatsAppMetadatazBusiness phone number metadata.

    Parameters:
        display_phone_number: Formatted phone number for display
        phone_number_id: WhatsApp Business API phone number ID
    display_phone_numberphone_number_idNr   r   r   r   r;   r;      s     r   r;   c                   F    e Zd ZU dZeed<   eed<   ee   ed<   ee	   ed<   y)WhatsAppConnectCallValuea  Webhook payload for incoming call events.

    Parameters:
        messaging_product: Always "whatsapp"
        metadata: Business phone number information
        contacts: List of contact information for involved parties
        calls: List of call connection events
    messaging_productmetadatacontactscallsN)
r   r   r   r   r   r   r;   r   r7   r!   r   r   r   r?   r?      s,     ?###$$r   r?   c                   P    e Zd ZU dZeed<   eed<   ee   ed<   dZ	e
ee      ed<   y)WhatsAppTerminateCallValuea  Webhook payload for call termination events.

    Parameters:
        messaging_product: Always "whatsapp"
        metadata: Business phone number information
        calls: List of call termination events
        errors: Optional list of errors that occurred during the call
    r@   rA   rC   Nerrors)r   r   r   r   r   r   r;   r   r-   rF   r   r   r   r   r   rE   rE      s5     %&&,0FHT-()0r   rE   c                   0    e Zd ZU dZeeef   ed<   eed<   y)WhatsAppChangezWebhook change event wrapper.

    Parameters:
        value: The actual event data (connect or terminate)
        field: Always "calls" for calling webhooks
    valuefieldN)	r   r   r   r   r   r?   rE   r   r   r   r   r   rH   rH      s      )+EEFFJr   rH   c                   ,    e Zd ZU dZeed<   ee   ed<   y)WhatsAppEntryzWebhook entry containing one or more changes.

    Parameters:
        id: WhatsApp Business Account ID
        changes: List of change events in this webhook delivery
    r"   changesN)r   r   r   r   r   r   r   rH   r   r   r   rL   rL      s     	G.!!r   rL   c                   ,    e Zd ZU dZeed<   ee   ed<   y)WhatsAppWebhookRequesta(  Complete webhook request from WhatsApp.

    This is the top-level structure for all webhook deliveries from
    the WhatsApp Cloud API for calling events.

    Parameters:
        object: Always "whatsapp_business_account"
        entry: List of webhook entries (usually contains one entry)
    objectentryN)r   r   r   r   r   r   r   rL   r   r   r   rO   rO      s     Kr   rO   c                       e Zd ZdZdZdededej                  ddfdZdefd	Z	defd
Z
dedededefdZdefdZdefdZy)WhatsAppApia  WhatsApp Cloud API client for handling calls.

    This class provides methods to interact with the WhatsApp Cloud API
    for managing voice calls, including answering, rejecting, and terminating calls.

    Parameters:
        BASE_URL: Base URL for WhatsApp Graph API v23.0
        phone_number_id: Your WhatsApp Business phone number ID
        session: aiohttp client session for making HTTP requests
        whatsapp_url: Complete URL for the calls endpoint
        whatsapp_token: Bearer token for API authentication
    z!https://graph.facebook.com/v23.0/whatsapp_tokenr=   r+   returnNc                 Z    || _         || _        | j                   | d| _        || _        y)a  Initialize the WhatsApp API client.

        Args:
            whatsapp_token: WhatsApp access token for authentication
            phone_number_id: Your business phone number ID from WhatsApp Business API
            session: aiohttp ClientSession for making HTTP requests
        z/callsN)_phone_number_id_sessionBASE_URL_whatsapp_url_whatsapp_token)selfrT   r=   r+   s       r   __init__zWhatsAppApi.__init__   s3     !0 $.?vF-r   c                     || _         y)z4Update the WhatsApp access token for authentication.N)r[   )r\   rT   s     r   update_whatsapp_tokenz!WhatsAppApi.update_whatsapp_token   s
    -r   c                     || _         y)z7Update the WhatsApp phone number ID for authentication.N)rW   )r\   r=   s     r   update_whatsapp_phone_number_idz+WhatsAppApi.update_whatsapp_phone_number_id   s
     /r   call_idactionr   r&   c                 \  K   t        j                  d| d|        | j                  j                  | j                  d| j
                   ddd||||ddd	
      4 d{   }|j                          d{   cddd      d{    S 7 -7 7 	# 1 d{  7  sw Y   yxY ww)a7  Answer an incoming WhatsApp call.

        This method handles the call answering process, supporting both "pre_accept"
        and "accept" actions as required by the WhatsApp calling workflow.

        Args:
            call_id: Unique identifier for the call (from connect webhook)
            action: Action to perform ("pre_accept" or "accept")
            sdp: Session Description Protocol answer for WebRTC connection
            from_: Caller's phone number (WhatsApp ID format)

        Returns:
            Dict containing the API response with success status and any error details

        Note:
            Calls must be pre-accepted before being accepted. The typical flow is:
            1. Receive connect webhook
            2. Call with action="pre_accept"
            3. Call with action="accept"
        zAnswering call z to WhatsApp, action:Bearer application/jsonAuthorizationzContent-Typewhatsappanswer)r   r   )r@   r'   rc   rb   r+   headersjsonNr   debugrX   postrZ   r[   rm   )r\   rb   rc   r   r&   responses         r   answer_call_to_whatsappz#WhatsAppApi.answer_call_to_whatsapp   s     * 	wi/DVHMN==%%#*4+?+?*@!A 2
 &0 "#&H= & 
 	) 	) !(	) 	) 	) )	) 	) 	) 	)sZ   A!B,#B$B,'B;B<B?B,BB,BB,B)B B)%B,c                 L  K   t        j                  d|        | j                  j                  | j                  d| j
                   dddd|d      4 d	{   }|j                          d	{   cd	d	d	      d	{    S 7 -7 7 	# 1 d	{  7  sw Y   y	xY ww)
al  Reject an incoming WhatsApp call.

        This method rejects a call that was received via connect webhook.
        The caller will receive a rejection notification and a terminate
        webhook will be sent with status "REJECTED".

        Args:
            call_id: Unique identifier for the call (from connect webhook)

        Returns:
            Dict containing the API response with success status and any error details

        Note:
            This should be called instead of answer_call_to_whatsapp when you want
            to decline the incoming call. The caller will see the call as rejected.
        zRejecting call re   rf   rg   ri   rejectr@   rc   rb   rk   Nrn   r\   rb   rq   s      r   reject_call_to_whatsappz#WhatsAppApi.reject_call_to_whatsapp"  s     " 	wi01==%%#*4+?+?*@!A 2
 &0"" & 
 	) 	) !(	) 	) 	) )	) 	) 	) 	)Z   AB$B	B$B3B4B7B$BB$BB$B!BB!B$c                 L  K   t        j                  d|        | j                  j                  | j                  d| j
                   dddd|d      4 d	{   }|j                          d	{   cd	d	d	      d	{    S 7 -7 7 	# 1 d	{  7  sw Y   y	xY ww)
a}  Terminate an active WhatsApp call.

        This method ends an ongoing call that has been previously accepted.
        Both parties will be disconnected and a terminate webhook will be
        sent with status "COMPLETED".

        Args:
            call_id: Unique identifier for the active call

        Returns:
            Dict containing the API response with success status and any error details

        Note:
            This should only be called for calls that have been accepted and are
            currently active. For incoming calls that haven't been accepted yet,
            use reject_call_to_whatsapp instead.
        zTerminating call re   rf   rg   ri   	terminateru   rk   Nrn   rv   s      r   terminate_call_to_whatsappz&WhatsAppApi.terminate_call_to_whatsappB  s     $ 	(	23==%%#*4+?+?*@!A 2
 &0%" & 
 	) 	) !(	) 	) 	) )	) 	) 	) 	)rx   )r   r   r   r   rY   r   aiohttpClientSessionr]   r_   ra   rr   rw   r{   r   r   r   rS   rS      s     3H.!.47.BIBWBW.	..C .0s 0$)S $)# $)C $)X[ $)L)S )@) )r   rS   )r   typingr   r   r   r   r   r|   logurur   pydanticr	   r
   r   r   r!   r-   r4   r7   r;   r?   rE   rH   rL   rO   rS   r   r   r   <module>r      s   
 4 3   %	i 	I  ) 2#I #Bi 	i 		y 	%y % 1 1 	Y 		"I 	"Y L) L)r   