
    hZ                       d Z ddlmZ ddlmZmZmZmZmZ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ZddlZddlmZmZmZmZmZmZ  ej        e          ZdZg dZej        Zej        Zej        Zej         Z ej!        Z!ej"        Z"ej#        Z#ej$        Z$ej%        Z%ej&        Z&ej'        Z'ej(        Z(ej)        Z)ej*        Z*ej+        Z+ej,        Z,ej-        Z-ej.        Z.ej/        Z/ej0        Z0ej1        Z1ej2        Z2d'dZ3d(d)dZ4	 	 d(d*dZ5	 	 d(d*dZ6	 	 d(d+dZ7d(dZ8d,dZ9d,dZ: G d d           Z; G d! d"          Z< G d# d          Z= G d$ d%          Z> G d& d          Z?dS )-z Firebase Cloud Messaging module.    )annotations)AnyCallableDictListOptionalcastN)_http_client_messaging_encoder_messaging_utils_utils
exceptionsApp
_messaging)!AndroidConfigAndroidFCMOptionsAndroidNotification
APNSConfigAPNSFCMOptionsAPNSPayloadApsApsAlertBatchResponseCriticalSound	ErrorInfo
FCMOptionsLightSettingsMessageMulticastMessageNotificationQuotaExceededErrorSenderIdMismatchErrorSendResponseThirdPartyAuthErrorTopicManagementResponseUnregisteredErrorWebpushConfigWebpushFCMOptionsWebpushNotificationWebpushNotificationActionsend	send_eachsend_each_asyncsend_each_for_multicastsend_each_for_multicast_asyncsubscribe_to_topicunsubscribe_from_topicappOptional[App]return_MessagingServicec                B    t          j        | t          t                    S N)r   get_app_service_MESSAGING_ATTRIBUTEr5   )r2   s    \/var/www/html/e360mart/e360mart_env/lib/python3.11/site-packages/firebase_admin/messaging.py_get_messaging_servicer;   h   s    !#';=NOOO    Fmessager   dry_runboolstrc                H    t          |                              | |          S )a  Sends the given message via Firebase Cloud Messaging (FCM).

    If the ``dry_run`` mode is enabled, the message will not be actually delivered to the
    recipients. Instead, FCM performs all the usual validations and emulates the send operation.

    Args:
        message: An instance of ``messaging.Message``.
        dry_run: A boolean indicating whether to run the operation in dry run mode (optional).
        app: An App instance (optional).

    Returns:
        string: A message ID string that uniquely identifies the sent message.

    Raises:
        FirebaseError: If an error occurs while sending the message to the FCM service.
        ValueError: If the input arguments are invalid.
    )r;   r+   )r=   r>   r2   s      r:   r+   r+   k   s"    $ "#&&++GW===r<   messagesList[Message]r   c                H    t          |                              | |          S )a  Sends each message in the given list via Firebase Cloud Messaging.

    If the ``dry_run`` mode is enabled, the message will not be actually delivered to the
    recipients. Instead, FCM performs all the usual validations and emulates the send operation.

    Args:
        messages: A list of ``messaging.Message`` instances.
        dry_run: A boolean indicating whether to run the operation in dry run mode (optional).
        app: An App instance (optional).

    Returns:
        BatchResponse: A ``messaging.BatchResponse`` instance.

    Raises:
        FirebaseError: If an error occurs while sending the message to the FCM service.
        ValueError: If the input arguments are invalid.
    )r;   r,   rB   r>   r2   s      r:   r,   r,      s"    , "#&&007CCCr<   c                X   K   t          |                              | |           d{V S )a  Sends each message in the given list asynchronously via Firebase Cloud Messaging.

    If the ``dry_run`` mode is enabled, the message will not be actually delivered to the
    recipients. Instead, FCM performs all the usual validations and emulates the send operation.

    Args:
        messages: A list of ``messaging.Message`` instances.
        dry_run: A boolean indicating whether to run the operation in dry run mode (optional).
        app: An App instance (optional).

    Returns:
        BatchResponse: A ``messaging.BatchResponse`` instance.

    Raises:
        FirebaseError: If an error occurs while sending the message to the FCM service.
        ValueError: If the input arguments are invalid.
    N)r;   r-   rE   s      r:   r-   r-      s8      , (,,<<XwOOOOOOOOOr<   multicast_messager   c                    K   t           t                    st          d           fd j        D             }t	          |                              ||           d{V S )a  Sends the given mutlicast message to each token asynchronously via Firebase Cloud Messaging
    (FCM).

    If the ``dry_run`` mode is enabled, the message will not be actually delivered to the
    recipients. Instead, FCM performs all the usual validations and emulates the send operation.

    Args:
        multicast_message: An instance of ``messaging.MulticastMessage``.
        dry_run: A boolean indicating whether to run the operation in dry run mode (optional).
        app: An App instance (optional).

    Returns:
        BatchResponse: A ``messaging.BatchResponse`` instance.

    Raises:
        FirebaseError: If an error occurs while sending the message to the FCM service.
        ValueError: If the input arguments are invalid.
    @Message must be an instance of messaging.MulticastMessage class.c                x    g | ]6}t          j        j        j        j        j        j        |           7S )datanotificationandroidwebpushapnsfcm_optionstokenr   rL   rM   rN   rO   rP   rQ   .0rR   rG   s     r:   
