o
    0=jãZ  ã                   @  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Ú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_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   Zget_app_serviceÚ_MESSAGING_ATTRIBUTEr3   )r0   © r6   úbC:\Users\psant\Downloads\Anu Raj Backend\school\venv\Lib\site-packages\firebase_admin/messaging.pyÚ_get_messaging_serviceh   s   r8   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.
    N)r8   r)   )r9   r:   r0   r6   r6   r7   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.
    N)r8   r*   ©r>   r:   r0   r6   r6   r7   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)r8   r+   r@   r6   r6   r7   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   rE   rF   rG   rH   rI   rJ   ©Ú.0rK   ©rA   r6   r7   Ú
<listcomp>È   ó    ø
ùz1send_each_for_multicast_async.<locals>.<listcomp>N)Ú
isinstancer   Ú
ValueErrorÚtokensr8   r+   ©rA   r:   r0   r>   r6   rO   r7   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.
    rB   c                   rC   rD   rL   rM   rO   r6   r7   rP   ç   rQ   z+send_each_for_multicast.<locals>.<listcomp>N)rR   r   rS   rT   r8   r*   rU   r6   rO   r7   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:batchAddN©r8   Úmake_topic_management_request©rT   Útopicr0   r6   r6   r7   r.   ò   ó   ÿr.   c                 C  rV   )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:batchRemoveNrW   rY   r6   r6   r7   r/     r[   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 r4   )Ú_indexÚ_reason)ÚselfÚindexÚreasonr6   r6   r7   Ú__init__  s   
zErrorInfo.__init__c                 C  ó   | j S )zBIndex of the registration token to which this error is related to.N)r\   ©r^   r6   r6   r7   r_      ó   zErrorInfo.indexc                 C  rb   )z*String describing the nature of the error.N)r]   rc   r6   r6   r7   r`   %  rd   zErrorInfo.reasonN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ra   Úpropertyr_   r`   r6   r6   r6   r7   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é   )	rR   ÚdictrS   Ú_success_countÚ_failure_countÚ_errorsÚ	enumerateÚappendr   )r^   Úrespr_   Úresultr6   r6   r7   ra   .  s   ûz TopicManagementResponse.__init__c                 C  rb   )zCNumber of tokens that were successfully subscribed or unsubscribed.N©rp   rc   r6   r6   r7   Úsuccess_count;  rd   z%TopicManagementResponse.success_countc                 C  rb   )zLNumber of tokens that could not be subscribed or unsubscribed due to errors.N)rq   rc   r6   r6   r7   Úfailure_count@  rd   z%TopicManagementResponse.failure_countc                 C  rb   )z;A list of ``messaging.ErrorInfo`` objects (possibly empty).N)rr   rc   r6   r6   r7   ÚerrorsE  rd   zTopicManagementResponse.errorsN)	re   rf   rg   rh   ra   ri   rx   ry   rz   r6   r6   r6   r7   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]r2   ÚNonec                 C  s   || _ tdd„ |D ƒƒ| _d S )Nc                 s  s   � | ]}|j rd V  qdS )rn   N)Úsuccess)rN   ru   r6   r6   r7   Ú	<genexpr>P  s   € z)BatchResponse.__init__.<locals>.<genexpr>)Ú
_responsesÚsumrp   )r^   r{   r6   r6   r7   ra   N  s   zBatchResponse.__init__c                 C  rb   )z>A list of ``messaging.SendResponse`` objects (possibly empty).N)r€   rc   r6   r6   r7   r{   R  rd   zBatchResponse.responsesÚintc                 C  rb   r4   rw   rc   r6   r6   r7   rx   W  s   zBatchResponse.success_countc                 C  s   t | jƒ| j S r4   )Úlenr{   rx   rc   r6   r6   r7   ry   [  s   zBatchResponse.failure_countN)r{   r|   r2   r}   )r2   r|   )r2   r‚   )	re   rf   rg   rh   ra   ri   r{   rx   ry   r6   r6   r6   r7   r   K  s    
c                   @  rj   )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^   ru   Ú	exceptionr6   r6   r7   ra   c  s
   ÿzSendResponse.__init__c                 C  rb   )z9A message ID string that uniquely identifies the message.N)r†   rc   r6   r6   r7   Ú
