U
    %FZh                     @   s@  d 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 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Zd	Zd
Zde	jejjejjZdZdZd%ddZ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e
jZ G dd dZ!G dd  d Z"G d!d" d"Z#G d#d$ d$ej$Z%dS )&as  Firebase Realtime Database module.

This module contains functions and classes that facilitate interacting with the Firebase Realtime
Database. It supports basic data manipulation operations, as well as complex queries such as
limit queries and range queries. However, it does not support realtime update notifications. This
module uses the Firebase REST API underneath.
    N)parse)
exceptions)_http_client)
_sseclient)_utilsZ	_databasez[].?#$)$key$value	$priorityz%Firebase/HTTP/{0}/{1}.{2}/AdminPython   ZFIREBASE_DATABASE_EMULATOR_HOST/c                 C   s$   t |tt}||}t|| dS )aH  Returns a database ``Reference`` representing the node at the specified path.

    If no path is specified, this function returns a ``Reference`` that represents the database
    root. By default, the returned References provide access to the Firebase Database specified at
    app initialization. To connect to a different database instance in the same Firebase project,
    specify the ``url`` parameter.

    Args:
      path: Path to a node in the Firebase realtime database (optional).
      app: An App instance (optional).
      url: Base URL of the Firebase Database instance (optional). When specified, takes
          precedence over the the ``databaseURL`` option set at app initialization.

    Returns:
      Reference: A newly initialized Reference.

    Raises:
      ValueError: If the specified path or app is invalid.
    clientpath)r   Zget_app_service_DB_ATTRIBUTE_DatabaseService
get_client	Reference)r   appurlZservicer    r   X/home/aprabhat/apps/x.techxrdev.in/venv/lib/python3.8/site-packages/firebase_admin/db.py	reference0   s    
r   c                    sP   t  tstd t fddtD r<td dd  dD S )z,Parses a path string into a set of segments.z+Invalid path: "{0}". Path must be a string.c                 3   s   | ]}| kV  qd S Nr   ).0chr   r   r   	<genexpr>L   s     z_parse_path.<locals>.<genexpr>z6Invalid path: "{0}". Path contains illegal characters.c                 S   s   g | ]}|r|qS r   r   )r   segr   r   r   
<listcomp>O   s      z_parse_path.<locals>.<listcomp>r   )
isinstancestr
ValueErrorformatany_INVALID_PATH_CHARACTERSsplitr   r   r   r   _parse_pathH   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 )Eventz>Represents a realtime update event received from the database.c                 C   s   || _ t|j| _d S r   )
_sse_eventjsonloadsdata_dataselfZ	sse_eventr   r   r   __init__U   s    zEvent.__init__c                 C   s
   | j d S )zParsed JSON data of this event.r+   r,   r.   r   r   r   r+   Y   s    z
Event.datac                 C   s
   | j d S )z9Path of the database reference that triggered this event.r   r0   r1   r   r   r   r   ^   s    z
Event.pathc                 C   s   | j jS )zEvent type string (put, patch).)r(   
event_typer1   r   r   r   r2   c   s    zEvent.event_typeN)	__name__
__module____qualname____doc__r/   propertyr+   r   r2   r   r   r   r   r'   R   s   

r'   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	ListenerRegistrationzERepresents the addition of an event listener to a database reference.c                 C   s*   || _ || _tj| jd| _| j  dS )a3  Initializes a new listener with given parameters.

        This is an internal API. Use the ``db.Reference.listen()`` method to start a
        new listener.

        Args:
          callback: The callback function to fire in case of event.
          sse: A transport session to make requests with.
        )targetN)	_callback_sse	threadingThread_start_listen_threadstart)r.   callbacksser   r   r   r/   l   s    
zListenerRegistration.__init__c                 C   s"   | j D ]}|r| t| qd S r   )r;   r:   r'   r-   r   r   r   r>   {   s    
z"ListenerRegistration._start_listenc                 C   s   | j   | j  dS )zStops the event listener represented by this registration

        This closes the SSE HTTP connection, and joins the background thread.
        N)r;   closer?   joinr1   r   r   r   rC      s    
