o
    d`6                     @   sD  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m	Z	 G dd de
ZG dd deZG d	d
 d
eZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd dejjZdd  ZG d!d" d"eZG d#d$ d$eZdS )%4A connection object to interface with REST services.    N)urllib)formatsc                   @      e Zd ZdZdddZdS )Errorz'A general error derived from Exception.Nc                 C   s   t | | || _|| _d S N)	Exception__init__urlcode)selfmsgr
   r    r   r/var/www/html/riverr-enterprise-integrations-main/venv/lib/python3.10/site-packages/pyactiveresource/connection.pyr	      s   
zError.__init__)NNN__name__
__module____qualname____doc__r	   r   r   r   r   r          r   c                   @   r   )ServerErrorz,An error caused by an ActiveResource server.Nc                 C   s0   |d urt | |j|j|j d S t |  d S r   )r   r	   r   r
   r   )r   responser   r   r   r	      s   zServerError.__init__r   r   r   r   r   r   r          r   c                   @   r   )ConnectionErrorz&An error caused by network connection.Nc                 C   sN   |st d d| _d }n	t || _|j}|st| j}t| ||| jj d S )N )Responser   from_httpresponser
   strr   r	   r   )r   r   messager
   r   r   r   r	   %   s   
zConnectionError.__init__NNr   r   r   r   r   r   "   r   r   c                   @      e Zd ZdZdS )RedirectionzHTTP 3xx redirection.Nr   r   r   r   r   r   r   r   r!   2   s    r!   c                   @   r    )ClientErrorz,An error caused by an ActiveResource client.Nr"   r   r   r   r   r#   7       r#   c                   @   r    )ResourceConflictz2An error raised when there is a resource conflict.Nr"   r   r   r   r   r%   =   r$   r%   c                   @   r    )ResourceInvalidz+An error raised when a resource is invalid.Nr"   r   r   r   r   r&   C   r$   r&   c                   @   r   )ResourceNotFoundz-An error raised when a resource is not found.Nc                 C   s4   |d ur|d u rd|j |jf }tj| ||d d S )Nz%s: %s)r   r   )r   r
   r#   r	   )r   r   r   r   r   r   r	   M   s   zResourceNotFound.__init__r   r   r   r   r   r   r'   I   r   r'   c                   @   r    )
BadRequestz0An error raised when client sends a bad request.Nr"   r   r   r   r   r(   T   r$   r(   c                   @   r    )UnauthorizedAccessz/An error raised when an access is unauthorized.Nr"   r   r   r   r   r)   Z   r$   r)   c                   @   r    )ForbiddenAccessz+An error raised when access is not allowed.Nr"   r   r   r   r   r*   `   r$   r*   c                   @   r    )MethodNotAllowedz-An error raised when a method is not allowed.Nr"   r   r   r   r   r+   f   r$   r+   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	Requestz1A request object which allows additional methods.c                 O   s&   d | _ tjjj| g|R i | d S r   )_methodr   requestr,   r	   )r   argskwargsr   r   r   r	   o   s    zRequest.__init__c                 C   s   | j s
tjj| S | j S )zReturn the HTTP method.)r-   r   r.   r,   
get_methodr   r   r   r   r1   s   s   zRequest.get_methodc                 C   s
   || _ dS )zSet the HTTP method.N)r-   )r   methodr   r   r   
set_methody   s   
zRequest.set_methodN)r   r   r   r   r	   r1   r4   r   r   r   r   r,   l   s
    r,   c                  C   s   t j} | d dko| d dkS )zKDetermines if our version of urllib.request.urlopen has a timeout argument.r            )sysversion_info)versionr   r   r   _urllib_has_timeout~   s   r;   c                   @   sH   e Zd ZdZdddZdd Zdd	 Zd
d ZdddZe	dd Z
dS )r   z+Represents a response from the http server.Nr   c                 C   s.   || _ || _|| _|du ri }|| _|| _dS )a  Initialize a new Response object.

        code, body, headers, msg are retrievable as instance attributes.
        Individual headers can be retrieved using dictionary syntax (i.e.
        response['header'] => value.

        Args:
            code: The HTTP response code returned by the server.
            body: The body of the response.
            headers: A dictionary of HTTP headers.
            msg: The HTTP message (e.g. 200 OK => 'OK').
            response: The original httplib.HTTPResponse (if any).
        N)r   r   bodyheadersr   )r   r   r<   r=   r   r   r   r   r   r	      s   
