
    .
0hV                        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 Z(d dZ)d dZ*d dZ+d dZ,d dZ-d!dZ.d!dZ/ G d d          Z0 G d d          Z1 G d d          Z2 G d d          Z3 G 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	send_eachsend_each_for_multicastsubscribe_to_topicunsubscribe_from_topicc                 B    t          j        | t          t                    S N)r	   get_app_service_MESSAGING_ATTRIBUTE_MessagingService)apps    S/var/www/html/nourish/venv/lib/python3.11/site-packages/firebase_admin/messaging.py_get_messaging_servicer4   d   s    !#';=NOOO    Fc                 H    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.
    )r4   r&   )messagedry_runr2   s      r3   r&   r&   g   s"    $ "#&&++GW===r5   c                 H    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.
    )r4   r)   messagesr8   r2   s      r3   r)   r)   {   s"    $ "#&&007CCCr5   c                      t           t                    st          d           f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                 x    g | ]6}t          j        j        j        j        j        j        |           7S )datanotificationandroidwebpushapnsfcm_optionstokenr   r@   rA   rB   rC   rD   rE   .0rF   multicast_messages     r3   
<listcomp>z+send_each_for_multicast.<locals>.<listcomp>   a     - - -  #&3!)!)#%1   - - -r5   )
isinstancer   
ValueErrortokensr4   r)   rJ   r8   r2   r;   s   `   r3   r*   r*      sv    $ ')9:: ][\\\- - - - %+- - -H "#&&007CCCr5   c                 |    t          j        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DeprecationWarningr4   r'   r:   s      r3   r'   r'      s6    ( MFHZ[[[!#&&//'BBBr5   c                      t          j        dt                     t           t                    st          d           f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.r=   c                 x    g | ]6}t          j        j        j        j        j        j        |           7S r?   rG   rH   s     r3   rK   z"send_multicast.<locals>.<listcomp>   rL   r5   )	rR   rS   rT   rM   r   rN   rO   r4   r'   rP   s   `   r3   r(   r(      s    ( MZ$& & &')9:: ][\\\- - - - %+- - -H "#&&//'BBBr5   c                 J    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r4   make_topic_management_requestrO   topicr2   s      r3   r+   r+      s,      "#&&DD(* * *r5   c                 J    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:batchRemoverX   rZ   s      r3   r,   r,      s,      "#&&DD+- - -r5   c                   D    e Zd ZdZd Zed             Zed             ZdS )r   zBAn error encountered when performing a topic management operation.c                 "    || _         || _        d S r.   )_index_reason)selfindexreasons      r3   __init__zErrorInfo.__init__  s    r5   c                     | j         S )zBIndex of the registration token to which this error is related to.)r_   ra   s    r3   rb   zErrorInfo.index  s     {r5   c                     | j         S )z*String describing the nature of the error.)r`   rf   s    r3   rc   zErrorInfo.reason       |r5   N)__name__
__module____qualname____doc__rd   propertyrb   rc    r5   r3   r   r     s_        LL     X   X  r5   r   c                   Z    e Zd ZdZd Zed             Zed             Zed             ZdS )r    z8The response received from a topic management operation.c                    t          |t                    rd|vr"t          d                    |                    d| _        d| _        g | _        t          |d                   D ]X\  }}d|v r?| xj        dz  c_        | j                            t          ||d                              H| xj        dz  c_        Yd S )Nresultsz*Unexpected topic management response: {0}.r   error   )
rM   dictrN   format_success_count_failure_count_errors	enumerateappendr   )ra   resprb   results       r3   rd   z TopicManagementResponse.__init__$  s    $%% 	X$)>)>IPPQUVVWWW&tI77 	) 	)ME6&  ##q(####IeVG_$E$EFFFF##q(###	) 	)r5   c                     | j         S )zCNumber of tokens that were successfully subscribed or unsubscribed.rv   rf   s    r3   success_countz%TopicManagementResponse.success_count1       ""r5   c                     | j         S )zLNumber of tokens that could not be subscribed or unsubscribed due to errors.)rw   rf   s    r3   failure_countz%TopicManagementResponse.failure_count6  r   r5   c                     | j         S )z;A list of ``messaging.ErrorInfo`` objects (possibly empty).)rx   rf   s    r3   errorszTopicManagementResponse.errors;  rh   r5   N)	ri   rj   rk   rl   rd   rm   r   r   r   rn   r5   r3   r    r    !  sz        BB) ) ) # # X# # # X#   X  r5   r    c                   Z    e Zd ZdZd Zed             Zed             Zed             ZdS )r   z:The response received from a batch request to the FCM API.c                 P    || _         t          d |D                       | _        d S )Nc                      g | ]}|j         	|S rn   )successrI   r{   s     r3   rK   z*BatchResponse.__init__.<locals>.<listcomp>F  s    "N"N"ND"N4"N"N"Nr5   )
_responseslenrv   )ra   	responsess     r3   rd   zBatchResponse.__init__D  s.    #!"N"NI"N"N"NOOr5   c                     | j         S )z>A list of ``messaging.SendResponse`` objects (possibly empty).)r   rf   s    r3   r   zBatchResponse.responsesH       r5   c                     | j         S r.   r~   rf   s    r3   r   zBatchResponse.success_countM  s    ""r5   c                 :    t          | j                  | j        z
  S r.   )r   r   r   rf   s    r3   r   zBatchResponse.failure_countQ  s    4>""T%777r5   N)	ri   rj   rk   rl   rd   rm   r   r   r   rn   r5   r3   r   r   A  s}        DDP P P   X # # X# 8 8 X8 8 8r5   r   c                   Z    e Zd ZdZd Zed             Zed             Zed             ZdS )r   zHThe response received from an individual batched request to the FCM API.c                 `    || _         d | _        |r|                    dd           | _        d S d S )Nname)