zListenerRegistration.closeN)r3   r4   r5   r6   r/   r>   rC   r   r   r   r   r8   i   s   r8   c                   @   s   e Zd ZdZdd Zedd Zedd Zedd	 Zd
d Z	d,ddZ
dd Zdd Z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d$d% Zd.d'd(Zd/d*d+Zd)S )0r   z>Reference represents a node in the Firebase realtime database.c                 K   sH   | d| _d|kr"| d| _nt| d| _dd| j | _dS )zCreates a new Reference using the provided parameters.

        This method is for internal use only. Use db.reference() to obtain an instance of
        Reference.
        r   segmentsr   r   N)get_client	_segmentsr&   rD   _pathurl)r.   kwargsr   r   r   r/      s
    zReference.__init__c                 C   s   | j r| j d S d S )N)rH   r1   r   r   r   key   s    
zReference.keyc                 C   s   | j S r   rI   r1   r   r   r   r      s    zReference.pathc                 C   s"   | j rt| j| j d d dS d S )NrK   )r   rE   )rH   r   rG   r1   r   r   r   parent   s    zReference.parentc                 C   sP   |rt |tstd||dr4td|| jd | }t| j|dS )a  Returns a Reference to the specified child node.

        The path may point to an immediate child of the current Reference, or a deeply nested
        child. Child paths must not begin with '/'.

        Args:
          path: Path to the child node.

        Returns:
          Reference: A database Reference representing the specified child node.

        Raises:
          ValueError: If the child path is not a string, not well-formed or begins with '/'.
        z>Invalid path argument: "{0}". Path must be a non-empty string.r   @Invalid path argument: "{0}". Child path must not start with "/"r   )r   r    r!   r"   
startswithrI   r   rG   )r.   r   	full_pathr   r   r   child   s    
zReference.childFc                 C   s^   |r<|rt d| jjd|  ddid\}}||dfS |rDdnd}| jjd|  |d	S )
a  Returns the value, and optionally the ETag, at the current location of the database.

        Args:
          etag: A boolean indicating whether the Etag value should be returned or not (optional).
          shallow: A boolean indicating whether to execute a shallow read (optional). Shallow
              reads do not retrieve the child nodes of the current database location. Cannot be
              set to True if ``etag`` is also set to True.

        Returns:
          object: If etag is False returns the decoded JSON value of the current database location.
          If etag is True, returns a 2-tuple consisting of the decoded JSON value and the Etag
          associated with the current database location.

        Raises:
          ValueError: If both ``etag`` and ``shallow`` are set to True.
          FirebaseError: If an error occurs while communicating with the remote database server.
        z,etag and shallow cannot both be set to True.rF   zX-Firebase-ETagtrueheadersETagzshallow=trueNparams)r!   rG   Zheaders_and_body_add_suffixrF   body)r.   etagZshallowrU   r+   rX   r   r   r   rF      s      
zReference.getc                 C   sP   t |tstd| jjd|  d|id}|jdkr:dS d| |j	dfS )	a  Gets data in this location only if the specified ETag does not match.

        Args:
          etag: The ETag value to be checked against the ETag of the current location.

        Returns:
          tuple: A 3-tuple consisting of a boolean, a decoded JSON value and an ETag. If the ETag
          specified by the caller did not match, the boolen value will be True and the JSON
          and ETag values would reflect the corresponding values in the database. If the ETag
          matched, the boolean value will be False and the other elements of the tuple will be
          None.

        Raises:
          ValueError: If the ETag is not a string.
          FirebaseError: If an error occurs while communicating with the remote database server.
        zETag must be a string.rF   zif-none-matchrT   i0  )FNNTrV   )
