
    ѮhZ                       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j0                  e      ZdZg dZej:                  Zej<                  Zej>                  Zej@                  Z ejB                  Z!ejD                  Z"ejF                  Z#ejH                  Z$ejJ                  Z%ejL                  Z&ejN                  Z'ejP                  Z(ejR                  Z)ejT                  Z*ejV                  Z+ejX                  Z,ejZ                  Z-ej\                  Z.ej^                  Z/ej`                  Z0ejb                  Z1ejd                  Z2dd	Z3ddd
Z4	 	 d	 	 	 	 	 	 	 ddZ5	 	 d	 	 	 	 	 	 	 ddZ6	 	 d	 	 	 	 	 	 	 ddZ7ddZ8ddZ9ddZ: G d d      Z; G d d      Z< G d d      Z= G d d      Z> G d d      Z?y) z Firebase Cloud Messaging module.    )annotations)AnyCallableDictListOptionalcastN)_http_client_messaging_encoder_messaging_utils_utils
exceptionsApp
_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_MessagingServicec                @    t        j                  | t        t              S N)r   get_app_service_MESSAGING_ATTRIBUTEr2   )apps    j/home/www/academy-backend.kofcorporation.com/venv/lib/python3.12/site-packages/firebase_admin/messaging.py_get_messaging_servicer9   h   s    !!#';=NOO    c                8    t        |      j                  | |      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.
    )r9   r+   )messagedry_runr7   s      r8   r+   r+   k   s    $ "#&++GW==r:   r   c                8    t        |      j                  | |      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.
    )r9   r,   messagesr=   r7   s      r8   r,   r,      s    , "#&007CCr:   c                T   K   t        |      j                  | |       d{   S 7 w)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)r9   r-   r?   s      r8   r-   r-      s&     , (,<<XwOOOOs   (&(c                ^  K   t        | t              st        d      | j                  D cg c]P  }t	        | j
                  | j                  | j                  | j                  | j                  | j                  |      R }}t        |      j                  ||       d{   S c c}w 7 	w)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.datanotificationandroidwebpushapnsfcm_optionstokenN)
isinstancer   
ValueErrortokensr   rE   rF   rG   rH   rI   rJ   r9   r-   multicast_messager=   r7   rK   r@   s        r8   r/   r/      s     . ')9:[\\ %++-  ##&33!))!))##%11 -H - (,<<XwOOO- Ps   *B-AB& B-!B+"
B-c                B   t        | t              st        d      | j                  D cg c]P  }t	        | j
                  | j                  | j                  | j                  | j                  | j                  |      R }}t        |      j                  ||      S c c}w )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.
    rC   rD   )rL   r   rM   rN   r   rE   rF   rG   rH   rI   rJ   r9   r,   rO   s        r8   r.   r.      s    $ ')9:[\\ %++-  ##&33!))!))##%11 -H - "#&007CC-s   ABc                :    t        |      j                  | |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r9   make_topic_management_requestrN   topicr7   s      r8   r0   r0      s$      "#&DD(* *r:   c                :    t        |      j                  | |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:batchRemoverS   rU   s      r8   r1   r1     s$      "#&DD+- -r:   c                  6    e Zd ZdZd Zed        Zed        Zy)r   zBAn error encountered when performing a topic management operation.c                     || _         || _        y r4   )_index_reason)selfindexreasons      r8   __init__zErrorInfo.__init__  s    r:   c                    | j                   S )zBIndex of the registration token to which this error is related to.)rZ   r\   s    r8   r]   zErrorInfo.index   s     {{r:   c                    | j                   S )z*String describing the nature of the error.)r[   ra   s    r8   r^   zErrorInfo.reason%       ||r:   N)__name__
