o
     iZ                     @  s  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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j0Z0ej1Z1ej2Z2d/ddZ3d0d1ddZ4		d0d2ddZ5		d0d2ddZ6		d0d3dd Z7d0d!d"Z8d4d#d$Z9d4d%d&Z:G d'd( d(Z;G d)d* d*Z<G d+d dZ=G d,d- d-Z>G d.d dZ?dS )5z 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                 C  s   t | ttS N)r   get_app_service_MESSAGING_ATTRIBUTEr4   )r1    r8   x/var/www/snowflake_co_dev_github/snow_flake_back_end_deploy/env/lib/python3.10/site-packages/firebase_admin/messaging.py_get_messaging_serviceh   s   r:   Fmessager   dry_runboolstrc                 C     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<   r1   r8   r8   r9   r*   k   s   r*   messagesList[Message]r   c                 C  r?   )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+   r@   r<   r1   r8   r8   r9   r+      s   r+   c                   s   t || |I dH 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,   rB   r8   r8   r9   r,      s   r,   multicast_messager   c                   s>   t  ts
td fdd jD }t|||I dH 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                   .   g | ]}t  j j j j j j|d qS )datanotificationandroidwebpushapnsfcm_optionstokenr   rG   rH   rI   rJ   rK   rL   .0rM   rC   r8   r9   
<listcomp>       
z1send_each_for_multicast_async.<locals>.<listcomp>N)
isinstancer   
ValueErrortokensr:   r,   rC   r<   r1   r@   r8   rQ   r9   r.      s   

	r.   c                   s6   t  ts	td fd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.
    rD   c                   rE   rF   rN   rO   rQ   r8   r9   rR      rS   z+send_each_for_multicast.<locals>.<listcomp>)rT   r   rU   rV   r:   r+   rW   r8   rQ   r9   r-      s   

	r-   c                 C     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rV   topicr1   r8   r8   r9   r/         r/   c                 C  rX   )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:batchRemoverY   r[   r8   r8   r9   r0     r]   r0   c                   @  s0   e Zd ZdZdd Zedd Zedd ZdS )	r   zBAn error encountered when performing a topic management operation.c                 C  s   || _ || _d S r5   )_index_reason)selfindexreasonr8   r8   r9   __init__  s   
zErrorInfo.__init__c                 C     | j S )zBIndex of the registration token to which this error is related to.)r^   r`   r8   r8   r9   ra         zErrorInfo.indexc                 C  rd   )z*String describing the nature of the error.)r_   re   r8   r8   r9   rb   %  rf   zErrorInfo.reasonN)__name__
__module____qualname____doc__rc   propertyra   rb   r8   r8   r8   r9   r     s    
r   c                   @  <   e Zd ZdZdd Zedd Zedd Zedd	 Zd
S )r$   z8The response received from a topic management operation.c                 C  s   t |tr	d|vrtd| dd| _d| _g | _t|d D ]"\}}d|v r;|  jd7  _| jt||d  q |  jd7  _q d S )Nresultsz&Unexpected topic management response: .r   error   )	rT   dictrU   _success_count_failure_count_errors	enumerateappendr   )r`   respra   resultr8   r8   r9   rc   .  s   z TopicManagementResponse.__init__c                 C  rd   )zCNumber of tokens that were successfully subscribed or unsubscribed.rr   re   r8   r8   r9   success_count;  rf   z%TopicManagementResponse.success_countc                 C  rd   )zLNumber of tokens that could not be subscribed or unsubscribed due to errors.)rs   re   r8   r8   r9   failure_count@  rf   z%TopicManagementResponse.failure_countc                 C  rd   )z;A list of ``messaging.ErrorInfo`` objects (possibly empty).)rt   re   r8   r8   r9   errorsE  rf   zTopicManagementResponse.errorsN)	rg   rh   ri   rj   rc   rk   rz   r{   r|   r8   r8   r8   r9   r$   +  s    

r$   c                   @  sD   e Zd ZdZdddZeddd	ZedddZedddZdS )r   z:The response received from a batch request to the FCM API.	responsesList[SendResponse]r3   Nonec                 C  s   || _ tdd |D | _d S )Nc                 s  s    | ]}|j rd V  qdS )rp   N)success)rP   rw   r8   r8   r9   	<genexpr>P  s    z)BatchResponse.__init__.<locals>.<genexpr>)
_responsessumrr   )r`   r}   r8   r8   r9   rc   N  s   zBatchResponse.__init__c                 C  rd   )z>A list of ``messaging.SendResponse`` objects (possibly empty).)r   re   r8   r8   r9   r}   R  rf   zBatchResponse.responsesintc                 C  rd   r5   ry   re   r8   r8   r9   rz   W  s   zBatchResponse.success_countc                 C  s   t | j| j S r5   )lenr}   rz   re   r8   r8   r9   r{   [  s   zBatchResponse.failure_countN)r}   r~   r3   r   )r3   r~   )r3   r   )	rg   rh   ri   rj   rc   rk   r}   rz   r{   r8   r8   r8   r9   r   K  s    
c                   @  rl   )r"   zHThe response received from an individual batched request to the FCM API.c                 C  s&   || _ d | _|r|dd | _d S d S )Nname)
_exception_message_idget)r`   rw   	exceptionr8   r8   r9   rc   c  s
   zSendResponse.__init__c                 C  rd   )z9A message ID string that uniquely identifies the message.)r   re   r8   r8   r9   
