
    dUh*                         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m	Z	 d dl
mZ d dlZd dlmZmZmZmZmZ  G d de      Zy)	    N)HTTPAdapter)Retry)service_account)Credentials)AuthenticationErrorInvalidDataErrorFCMSenderIdMismatchErrorFCMServerErrorFCMNotRegisteredErrorc                       e Zd ZdZ	 	 	 	 	 	 	 ddededefdZed        ZddZ	d	 Z
d
 Zd Zd Zd Z	 	 	 	 	 	 	 	 	 	 	 	 ddZy)BaseAPIz&https://fcm.googleapis.com/v1/projectsNservice_account_file
project_idcredentialsc                 D   |s|st        d      ||| _        n't        j                  j	                  |dg      | _        t        | j                  dd      xs |}|st        d      | j                  d| dz   | _        || _        t        j                         | _        |r=t        |t              r-d	|v sd
|v r%| j                  j                  j!                  |       |dk(  r	 ddlm} |j'                          || _        y|| _        y# t(        $ r
 Y || _        yw xY w)a  
        Override existing init function to give ability to use v1 endpoints of Firebase Cloud Messaging API
        Attributes:
            service_account_file (str): path to service account JSON file
            project_id (str): project ID of Google account
            credentials (Credentials): Google oauth2 credentials instance, such as ADC
            proxy_dict (dict): proxy settings dictionary, use proxy (keys: `http`, `https`)
            env (dict): environment settings dictionary, for example "app_engine"
            json_encoder (BaseJSONEncoder): JSON encoder
            adapter (BaseAdapter): adapter instance
        zLPlease provide a service account file path or credentials in the constructorNz2https://www.googleapis.com/auth/firebase.messaging)scopesr   zLPlease provide a project_id either explicitly or through Google credentials./z/messages:sendhttphttps
app_enginer   )	appengine)r   r   r   r   from_service_account_filegetattrFCM_END_POINT_BASEfcm_end_pointcustom_adapter	threadinglocalthread_local
isinstancedictrequests_sessionproxiesupdaterequests_toolbelt.adaptersr   monkeypatchModuleNotFoundErrorjson_encoder)	selfr   r   r   
proxy_dictenvr(   adapterr   s	            M/var/www/html/Ryun_Seer/newvenv/lib/python3.12/site-packages/pyfcm/baseapi.py__init__zBaseAPI.__init__   s5   * %%^  "*D.::TT$LM  U  D T--|TBPj
%^  "44:,n7UU%%OO- :t,J&Gz,A!!))00<,@%%' )L ' (s   &D 	DDc                    t        | j                  dd       t        dddgt        j                  t	        dg      z        }| j
                  xs t        |      }t        j                         | j                  _	        | j                  j                  j                  d|       | j                  j                  j                  d	|       d
| j                  _        t        j                         }| j                  j                  |k  rQ| j                  j                  j                  j                  | j                                |dz   | j                  _        | j                  j                  S )Nr"      i  i  POST)backoff_factorstatus_forcelistallowed_methods)max_retrieszhttp://zhttps://r   i  )r   r   r   DEFAULT_ALLOWED_METHODS	frozensetr   r   requestsSessionr"   mounttoken_expirytimeheadersr$   request_headers)r)   retriesr,   current_timestamps       r-   r"   zBaseAPI.requests_session^   s$   4$$&8$?G "%s!&!>!>F8AT!TG
 ))M[W-MG191A1A1CD...44YH..44ZI-.D* IIK)),==..66==d>R>R>TU->-ED*  111    c                 &   | j                   j                  | j                  ||      }d|j                  v rZt	        |j                  d         dkD  r?t	        |j                  d         }t        j                  |       | j                  ||      S |S )N)datatimeoutzRetry-Afterr   )r"   postr   r=   intr<   sleepsend_request)r)   payloadrD   response
sleep_times        r-   rH   zBaseAPI.send_requestr   s    ((--Wg . 
 X---H$$]34q8X--m<=JJJz"$$Wg66rA   c                     dd l }ddlm} |D cg c]  } | j                  di | }}|j	                         j                   || j                  | j                         ||            }|S c c}w )Nr   r0   )fetch_tasks)	end_pointr=   payloadsrD    )asyncio	async_fcmrM   parse_payloadnew_event_looprun_until_completer   r>   )r)   params_listrD   rQ   rM   paramsrO   	responsess           r-   send_async_requestzBaseAPI.send_async_request   sw    *?JK{V&D&&00{K**,??,,,,.!	
	  Ls   A-c                    	 t         j                  j                  j                  j	                         }| j
                  j                  |       | j
                  j                  S # t        $ r}t        |      d}~ww xY w)z
        Generates access token from credentials.
        If token expires then new access token is generated.
        Returns:
             str: Access token
        N)