r   r    r!   rG   requestrY   status_coder)   rU   rF   )r.   r[   respr   r   r   get_if_changed   s    

zReference.get_if_changedc                 C   s,   |dkrt d| jjd|  |dd dS )a  Sets the data at this location to the given value.

        The value must be JSON-serializable and not None.

        Args:
          value: JSON-serializable value to be set at this location.

        Raises:
          ValueError: If the provided value is None.
          TypeError: If the value is not JSON-serializable.
          FirebaseError: If an error occurs while communicating with the remote database server.
        NValue must not be None.putprint=silentr)   rX   )r!   rG   r\   rY   r.   valuer   r   r   set   s    zReference.setc              
   C   s   t |tstd|dkr"tdz.| jjd|  |d|id}d||dfW S  tjk
r } zD|j	}|dk	rd|jkr|jd }|
 }d	||f W Y 
S |W 5 d}~X Y nX dS )
a<  Conditonally sets the data at this location to the given value.

        Sets the data at this location to the given value only if ``expected_etag`` is same as the
        ETag value in the database.

        Args:
          expected_etag: Value of ETag we want to check.
          value: JSON-serializable value to be set at this location.

        Returns:
          tuple: A 3-tuple consisting of a boolean, a decoded JSON value and an ETag. The boolean
          indicates whether the set operation was successful or not. The decoded JSON and the
          ETag corresponds to the latest value in this database location.

        Raises:
          ValueError: If the value is None, or if expected_etag is not a string.
          FirebaseError: If an error occurs while communicating with the remote database server.
        zExpected ETag must be a string.NzValue must not be none.ra   zif-match)r)   rU   TrV   F)r   r    r!   rG   rU   rY   rF   r   ZFailedPreconditionErrorhttp_responser)   )r.   Zexpected_etagre   rU   errorrg   r[   Zsnapshotr   r   r   set_if_unchanged
  s&    
   
zReference.set_if_unchanged c                 C   s:   |dkrt d| jjd|  |d}|d}| |S )as  Creates a new child node.

        The optional value argument can be used to provide an initial value for the child node. If
        no value is provided, child node will have empty string as the default value.

        Args:
          value: JSON-serializable initial value for the child node (optional).

        Returns:
          Reference: A Reference representing the newly created child node.

        Raises:
          ValueError: If the value is None.
          TypeError: If the value is not JSON-serializable.
          FirebaseError: If an error occurs while communicating with the remote database server.
        Nr`   post)r)   name)r!   rG   rZ   rY   rF   rR   )r.   re   outputZpush_idr   r   r   push0  s
    
zReference.pushc                 C   sF   |rt |tstdd| kr*td| jjd|  |dd dS )aj  Updates the specified child keys of this Reference to the provided values.

        Args:
          value: A dictionary containing the child keys to update, and their new values.

        Raises:
          ValueError: If value is empty or not a dictionary.
          FirebaseError: If an error occurs while communicating with the remote database server.
        z.Value argument must be a non-empty dictionary.Nz&Dictionary must not contain None keys.patchrb   rc   )r   dictr!   keysrG   r\   rY   rd   r   r   r   updateG  s
    
zReference.updatec                 C   s   | j d|   dS )zDeletes this node from the database.

        Raises:
          FirebaseError: If an error occurs while communicating with the remote database server.
        deleteN)rG   r\   rY   r1   r   r   r   rs   W  s    zReference.deletec                 C   s
   |  |S )a  Registers the ``callback`` function to receive realtime updates.

        The specified callback function will get invoked with ``db.Event`` objects for each
        realtime update received from the database. It will also get called whenever the SDK
        reconnects to the server due to network issues or credential expiration. In general,
        the OAuth2 credentials used to authorize connections to the server expire every hour.
        Therefore clients should expect the ``callback`` to fire at least once every hour, even if
        there are no updates in the database.

        This API is based on the event streaming support available in the Firebase REST API. Each
        call to ``listen()`` starts a new HTTP connection and a background thread. This is an
        experimental feature. It currently does not honor the auth overrides and timeout settings.
        Cannot be used in thread-constrained environments like Google App Engine.

        Args:
          callback: A function to be called when a data change is detected.

        Returns:
          ListenerRegistration: An object that can be used to stop the event listener.

        Raises:
          FirebaseError: If an error occurs while starting the initial HTTP connection.
        )_listen_with_session)r.   rA   r   r   r   listen_  s    zReference.listenc                 C   sd   t |stdd}| jdd\}}|tk rX||}| ||\}}}|rN|S |d7 }q$tddS )a  Atomically modifies the data at this location.

        Unlike a normal ``set()``, which just overwrites the data regardless of its previous state,
        ``transaction()`` is used to modify the existing value to a new value, ensuring there are
        no conflicts with other clients simultaneously writing to the same location.

        This is accomplished by passing an update function which is used to transform the current
        value of this reference into a new value. If another client writes to this location before
        the new value is successfully saved, the update function is called again with the new
        current value, and the write will be retried. In case of repeated failures, this method
        will retry the transaction up to 25 times before giving up and raising a
        TransactionAbortedError. The update function may also force an early abort by raising an
        exception instead of returning a value.

        Args:
          transaction_update: A function which will be passed the current data stored at this
              location. The function should return the new value it would like written. If
              an exception is raised, the transaction will be aborted, and the data at this
              location will not be modified. The exceptions raised by this function are
              propagated to the caller of the transaction method.

        Returns:
          object: New value of the current database Reference (only if the transaction commits).

        Raises:
          TransactionAbortedError: If the transaction aborts after exhausting all retry attempts.
          ValueError: If transaction_update is not a function.
        z&transaction_update must be a function.r   T)r[      z)Transaction aborted after failed retries.N)callabler!   rF   _TRANSACTION_MAX_RETRIESri   TransactionAbortedError)r.   Ztransaction_updatetriesr+   r[   Znew_datasuccessr   r   r   transactiony  s    
zReference.transactionc                 C   s*   |t krtd|t|| j|  dS )a  Returns a Query that orders data by child values.

        Returned Query can be used to set additional parameters, and execute complex database
        queries (e.g. limit queries, range queries).

        Args:
          path: Path to a valid child of the current Reference.

        Returns:
          Query: A database Query instance.

        Raises:
          ValueError: If the child path is not a string, not well-formed or None.
        zIllegal child path: {0}order_byr   pathurl)_RESERVED_FILTERSr!   r"   QueryrG   rY   )r.   r   r   r   r   order_by_child  s    zReference.order_by_childc                 C   s   t d| j|  dS )a  Creates a Query that orderes data by key.

        Returned Query can be used to set additional parameters, and execute complex database
        queries (e.g. limit queries, range queries).

        Returns:
          Query: A database Query instance.
        r   r}   r   rG   rY   r1   r   r   r   order_by_key  s    	zReference.order_by_keyc                 C   s   t d| j|  dS )a  Creates a Query that orderes data by value.

        Returned Query can be used to set additional parameters, and execute complex database
        queries (e.g. limit queries, range queries).

        Returns:
          Query: A database Query instance.
        r   r}   r   r1   r   r   r   order_by_value  s    	zReference.order_by_value.jsonc                 C   s
   | j | S r   rM   )r.   suffixr   r   r   rY     s    zReference._add_suffixNc              
   C   sx   | j j|   }|s| j  }z$tj||fd| j ji}t||W S  tj	j
k
rr } zt|W 5 d }~X Y nX d S )NrX   )rG   base_urlrY   create_listener_sessionr   Z	SSEClientrX   r8   requestsr   RequestException_Clienthandle_rtdb_error)r.   rA   sessionr   rB   rh   r   r   r   rt     s    
zReference._listen_with_session)FF)rj   )r   )N)r3   r4   r5   r6   r/   r7   rL   r   rN   rR   rF   r_   rf   ri   rn   rr   rs   ru   r|   r   r   r   rY   rt   r   r   r   r   r      s.   



&
+
r   c                   @   sT   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	e
dd Zdd ZdS )r   a  Represents a complex query that can be executed on a Reference.

    Complex queries can consist of up to 2 components: a required ordering constraint, and an
    optional filtering constraint. At the server, data is first sorted according to the given
    ordering constraint (e.g. order by child). Then the filtering constraint (e.g. limit, range)
    is applied on the sorted data to produce the final result. Despite the ordering constraint,
    the final result is returned by the server as an unordered collection. Therefore the Query
    interface performs another round of sorting at the client-side before returning the results
    to the caller. This client-side sorted results are returned to the user as a Python
    OrderedDict.
    c                 K   s   | d}|rt|ts td|tkrR|dr@td|t|}d|}| d| _	| d| _
|| _dt|i| _|rtd|d S )	Nr~   z)order_by field must be a non-empty stringr   rO   r   r   ZorderByz!Unexpected keyword arguments: {0})popr   r    r!   r   rP   r"   r&   rD   rG   rI   	_order_byr)   dumps_params)r.   rJ   r~   rE   r   r   r   r/     s     


zQuery.__init__c                 C   s:   t |tr|dk rtdd| jkr,td|| jd< | S )aM  Creates a query with limit, and anchors it to the start of the window.

        Args:
          limit: The maximum number of child nodes to return.

        Returns:
          Query: The updated Query instance.

        Raises:
          ValueError: If the value is not an integer, or set_limit_last() was called previously.
        r   %Limit must be a non-negative integer.limitToLast&Cannot set both first and last limits.limitToFirstr   intr!   r   r.   limitr   r   r   limit_to_first  s    

zQuery.limit_to_firstc                 C   s:   t |tr|dk rtdd| jkr,td|| jd< | S )aL  Creates a query with limit, and anchors it to the end of the window.

        Args:
          limit: The maximum number of child nodes to return.

        Returns:
          Query: The updated Query instance.

        Raises:
          ValueError: If the value is not an integer, or set_limit_first() was called previously.
        r   r   r   r   r   r   r   r   r   r   limit_to_last  s    

zQuery.limit_to_lastc                 C   s$   |dkrt dt|| jd< | S )as  Sets the lower bound for a range query.

        The Query will only return child nodes with a value greater than or equal to the specified
        value.

        Args:
          start: JSON-serializable value to start at, inclusive.

        Returns:
          Query: The updated Query instance.

        Raises:
          ValueError: If the value is ``None``.
        NzStart value must not be None.ZstartAtr!   r)   r   r   )r.   r@   r   r   r   start_at   s    zQuery.start_atc                 C   s$   |dkrt dt|| jd< | S )al  Sets the upper bound for a range query.

        The Query will only return child nodes with a value less than or equal to the specified
        value.

        Args:
          end: JSON-serializable value to end at, inclusive.

        Returns:
          Query: The updated Query instance.

        Raises:
          ValueError: If the value is ``None``.
        NzEnd value must not be None.ZendAtr   )r.   endr   r   r   end_at4  s    zQuery.end_atc                 C   s$   |dkrt dt|| jd< | S )aS  Sets an equals constraint on the Query.

        The Query will only return child nodes whose value is equal to the specified value.

        Args:
          value: JSON-serializable value to query for.

        Returns:
          Query: The updated Query instance.

        Raises:
          ValueError: If the value is ``None``.
        Nz Equal to value must not be None.ZequalTor   rd   r   r   r   equal_toH  s    zQuery.equal_toc                 C   s6   g }t | jD ]}|d|| j|  qd|S )N{0}={1}&)sortedr   appendr"   rD   )r.   rX   rL   r   r   r   	_querystr[  s    zQuery._querystrc                 C   sB   | j jd| j| jd}t|ttfr>| jdkr>t|| j	 S |S )a7  Executes this Query and returns the results.

        The results will be returned as a sorted list or an OrderedDict.

        Returns:
          object: Decoded JSON result of the Query.

        Raises:
          FirebaseError: If an error occurs while communicating with the remote database server.
        rF   rW   r	   )
rG   rZ   rI   r   r   rp   listr   _SorterrF   )r.   resultr   r   r   rF   b  s    z	Query.getN)r3   r4   r5   r6   r/   r   r   r   r   r   r7   r   rF   r   r   r   r   r     s   
r   c                   @   s   e Zd ZdZdd ZdS )ry   zGA transaction was aborted aftr exceeding the maximum number of retries.c                 C   s   t j| | d S r   )r   AbortedErrorr/   )r.   messager   r   r   r/   v  s    z TransactionAbortedError.__init__N)r3   r4   r5   r6   r/   r   r   r   r   ry   s  s   ry   c                   @   s    e Zd ZdZdd Zdd ZdS )r   z'Helper class for sorting query results.c                    sp   t |tr(d| _ fdd| D }n:t |trPd| _ fddt|D }ntdt|t	|| _
d S )NTc                    s   g | ]\}}t || qS r   
_SortEntryr   kvr~   r   r   r     s     z$_Sorter.__init__.<locals>.<listcomp>Fc                    s   g | ]\}}t || qS r   r   r   r   r   r   r     s     z'Sorting not supported for "{0}" object.)r   rp   
dict_inputitemsr   	enumerater!   r"   typer   sort_entries)r.   resultsr~   entriesr   r   r   r/   }  s    

z_Sorter.__init__c                 C   s,   | j rtdd | jD S dd | jD S )Nc                 S   s   g | ]}|j |jfqS r   )rL   re   r   er   r   r   r     s     z_Sorter.get.<locals>.<listcomp>c                 S   s   g | ]
}|j qS r   )re   r   r   r   r   r     s     )r   collectionsOrderedDictr   r1   r   r   r   rF     s    z_Sorter.getN)r3   r4   r5   r6   r/   rF   r   r   r   r   r   z  s   r   c                   @   s   e Zd ZdZdZdZdZd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edd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"S )#r   z;A wrapper that is capable of sorting items in a dictionary.r   rv               c                 C   sL   || _ || _|dkr|| _n|dkr,|| _nt||| _t| j| _d S )N)r   r	   r   )_key_value_indexr   _extract_child_get_index_type_index_type)r.   rL   re   r~   r   r   r   r/     s    z_SortEntry.__init__c                 C   s   | j S r   )r   r1   r   r   r   rL     s    z_SortEntry.keyc                 C   s   | j S r   )r   r1   r   r   r   index  s    z_SortEntry.indexc                 C   s   | j S r   )r   r1   r   r   r   
index_type  s    z_SortEntry.index_typec                 C   s   | j S r   )r   r1   r   r   r   re     s    z_SortEntry.valuec                 C   s`   |dkr| j S t|tr"|s"| jS t|tr6|r6| jS t|ttfrJ| jS t|trZ| j	S | j
S )zAssigns an integer code to the type of the index.

        The index type determines how differently typed values are sorted. This ordering is based
        on https://firebase.google.com/docs/database/rest/retrieve-data#section-rest-ordered-data
        N)