message_idi  rd   zSendResponse.message_idc                 C  s   | j duo| j S )z3A boolean indicating if the request was successful.N)r†   r…   rc   r6   r6   r7   r~   n  s   zSendResponse.successc                 C  rb   )zTA ``FirebaseError`` if an error occurs while sending the message to the FCM service.N)r…   rc   r6   r6   r7   rˆ   s  rd   zSendResponse.exceptionN)	re   rf   rg   rh   ra   ri   r‰   r~   rˆ   r6   r6   r6   r7   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 )Er3   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UNREGISTEREDr0   r   r2   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 )NzÀProject 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-CLIENTZhttpTimeout)Ú
credentialÚtimeout)Ú
project_idrS   r3   ÚFCM_URLÚformatÚ_fcm_urlÚfirebase_adminÚ__version__Ú_fcm_headersÚoptionsr‡   r	   ZDEFAULT_TIMEOUT_SECONDSrŒ   Úget_credentialZ_credentialZJsonHttpClientÚ_clientZHttpxAsyncClientÚ_async_client)r^   r0   rŽ   r�   r6   r6   r7   ra   ‰  s   ÿ
þÿz_MessagingService.__init__c                 C  s   t |tƒs	tdƒ‚| j |¡S )Nz7Message must be an instance of messaging.Message class.)rR   r   rS   ÚJSON_ENCODERÚdefault)Úclsr9   r6   r6   r7   Úencode_message›  s   
z _MessagingService.encode_messageFr9   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^   r9   r:   rE   ru   rm   r6   r6   r7   r)   ¡  s   
ü
€ÿz_MessagingService.sendr>   r?   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ž   )ru   rˆ   )rˆ   )	r—   r£   r‘   r”   r¤   r   r¥   r!   r¦   ©rE   ru   rˆ   rc   r6   r7   Ú	send_data¶  s   
ü€ÿz._MessagingService.send_each.<locals>.send_datac                   ó   g | ]}ˆ  |ˆ ¡‘qS r6   ©r¢   ©rN   r9   ©r:   r^   r6   r7   rP   Á  ó    z/_MessagingService.send_each.<locals>.<listcomp>)Úmax_workersNú1Unknown error while making remote service calls: ©r9   Úcause)rR   ÚlistrS   rƒ   Ú
concurrentÚfuturesÚThreadPoolExecutorÚmapr   Ú	Exceptionr   ÚUnknownError)r^   r>   r:   r­   Úmessage_dataÚexecutorr{   rm   r6   r±   r7   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¬   rc   r6   r7   r­   Ò  s    €ü€€ÿz4_MessagingService.send_each_async.<locals>.send_datac                   r®   r6   r¯   r°   r±   r6   r7   rP   à  r²   z5_MessagingService.send_each_async.<locals>.<listcomp>c                   s   g | ]}ˆ |ƒ‘qS r6   r6   r°   )r­   r6   r7   rP   â  s    Nr´   rµ   )
rR   r·   rS   rƒ   ÚasyncioÚgatherr   r¼   r   r½   )r^   r>   r:   r¾   r{   rm   r6   )r:   r^   r­   r7   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 r6   )rR   r<   )rN   Útr6   r6   r7   rP   ï  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/)ÚtoZregistration_tokensú/r�   )rŸ   r¡   r    N)rR   r<   r·   rS   Ú
startswithr3   ÚIID_URLr—   r£   ÚIID_HEADERSr¤   r   r¥   Ú_handle_iid_errorr#   )	r^   rT   rZ   Z	operationZinvalid_strrE   rŸ   ru   rm   r6   r6   r7   rX   é  s6   


þüþ
€ÿz/_MessagingService.make_topic_management_requestc                 C  s   dt  |¡i}|rd|d< |S )Nr9   TZvalidate_only)r3   rœ   )r^   r9   r:   rE   r6   r6   r7   r¢     s   z_MessagingService._message_datac                 C  s   t  | ¡ ¡S )z'Handle response from batch API request.N)r¡   ÚloadsÚdecode)r^   Ú_r£   r6   r6   r7   Ú	_postproc  s   z_MessagingService._postprocc                 C  ó   t  |tj¡S ©z)Handles errors received from the FCM API.N)r   Z#handle_platform_error_from_requestsr3   Ú_build_fcm_error_requests©r^   rm   r6   r6   r7   r¦     ó   ÿz#_MessagingService._handle_fcm_errorrm   úhttpx.HTTPErrorúexceptions.FirebaseErrorc                 C  rÑ   rÒ   )r   Z handle_platform_error_from_httpxr3   Ú_build_fcm_error_httpxrÔ   r6   r6   r7   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.Nrm   z%Error while calling the IID service: z&Unexpected HTTP response with status: z; body: )Úresponser   Zhandle_requests_errorr¡   rR   ro   rS   r‡   Ústatus_codeÚcontentrÎ   )r^   rm   rE   Zparsed_bodyÚcodeÚmsgr6   r6   r7   rÌ     s(   



€ÿ

ÿÿz#_MessagingService._handle_iid_errorc                 C  s   t  | j ¡ ¡ d S r4   )rÄ   Úrunr˜   Úacloserc   r6   r6   r7   Ú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›   rm   r9   Ú
error_dictÚexc_typer6   r6   r7   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ã   rR   rÁ   ZHTTPStatusErrorrÙ   rä   r6   r6   r7   rØ   A  s   
	ÿÿÿz(_MessagingService._build_fcm_error_httpxú1Optional[Callable[..., exceptions.FirebaseError]]c                 C  sN   |sdS d}|  dg ¡D ]}|  d¡dkr|  d¡} q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.FcmErrorZ	errorCode)r‡   r3   ÚFCM_ERROR_TYPES)r›   rå   Zfcm_codeZdetailr6   r6   r7   rã   R  s   
þz"_MessagingService._build_fcm_errorN)r0   r   r2   r}   )F)r9   r   r:   r;   r2   r<   )r>   r?   r:   r;   r2   r   )T)rm   rÖ   r2   r×   )r2   r}   )rm   rÖ   r9   r<   rå   rç   r2   rè   )rå   rç   r2   ré   ) re   rf   rg   rh   r�   ZFCM_BATCH_URLrÊ   rË   r
   ZMessageEncoderr™   r"   r   r    r$   rë   ra   Úclassmethodrœ   r)   r*   r+   rX   r¢   rÐ   r¦   rÃ   rÌ   rà   rÓ   rØ   rã   r6   r6   r6   r7   r3   x  s@    û




)r0   r1   r2   r3   )FN)r9   r   r:   r;   r0   r1   r2   r<   )r>   r?   r:   r;   r0   r1   r2   r   )rA   r   r:   r;   r0   r1   r2   r   r4   )@rh   Ú
__future__r   Útypingr   r   r   r   r   r   Úconcurrent.futuresr¸   r¡   rÄ   Úloggingr¤   rÁ   r’   r	   r
   r   r   r   r   Ú	getLoggerre   Úloggerr5   Ú__all__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r%   r&   r'   r(   r   r    r"   r$   r8   r)   r*   r+   r-   r,   r.   r/   r   r#   r   r!   r3   r6   r6   r6   r7   Ú<module>   sn     
	&
ýýý
$

 