<listcomp>z1send_each_for_multicast_async.<locals>.<listcomp>   a     - - -  #&3!)!)#%1   - - -r<   N)
isinstancer   
ValueErrortokensr;   r-   rG   r>   r2   rB   s   `   r:   r/   r/      s      . ')9:: ][\\\- - - - %+- - -H (,,<<XwOOOOOOOOOr<   c                     t           t                    st          d           fd j        D             }t	          |                              ||          S )a  Sends the given mutlicast message to each token via Firebase Cloud Messaging (FCM).

    If the ``dry_run`` mode is enabled, the message will not be actually delivered to the
    recipients. Instead, FCM performs all the usual validations and emulates the send operation.

    Args:
        multicast_message: An instance of ``messaging.MulticastMessage``.
        dry_run: A boolean indicating whether to run the operation in dry run mode (optional).
        app: An App instance (optional).

    Returns:
        BatchResponse: A ``messaging.BatchResponse`` instance.

    Raises:
        FirebaseError: If an error occurs while sending the message to the FCM service.
        ValueError: If the input arguments are invalid.
    rI   c                x    g | ]6}t          j        j        j        j        j        j        |           7S rK   rS   rT   s     r:   rV   z+send_each_for_multicast.<locals>.<listcomp>   rW   r<   )rX   r   rY   rZ   r;   r,   r[   s   `   r:   r.   r.      sv    $ ')9:: ][\\\- - - - %+- - -H "#&&007CCCr<   c                J    t          |                              | |d          S )a4  Subscribes a list of registration tokens to an FCM topic.

    Args:
        tokens: A non-empty list of device registration tokens. List may not have more than 1000
            elements.
        topic: Name of the topic to subscribe to. May contain the ``/topics/`` prefix.
        app: An App instance (optional).

    Returns:
        TopicManagementResponse: A ``TopicManagementResponse`` instance.

    Raises:
        FirebaseError: If an error occurs while communicating with instance ID service.
        ValueError: If the input arguments are invalid.
    ziid/v1:batchAddr;   make_topic_management_requestrZ   topicr2   s      r:   r0   r0      s,      "#&&DD(* * *r<   c                J    t          |                              | |d          S )a<  Unsubscribes a list of registration tokens from an FCM topic.

    Args:
        tokens: A non-empty list of device registration tokens. List may not have more than 1000
            elements.
        topic: Name of the topic to unsubscribe from. May contain the ``/topics/`` prefix.
        app: An App instance (optional).

    Returns:
        TopicManagementResponse: A ``TopicManagementResponse`` instance.

    Raises:
        FirebaseError: If an error occurs while communicating with instance ID service.
        ValueError: If the input arguments are invalid.
    ziid/v1:batchRemover_   ra   s      r:   r1   r1     s,      "#&&DD+- - -r<   c                  D    e Zd ZdZd Zed             Zed             ZdS )r   zBAn error encountered when performing a topic management operation.c                "    || _         || _        d S r7   )_index_reason)selfindexreasons      r:   __init__zErrorInfo.__init__  s    r<   c                    | j         S )zBIndex of the registration token to which this error is related to.)rf   rh   s    r:   ri   zErrorInfo.index   s     {r<   c                    | j         S )z*String describing the nature of the error.)rg   rm   s    r:   rj   zErrorInfo.reason%       |r<   N)__name__