message_idi  rf   zSendResponse.message_idc                 C  s   | j duo| j S )z3A boolean indicating if the request was successful.N)r   r   re   r8   r8   r9   r   n  s   zSendResponse.successc                 C  rd   )zTA ``FirebaseError`` if an error occurs while sending the message to the FCM service.)r   re   r8   r8   r9   r   s  rf   zSendResponse.exceptionN)	rg   rh   ri   rj   rc   rk   r   r   r   r8   r8   r8   r9   r"   `  s    

r"   c                   @  s   e Zd ZdZdZdZdZddiZe	 Z
eeeeedZd<ddZedd Zd=d>ddZd=d?ddZd@d?ddZd d! Zd"d# Zd$d% Zd&d' ZdAd+d,Zd-d. ZdBd/d0Zed1d2 ZedCd6d7ZedDd9d:Zd;S )Er4   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UNREGISTEREDr1   r   r3   r   c                 C  sx   |j }|s	tdtj|| _ddtj d| _|j	
dtj}|j | _tj| j|d| _tj| j|d| _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_idrU   r4   FCM_URLformat_fcm_urlfirebase_admin__version___fcm_headersoptionsr   r	   DEFAULT_TIMEOUT_SECONDSr   get_credential_credentialJsonHttpClient_clientHttpxAsyncClient_async_client)r`   r1   r   r   r8   r8   r9   rc     s   
z_MessagingService.__init__c                 C  s   t |ts	td| j|S )Nz7Message must be an instance of messaging.Message class.)rT   r   rU   JSON_ENCODERdefault)clsr;   r8   r8   r9   encode_message  s   
z _MessagingService.encode_messageFr;   r   r<   r=   r>   c              
   C  s^   |  ||}z| jjd| j| j|d}W n tjjy' } z| |d}~w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>   )r`   r;   r<   rG   rw   ro   r8   r8   r9   r*     s   

z_MessagingService.sendr@   rA   r   c              
     s   t |ts	tdt|dkrtdfdd} fdd|D }z)tjjt|d}t|||}t|W  d	   W S 1 sEw   Y  W d	S  t	yb } z
t
jd
| |dd	}~w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              
     sd   z j jd j j| d}W n tjjy+ } ztd  |dW  Y d }~S d }~ww t|d dS Nr   r   )rw   r   )r   )	r   r   r   r   r   r   r   r"   r   rG   rw   r   re   r8   r9   	send_data  s   
z._MessagingService.send_each.<locals>.send_datac                      g | ]} | qS r8   r   rP   r;   r<   r`   r8   r9   rR         z/_MessagingService.send_each.<locals>.<listcomp>)max_workersN1Unknown error while making remote service calls: r;   cause)rT   listrU   r   
concurrentfuturesThreadPoolExecutormapr   	Exceptionr   UnknownError)r`   r@   r<   r   message_dataexecutorr}   ro   r8   r   r9   r+     s$   
(z_MessagingService.send_eachTc              
     s   t |ts
tdt|dkrtdfdd fdd|D }ztjfdd|D  I d	H }t|W S  tyN } z
tj	d
| |dd	}~ww )r   r   r   r   c              
     s   z j jd j j| dI d H }W n8 tjy. } ztd  |dW  Y d }~S d }~w tj	j
yJ } ztd  |dW  Y d }~S d }~ww t| d dS r   )r   requestr   r   httpx	HTTPErrorr"   _handle_fcm_httpx_errorr   r   r   r   r   r   re   r8   r9   r     s    z4_MessagingService.send_each_async.<locals>.send_datac                   r   r8   r   r   r   r8   r9   rR     r   z5_MessagingService.send_each_async.<locals>.<listcomp>c                   s   g | ]} |qS r8   r8   r   )r   r8   r9   rR     s    Nr   r   )
rT   r   rU   r   asynciogatherr   r   r   r   )r`   r@   r<   r   r}   ro   r8   )r<   r`   r   r9   r,     s"   

