o
    }l~iV                     @   s  d Z ddlZddlZddlZddlZddlmZ ddlmZ ddl	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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j%Z%ej&Z&ej'Z'dd Z(d(ddZ)d(ddZ*d(ddZ+d(ddZ,d(ddZ-d)ddZ.d)ddZ/G dd dZ0G d d! d!Z1G d"d# d#Z2G d$d% d%Z3G d&d' d'Z4dS )*z Firebase Cloud Messaging module.    N)http)_auth)_http_client)_messaging_encoder)_messaging_utils)_gapic_utils)_utils)
exceptions
_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_allsend_multicastsubscribe_to_topicunsubscribe_from_topicc                 C   s   t | ttS N)r   get_app_service_MESSAGING_ATTRIBUTE_MessagingService)app r/   _/var/www/newdalilibackend/backend/venv/lib/python3.10/site-packages/firebase_admin/messaging.py_get_messaging_serviceb   s   r1   Fc                 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.
    )r1   r%   )messagedry_runr.   r/   r/   r0   r%   e      r%   c                 C   r2   )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.
    )r1   	send_eachmessagesr4   r.   r/   r/   r0   r6   y   r5   r6   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.
    @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   r<   r=   r>   r?   r@   rA   .0rB   multicast_messager/   r0   
<listcomp>       
z+send_each_for_multicast.<locals>.<listcomp>)
isinstancer   
ValueErrortokensr1   r6   rG   r4   r.   r8   r/   rF   r0   send_each_for_multicast   s   

	rN   c                 C   s   t dt t|| |S )a  Sends the given list of messages via Firebase Cloud Messaging as a single batch.

    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.

    send_all() is deprecated. Use send_each() instead.
    z2send_all() is deprecated. Use send_each() instead.)warningswarnDeprecationWarningr1   r&   r7   r/   r/   r0   r&      s   r&   c                    sB   t dt t tstd fdd jD }t|||S )a'  Sends the given mutlicast message to all tokens 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.

    send_multicast() is deprecated. Use send_each_for_multicast() instead.
    zFsend_multicast() is deprecated. Use send_each_for_multicast() instead.r9   c                    r:   r;   rC   rD   rF   r/   r0   rH      rI   z"send_multicast.<locals>.<listcomp>)	rO   rP   rQ   rJ   r   rK   rL   r1   r&   rM   r/   rF   r0   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r1   make_topic_management_requestrL   topicr.   r/   r/   r0   r(         r(   c                 C   rR   )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:batchRemoverS   rU   r/   r/   r0   r)      rW   r)   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 r*   )_index_reason)selfindexreasonr/   r/   r0   __init__  s   
zErrorInfo.__init__c                 C      | j S )zBIndex of the registration token to which this error is related to.)rX   rZ   r/   r/   r0   r[        zErrorInfo.indexc                 C   r^   )z*String describing the nature of the error.)rY   r_   r/   r/   r0   r\     r`   zErrorInfo.reasonN)__name__
__module____qualname____doc__r]   propertyr[   r\   r/   r/   r/   r0   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| _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: {0}.r   error   )
rJ   dictrK   format_success_count_failure_count_errors	enumerateappendr   )rZ   respr[   resultr/   r/   r0   r]   "  s   z TopicManagementResponse.__init__c                 C   r^   )zCNumber of tokens that were successfully subscribed or unsubscribed.rl   r_   r/   r/   r0   success_count/  r`   z%TopicManagementResponse.success_countc                 C   r^   )zLNumber of tokens that could not be subscribed or unsubscribed due to errors.)rm   r_   r/   r/   r0   failure_count4  r`   z%TopicManagementResponse.failure_countc                 C   r^   )z;A list of ``messaging.ErrorInfo`` objects (possibly empty).)rn   r_   r/   r/   r0   errors9  r`   zTopicManagementResponse.errorsN)	ra   rb   rc   rd   r]   re   rt   ru   rv   r/   r/   r/   r0   r     s    