__module____qualname____doc__rk   propertyri   rj    r<   r:   r   r     s_        LL     X   X  r<   r   c                  Z    e Zd ZdZd Zed             Zed             Zed             ZdS )r%   z8The response received from a topic management operation.c                d   t          |t                    rd|vrt          d| d          d| _        d| _        g | _        t          |d                   D ]X\  }}d|v r?| xj        dz  c_        | j                            t          ||d                              H| xj        dz  c_        Yd S )Nresultsz&Unexpected topic management response: .r   error   )	rX   dictrY   _success_count_failure_count_errors	enumerateappendr   )rh   respri   results       r:   rk   z TopicManagementResponse.__init__.  s    $%% 	O$)>)>MdMMMNNN&tI77 	) 	)ME6&  ##q(####IeVG_$E$EFFFF##q(###	) 	)r<   c                    | j         S )zCNumber of tokens that were successfully subscribed or unsubscribed.r}   rm   s    r:   success_countz%TopicManagementResponse.success_count;       ""r<   c                    | j         S )zLNumber of tokens that could not be subscribed or unsubscribed due to errors.)r~   rm   s    r:   failure_countz%TopicManagementResponse.failure_count@  r   r<   c                    | j         S )z;A list of ``messaging.ErrorInfo`` objects (possibly empty).)r   rm   s    r:   errorszTopicManagementResponse.errorsE  ro   r<   N)	rp   rq   rr   rs   rk   rt   r   r   r   ru   r<   r:   r%   r%   +  sz        BB) ) ) # # X# # # X#   X  r<   r%   c                  b    e Zd ZdZddZedd            Zedd	            Zedd
            ZdS )r   z:The response received from a batch request to the FCM API.	responsesList[SendResponse]r4   Nonec                P    || _         t          d |D                       | _        d S )Nc              3  (   K   | ]}|j         	d V  dS )r{   N)success)rU   r   s     r:   	<genexpr>z)BatchResponse.__init__.<locals>.<genexpr>P  s)      !J!JT\!J!!J!J!J!J!J!Jr<   )
_responsessumr}   )rh   r   s     r:   rk   zBatchResponse.__init__N  s.    #!!J!J	!J!J!JJJr<   c                    | j         S )z>A list of ``messaging.SendResponse`` objects (possibly empty).)r   rm   s    r:   r   zBatchResponse.responsesR       r<   intc                    | j         S r7   r   rm   s    r:   r   zBatchResponse.success_countW  s    ""r<   c                :    t          | j                  | j        z
  S r7   )lenr   r   rm   s    r:   r   zBatchResponse.failure_count[  s    4>""T%777r<   N)r   r   r4   r   )r4   r   )r4   r   )	rp   rq   rr   rs   rk   rt   r   r   r   ru   r<   r:   r   r   K  s        DDK K K K    X # # # X# 8 8 8 X8 8 8r<   c                  Z    e Zd ZdZd Zed             Zed             Zed             ZdS )r#   zHThe response received from an individual batched request to the FCM API.c                `    || _         d | _        |r|                    dd           | _        d S d S )Nname)