__module____qualname____doc__r_   propertyr]   r^    r:   r8   r   r     s2    L    r:   r   c                  F    e Zd ZdZd Zed        Zed        Zed        Zy)r%   z8The response received from a topic management operation.c                N   t        |t              rd|vrt        d| d      d| _        d| _        g | _        t        |d         D ]\  \  }}d|v r>| xj                  dz  c_        | j
                  j                  t        ||d                H| xj                  dz  c_        ^ y )Nresultsz&Unexpected topic management response: .r   error   )	rL   dictrM   _success_count_failure_count_errors	enumerateappendr   )r\   respr]   results       r8   r_   z TopicManagementResponse.__init__.  s    $%$)>EdV1MNN&tI7 	)ME6& ##q(###IeVG_$EF##q(#	)r:   c                    | j                   S )zCNumber of tokens that were successfully subscribed or unsubscribed.rq   ra   s    r8   success_countz%TopicManagementResponse.success_count;       """r:   c                    | j                   S )zLNumber of tokens that could not be subscribed or unsubscribed due to errors.)rr   ra   s    r8   failure_countz%TopicManagementResponse.failure_count@  r{   r:   c                    | j                   S )z;A list of ``messaging.ErrorInfo`` objects (possibly empty).)rs   ra   s    r8   errorszTopicManagementResponse.errorsE  rc   r:   N)	rd   re   rf   rg   r_   rh   rz   r}   r   ri   r:   r8   r%   r%   +  sF    B) # # # #  r:   r%   c                  N    e Zd ZdZddZedd       Zed	d       Zed	d       Zy)
r   z:The response received from a batch request to the FCM API.c                @    || _         t        d |D              | _        y )Nc              3  :   K   | ]  }|j                   sd   yw)ro   N)success).0rv   s     r8   	<genexpr>z)BatchResponse.__init__.<locals>.<genexpr>P  s     !JT\\!!Js   )
_responsessumrq   )r\   	responsess     r8   r_   zBatchResponse.__init__N  s    #!!J	!JJr:   c                    | j                   S )z>A list of ``messaging.SendResponse`` objects (possibly empty).)r   ra   s    r8   r   zBatchResponse.responsesR       r:   c                    | j                   S r4   ry   ra   s    r8   rz   zBatchResponse.success_countW  s    """r:   c                F    t        | j                        | j                  z
  S r4   )lenr   rz   ra   s    r8   r}   zBatchResponse.failure_count[  s    4>>"T%7%777r:   N)r   List[SendResponse]returnNone)r   r   )r   int)	rd   re   rf   rg   r_   rh   r   rz   r}   ri   r:   r8   r   r   K  sG    DK   # # 8 8r:   c                  F    e Zd ZdZd Zed        Zed        Zed        Zy)r#   zHThe response received from an individual batched request to the FCM API.c                T    || _         d | _        |r|j                  dd       | _        y y )Nname)
_exception_message_idget)r\   rv   	exceptions      r8   r_   zSendResponse.__init__c  s,    ##xx5D r:   c                    | j                   S )z9A message ID string that uniquely identifies the message.)r   ra   s    r8   
message_idzSendResponse.message_idi  s     r:   c                <    | j                   duxr | j                   S )z3A boolean indicating if the request was successful.N)r   r   ra   s    r8   r   zSendResponse.successn  s!     t+CDOO0CCr:   c                    | j                   S )zTA ``FirebaseError`` if an error occurs while sending the message to the FCM service.)r   ra   s    r8   r   zSendResponse.exceptions  r   r:   N)	rd   re   rf   rg   r_   rh   r   r   r   ri   r:   r8   r#   r#   `  sH    R6     D D  r:   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dZed	        Zddd
ZdddZdddZd Zd Zd Zd ZddZd ZddZed        Ze	 	 	 	 	 	 	 	 dd       Ze	 	 	 	 d d       Zy)!r2   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                  j	                  |      | _        ddt        j                   d| _        |j                  j                  dt        j                        }|j                  j                         | _        t        j                   | j                  |      | _        t        j$                  | j                  |      | _        y )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/)zX-GOOG-API-FORMAT-VERSIONzX-FIREBASE-CLIENThttpTimeout)
credentialtimeout)
project_idrM   r2   FCM_URLformat_fcm_urlfirebase_admin__version___fcm_headersoptionsr   r
   DEFAULT_TIMEOUT_SECONDSr   get_credential_credentialJsonHttpClient_clientHttpxAsyncClient_async_client)r\   r7   r   r   s       r8   r_   z_MessagingService.__init__  s    ^^