_type_noner   bool_type_bool_false_type_bool_truer   float_type_numericr    _type_string_type_object)clsr   r   r   r   r     s    
z_SortEntry._get_index_typec                 C   s8   | d}|}|D ] }t|tr,||}q d S q|S )Nr   )r%   r   rp   rF   )r   re   r   rE   currentsegmentr   r   r   r     s    

z_SortEntry._extract_childc                 C   sl   | j |j  }}||krP|| j| jfkrB| j|jkrB| j|j }}n| j|j }}||k r\dS ||krhdS dS )ab  Compares two _SortEntry instances.

        If the indices have the same numeric or string type, compare them directly. Ties are
        broken by comparing the keys. If the indices have the same type, but are neither numeric
        nor string, compare the keys. In all other cases compare based on the ordering provided
        by index types.
        rK   rv   r   )r   r   r   r   rL   )r.   otherZself_keyZ	other_keyr   r   r   _compare  s    z_SortEntry._comparec                 C   s   |  |dk S Nr   r   r.   r   r   r   r   __lt__  s    z_SortEntry.__lt__c                 C   s   |  |dkS r   r   r   r   r   r   __le__  s    z_SortEntry.__le__c                 C   s   |  |dkS r   r   r   r   r   r   __gt__  s    z_SortEntry.__gt__c                 C   s   |  |dkS r   r   r   r   r   r   __ge__  s    z_SortEntry.__ge__c                 C   s   |  |dkS r   r   r   r   r   r   __eq__  s    z_SortEntry.__eq__N)r3   r4   r5   r6   r   r   r   r   r   r   r/   r7   rL   r   r   re   classmethodr   r   r   r   r   r   r   r   r   r   r   r   r     s4   






