a
    |fG                     @   s  d Z ddlZddlmZ ddlmZ ddl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
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)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 )(z Firebase Cloud Messaging module.    N)http)_auth)_http_client)_messaging_encoder)_messaging_utils)_gapic_utils)_utilsZ
_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   Zget_app_service_MESSAGING_ATTRIBUTE_MessagingService)app r,   RD:\Projects\storyit_web\backend\venv\Lib\site-packages\firebase_admin/messaging.py_get_messaging_service_   s    r.   Fc                 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#   )messagedry_runr+   r,   r,   r-   r#   b   s    r#   c                 C   s   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.
    )r.   r$   )messagesr0   r+   r,   r,   r-   r$   v   s    r$   c                    s6   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.
    z@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   r2   r3   r4   r5   r6   r7   ).0r8   multicast_messager,   r-   
<listcomp>   s   z"send_multicast.<locals>.<listcomp>)
isinstancer   
ValueErrortokensr.   r$   )r;   r0   r+   r1   r,   r:   r-   r%      s    

	r%   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r?   topicr+   r,   r,   r-   r&      s    r&   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@   rB   r,   r,   r-   r'      s    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,   r-   __init__   s    zErrorInfo.__init__c                 C   s   | j S )zBIndex of the registration token to which this error is related to.)rD   rF   r,   r,   r-   rG      s    zErrorInfo.indexc                 C   s   | j S )z*String describing the nature of the error.)rE   rJ   r,   r,   r-   rH      s    zErrorInfo.reasonN)__name__
__module____qualname____doc__rI   propertyrG   rH   r,   r,   r,   r-   r      s   
r   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|vr td|d| _d| _g | _t|d D ]D\}}d|v rt|  jd7  _| jt	||d  q>|  jd7  _q>d S )Nresultsz*Unexpected topic management response: {0}.r   error   )
r=   dictr>   format_success_count_failure_count_errors	enumerateappendr   )rF   resprG   resultr,   r,   r-   rI      s    z TopicManagementResponse.__init__c                 C   s   | j S )zCNumber of tokens that were successfully subscribed or unsubscribed.rU   rJ   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.)rV   rJ   r,   r,   r-   failure_count   s    z%TopicManagementResponse.failure_countc                 C   s   | j S )z;A list of ``messaging.ErrorInfo`` objects (possibly empty).)rW   rJ   r,   r,   r-   errors   s    zTopicManagementResponse.errorsN)	rK   rL   rM   rN   rI   rO   r]   r^   r_   r,   r,   r,   r-   r      s   

r   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   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)r9   rZ   r,   r,   r-   r<         z*BatchResponse.__init__.<locals>.<listcomp>)
_responseslenrU   )rF   	responsesr,   r,   r-   rI     s    zBatchResponse.__init__c                 C   s   | j S )z>A list of ``messaging.SendResponse`` objects (possibly empty).)rb   rJ   r,   r,   r-   rd   	  s    zBatchResponse.responsesc                 C   s   | j S r(   r\   rJ   r,   r,   r-   r]     s    zBatchResponse.success_countc                 C   s   t | j| j S r(   )rc   rd   r]   rJ   r,   r,   r-   r^     s    zBatchResponse.failure_countN)	rK   rL   rM   rN   rI   rO   rd   r]   r^   r,   r,   r,   r-   r     s   