=> > *1188D),#5n6P6P5Q!R
 ++//-1U1UV>>88:#22d>N>NX_`)::'':r:   c                n    t        |t              st        d      | j                  j	                  |      S )Nz7Message must be an instance of messaging.Message class.)rL   r   rM   JSON_ENCODERdefault)clsr<   s     r8   encode_messagez _MessagingService.encode_message  s/    '7+VWW''00r:   c                    | j                  ||      }	 | j                  j                  d| j                  | j                  |      }t        t        |d         S # t
        j                  j                  $ r}| j                  |      d}~ww xY w)z2Sends the given message to FCM via the FCM v1 API.posturlheadersjsonNr   )_message_datar   bodyr   r   requestsr   RequestException_handle_fcm_errorr	   str)r\   r<   r=   rE   rv   rn   s         r8   r+   z_MessagingService.send  s    !!'73	0<<$$MM))	 % D Cf&& ""33 	0((//	0s   3A B7BBc                    t        |t              st        d      t        |      dkD  rt        d       fd}|D cg c]  } j	                  ||       }}	 t
        j                  j                  t        |            5 }t        |j                  ||            }t        |      cddd       S c c}w # 1 sw Y   yxY w# t        $ r}t        j                  d| |      d}~ww xY 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                   	 j                   j                  dj                  j                  |       }t        |d       S # t        j
                  j                  $ r&}t        d j                  |            cY d }~S d }~ww xY wNr   r   )rv   r   )r   )	r   r   r   r   r   r   r   r#   r   rE   rv   r   r\   s      r8   	send_dataz._MessagingService.send_each.<locals>.send_data  s    \||(( --	 )   55 &&77 \#9O9OPY9Z[[\s   3A B B;BB)max_workersN1Unknown error while making remote service calls: r<   cause)rL   listrM   r   r   
concurrentfuturesThreadPoolExecutormapr   	Exceptionr   UnknownError)	r\   r@   r=   r   r<   message_dataexecutorr   rn   s	   `        r8   r,   z_MessagingService.send_each  s    (D)VWWx=3PQQ		6 MUU**7G<UU	##663|CT6U 0Ya i!FG	$Y/0 0 V0 0  	))KE7S 	s;   B4)C &B9*	C 9C>C C 	C-C((C-c                   K   t        |t              st        d      t        |      dkD  rt        d       fd}|D cg c]  } j	                  ||       }}	 t        j                  |D cg c]
  } ||       c}  d{   }t        |      S c c}w c c}w 7 # t        $ r}t        j                  d| |      d}~ww xY ww)r   r   r   r   c                  K   	 j                   j                  dj                  j                  |        d {   }t        |j                         d       S 7 # t        j
                  $ r&}t        d j                  |            cY d }~S d }~wt        j                  j                  $ r&}t        d j                  |            cY d }~S d }~ww xY wwr   )r   requestr   r   httpx	HTTPErrorr#   _handle_fcm_httpx_errorr   r   r   r   r   r   s      r8   r   z4_MessagingService.send_each_async.<locals>.send_data  s     
\!//77 --	 8    		t<<
 ?? b#9U9UV_9`aa&&77 \#9O9OPY9Z[[\s\   C6A AA  CA C0BCC C1CCCCCNr   r   )rL   r   rM   r   r   asynciogatherr   r   r   r   )r\   r@   r=   r   r<   r   r   rn   s   `       r8   r-   z!_MessagingService.send_each_async  s     (D)VWWx=3PQQ	= MUU**7G<UU	%nnQ].^gy/A.^__I ++ V.^_ 	))KE7S 	sS   >CBCB" 0B?B" B B" CB" "	C
+CC

Cc                B   t        |t              r|g}t        |t              r|st        d      |D cg c]  }t        |t              r|r| }}|rt        d      t        |t              r|st        d      |j	                  d      sd| }||d}t
        j                   d| }	 | j                  j                  d||t
        j                        }t        |      S c c}w # t        j                  j                  $ r}	| j                  |	      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.z!Tokens must be non-empty strings.z!Topic must be a non-empty string.z/topics/)toregistration_tokens/r   )r   r   r   N)rL   r   r   rM   
startswithr2   IID_URLr   r   IID_HEADERSr   r   r   _handle_iid_errorr%   )
r\   rN   rV   	operationtinvalid_strrE   r   rv   rn   s
             r8   rT   z/_MessagingService.make_topic_management_request  s"   fc"XF&$'vVWW"(LQ