_exception_message_idget)rh   r   	exceptions      r:   rk   zSendResponse.__init__c  s?    # 	6#xx55D	6 	6r<   c                    | j         S )z9A message ID string that uniquely identifies the message.)r   rm   s    r:   
message_idzSendResponse.message_idi  s     r<   c                $    | j         duo| j         S )z3A boolean indicating if the request was successful.N)r   r   rm   s    r:   r   zSendResponse.successn  s     t+CDO0CCr<   c                    | j         S )zTA ``FirebaseError`` if an error occurs while sending the message to the FCM service.)r   rm   s    r:   r   zSendResponse.exceptions  r   r<   N)	rp   rq   rr   rs   rk   rt   r   r   r   ru   r<   r:   r#   r#   `  s}        RR6 6 6     X  D D XD   X  r<   r#   c                     e Zd ZdZdZdZdZddiZ ej	                    Z
eeeeedZd-dZed             Zd.d/dZd.d0dZd1d0dZd Zd Zd Zd Zd2d"Zd# Zd3d$Zed%             Zed4d)            Zed5d+            Zd,S )6r5   zKService class that implements Firebase Cloud Messaging (FCM) functionality.z8https://fcm.googleapis.com/v1/projects/{0}/messages:sendz https://fcm.googleapis.com/batchzhttps://iid.googleapis.comaccess_token_authtrue)APNS_AUTH_ERRORQUOTA_EXCEEDEDSENDER_ID_MISMATCHTHIRD_PARTY_AUTH_ERRORUNREGISTEREDr2   r   r4   r   c                   |j         }|st          d          t          j                            |          | _        ddt          j         d| _        |j	        
                    dt          j                  }|j                                        | _        t          j        | j        |          | _        t          j        | j        |          | _        d S )NzProject ID is required to access Cloud Messaging service. Either set the projectId option, or use service account credentials. Alternatively, set the GOOGLE_CLOUD_PROJECT environment variable.2zfire-admin-python/)zX-GOOG-API-FORMAT-VERSIONzX-FIREBASE-CLIENThttpTimeout)
credentialtimeout)
project_idrY   r5   FCM_URLformat_fcm_urlfirebase_admin__version___fcm_headersoptionsr   r
   DEFAULT_TIMEOUT_SECONDSr   get_credential_credentialJsonHttpClient_clientHttpxAsyncClient_async_client)rh   r2   r   r   s       r:   rk   z_MessagingService.__init__  s    ^
 	>=> > > *188DD),!Rn6P!R!R
 
 +//-1UVV>88::#2d>NX_```):': : :r<   c                ~    t          |t                    st          d          | j                            |          S )Nz7Message must be an instance of messaging.Message class.)rX   r   rY   JSON_ENCODERdefault)clsr=   s     r:   encode_messagez _MessagingService.encode_message  s;    '7++ 	XVWWW''000r<   Fr=   r   r>   r?   r@   c                   |                      ||          }	 | j                            d| j        | j        |          }n1# t
          j        j        $ r}|                     |          d}~ww xY wt          t          |d                   S )z2Sends the given message to FCM via the FCM v1 API.posturlheadersjsonNr   )_message_datar   bodyr   r   requestsr   RequestException_handle_fcm_errorr	   r@   )rh   r=   r>   rL   r   rz   s         r:   r+   z_MessagingService.send  s    !!'733	0<$$M)	 %  DD "3 	0 	0 	0((///	0Cf&&&s   (A A/A**A/rB   rC   r   c                    t          |t                    st          d          t          |          dk    rt          d           fd} fd|D             }	 t          j                            t          |                    5 }t          |                    ||                    }t          |          cddd           S # 1 swxY w Y   dS # t          $ r}t          j        d| |	          d}~ww xY w)
3Sends the given messages to FCM via the FCM v1 API.7messages must be a list of messaging.Message instances.  1messages must not contain more than 500 elements.c                   	 j                             dj        j        |           }nE# t          j        j        $ r.}t          d                     |                    cY d }~S d }~ww xY wt          |d           S Nr   r   )r   r   )r   )	r   r   r   r   r   r   r   r#   r   rL   r   r   rh   s      r:   	send_dataz._MessagingService.send_each.<locals>.send_data  s    \|(( -	 )  
 &7 \ \ \#9O9OPY9Z9Z[[[[[[[[[\5555s   (, A. #A)#A.)A.c                <    g | ]}                     |          S ru   r   rU   r=   r>   rh   s     r:   rV   z/_MessagingService.send_each.<locals>.<listcomp>  )    UUU**7G<<UUUr<   )max_workersN1Unknown error while making remote service calls: r=   cause)rX   listrY   r   
