U
    
ڲg/                     @   s   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	m
Z
 i Ze ZejjZdZdZdd	d
ddgZddefddZdd ZefddZG dd dZG dd dZdS )zFirebase Admin SDK for Python.    N)DefaultCredentialsError)credentials)__version__z	[DEFAULT]ZFIREBASE_CONFIGZdatabaseAuthVariableOverrideZdatabaseURLZhttpTimeout	projectIdZstorageBucketc              
   C   sr   | dkrt  } t|| |}t* |jtkrF|t|j< |W  5 Q R  S W 5 Q R X |tkr`tdtd|dS )ar  Initializes and returns a new App instance.

    Creates a new App instance using the specified options
    and the app name. If an instance already exists by the same
    app name a ValueError is raised.
    If options are not provided an attempt is made to load the options from the environment.
    This is done by looking up the ``FIREBASE_CONFIG`` environment variable. If the value of
    the variable starts with ``"{"``, it is parsed as a JSON object. Otherwise it is treated
    as a file name and the JSON content is read from the corresponding file.
    Use this function whenever a new App instance is required. Do not directly invoke the
    App constructor.

    Args:
      credential: A credential object used to initialize the SDK (optional). If none is provided,
          Google Application Default Credentials are used.
      options: A dictionary of configuration options (optional). Supported options include
          ``databaseURL``, ``storageBucket``, ``projectId``, ``databaseAuthVariableOverride``,
          ``serviceAccountId`` and ``httpTimeout``. If ``httpTimeout`` is not set, the SDK uses
          a default timeout of 120 seconds.

      name: Name of the app (optional).
    Returns:
      App: A newly initialized instance of App.

    Raises:
      ValueError: If the app name is already in use, or any of the
          provided arguments are invalid.
    NaJ  The default Firebase app already exists. This means you called initialize_app() more than once without providing an app name as the second argument. In most cases you only need to call initialize_app() once. But if you do want to initialize multiple apps, pass a second argument to initialize_app() to give each app a unique name.zFirebase app named "{0}" already exists. This means you called initialize_app() more than once with the same app name as the second argument. Make sure you provide a unique name every time you call initialize_app().)	r   ZApplicationDefaultApp
_apps_lockname_apps_DEFAULT_APP_NAME
ValueErrorformat)
credentialoptionsr   app r   ;/tmp/pip-unpacked-wheel-p0r7i5ii/firebase_admin/__init__.pyinitialize_app#   s     

r   c              	   C   s   t | tstdt| t4 t| j| krPt| j= | 	  W 5 Q R  dS W 5 Q R X | jt
krltdtd| jdS )zGracefully deletes an App instance.

    Args:
      app: The app instance to be deleted.

    Raises:
      ValueError: If the app is not initialized.
    z>Illegal app argument type: "{}". Argument must be of type App.NzqThe default Firebase app is not initialized. Make sure to initialize the default app by calling initialize_app().zFirebase app named "{0}" is not initialized. Make sure to initialize the app by calling initialize_app() with your app name as the second argument.)
isinstancer   r   r   typer   r	   getr   _cleanupr
   )r   r   r   r   
delete_appX   s$    	

r   c              
   C   sj   t | tstdt| t" | tkr>t|  W  5 Q R  S W 5 Q R X | tkrXtdtd| dS )a%  Retrieves an App instance by name.

    Args:
      name: Name of the App instance to retrieve (optional).

    Returns:
      App: An App instance with the given name.

    Raises:
      ValueError: If the specified name is not a string, or if the specified
          app does not exist.
    z@Illegal app name argument type: "{}". App name must be a string.zeThe default Firebase app does not exist. Make sure to initialize the SDK by calling initialize_app().zFirebase app named "{0}" does not exist. Make sure to initialize the SDK by calling initialize_app() with your app name as the second argument.N)r   strr   r   r   r   r	   r
   )r   r   r   r   get_appt   s     
r   c                   @   s*   e Zd ZdZdd Zd	ddZdd ZdS )
_AppOptionsz1A collection of configuration options for an App.c                 C   s6   |d kr|   }t|ts,tdt||| _d S )NzEIllegal Firebase app options type: {0}. Options must be a dictionary.)_load_from_environmentr   dictr   r   r   _options)selfr   r   r   r   __init__   s    
z_AppOptions.__init__Nc                 C   s   | j ||S )z2Returns the option identified by the provided key.)r   r   )r   keydefaultr   r   r   r      s    z_AppOptions.getc              
   C   s   t t}|si S |dr"|}nVz"t|d}| }W 5 Q R X W n2 tk
rv } ztd||W 5 d}~X Y nX zt	
|}W n2 tk
r } ztd||W 5 d}~X Y nX dd | D S )a  Invoked when no options are passed to __init__, loads options from FIREBASE_CONFIG.

        If the value of the FIREBASE_CONFIG environment variable starts with "{" an attempt is made
        to parse it as a JSON object, otherwise it is assumed to be pointing to a JSON file.
        {rzUnable to read file {}. {}Nz(JSON string "{0}" is not valid json. {1}c                 S   s   i | ]\}}|t kr||qS r   )_CONFIG_VALID_KEYS).0kvr   r   r   
<dictcomp>   s       z6_AppOptions._load_from_environment.<locals>.<dictcomp>)osgetenv_FIREBASE_CONFIG_ENV_VAR
startswithopenread	Exceptionr   r   jsonloadsitems)r   config_fileZjson_strZ	json_fileerrZ	json_datar   r   r   r      s    

""z"_AppOptions._load_from_environment)N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r      s   	
r   c                   @   sl   e Zd ZdZdd Zedd Zedd Zedd	 Z	ed
d Z
edd Zdd Zdd Zdd ZdS )r   zThe entry point for Firebase Python SDK.

    Represents a Firebase app, while holding the configuration and state
    common to all Firebase APIs.
    c                 C   sr   |rt |tstd||| _t |tjs6td|| _t|| _	t
 | _i | _t| j	d d| _dS )a)  Constructs a new App using the provided name and options.

        Args:
          name: Name of the application.
          credential: A credential object.
          options: A dictionary of configuration options.

        Raises:
          ValueError: If an argument is None or invalid.
        zNIllegal Firebase app name "{0}" provided. App name must be a non-empty string.z_Illegal Firebase credential provided. App must be initialized with a valid credential instance.r   FN)r   r   r   r   _namer   ZBase_credentialr   r   	threadingRLock_lock	_servicesr   _validate_project_idr   _project_id_initialized)r   r   r   r   r   r   r   r      s    

zApp.__init__c                 C   s$   |d k	r t |ts td|d S )Nz7Invalid project ID: "{0}". project ID must be a string.)r   r   r   r   )cls
project_idr   r   r   r?      s    zApp._validate_project_idc                 C   s   | j S N)r9   r   r   r   r   r      s    zApp.namec                 C   s   | j S rC   )r:   rD   r   r   r   r      s    zApp.credentialc                 C   s   | j S rC   )r   rD   r   r   r   r      s    zApp.optionsc                 C   s   | j s|  | _d| _ | jS )NT)r@   _lookup_project_idZ_project_idrD   r   r   r   rB      s    
zApp.project_idc              	   C   sf   | j d}|s6z| jj}W n ttfk
r4   Y nX |sPtjdtjd}t	| j d |S )a  Looks up the Firebase project ID associated with an App.

        If a ``projectId`` is specified in app options, it is returned. Then tries to
        get the project ID from the credential used to initialize the app. If that also fails,
        attempts to look up the ``GOOGLE_CLOUD_PROJECT`` and ``GCLOUD_PROJECT`` environment
        variables.

        Returns:
            str: A project ID string or None.
        r   ZGOOGLE_CLOUD_PROJECTZGCLOUD_PROJECT)
r   r   r:   rB   AttributeErrorr   r)   environr   r?   )r   rB   r   r   r   rE      s    
zApp._lookup_project_idc              
   C   sv   |rt |tstd|| jJ | jdkr>td| j|| jkrV|| | j|< | j| W  5 Q R  S Q R X dS )a1  Returns the service instance identified by the given name.

        Services are functional entities exposed by the Admin SDK (e.g. auth, database). Each
        service instance is associated with exactly one App. If the named service
        instance does not exist yet, _get_service() calls the provided initializer function to
        create the service instance. The created instance will be cached, so that subsequent
        calls would always fetch it from the cache.

        Args:
          name: Name of the service to retrieve.
          initializer: A function that can be used to initialize a service for the first time.

        Returns:
          object: The specified service instance.

        Raises:
          ValueError: If the provided name is invalid, or if the App is already deleted.
        z>Illegal name argument: "{0}". Name must be a non-empty string.Nz3Service requested from deleted Firebase App: "{0}".)r   r   r   r   r=   r>   r9   )r   r   Zinitializerr   r   r   _get_service  s    


zApp._get_servicec              	   C   sJ   | j : | j D ]"}t|drt|jdr|  qd| _W 5 Q R X dS )a  Cleans up any services associated with this App.

        Checks whether each service contains a close() method, and calls it if available.
        This is to be called when an App is being deleted, thus ensuring graceful termination of
        any services started by the App.
        close__call__N)r=   r>   valueshasattrrI   )r   Zservicer   r   r   r   ,  s
    
zApp._cleanupN)r5   r6   r7   r8   r   classmethodr?   propertyr   r   r   rB   rE   rH   r   r   r   r   r   r      s   




r   )r8   datetimer0   r)   r;   Zgoogle.auth.exceptionsr   Zfirebase_adminr   Zfirebase_admin.__about__r   r	   r<   r   utcnowZ_clockr
   r+   r$   r   r   r   r   r   r   r   r   r   <module>   s(   5)