zResponse.__init__c                 C   s.   t |tr| j| j| jf|j|j|jfkS dS )NF)
isinstancer   r   r<   r=   )r   otherr   r   r   __eq__   s
   
zResponse.__eq__c                 C   s   d| j | j| j| jf S )Nz2Response(code=%s, body="%s", headers=%s, msg="%s"))r   r<   r=   r   r2   r   r   r   __repr__   s   zResponse.__repr__c                 C   s
   | j | S r   r=   )r   keyr   r   r   __getitem__   s   
zResponse.__getitem__c                 C   s   | j ||S r   )r=   get)r   rC   valuer   r   r   rE      s   zResponse.getc                 C   s   | |j | t|j|j|S )zCreate a Response object based on an httplib.HTTPResponse object.

        Args:
            response: An httplib.HTTPResponse object.
        Returns:
            A Response object.
        )r   readdictr=   r   )clsr   r   r   r   r      s   	zResponse.from_httpresponse)Nr   Nr   )r   r   r   r   r	   r@   rA   rD   rE   classmethodr   r   r   r   r   r      s    

r   c                   @   s   e Zd ZdZdddejfddZdd Zdd Zdd	d
Z	dd Z
dddZdddZdddZdddZdddZdddZdd ZdS )
Connectionr   Nc                 C   s   |du rt d| |\| _| _| _|p| jpd| _|p!| jp!d| _| js)| jr<td| j| jf dd| _	nd| _	|| _
td| _|| _dS )aR  Initialize a new Connection object.

        Args:
            site: The base url for connections (e.g. 'http://foo')
            user: username for basic authentication.
            password: password for basic authentication.
            timeout: socket timeout.
            format: format object for en/decoding resource data.
        Nz&Connection site argument requires siter   z%s:%szutf-8zpyactiveresource.connection)
ValueError_parse_sitesiteuserpasswordbase64	b64encodeencodedecodeauthtimeoutlogging	getLoggerlogformat)r   rN   rO   rP   rV   rZ   r   r   r   r	      s   &
zConnection.__init__c                 C   sR   t j|}|j}|jr|dt|j 7 }t j|j|ddddf}||j|j	fS )zRetrieve the auth information and base url for a site.

        Args:
            site: The URL to parse.
        Returns:
            A tuple containing (site, username, password).
        :r   )
r   parseurlparsehostnameportr   
urlunparseschemeusernamerP   )r   rN   partshostnew_siter   r   r   rM      s   zConnection._parse_sitec                 C   s   t |S )zReturn a new request object.

        Args:
            url: The url to connect to.
        Returns:
            A Request object.
        )r,   )r   r
   r   r   r   _request   s   zConnection._requestc              
   C   s  t j| j|}| jd|| | |}|| |r,t	|D ]
\}}|
|| q!| jr8|
dd| j  |jrPddd t	|jD }	| jd|	 |rf|
d| jj ||_| jd	|j n|d
v rx|
d| jj |
dd | jrt st }
t| j z\d}z
| | |}W n+ t jjy } z| |}W Y d}~nd}~w t jjy } zt||d}~ww t|}| jd|j|j|j  W |r|!  | jrt st|
 n|r|!  | jrt st|
 w w w | jd|j|j t"|j# |S )aE  Perform an HTTP request.

        Args:
            method: The HTTP method (GET, PUT, POST, DELETE).
            path: The HTTP path to retrieve.
            headers: A dictionary of HTTP headers to add.
            data: The data to send as the body of the request.
        Returns:
             A Response object.
        z%s %sAuthorizationzBasic 
c                 S   s   g | ]\}}d  ||fqS )r[   )join).0kvr   r   r   
<listcomp>  s    z$Connection._open.<locals>.<listcomp>zrequest-headers:%szContent-Typezrequest-body:%s)POSTPUTzContent-Length0Nz'Response(code=%d, headers=%s, msg="%s")z--> %d %s %db)$r   r\   urljoinrN   rY   inforf   r4   six	iteritems
add_headerrU   r=   ri   debugrZ   	mime_typedatarV   r;   socketgetdefaulttimeoutsetdefaulttimeout_handle_error_urlopenerror	HTTPErrorURLErrorr   r   r   r   r   closelenr<   )r   r3   pathr=   rx   r
   r.   rC   rF   header_stringold_timeouthttp_responseerrr   r   r   r   _open   sj   