_exception_message_idget)ra   r{   	exceptions      r3   rd   zSendResponse.__init__Y  s?    # 	6#xx55D	6 	6r5   c                     | j         S )z9A message ID string that uniquely identifies the message.)r   rf   s    r3   
message_idzSendResponse.message_id_  s     r5   c                 $    | j         duo| j         S )z3A boolean indicating if the request was successful.N)r   r   rf   s    r3   r   zSendResponse.successd  s     t+CDO0CCr5   c                     | j         S )zTA ``FirebaseError`` if an error occurs while sending the message to the FCM service.)r   rf   s    r3   r   zSendResponse.exceptioni  r   r5   N)	ri   rj   rk   rl   rd   rm   r   r   r   rn   r5   r3   r   r   V  s}        RR6 6 6     X  D D XD   X  r5   r   c                       e Zd ZdZdZdZdZddiZ ej	                    Z
eeeeedZd Zed	             ZddZddZddZd Zd Zd Zd Zd Zd Zed             Zed             Zed             ZdS )r1   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                    |j         }|st          d          t          j                            |          | _        dd                    t          j                  d| _        |j	        
                    dt          j                  }|j                                        | _        t          j        | j        |          | _        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_idrN   r1   FCM_URLru   _fcm_urlfirebase_admin__version___fcm_headersoptionsr   r   DEFAULT_TIMEOUT_SECONDSr   get_credential_credentialJsonHttpClient_clientr   authorized_http_build_transport)ra   r2   r   r   s       r3   rd   z_MessagingService.__init__  s    ^
 	>=> > > *188DD),!8!?!?@Z![![
 
 +//-1UVV>88::#2d>NX_``` % 5r5   c                 ~    t          |t                    st          d          | j                            |          S )Nz7Message must be an instance of messaging.Message class.)rM   r   rN   JSON_ENCODERdefault)clsr7   s     r3   encode_messagez _MessagingService.encode_message  s;    '7++ 	XVWWW''000r5   Fc                     |                      ||          }	 | j                            d| j        | j        |          }|d         S # t
          j        j        $ r}|                     |          d}~ww xY w)z2Sends the given message to FCM via the FCM v1 API.posturlheadersjsonr   N)	_message_datar   bodyr   r   requestsr
   RequestException_handle_fcm_error)ra   r7   r8   r@   r{   rr   s         r3   r&   z_MessagingService.send  s    !!'733
	 <$$M)	 %  D < "3 	0 	0 	0((///	0s   (A A6A11A6c                     t          |t                    st          d          t          |          dk    rt          d           fd} fd|D             }	 t          j                            t          |                    5 }d |                    ||          D             }t          |          cddd           S # 1 swxY w Y   dS # t          $ r.}t          j        d	                    |          |
          d}~ww xY 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                    	 j                             dj        j        |           }t	          |d           S # t
          j        j        $ r.}t	          d                     |                    cY d }~S d }~ww xY w)Nr   r   )r   )r{   r   )	r   r   r   r   r   r   r
   r   r   )r@   r{   r   ra   s      r3   	send_dataz._MessagingService.send_each.<locals>.send_data  s    	:|(( -	 )   $DD9999 &7 \ \ \#9O9OPY9Z9Z[[[[[[[[[\s   (< A>#A93A>9A>c                 <    g | ]}                     |          S rn   )r   )rI   r7   r8   ra   s     r3   rK   z/_MessagingService.send_each.<locals>.<listcomp>  s)    UUU**7G<<UUUr5   )max_workersc                     g | ]}|S rn   rn   r   s     r3   rK   z/_MessagingService.send_each.<locals>.<listcomp>  s    TTTdTTTTr5   Nz4Unknown error while making remote service calls: {0})r7   cause)rM   listrN   r   
concurrentfuturesThreadPoolExecutormapr   	Exceptionr
   UnknownErrorru   )ra   r;   r8   r   message_dataexecutorr   rr   s   ` `     r3   r)   z_MessagingService.send_each  s   (D)) 	XVWWWx==3PQQQ
	: 
	: 
	: 
	: 
	: VUUUUHUUU	#663|CTCT6UU 0YaTThll9l.S.STTT	$Y//0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0  	 	 	)NUUV[\\   	s<   -C /C:C CC CC 