googleauth	transportr8   Requestr   refreshtoken	Exceptionr   )r)   requestes      r-   _get_access_tokenzBaseAPI._get_access_token   sf    	&kk++44<<>G$$W-##))) 	&"1%%	&s   A"A% %	A>.A99A>c                 .    dd| j                         z   dS )z
        Generates request headers including Content-Type and Authorization of Bearer token

        Returns:
            dict: request headers
        zapplication/jsonzBearer )zContent-TypeAuthorization)rd   )r)   s    r-   r>   zBaseAPI.request_headers   s"     /&)?)?)AA
 	
rA   c                 h    t        j                  |dd| j                  d      j                  d      S )z
        Standardized json.dumps function with separators and sorted keys set

        Args:
            data (dict or list): data to be dumped

        Returns:
            string: json
        ),:TF)
separators	sort_keysclsensure_asciiutf8)jsondumpsr(   encode)r)   rC   s     r-   
json_dumpszBaseAPI.json_dumps   s5     zz!!!
 &.	rA   c                    |j                   dk(  rDd|j                  v r&t        |j                  d         dk  rt        d      |j	                         S |j                   dk(  rt        d      |j                   dk(  rt        |j                        |j                   dk(  rt        d	      |j                   d
k(  rt        d      t        d|j                    d      )a  
        Parses the json response sent back by the server and tries to get out the important return variables

        Returns:
            dict: name (str) - The identifier of the message sent, in the format of projects/*/messages/{message_id}

        Raises:
            FCMServerError: FCM is temporary not available
            AuthenticationError: error authenticating the sender account
            InvalidDataError: data passed to FCM was incorrecly structured
            FCMSenderIdMismatchError: the authenticated sender is different from the sender registered to the token
            FCMNotRegisteredError: device token is missing, not registered, or invalid
           zcontent-lengthr   z2FCM server connection error, the response is emptyi  z4There was an error authenticating the sender accounti  i  zWThe authenticated sender ID is different from the sender ID for the registration token.i  zToken not registeredz)FCM server error: Unexpected status code z.. The server might be temporarily unavailable.)
status_coder=   rF   r
   ro   r   r   textr	   r   )r)   rJ   s     r-   parse_responsezBaseAPI.parse_response   s     3& H$4$44(()9:;q@$H   }}&!!S(%F  !!S("8==11!!S(*i  !!S('(>?? ;H<P<P;QQ  A rA   c                    t               }|r||d<   |r||d<   |r||d<   |r!t        |t               r||d<   nt        d      |r!t        |t               r||d<   nt        d      |
r!t        |
t               r|
|d<   nt        d	      |	r!t        |	t               r|	|d
<   nt        d      |r!t        |t               r||d<   nt        d      i |d<   |r||d   d<   |r||d   d<   |r||d   d<   |r|s|s|d= | j                  ||d      S )z

        :rtype: json
        r`   topic	conditionrC   z,Provided data_payload is in the wrong formatandroidz.Provided android_config is in the wrong formatwebpushz.Provided webpush_config is in the wrong formatapnsz+Provided apns_config is in the wrong formatfcm_optionsz+Provided fcm_options is in the wrong formatnotificationtitlebodyimage)messagevalidate_only)r!   r    r   rr   )r)   	fcm_tokennotification_titlenotification_bodynotification_imagedata_payload
topic_nametopic_conditionandroid_configapns_configwebpush_configr~   dry_runfcm_payloads                 r-   rS   zBaseAPI.parse_payload   sR   & f#,K #-K '6K$,-&2F#&'UVV.$/)7I&&'WXX.$/)7I&&'WXX+t,&1F#&'TUU+t,-8M*&'TUU
  		
 3EK'02CK'/3EK'0 !3<MN+;QRRrA   )NNNNNNN)NN)NNNNNNNNNNNF)__name__
__module____qualname__r   strr   r.   propertyr"   rH   rY   rd   r>   rr   rw   rS   rP   rA   r-   r   r      s    A %)#'?)!?) ?) !	?)B 2 2& &

$(X LSrA   r   )ro   r<   r   r8   requests.adaptersr   urllib3r   google.oauth2r   google.oauth2.credentialsr   google.auth.transport.requestsr[   pyfcm.errorsr   r   r	   r
   r   objectr   rP   rA   r-   <module>r      s<        )  ) 1 % XSf XSrA   