1c0B!qLL@AA%%U@AA
+ug&E#)
 #**+1YK8	0<<$$)55	 % D 't,,- M( ""33 	0((//	0s#   C&C&.-C+ +DDDc                B    dt         j                  |      i}|rd|d<   |S )Nr<   Tvalidate_only)r2   r   )r\   r<   r=   rE   s       r8   r   z_MessagingService._message_data  s*    ,;;GDE$(D!r:   c                H    t        j                  |j                               S )z'Handle response from batch API request.)r   loadsdecode)r\   _r   s      r8   	_postprocz_MessagingService._postproc  s     zz$++-((r:   c                J    t        j                  |t        j                        S z)Handles errors received from the FCM API.)r   #handle_platform_error_from_requestsr2   _build_fcm_error_requestsr\   rn   s     r8   r   z#_MessagingService._handle_fcm_error  s#    99$>>@ 	@r:   c                J    t        j                  |t        j                        S r   )r    handle_platform_error_from_httpxr2   _build_fcm_error_httpxr   s     r8   r   z)_MessagingService._handle_fcm_httpx_error  s!    66$;;= 	=r:   c                   |j                   t        j                  |      i }	 |j                   j                         }t	        |t
              r|}|j                  d      }d}|rd| }n>d|j                   j                   d|j                   j                  j                          }t        j                  ||      S # t        $ r Y zw xY w)z1Handles errors received from the Instance ID API.Nrn   z%Error while calling the IID service: z&Unexpected HTTP response with status: z; body: )responser   handle_requests_errorr   rL   rp   rM   r   status_codecontentr   )r\   rn   rE   parsed_bodycodemsgs         r8   r   z#_MessagingService._handle_iid_error  s    >>!..u55	..--/K+t,"
 xx 9$@C 99S9S8TT\>>))00235 
 ++E377  		s   ,C   	CCc                ^    t        j                  | j                  j                                y r4   )r   runr   aclosera   s    r8   closez_MessagingService.close6  s    D&&--/0r:   c                V    | j                  |      }|r ||||j                        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   rn   r<   
error_dictexc_types        r8   r   z+_MessagingService._build_fcm_error_requests9  s/     ''
3OWxuENNKa]aar:   c                    | j                  |      }t        |t        j                        r|r ||||j                        S dS |r
 |||      S dS )zkParses a httpx error response from the FCM API and creates a FCM-specific exception if
        appropriate.r  N)r   )r  rL   r   HTTPStatusErrorr  r  s        r8   r  z(_MessagingService._build_fcm_error_httpxA  sf     ''
3eU223 HP uENND ZUYZ 2:xu-CtCr:   c                    |syd}|j                  dg       D ])  }|j                  d      dk(  s|j                  d      } n |rt        j                  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.FcmError	errorCode)r   r2   FCM_ERROR_TYPES)r   r  fcm_codedetails       r8   r  z"_MessagingService._build_fcm_errorR  sp      nnY3 	Fzz'"&[[!::k2	 CK 0044X>TPTTr:   N)r7   r   r   r   )F)r<   r   r=   boolr   r   )r@   List[Message]r=   r  r   r   )T)rn   httpx.HTTPErrorr   zexceptions.FirebaseError)r   r   )rn   r  r<   r   r  Optional[Dict[str, Any]]r   z"Optional[exceptions.FirebaseError])r  r   r   z1Optional[Callable[..., exceptions.FirebaseError]]) rd   re   rf   rg   r   FCM_BATCH_URLr   r   r   MessageEncoderr   r$   r!   r"   r&   r  r_   classmethodr   r+   r,   r-   rT   r   r   r   r   r   r  r   r  r  ri   r:   r8   r2   r2   x  s   UHG6M*G&/K4%446L /,3"5)O:$ 1 1
'8<-<)
@
=
841 b b D"D D 1	D
 0D D  U0U ?U Ur:   )r7   Optional[App]r   r2   )FN)r<   r   r=   r  r7   r$  r   r   )r@   r  r=   r  r7   r$  r   r   )rP   r   r=   r  r7   r$  r   r   r4   )@rg   
__future__r   typingr   r   r   r   r   r	   concurrent.futuresr   r   r   loggingr   r   r   r
   r   r   r   r   r   	getLoggerrd   loggerr6   __all__r   r   r   r   r   r   r   r   r   r   r   r   r   r    r'   r(   r)   r*   r!   r"   r$   r&   r9   r+   r,   r-   r/   r.   r0   r1   r   r%   r   r#   r2   ri   r:   r8   <module>r,     sG   ' " < <         
		8	$# #L !..$66 &:: ((
!00**$$ ..((
 ..

$
$%66 ,, ..$66 &:: ,FF %88 (>> &:: $66 P>, !DDD D 
	D4 !PPP P 
	P4 !"P+"P"P "P 
	"PHD>*&-( $ @8 8* 0gU gUr:   