r   c                   @   sN   e Zd ZdZdZdd ZdddZdd	 Zed
d Z	edd Z
dd ZdS )r   z8Service that maintains a collection of database clients.Z_admin_c                 C   s   |j | _|jd}|r || _nd | _t|}|| ji fkrPtj	|dd| _
nd | _
|jdtj| _i | _tjt}|rd|krtdt||| _nd | _d S )NZdatabaseURL),:)
separatorsZhttpTimeoutz//z6Invalid {0}: "{1}". It must follow format "host:port".)
credential_credentialoptionsrF   _db_urlr   _get_auth_override_DEFAULT_AUTH_OVERRIDEr)   r   _auth_overrider   ZDEFAULT_TIMEOUT_SECONDS_timeout_clientsosenviron_EMULATOR_HOST_ENV_VARr!   r"   _emulator_host)r.   r   db_urlauth_overrideZemulator_hostr   r   r   r/     s,    
 z_DatabaseService.__init__Nc           	      C   s   |dkr| j }|rt|ts*td|t|}|jsHtd|| |}|rpt	
 }|j}d|ji}n| j }d|j}i }| jr| j|d< |tj|ddf}|| jkrt||| j|}|| j|< | j| S )	z<Creates a client based on the db_url. Clients may be cached.NzIInvalid database URL: "{0}". Database URL must be a non-empty URL string.zJInvalid database URL: "{0}". Database URL must be a wellformed URL string.nszhttps://{0}Zauth_variable_overrideT)	sort_keys)r   r   r    r!   r"   r   urlparsenetloc_get_emulator_configr   ZEmulatorAdminCredentialsr   	namespacer   get_credentialr   r)   r   r   r   r   )	r.   r   