z!_MessagingService.send_each_asyncc           	   
   C  s   t |tr|g}t |tr|stddd |D }|r tdt |tr'|s+td|ds5d| }||d}tj d| }z| jjd	||tj	d
}W t|S  t
jjye } z| |d}~ww )z;Invokes the IID service for topic management functionality.z7Tokens must be a string or a non-empty list of strings.c                 S  s   g | ]}t |tr|s|qS r8   )rT   r>   )rP   tr8   r8   r9   rR     s    zC_MessagingService.make_topic_management_request.<locals>.<listcomp>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)rT   r>   r   rU   
startswithr4   IID_URLr   r   IID_HEADERSr   r   r   _handle_iid_errorr$   )	r`   rV   r\   	operationinvalid_strrG   r   rw   ro   r8   r8   r9   rZ     s6   



z/_MessagingService.make_topic_management_requestc                 C  s   dt |i}|rd|d< |S )Nr;   Tvalidate_only)r4   r   )r`   r;   r<   rG   r8   r8   r9   r     s   z_MessagingService._message_datac                 C  s   t | S )z'Handle response from batch API request.)r   loadsdecode)r`   _r   r8   r8   r9   	_postproc  s   z_MessagingService._postprocc                 C     t |tjS z)Handles errors received from the FCM API.)r   #handle_platform_error_from_requestsr4   _build_fcm_error_requestsr`   ro   r8   r8   r9   r        z#_MessagingService._handle_fcm_errorro   httpx.HTTPErrorexceptions.FirebaseErrorc                 C  r   r   )r    handle_platform_error_from_httpxr4   _build_fcm_error_httpxr   r8   r8   r9   r     r   z)_MessagingService._handle_fcm_httpx_errorc                 C  s   |j du r
t|i }z|j  }t|tr|}W n	 ty#   Y nw |d}d}|r3d| }nd|j j d|j j	
  }t||S )z1Handles errors received from the Instance ID API.Nro   z%Error while calling the IID service: z&Unexpected HTTP response with status: z; body: )responser   handle_requests_errorr   rT   rq   rU   r   status_codecontentr   )r`   ro   rG   parsed_bodycodemsgr8   r8   r9   r     s(   





z#_MessagingService._handle_iid_errorc                 C  s   t | j  d S r5   )r   runr   aclosere   r8   r8   r9   close6  s   z_MessagingService.closec                 C  s"   |  |}|r||||jdS 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   ro   r;   
error_dictexc_typer8   r8   r9   r   9  s   
z+_MessagingService._build_fcm_error_requestsr   Optional[Dict[str, Any]]"Optional[exceptions.FirebaseError]c                 C  sB   |  |}t|tjr|r||||jdS dS |r|||dS dS )zkParses a httpx error response from the FCM API and creates a FCM-specific exception if
        appropriate.r   N)r   )r   rT   r   HTTPStatusErrorr   r   r8   r8   r9   r   A  s   
	z(_MessagingService._build_fcm_error_httpx1Optional[Callable[..., exceptions.FirebaseError]]c                 C  sN   |sdS d}| dg D ]}| ddkr| d} nq|r%tj |S 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   r4   FCM_ERROR_TYPES)r   r   fcm_codedetailr8   r8   r9   r   R  s   
z"_MessagingService._build_fcm_errorN)r1   r   r3   r   )F)r;   r   r<   r=   r3   r>   )r@   rA   r<   r=   r3   r   )T)ro   r   r3   r   )r3   r   )ro   r   r;   r>   r   r   r3   r   )r   r   r3   r   ) rg   rh   ri   rj   r   FCM_BATCH_URLr   r   r
   MessageEncoderr   r#   r    r!   r%   r  rc   classmethodr   r*   r+   r,   rZ   r   r   r   r   r   r   r   r   r   r8   r8   r8   r9   r4   x  s@    




)r1   r2   r3   r4   )FN)r;   r   r<   r=   r1   r2   r3   r>   )r@   rA   r<   r=   r1   r2   r3   r   )rC   r   r<   r=   r1   r2   r3   r   r5   )@rj   
__future__r   typingr   r   r   r   r   r   concurrent.futuresr   r   r   loggingr   r   r   r	   r
   r   r   r   r   	getLoggerrg   loggerr7   __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-   r/   r0   r   r$   r   r"   r4   r8   r8   r8   r9   <module>   sn     
	&

$

 