zConnection._openc                 C   s$   t  rtjj|| jdS tj|S )a  Wrap calls to urllib so they can be overriden.

        Args:
            request: A Request object.
        Returns:
            An httplib.HTTPResponse object.
        Raises:
            urllib.error.HTTPError on server errors.
            urllib.error.URLError on IO errors.
        )rV   )r;   r   r.   urlopenrV   )r   r.   r   r   r   r}   0  s   zConnection._urlopenc                 C      | j d||dS )zPerform an HTTP get request.

        Args:
            path: The HTTP path to retrieve.
            headers: A dictionary of HTTP headers to add.
        Returns:
            A Response object.
        GETrB   r   r   r   r=   r   r   r   rE   @     	zConnection.getc                 C   s   | j | ||jS )zPerform an HTTP get request and return the formatted response.

        Args:
            path: The HTTP path to retrieve.
            headers: A dictionary of HTTP headers to add.
        Returns:
            The resource as a dict.
        )rZ   rT   rE   r<   r   r   r   r   get_formattedK  s   	zConnection.get_formattedc                 C   r   )zPerform an HTTP delete request.

        Args:
            path: The HTTP path to retrieve.
            headers: A dictionary of HTTP headers to add.
        Returns:
            A Response object.
        DELETErB   r   r   r   r   r   deleteV  r   zConnection.deletec                 C      | j d|||dS )a
  Perform an HTTP put request.

        Args:
            path: The HTTP path to retrieve.
            headers: A dictionary of HTTP headers to add.
            data: The data to send as the body of the request.
        Returns:
            A Response object.
        ro   r=   rx   r   r   r   r=   rx   r   r   r   puta     
zConnection.putc                 C   r   )a  Perform an HTTP post request.

        Args:
            path: The HTTP path to retrieve.
            headers: A dictionary of HTTP headers to add.
            data: The data to send as the body of the request.
        Returns:
            A Response object.
        rn   r   r   r   r   r   r   postm  r   zConnection.postc                 C   r   )zPerform an HTTP put request.

        Args:
            path: The HTTP path to retrieve.
            headers: A dictionary of HTTP headers to add.
        Returns:
            A Response object.
        HEADrB   r   r   r   r   r   heady  r   zConnection.headc                 C   s   |j dv r	t|d|j   krdk r|S  |j dkrt||j dkr(t||j dkr1t||j dkr:t||j dkrCt||j dkrLt||j d	krUt|d|j   krcd
k rdt	| d
|j   krrdk rwt
| t|t|)a  Handle an HTTP error.

        Args:
            err: A urllib.error.HTTPError object.
        Returns:
            An HTTP response object if the error is recoverable.
        Raises:
            Redirection: if HTTP error code 301,302 returned.
            BadRequest: if HTTP error code 400 returned.
            UnauthorizedAccess: if HTTP error code 401 returned.
            ForbiddenAccess: if HTTP error code 403 returned.
            ResourceNotFound: if HTTP error code 404 is returned.
            MethodNotAllowed: if HTTP error code 405 is returned.
            ResourceConflict: if HTTP error code 409 is returned.
            ResourceInvalid: if HTTP error code 422 is returned.
            ClientError: if HTTP error code falls in 401 - 499.
            ServerError: if HTTP error code falls in 500 - 599.
            ConnectionError: if unknown HTTP error code returned.
        )i-  i.     i  i  i  i  i  i  i  i  iX  )r   r!   r(   r)   r*   r'   r+   r%   r&   r#   r   r   )r   r   r   r   r   r|     s4   







zConnection._handle_errorr   r   )r   r   r   r   r   
JSONFormatr	   rM   rf   r   r}   rE   r   r   r   r   r   r|   r   r   r   r   rK      s     


;





rK   )r   rQ   rW   ry   r8   rs   	six.movesr   pyactiveresourcer   r   r   r   r   r!   r#   r%   r&   r'   r(   r)   r*   r+   r.   r,   r;   objectr   rK   r   r   r   r   <module>   s0   	6