parsed_urlZemulator_configr   r   rX   Zclient_cache_keyr   r   r   r   r     s<    





z_DatabaseService.get_clientc                 C   sb   t dddg}|jdkr2t|\}}|||S | jr^d| j}|jdd }|||S dS )	z;Checks whether the SDK should connect to the RTDB emulator.EmulatorConfigr   r   httpsz
http://{0}.r   N)	r   
namedtupleschemer   _parse_emulator_urlr   r"   r   r%   )r.   r   r   r   r   r   r   r   r   =  s    


z%_DatabaseService._get_emulator_configc                 C   sf   t |jd}|jdks4|r4t|dks4|d sFtd| |d }d|j|j	}||fS )z:Parses emulator URL like http://localhost:8080/?ns=foo-barr   httprv   r   zgInvalid database URL: "{0}". Database URL must be a valid URL to a Firebase Realtime Database instance.z	{0}://{1})
r   parse_qsqueryrF   r   lenr!   r"   geturlr   )r   r   Zquery_nsr   r   r   r   r   r   L  s    "z$_DatabaseService._parse_emulator_urlc                 C   sB   |j d| j}|| jks"|d kr&|S t|ts>td||S )NZdatabaseAuthVariableOverridezZInvalid databaseAuthVariableOverride option: "{0}". Override value must be a dict or None.)r   rF   r   r   rp   r!   r"   )r   r   r   r   r   r   r   Y  s    
z#_DatabaseService._get_auth_overridec                 C   s"   | j  D ]}|  q
i | _ d S r   )r   valuesrC   rd   r   r   r   rC   d  s    
z_DatabaseService.close)N)r3   r4   r5   r6   r   r/   r   r   r   r   r   rC   r   r   r   r   r     s   
%