r   c                   @   rf   )r   z:The response received from a batch request to the FCM API.c                 C   s   || _ tdd |D | _d S )Nc                 S   s   g | ]}|j r|qS r/   )successrE   rq   r/   r/   r0   rH   D  s    z*BatchResponse.__init__.<locals>.<listcomp>)
_responseslenrl   )rZ   	responsesr/   r/   r0   r]   B  s   zBatchResponse.__init__c                 C   r^   )z>A list of ``messaging.SendResponse`` objects (possibly empty).)ry   r_   r/   r/   r0   r{   F  r`   zBatchResponse.responsesc                 C   r^   r*   rs   r_   r/   r/   r0   rt   K  s   zBatchResponse.success_countc                 C   s   t | j| j S r*   )rz   r{   rt   r_   r/   r/   r0   ru   O  s   zBatchResponse.failure_countN)	ra   rb   rc   rd   r]   re   r{   rt   ru   r/   r/   r/   r0   r   ?  s    

r   c                   @   rf   )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)rZ   rq   	exceptionr/   r/   r0   r]   W  s
   zSendResponse.__init__c                 C   r^   )z9A message ID string that uniquely identifies the message.)r~   r_   r/   r/   r0   
message_id]  r`   zSendResponse.message_idc                 C   s   | j duo| j S )z3A boolean indicating if the request was successful.N)r~   r}   r_   r/   r/   r0   rw   b  s   zSendResponse.successc                 C   r^   )zTA ``FirebaseError`` if an error occurs while sending the message to the FCM service.)r}   r_   r/   r/   r0   r   g  r`   zSendResponse.exceptionN)	ra   rb   rc   rd   r]   re   r   rw   r   r/   r/   r/   r0   r   T  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	 Zed
d Zd&ddZd&ddZd&ddZdd Zdd Zdd Zdd Zdd Zdd Zedd  Zed!d" Zed#d$ Zd%S )'r-   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UNREGISTEREDc                 C   sn   |j }|s	tdtj|| _ddtjd| _|j	
dtj}|j | _tj| j|d| _t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/{0})zX-GOOG-API-FORMAT-VERSIONzX-FIREBASE-CLIENThttpTimeout)
credentialtimeout)
project_idrK   r-   FCM_URLrk   _fcm_urlfirebase_admin__version___fcm_headersoptionsr   r   DEFAULT_TIMEOUT_SECONDSr   get_credential_credentialJsonHttpClient_clientr   authorized_http_build_transport)rZ   r.   r   r   r/   r/   r0   r]   ~  s   
z_MessagingService.__init__c                 C   s   t |ts	td| j|S )Nz7Message must be an instance of messaging.Message class.)rJ   r   rK   JSON_ENCODERdefault)clsr3   r/   r/   r0   encode_message  s   
z _MessagingService.encode_messageFc              
   C   sV   |  ||}z| jjd| j| j|d}W |d S  tjjy* } z| |d}~ww )z2Sends the given message to FCM via the FCM v1 API.posturlheadersjsonNr|   )	_message_datar   bodyr   r   requestsr	   RequestException_handle_fcm_error)rZ   r3   r4   r<   rq   rh   r/   r/   r0   r%     s   	
z_MessagingService.sendc              
      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}d	d |||D }t|W  d
   W S 1 sHw   Y  W d
S  t	ye } z
t
jd||dd
}~ww )z3Sends 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   )rq   r   )r   )	r   r   r   r   r   r	   r   r   r   )r<   rq   r   r_   r/   r0   	send_data  s   
z._MessagingService.send_each.<locals>.send_datac                    s   g | ]} | qS r/   )r   )rE   r3   r4   rZ   r/   r0   rH     s    z/_MessagingService.send_each.<locals>.<listcomp>)max_workersc                 S   s   g | ]}|qS r/   r/   rx   r/   r/   r0   rH     s    Nz4Unknown error while making remote service calls: {0})r3   cause)rJ   listrK   rz   
concurrentfuturesThreadPoolExecutormapr   	Exceptionr	   UnknownErrorrk   )rZ   r8   r4   r   message_dataexecutorr{   rh   r/   r   r0   r6     s$   
(z_MessagingService.send_eachc           
   
      s   t |ts	tdt|dkrtdg   fdd}tj|tjd}j	}|D ]}t
||}tj|jjd|jd}|| q,z	|  W t S  tye }	 z|	d	}	~	ww )
z2Sends the given messages to FCM via the batch API.r   r   r   c                    s*   d }|r	 |}t||} | d S r*   )_handle_batch_errorr   rp   )_responserh   r   send_responser{   rZ   r/   r0   batch_callback  s
   

z2_MessagingService.send_all.<locals>.batch_callback)callback	batch_uriPOST)r   postprocurimethodr   r   N)rJ   r   rK   rz   r   BatchHttpRequestr-   FCM_BATCH_URLr   r   r   dumpsr   HttpRequest	_postprocr   r   addexecuter   r   r   )
rZ   r8   r4   r   batch	transportr3   r   reqrh   r/   r   r0   r&     s8   


z_MessagingService.send_allc           	   
   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}d	tj|}z| jj	d
||tj
d}W t|S  tjjyd } 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 r/   )rJ   str)rE   tr/   r/   r0   rH     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/z/topics/{0})toregistration_tokensz{0}/{1}r   )r   r   r   N)rJ   r   r   rK   
startswithrk   r-   IID_URLr   r   IID_HEADERSr   r	   r   _handle_iid_errorr   )	rZ   rL   rV   	operationinvalid_strr<   r   rq   rh   r/   r/   r0   rT     s6   


	
z/_MessagingService.make_topic_management_requestc                 C   s   dt |i}|rd|d< |S )Nr3   Tvalidate_only)r-   r   )rZ   r3   r4   r<   r/   r/   r0   r     s   z_MessagingService._message_datac                 C   s   t | S )z'Handle response from batch API request.)r   loadsdecode)rZ   r   r   r/   r/   r0   r     s   z_MessagingService._postprocc                 C      t |tjS )z)Handles errors received from the FCM API.)r   #handle_platform_error_from_requestsr-   _build_fcm_error_requestsrZ   rh   r/   r/   r0   r        z#_MessagingService._handle_fcm_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	|j j
 }t||S )z1Handles errors received from the Instance ID API.Nrh   z(Error while calling the IID service: {0}z4Unexpected HTTP response with status: {0}; body: {1})r   r   handle_requests_errorr   rJ   rj   rK   r   rk   status_codecontentr   )rZ   rh   r<   parsed_bodycodemsgr/   r/   r0   r     s&   




z#_MessagingService._handle_iid_errorc                 C   r   )zMHandles errors received from the googleapiclient while making batch requests.)r   *handle_platform_error_from_googleapiclientr-    _build_fcm_error_googleapiclientr   r/   r/   r0   r   .  r   z%_MessagingService._handle_batch_errorc                 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   rh   r3   
error_dictexc_typer/   r/   r0   r   3  s   
z+_MessagingService._build_fcm_error_requestsc                 C   s    |  |}|r||||dS dS r   )r   )r   rh   r3   r   r   r   r/   r/   r0   r   :  s   
z2_MessagingService._build_fcm_error_googleapiclientc                 C   sF   |sd S d }| dg D ]}| ddkr| d} nqtj |S )Ndetailsz@typez3type.googleapis.com/google.firebase.fcm.v1.FcmError	errorCode)r   r-   FCM_ERROR_TYPES)r   r   fcm_codedetailr/   r/   r0   r   A  s   
z"_MessagingService._build_fcm_errorN)F)ra   rb   rc   rd   r   r   r   r   r   MessageEncoderr   r   r   r   r    r   r]   classmethodr   r%   r6   r&   rT   r   r   r   r   r   r   r   r   r/   r/   r/   r0   r-   m  s>    



&

r-   )FNr*   )5rd   concurrent.futuresr   r   rO   r   googleapiclientr   r   r   r   r   r   r   r   r	   r,   __all__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r!   r"   r#   r$   r   r   r   r    r1   r%   r6   rN   r&   r'   r(   r)   r   r   r   r   r-   r/   r/   r/   r0   <module>   sf   $





#
 