D)DDc           	         
 t          |t                    st          d          t          |          dk    rt          d          g 

 fd}t	          j        |t          j                  }                      j	                  }|D ]h}t          j                             ||                    }t	          j        | j         j        d| j                  }|                    |           i	 |                                 t'          
          S # t(          $ r}	                     |	          d}	~	ww xY w)	z2Sends the given messages to FCM via the batch API.r   r   r   c                     d }|r                     |          }t          ||          }                    |           d S r.   )_handle_batch_errorr   rz   )_responserr   r   send_responser   ra   s        r3   batch_callbackz2_MessagingService.send_all.<locals>.batch_callback  sL    I < 44U;;	(9==M]+++++r5   )callback	batch_uriPOST)r   postprocurimethodr   r   N)rM   r   rN   r   r   BatchHttpRequestr1   FCM_BATCH_URLr   r   r   dumpsr   HttpRequest	_postprocr   r   addexecuter   r   r   )ra   r;   r8   r   batch	transportr7   r   reqrr   r   s   `         @r3   r'   z_MessagingService.send_all  sl   (D)) 	XVWWWx==3PQQQ		, 	, 	, 	, 	, 	, %#/@/NP P P))$*:;;	 
	 
	G:d00'BBCCD"M)  C IIcNNNN	,MMOOO !+++  	2 	2 	2**5111	2s   7D 
D>$D99D>c                 t   t          |t                    r|g}t          |t                    r|st          d          d |D             }|rt          d          t          |t                    r|st          d          |                    d          sd                    |          }||d}d                    t          j        |          }	 | j        	                    d	||t          j
        
          }t          |          S # t          j        j        $ r}|                     |          d}~ww xY w)z;Invokes the IID service for topic management functionality.z7Tokens must be a string or a non-empty list of strings.c                 @    g | ]}t          |t                    r||S rn   )rM   str)rI   ts     r3   rK   zC_MessagingService.make_topic_management_request.<locals>.<listcomp>  s,    LLLQ