r   c                       sN   e Zd ZdZd fdd	Z fddZdd Zed	d
 Zedd Z	  Z
S )r   zHTTP client used to make REST calls.

    _Client maintains an HTTP session, and handles authenticating HTTP requests along with
    marshalling and unmarshalling of JSON data.
    Nc                    s0   t  j|||dtid || _|r&|ni | _dS )a  Creates a new _Client from the given parameters.

        This exists primarily to enable testing. For regular use, obtain _Client instances by
        calling the from_app() class method.

        Args:
          credential: A Google credential that can be used to authenticate requests.
          base_url: A URL prefix to be added to all outgoing requests. This is typically the
              Firebase Realtime Database URL.
          timeout: HTTP request timeout in seconds. If set to None connections will never
              timeout, which is the default behavior of the underlying requests library.
          params: Dict of query parameters to add to all outgoing requests.
        z
User-Agent)r   r   timeoutrU   N)superr/   _USER_AGENTr   rX   )r.   r   r   r  rX   	__class__r   r   r/   q  s      z_Client.__init__c              
      s   d  fdd jD }|d}|r>|r:|d | }n|}||d< ztt j||f|W S  tjjk
r } zt	|W 5 d}~X Y nX dS )a  Makes an HTTP call using the Python requests library.

        Extends the request() method of the parent JsonHttpClient class. Handles default
        params like auth overrides, and low-level exceptions.

        Args:
          method: HTTP method name as a string (e.g. get, post).
          url: URL path of the remote endpoint. This will be appended to the server's base URL.
          **kwargs: An additional set of keyword arguments to be passed into requests API
              (e.g. json, params).

        Returns:
          Response: An HTTP response object.

        Raises:
          FirebaseError: If an error occurs while making the HTTP call.
        r   c                 3   s    | ]}d  | j| V  qdS )r   N)r"   rX   )r   rL   r1   r   r   r     s     z"_Client.request.<locals>.<genexpr>rX   N)