concurrentfuturesThreadPoolExecutormapr   	Exceptionr   UnknownError)rh   rB   r>   r   message_dataexecutorr   rz   s   ` `     r:   r,   z_MessagingService.send_each  sv   (D)) 	XVWWWx==3PQQQ		6 		6 		6 		6 		6 VUUUUHUUU	#663|CTCT6UU 0Ya i!F!FGG	$Y//0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0  	 	 	)SESS   	s<   -C 2C
=C 
CC CC 
C?!C::C?Tc                v   K   t          |t                    st          d          t          |          dk    rt          d           fd fd|D             }	 t	          j        fd|D               d{V }t          |          S # t          $ r}t          j	        d| |	          d}~ww xY w)
r   r   r   r   c                  K   	 j                             dj        j        |            d {V }n# t          j        $ r.}t          d                     |                    cY d }~S d }~wt          j	        j
        $ r.}t          d                     |                    cY d }~S d }~ww xY wt          |                                d           S r   )r   requestr   r   httpx	HTTPErrorr#   _handle_fcm_httpx_errorr   r   r   r   r   r   s      r:   r   z4_MessagingService.send_each_async.<locals>.send_data  s     
\!/77 -	 8        
 ? b b b#9U9UV_9`9`aaaaaaaaa&7 \ \ \#9O9OPY9Z9Z[[[[[[[[[\		t<<<<s-   .4 B1#A,&B1,B1#B,&B1,B1c                <    g | ]}                     |          S ru   r   r   s     r:   rV   z5_MessagingService.send_each_async.<locals>.<listcomp>  r   r<   c                &    g | ]} |          S ru   ru   )rU   r=   r   s     r:   rV   z5_MessagingService.send_each_async.<locals>.<listcomp>  s#    .^.^.^gyy/A/A.^.^.^r<   Nr   r   )
