U
    %FZhm                  #   @  sl  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 ddlmZ ddlZddlmZmZmZmZmZmZmZ eeZdZ d	d
dddddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+g#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j2Z2ej3Z3ej4Z4ej5Z5ej6Z6ej7Z7d,d-d.d/d0Z8dFdd2d,d3d4d5d#Z9dGd6d2d,dd7d8d&Z:dHd6d2d,dd7d9d'Z;dIdd2d,dd:d;d)Z<dJd<d(Z=dKd=d$Z>dLd>d%Z?dMd?d*Z@dNd@d+ZAG dAd dZBG dBd dZCG dCd dZDG dDd dZEG dEd- d-ZFdS )Oz Firebase Cloud Messaging module.    )annotations)AnyCallableDictListOptionalcastN)http)_auth)_http_client_messaging_encoder_messaging_utils_gapic_utils_utils
exceptionsAppZ
_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	send_eachsend_each_asyncsend_each_for_multicastsend_each_for_multicast_asyncsubscribe_to_topicunsubscribe_from_topiczOptional[App]_MessagingServiceappreturnc                 C  s   t | ttS N)r   Zget_app_service_MESSAGING_ATTRIBUTEr5   )r7    r;   _/home/aprabhat/apps/x.techxrdev.in/venv/lib/python3.8/site-packages/firebase_admin/messaging.py_get_messaging_serviceo   s    r=   Fboolstr)messagedry_runr7   r8   c                 C  s   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@   rA   r7   r;   r;   r<   r,   r   s    List[Message])messagesrA   r7   r8   c                 C  s   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/   rC   rA   r7   r;   r;   r<   r/      s    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=   r0   rD   r;   r;   r<   r0      s    )multicast_messagerA   r7   r8   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                   s.   g | ]&}t  j j j j j j|d qS )datanotificationandroidwebpushapnsfcm_optionstokenr   rH   rI   rJ   rK   rL   rM   .0rN   rE   r;   r<   
<listcomp>   s   z1send_each_for_multicast_async.<locals>.<listcomp>N)
isinstancer    
ValueErrortokensr=   r0   rE   rA   r7   rC   r;   rR   r<   r2      s    

	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.
    rF   c                   s.   g | ]&}t  j j j j j j|d qS rG   rO   rP   rR   r;   r<   rS      s   z+send_each_for_multicast.<locals>.<listcomp>)rT   r    rU   rV   r=   r/   rW   r;   rR   r<   r1      s    

	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DeprecationWarningr=   r-   rD   r;   r;   r<   r-      s    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.rF   c                   s.   g | ]&}t  j j j j j j|d qS rG   rO   rP   rR   r;   r<   rS   (  s   z"send_multicast.<locals>.<listcomp>)	rX   rY   rZ   rT   r    rU   rV   r=   r-   rW   r;   rR   r<   r.     s    

	c                 C  s   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   topicr7   r;   r;   r<   r3   3  s
      c                 C  s   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[   r]   r;   r;   r<   r4   F  s
      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 r9   )_index_reason)selfindexreasonr;   r;   r<   __init__]  s    zErrorInfo.__init__c                 C  s   | j S )zBIndex of the registration token to which this error is related to.)r_   ra   r;   r;   r<   rb   a  s    zErrorInfo.indexc                 C  s   | j S )z*String describing the nature of the error.)r`   re   r;   r;   r<   rc   f  s    zErrorInfo.reasonN)__name__
__module____qualname____doc__rd   propertyrb   rc   r;   r;   r;   r<   r   Z  s   
c                   @  s<   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|kr td|d| _d| _g | _t|d D ]D\}}d|krt|  jd7  _| jt	||d  q>|  jd7  _q>d S )Nresultsz*Unexpected topic management response: {0}.r   error   )
rT   dictrU   format_success_count_failure_count_errors	enumerateappendr   )ra   resprb   resultr;   r;   r<   rd   o  s    z TopicManagementResponse.__init__c                 C  s   | j S )zCNumber of tokens that were successfully subscribed or unsubscribed.rp   re   r;   r;   r<   success_count|  s    z%TopicManagementResponse.success_countc                 C  s   | j S )zLNumber of tokens that could not be subscribed or unsubscribed due to errors.)rq   re   r;   r;   r<   failure_count  s    z%TopicManagementResponse.failure_countc                 C  s   | j S )z;A list of ``messaging.ErrorInfo`` objects (possibly empty).)rr   re   r;   r;   r<   errors  s    zTopicManagementResponse.errorsN)	rf   rg   rh   ri   rd   rj   rx   ry   rz   r;   r;   r;   r<   r&   l  s   

c                   @  sV   e Zd ZdZdddddZedddd	Zed
dddZed
dddZdS )r   z:The response received from a batch request to the FCM API.zList[SendResponse]None)	responsesr8   c                 C  s   || _ tdd |D | _d S )Nc                 s  s   | ]}|j rd V  qdS )rm   N)successrQ   ru   r;   r;   r<   	<genexpr>  s      z)BatchResponse.__init__.<locals>.<genexpr>)
_responsessumrp   )ra   r|   r;   r;   r<   rd     s    zBatchResponse.__init__r8   c                 C  s   | j S )z>A list of ``messaging.SendResponse`` objects (possibly empty).)r   re   r;   r;   r<   r|     s    zBatchResponse.responsesintc                 C  s   | j S r9   rw   re   r;   r;   r<   rx     s    zBatchResponse.success_countc                 C  s   t | j| j S r9   )lenr|   rx   re   r;   r;   r<   ry     s    zBatchResponse.failure_countN)	rf   rg   rh   ri   rd   rj   r|   rx   ry   r;   r;   r;   r<   r     s   c                   @  s<   e Zd ZdZdd Zedd Zedd Zedd	 Zd
S )r$   zHThe response received from an individual batched request to the FCM API.c                 C  s"   || _ d | _|r|dd | _d S )Nname)
_exception_message_idget)ra   ru   	exceptionr;   r;   r<   rd     s    zSendResponse.__init__c                 C  s   | j S )z9A message ID string that uniquely identifies the message.)r   re   r;   r;   r<   
message_id  s    zSendResponse.message_idc                 C  s   | j dk	o| j S )z3A boolean indicating if the request was successful.N)r   r   re   r;   r;   r<   r}     s    zSendResponse.successc                 C  s   | j S )zTA ``FirebaseError`` if an error occurs while sending the message to the FCM service.)r   re   r;   r;   r<   r     s    zSendResponse.exceptionN)	rf   rg   rh   ri   rd   rj   r   r}   r   r;   r;   r;   r<   r$     s   

c                   @  s0  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
ddZedd ZdBddddddZdCddddddZdDddddddZdEddZd d! Zd"d# Zd$d% Zd&d' Zd(d)d*d+d,Zd-d. Zd/d0 Zd	d1d2d3Zed4d5 Zed(dd6d7d8d9d:Z ed;d< Z!ed6d=d>d?d@Z"dAS )Fr5   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.comZaccess_token_authtrue)ZAPNS_AUTH_ERRORZQUOTA_EXCEEDEDZSENDER_ID_MISMATCHZTHIRD_PARTY_AUTH_ERRORZUNREGISTEREDr   r{   r6   c                 C  s   |j }|stdtj|| _ddtjd| _|j	
dtj}|j | _tj| j|d| _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-CLIENTZhttpTimeout)
credentialtimeout)
project_idrU   r5   FCM_URLro   _fcm_urlfirebase_admin__version___fcm_headersoptionsr   r   ZDEFAULT_TIMEOUT_SECONDSr   get_credential_credentialZJsonHttpClient_clientZHttpxAsyncClient_async_clientr
   Zauthorized_http_build_transport)ra   r7   r   r   r;   r;   r<   rd     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@   r;   r;   r<   encode_message  s    
z _MessagingService.encode_messageFr   r>   r?   )r@   rA   r8   c              
   C  sl   |  ||}z| jjd| j| j|d}W n0 tjjk
rX } z| |W 5 d}~X Y nX t	t
|d S 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?   )ra   r@   rA   rH   ru   rl   r;   r;   r<   r,     s    
z_MessagingService.sendrB   r   )rC   rA   r8   c              
     s   t |tstdt|dkr&tdfdd} fdd|D }zJtjjt|d.}d	d |||D }t|W  5 Q R  W S Q R X W n6 t	k
r } zt
jd
||dW 5 d}~X Y nX dS )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              
     sj   z j jd j j| d}W n< tjjk
rX } ztd  |d W Y S d }~X Y nX t|d dS d S Nr   r   )ru   r   )r   )	r   r   r   r   r   r   r   r$   r   rH   ru   r   re   r;   r<   	send_data  s    
(z._MessagingService.send_each.<locals>.send_datac                   s   g | ]} | qS r;   r   rQ   r@   rA   ra   r;   r<   rS     s     z/_MessagingService.send_each.<locals>.<listcomp>)max_workersc                 S  s   g | ]}|qS r;   r;   r~   r;   r;   r<   rS     s     4Unknown error while making remote service calls: {0}r@   causeN)rT   listrU   r   
concurrentZfuturesZThreadPoolExecutormapr   	Exceptionr   UnknownErrorro   )ra   rC   rA   r   message_dataexecutorr|   rl   r;   r   r<   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k
r } ztj	d

||dW 5 d	}~X Y nX d	S )r   r   r   r   c              
     s   z" j jd j j| dI d H }W nt tjk
r\ } ztd  |d W Y S d }~X Y nL tj	j
k
r } ztd  |d W Y S d }~X Y nX t| d dS d S r   )r   requestr   r   httpx	HTTPErrorr$   _handle_fcm_httpx_errorr   r   r   r   r   r   re   r;   r<   r     s    &(z4_MessagingService.send_each_async.<locals>.send_datac                   s   g | ]} | qS r;   r   r   r   r;   r<   rS   %  s     z5_MessagingService.send_each_async.<locals>.<listcomp>c                   s   g | ]} |qS r;   r;   r   )r   r;   r<   rS   '  s     Nr   r   )rT   r   rU   r   asyncioZgatherr   r   r   r   ro   )ra   rC   rA   r   r|   rl   r;   )rA   ra   r   r<   r0     s    

z!_MessagingService.send_each_asyncc           
   
     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}|| qXz|  W n, tk
r }	 z|	W 5 d	}	~	X Y n
X t S d	S )
z2Sends the given messages to FCM via the batch API.r   r   r   c                   s*   d }|r |}t||} | d S r9   )_handle_batch_errorr$   rt   )_responserl   r   Zsend_responser|   ra   r;   r<   batch_callback8  s
    

z2_MessagingService.send_all.<locals>.batch_callback)callbackZ	batch_uriPOST)r	   Zpostprocurimethodr   r   N)rT   r   rU   r   r	   ZBatchHttpRequestr5   FCM_BATCH_URLr   r   r   dumpsr   ZHttpRequest	_postprocr   r   addexecuter   r   r   )
ra   rC   rA   r   batch	transportr@   r   reqrl   r;   r   r<   r-   /  s6    
 z_MessagingService.send_allc           	   
   C  s   t |tr|g}t |tr|s&tddd |D }|r@tdt |trN|sVtd|dsjd|}||d}d	tj|}z| jj	d
||tj
d}W n0 tjjk
r } z| |W 5 d}~X Y n
X t|S dS )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;   )rT   r?   )rQ   tr;   r;   r<   rS   [  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})toZregistration_tokensz{0}/{1}r   )r   r   r   N)rT   r?   r   rU   
startswithro   r5   IID_URLr   r   IID_HEADERSr   r   r   _handle_iid_errorr&   )	ra   rV   r^   Z	operationZinvalid_strrH   r   ru   rl   r;   r;   r<   r\   U  s2    



z/_MessagingService.make_topic_management_requestc                 C  s   dt |i}|rd|d< |S )Nr@   TZvalidate_only)r5   r   )ra   r@   rA   rH   r;   r;   r<   r   t  s    z_MessagingService._message_datac                 C  s   t | S )z'Handle response from batch API request.)r   loadsdecode)ra   r   r   r;   r;   r<   r   z  s    z_MessagingService._postprocc                 C  s   t |tjS z)Handles errors received from the FCM API.)r   Z#handle_platform_error_from_requestsr5   _build_fcm_error_requestsra   rl   r;   r;   r<   r     s     z#_MessagingService._handle_fcm_errorzhttpx.HTTPErrorzexceptions.FirebaseError)rl   r8   c                 C  s   t |tjS r   )r   Z handle_platform_error_from_httpxr5   _build_fcm_error_httpxr   r;   r;   r<   r     s     z)_MessagingService._handle_fcm_httpx_errorc                 C  s   |j dkrt|i }z|j  }t|tr2|}W n tk
rH   Y nX |d}d}|rhd|}nd|j j	|j j
 }t||S )z1Handles errors received from the Instance ID API.Nrl   z(Error while calling the IID service: {0}z4Unexpected HTTP response with status: {0}; body: {1})r   r   Zhandle_requests_errorr   rT   rn   rU   r   ro   status_codecontentr   )ra   rl   rH   Zparsed_bodycodemsgr;   r;   r<   r     s$    




 
z#_MessagingService._handle_iid_errorc                 C  s   t |tjS )zMHandles errors received from the googleapiclient while making batch requests.)r   Z*handle_platform_error_from_googleapiclientr5    _build_fcm_error_googleapiclientr   r;   r;   r<   r     s     z%_MessagingService._handle_batch_errorr   c                 C  s   t | j  d S r9   )r   runr   aclosere   r;   r;   r<   close  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   rl   r@   
error_dictexc_typer;   r;   r<   r     s    
z+_MessagingService._build_fcm_error_requestszOptional[Dict[str, Any]]z"Optional[exceptions.FirebaseError])rl   r@   r   r8   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   ZHTTPStatusErrorr   r   r;   r;   r<   r     s    	
  z(_MessagingService._build_fcm_error_httpxc                 C  s    |  |}|r||||dS dS r   )r   )r   rl   r@   r   r   r   r;   r;   r<   r     s    
z2_MessagingService._build_fcm_error_googleapiclientz1Optional[Callable[..., exceptions.FirebaseError]])r   r8   c                 C  sN   |sdS d}| dg D ] }| ddkr| d} q:q|rJt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.FcmErrorZ	errorCode)r   r5   FCM_ERROR_TYPES)r   r   Zfcm_codedetailr;   r;   r<   r     s    
z"_MessagingService._build_fcm_errorN)F)F)T)F)#rf   rg   rh   ri   r   r   r   r   r   ZMessageEncoderr   r%   r"   r#   r'   r   rd   classmethodr   r,   r/   r0   r-   r\   r   r   r   r   r   r   r   r   r   r   r   r;   r;   r;   r<   r5     sF   
 
&

)FN)FN)FN)FN)FN)FN)FN)N)N)Gri   
__future__r   typingr   r   r   r   r   r   concurrent.futuresr   r   rX   r   loggingr   r   Zgoogleapiclientr	   r
   r   r   r   r   r   r   r   r   	getLoggerrf   loggerr:   __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/   r0   r2   r1   r-   r.   r3   r4   r   r&   r   r$   r5   r;   r;   r;   r<   <module>   s    $

(      $


#

 