r   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)rF   rZ   	exceptionr,   r,   r-   rI     s    zSendResponse.__init__c                 C   s   | j S )z9A message ID string that uniquely identifies the message.)rg   rJ   r,   r,   r-   
message_id   s    zSendResponse.message_idc                 C   s   | j duo| j S )z3A boolean indicating if the request was successful.N)rg   rf   rJ   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.)rf   rJ   r,   r,   r-   ri   *  s    zSendResponse.exceptionN)	rK   rL   rM   rN   rI   rO   rj   r`   ri   r,   r,   r,   r-   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	 Ze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.comZaccess_token_authtrue)ZAPNS_AUTH_ERRORZQUOTA_EXCEEDEDZSENDER_ID_MISMATCHZTHIRD_PARTY_AUTH_ERRORZ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-CLIENTZhttpTimeout)
credentialtimeout)
project_idr>   r*   FCM_URLrT   _fcm_urlfirebase_admin__version___fcm_headersoptionsrh   r   ZDEFAULT_TIMEOUT_SECONDSrm   get_credential_credentialZJsonHttpClient_clientr   Zauthorized_http_build_transport)rF   r+   ro   rn   r,   r,   r-   rI   A  s    
z_MessagingService.__init__c                 C   s   t |tstd| j|S )Nz7Message must be an instance of messaging.Message class.)r=   r   r>   JSON_ENCODERdefault)clsr/   r,   r,   r-   encode_messageR  s    
z _MessagingService.encode_messageFc              
   C   sh   |  ||}z| jjd| j| j|d}W n2 tjjyZ } z| |W Y d}~nd}~0 0 |d S dS )z2Sends the given message to FCM via the FCM v1 API.post)urlheadersjsonNre   )	_message_datarx   bodyrq   rt   requests
exceptionsRequestException_handle_fcm_error)rF   r/   r0   r2   rZ   rQ   r,   r,   r-   r#   X  s    
 z_MessagingService.sendc           
   
      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y }	 z|	W Y d	}	~	nd	}	~	0 0 t S d	S )
z2Sends the given messages to FCM via the batch API.z7messages must be a list of messaging.Message instances.i  z1messages must not contain more than 500 elements.c                    s*   d }|r |}t||} | d S r(   )_handle_batch_errorr   rY   )_responserQ   ri   Zsend_responserd   rF   r,   r-   batch_callbackp  s
    

z2_MessagingService.send_all.<locals>.batch_callback)callbackZ	batch_uriPOST)r   Zpostprocurimethodr   r   N)r=   listr>   rc   r   ZBatchHttpRequestr*   FCM_BATCH_URLry   rw   r   dumpsr   ZHttpRequest	_postprocrq   rt   addexecute	Exceptionr   r   )
rF   r1   r0   r   batch	transportr/   r   reqrQ   r,   r   r-   r$   g  s4    
 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 n2 tjjy } z| |W Y d}~nd}~0 0 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,   )r=   str)r9   tr,   r,   r-   r<     ra   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)r=   r   r   r>   
startswithrT   r*   IID_URLrx   r   IID_HEADERSr   r   r   _handle_iid_errorr   )	rF   r?   rC   Z	operationZinvalid_strr2   r   rZ   rQ   r,   r,   r-   rA     s2    



 z/_MessagingService.make_topic_management_requestc                 C   s   dt |i}|rd|d< |S )Nr/   TZvalidate_only)r*   r}   )rF   r/   r0   r2   r,   r,   r-   r     s    z_MessagingService._message_datac                 C   s   t | S )z'Handle response from batch API request.)r   loadsdecode)rF   r   r   r,   r,   r-   r     s    z_MessagingService._postprocc                 C   s   t |tjS )z)Handles errors received from the FCM API.)r   Z#handle_platform_error_from_requestsr*   _build_fcm_error_requestsrF   rQ   r,   r,   r-   r     s    z#_MessagingService._handle_fcm_errorc                 C   s   |j du rt|i }z|j  }t|tr2|}W n tyF   Y n0 |d}d}|rfd|}nd|j j	|j j
 }t||S )z1Handles errors received from the Instance ID API.NrQ   z(Error while calling the IID service: {0}z4Unexpected HTTP response with status: {0}; body: {1})r   r   Zhandle_requests_errorr   r=   rS   r>   rh   rT   status_codecontentr   )rF   rQ   r2   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_googleapiclientr*    _build_fcm_error_googleapiclientr   r,   r,   r-   r     s    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.)causehttp_responseN)_build_fcm_errorr   )r|   rQ   r/   
error_dictexc_typer,   r,   r-   r     s    
z+_MessagingService._build_fcm_error_requestsc                 C   s    |  |}|r||||dS dS r   )r   )r|   rQ   r/   r   r   r   r,   r,   r-   r     s    
z2_MessagingService._build_fcm_error_googleapiclientc                 C   sF   |sd S d }| dg D ] }| ddkr| d} q:qtj |S )Ndetailsz@typez3type.googleapis.com/google.firebase.fcm.v1.FcmErrorZ	errorCode)rh   r*   FCM_ERROR_TYPES)r|   r   Zfcm_codedetailr,   r,   r-   r     s    
z"_MessagingService._build_fcm_errorN)F)F)rK   rL   rM   rN   rp   r   r   r   r   ZMessageEncoderrz   r   r   r   r   r   rI   classmethodr}   r#   r$   rA   r   r   r   r   r   r   r   r   r,   r,   r,   r-   r*   0  s:   


&

r*   )FN)FN)FN)N)N)/rN   r   Zgoogleapiclientr   r   r   rr   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   r.   r#   r$   r%   r&   r'   r   r   r   r   r*   r,   r,   r,   r-   <module>   sZ   $




 