rX   r   rY   r   asynciogatherr   r   r   r   )rh   rB   r>   r   r   rz   r   s   ` `   @r:   r-   z!_MessagingService.send_each_async  s     (D)) 	XVWWWx==3PQQQ	= 	= 	= 	= 	= VUUUUHUUU	%n.^.^.^.^Q].^.^.^_______I +++ 	 	 	)SESS   	s   !.B 
B8B33B8c                8   t          |t                    r|g}t          |t                    r|st          d          d |D             }|rt          d          t          |t                    r|st          d          |                    d          sd| }||d}t
          j         d| }	 | j                            d||t
          j	        	          }n1# t          j        j        $ r}|                     |          d
}~ww xY wt          |          S )z;Invokes the IID service for topic management functionality.z7Tokens must be a string or a non-empty list of strings.c                @    g | ]}t          |t                    r||S ru   )rX   r@   )rU   ts     r:   rV   zC_MessagingService.make_topic_management_request.<locals>.<listcomp>  s,    LLLQ
1c0B0BL!LqLLLr<   z!Tokens must be non-empty strings.z!Topic must be a non-empty string.z/topics/)toregistration_tokens/r   )r   r   r   N)rX   r@   r   rY   
startswithr5   IID_URLr   r   IID_HEADERSr   r   r   _handle_iid_errorr%   )	rh   rZ   rb   	operationinvalid_strrL   r   r   rz   s	            r:   r`   z/_MessagingService.make_topic_management_request  sb   fc"" 	XF&$'' 	Xv 	XVWWWLL&LLL 	B@AAA%%% 	BU 	B@AAA
++ 	'&u&&E#)
 
 #*88Y88	0<$$)5	 %  DD "3 	0 	0 	0((///	0&t,,,s   3(C D
0DD
c                L    dt                               |          i}|rd|d<   |S )Nr=   Tvalidate_only)r5   r   )rh   r=   r>   rL   s       r:   r   z_MessagingService._message_data  s2    ,;;GDDE 	)$(D!r<   c                N    t          j        |                                          S )z'Handle response from batch API request.)r   loadsdecode)rh   _r   s      r:   	_postprocz_MessagingService._postproc  s     z$++--(((r<   c                @    t          j        |t          j                  S z)Handles errors received from the FCM API.)r   #handle_platform_error_from_requestsr5   _build_fcm_error_requestsrh   rz   s     r:   r   z#_MessagingService._handle_fcm_error  s#    9$>@ @ 	@r<   rz   httpx.HTTPErrorexceptions.FirebaseErrorc                @    t          j        |t          j                  S r  )r    handle_platform_error_from_httpxr5   _build_fcm_error_httpxr  s     r:   r   z)_MessagingService._handle_fcm_httpx_error  s     6$;= = 	=r<   c                   |j         t          j        |          i }	 |j                                         }t	          |t
                    r|}n# t          $ r Y nw xY w|                    d          }d}|rd| }n.d|j         j         d|j         j	        
                                 }t          j        ||          S )z1Handles errors received from the Instance ID API.Nrz   z%Error while calling the IID service: z&Unexpected HTTP response with status: z; body: )responser   handle_requests_errorr   rX   r|   rY   r   status_codecontentr  )rh   rz   rL   parsed_bodycodemsgs         r:   r   z#_MessagingService._handle_iid_error  s    >!.u555	.--//K+t,, #" 	 	 	D	 xx   	@$@@CC59S 5 5>)00225 5 
 +E3777s   0A 
AAc                \    t          j        | j                                                   d S r7   )r   runr   acloserm   s    r:   closez_MessagingService.close6  s'    D&--//00000r<   c                Z    |                      |          }|r ||||j                  ndS )zfParses an error response from the FCM API and creates a FCM-specific exception if
        appropriate.r   http_responseN)_build_fcm_errorr  r   rz   r=   
error_dictexc_types        r:   r  z+_MessagingService._build_fcm_error_requests9  s;     ''
33OWaxxuENKKKK]aar<   r%  Optional[Dict[str, Any]]"Optional[exceptions.FirebaseError]c                    |                      |          }t          |t          j                  r|r ||||j                  ndS |r |||          ndS )zkParses a httpx error response from the FCM API and creates a FCM-specific exception if
        appropriate.r!  N)r   )r#  rX   r   HTTPStatusErrorr  r$  s        r:   r  z(_MessagingService._build_fcm_error_httpxA  s     ''
33eU233 	Z HPZ88uEND D D DUYZ 2:Cxxu----tCr<   1Optional[Callable[..., exceptions.FirebaseError]]c                    |sdS d}|                     dg           D ]2}|                     d          dk    r|                     d          } n3|rt          j                             |          ndS )zNParses an error response to determine the appropriate FCM-specific error type.Ndetailsz@typez3type.googleapis.com/google.firebase.fcm.v1.FcmError	errorCode)r   r5   FCM_ERROR_TYPES)r   r%  fcm_codedetails       r:   r#  z"_MessagingService._build_fcm_errorR  s      	4 nnY33 	 	Fzz'""&[[[!::k22 \ CKT 044X>>>PTTr<   N)r2   r   r4   r   )F)r=   r   r>   r?   r4   r@   )rB   rC   r>   r?   r4   r   )T)rz   r  r4   r  )r4   r   )rz   r  r=   r@   r%  r'  r4   r(  )r%  r'  r4   r+  ) rp   rq   rr   rs   r   FCM_BATCH_URLr   r   r   MessageEncoderr   r$   r!   r"   r&   r/  rk   classmethodr   r+   r,   r-   r`   r   r	  r   r   r   r  r  r  r#  ru   r<   r:   r5   r5   x  s       UUHG6M*G&/K4%466L /,3"5) O: : : :$ 1 1 [1
' ' ' ' '    8    <- - -<  ) ) )
@ @ @
= = = =
8 8 841 1 1 1 b b [b D D D [D  U U U [U U Ur<   )r2   r3   r4   r5   )FN)r=   r   r>   r?   r2   r3   r4   r@   )rB   rC   r>   r?   r2   r3   r4   r   )rG   r   r>   r?   r2   r3   r4   r   r7   )@rs   
__future__r   typingr   r   r   r   r   r	   concurrent.futuresr   r   r   loggingr   r   r   r
   r   r   r   r   r   	getLoggerrp   loggerr9   __all__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,   r-   r/   r.   r0   r1   r   r%   r   r#   r5   ru   r<   r:   <module>r<     s   ' & " " " " " " < < < < < < < < < < < < < < < <                             
	8	$	$# # # #L !.$6 &: (
!0*$ .(
 .

$%6 , .$6 &: ,F %8 (> &: $6 P P P P> > > > >, !D D D D D4 !P P P P P4 !"P "P "P "P "PHD D D D>* * * *&- - - -(       $       @8 8 8 8 8 8 8 8*       0gU gU gU gU gU gU gU gU gU gUr<   