rD   rX   rF   r  r   r\   r   r   r   r   )r.   methodr   rJ   r  Zextra_paramsrh   r  r1   r   r\     s    
z_Client.requestc                 C   s   t | jS r   )r   ZKeepAuthSessionr   r1   r   r   r   r     s    z_Client.create_listener_sessionc                 C   s.   |j dkrt|S | |j }tj||dS )zFConverts an error encountered while calling RTDB into a FirebaseError.N)r   )responser   Zhandle_requests_error_extract_error_message)r   rh   r   r   r   r   r     s    

z_Client.handle_rtdb_errorc                 C   sR   d}z |  }t|tr"|d}W n tk
r8   Y nX |sNd|j }|S )ai  Extracts an error message from an error response.

        If the server has sent a JSON response with an 'error' field, which is the typical
        behavior of the Realtime Database REST API, parses the response to retrieve the error
        message. If the server has sent a non-JSON response, returns the full response
        as the error message.
        Nrh   z&Unexpected response from database: {0})r)   r   rp   rF   r!   r"   contentdecode)r   r  r   r+   r   r   r   r    s    	
z_Client._extract_error_message)N)r3   r4   r5   r6   r/   r\   r   r   r   r  __classcell__r   r   r  r   r   j  s    
r   )r   NN)&r6   r   r)   r   sysr<   urllibr   r   Zfirebase_adminr   r   r   r   r   r$   r   r"   __version__version_infomajorminorr  rx   r   r   r&   r'   r8   r   r   r   ry   r   r   r   ZJsonHttpClientr   r   r   r   r   <module>   sH     

"  S jq