1c0B0BL!LqLLLr5   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)rM   r   r   rN   
startswithru   r1   IID_URLr   r   IID_HEADERSr    r   r
   r   _handle_iid_error)	ra   rO   r[   	operationinvalid_strr@   r   r{   rr   s	            r3   rY   z/_MessagingService.make_topic_management_request  sk   fc"" 	XF&$'' 	Xv 	XVWWWLL&LLL 	B@AAA%%% 	BU 	B@AAA
++ 	0!((//E#)
 
 08)DD
	1<$$)5	 %  D +4000 "3 	0 	0 	0((///	0s   (D	 	D7D22D7c                 L    dt                               |          i}|rd|d<   |S )Nr7   Tvalidate_only)r1   r   )ra   r7   r8   r@   s       r3   r   z_MessagingService._message_data  s2    ,;;GDDE 	)$(D!r5   c                 N    t          j        |                                          S )z'Handle response from batch API request.)r   loadsdecode)ra   r   r   s      r3   r   z_MessagingService._postproc  s     z$++--(((r5   c                 @    t          j        |t          j                  S )z)Handles errors received from the FCM API.)r	   #handle_platform_error_from_requestsr1   _build_fcm_error_requestsra   rr   s     r3   r   z#_MessagingService._handle_fcm_error  s#    9$>@ @ 	@r5   c                    |j         t          j        |          i }	 |j                                         }t	          |t
                    r|}n# t          $ r Y nw xY w|                    d          }d}|rd                    |          }n<d                    |j         j	        |j         j
                                                  }t          j        ||          S )z1Handles errors received from the Instance ID API.Nrr   z(Error while calling the IID service: {0}z4Unexpected HTTP response with status: {0}; body: {1})r   r	   handle_requests_errorr   rM   rt   rN   r   ru   status_codecontentr  )ra   rr   r@   parsed_bodycodemsgs         r3   r   z#_MessagingService._handle_iid_error  s    >!.u555	.--//K+t,, #" 	 	 	D	 xx   	M<CCDIICCHOO*EN,B,I,I,K,KM MC +E3777s   0A 
AAc                 @    t          j        |t          j                  S )zMHandles errors received from the googleapiclient while making batch requests.)r   *handle_platform_error_from_googleapiclientr1    _build_fcm_error_googleapiclientr  s     r3   r   z%_MessagingService._handle_batch_error0  s#    F$EG G 	Gr5   c                 Z    |                      |          }|r ||||j                  n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   rr   r7   
error_dictexc_types        r3   r  z+_MessagingService._build_fcm_error_requests5  s;     ''
33OWaxxuENKKKK]aar5   c                 P    |                      |          }|r ||||          ndS r  )r  )r   rr   r7   r  r  r  s         r3   r  z2_MessagingService._build_fcm_error_googleapiclient<  s9     ''
33NV`xxuMJJJJ\``r5   c                     |sd S d }|                     dg           D ]2}|                     d          dk    r|                     d          } n3t          j                             |          S )Ndetailsz@typez3type.googleapis.com/google.firebase.fcm.v1.FcmError	errorCode)r   r1   FCM_ERROR_TYPES)r   r  fcm_codedetails       r3   r  z"_MessagingService._build_fcm_errorC  s~     	4 nnY33 	 	Fzz'""&[[[!::k22 \ !044X>>>r5   N)F)ri   rj   rk   rl   r   r   r   r   r   MessageEncoderr   r   r   r   r!   r  rd   classmethodr   r&   r)   r'   rY   r   r   r   r   r   r  r  r  rn   r5   r3   r1   r1   o  s       UUHG6M*G&/K4%466L /,3"5) O6 6 6" 1 1 [1
          :$, $, $, $,L1 1 1>  ) ) )
@ @ @
8 8 80G G G
 b b [b a a [a ? ? [? ? ?r5   r1   )FNr.   )5rl   concurrent.futuresr   r   rR   r   googleapiclientr   r   r   r   r   r   r   r	   r
   r0   __all__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r"   r#   r$   r%   r   r   r   r!   r4   r&   r)   r*   r'   r(   r+   r,   r   r    r   r   r1   rn   r5   r3   <module>r"     s2   ' &                    ! ! ! ! ! !     ' ' ' ' ' ' - - - - - - + + + + + + ' ' ' ' ' ' ! ! ! ! ! ! % % % % % % $ # # #L !.$6 &: (
!0*$ .(
 .

$%6 , .$6 &: ,F %8 (> &: $6 P P P> > > >(D D D D(D D D D>C C C C.!C !C !C !CF* * * *&- - - -(       $       @8 8 8 8 8 8 8 8*       2]? ]? ]? ]? ]? ]? ]? ]? ]? ]?r5   