B
    d76                 @   s   d 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mZ dd	lmZ dd
lmZmZ dZddgZG dd dejZG dd dejeZdS )z2Connection utilities for the GW datafind service.
    N)client)loads)	HTTPError)urlparse)segments   )api)get_default_hostfile_segmentz(Duncan Macleod <duncan.macleod@ligo.org>HTTPConnectionHTTPSConnectionc               @   s   e Zd ZdZddejd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 Zd&ddZd'ddZdd  ZdS )(r   a  Connect to a GWDataFind host using HTTP.

    .. warning::

        This class is deprecated and will be removed in a future release.
        Use the functions from the :ref:`gwdatafind-top-api` instead.

    Parameters
    ----------
    host : `str`
        the name of the server with which to connect.

    port : `int`, optional
        the port on which to connect.

    kwargs
        other keywords are passed directly to `http.client.HTTPConnection`
    Nc             K   s6   t dt |dkrt }tjj| ||||f| dS )z!Create a new connection.
        zmthis class is deprecated and will be removed in a future release, please use the gwdatafind.ui module insteadN)warningswarnDeprecationWarningr	   http_clientr   __init__)selfhostporttimeoutsource_addresskwargs r   \/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/gwdatafind/http.pyr   ;   s    zHTTPConnection.__init__c             K   sT   | dsd| }| j||f| |  }|jdkrPt||j|j| |j|S )a  Internal method to perform request and verify reponse.

        Parameters
        ----------
        method : `str`
            name of the method to use (e.g. ``'GET'``).

        url : `str`
            remote URL to query.

        kwargs
            other keyword arguments are passed to
            :meth:`http.client.HTTPConnection.request`.

        Returns
        -------
        response : `str`
            reponse from server query

        Raises
        ------
        RuntimeError
            if query is unsuccessful
        /   )
startswithrequestgetresponsestatusr   reason
getheadersfp)r   methodurlr   responser   r   r   _request_responseJ   s    


z HTTPConnection._request_responsec             K   s0   | j d|f| }t|tr(|d}t|S )a  Perform a 'GET' request and return the decode the result as JSON

        Parameters
        ----------
        url : `str`
            remote URL to query

        kwargs
            other keyword arguments are passed to
            :meth:`HTTPConnection._request_response`

        Returns
        -------
        data : `object`
            JSON decoded using :func:`json.loads`
        GETzutf-8)r&   read
isinstancebytesdecoder   )r   r$   r   r%   r   r   r   get_jsonl   s    

zHTTPConnection.get_jsonignorec                sX   | j |f|} r(tt fdd|}|sTd}|dkrDt| n|dkrTt||S )a  Perform a 'GET' request and return a list of URLs.

        Parameters
        ----------
        url : `str`
            remote URL to query

        scheme : `str`, `None`, optional
            the URL scheme to match, default: `None`

        on_missing : `str`, optional
            how to handle an empty (but successful) response, one of

            - ``'ignore'``: do nothing, return empty `list`
            - ``'warn'``: print warning, return empty `list`
            - ``'raise'``: raise `RuntimeError`

        kwargs
            other keyword arguments are passed to
            :meth:`HTTPConnection.get_json`

        Returns
        -------
        urls : `list` of `str`
            a list of file paths as returned from the server.
        c                s   t | j kS )N)r   scheme)e)r.   r   r   <lambda>       z)HTTPConnection.get_urls.<locals>.<lambda>zno files foundr   r-   )r,   listfilterr   r   RuntimeError)r   r$   r.   
on_missingr   urlserrr   )r.   r   get_urls   s    zHTTPConnection.get_urlsc             C   s   |  dt  dS )z~Ping the LDR host to test for life.

        Raises
        ------
        RuntimeError
            if the ping fails
        HEADr   )r&   r   Z	ping_path)r   r   r   r   ping   s    zHTTPConnection.pingc                s:   t | t }|r2t|  fdd|D S t|S )a  Query the LDR host for observatories.

        Parameters
        ----------
        match : `str`, `re.Pattern`
            restrict returned observatories to those matching a
            regular expression.

        Returns
        -------
        obs : `list` of `str`
            the list of known osbervatory prefices (and combinations)

        Examples
        --------
        >>> from gwdatafind import connect
        >>> conn = connect()
        >>> conn.find_observatories()
        ['AGHLT', 'G', 'GHLTV', 'GHLV', 'GHT', 'H', 'HL', 'HLT',
         'L', 'T', 'V', 'Z']
        >>> conn.find_observatories("H")
        ['H', 'HL', 'HLT']
        c                s   g | ]}  |r|qS r   )search).0site)regmatchr   r   
<listcomp>   s    z5HTTPConnection.find_observatories.<locals>.<listcomp>)setr,   r   Zfind_observatories_pathrecompiler2   )r   matchZsitelistr   )r>   r   find_observatories   s
    
z!HTTPConnection.find_observatoriesc                sB   t j|d}t| |}|r:t|  fdd|D S t|S )a  Query the LDR host for frame types.

        Parameters
        ----------
        site : `str`
            single-character name of site to match

        match : `str`, `re.Pattern`
            regular expression to match against known types

        Returns
        -------
        types  : `list` of `str`
            list of frame types

        Examples
        --------
        >>> from gwdatafind import connect
        >>> conn = connect()
        >>> conn.find_types("L", "RDS")
        ['L1_RDS_C01_LX',
         'L1_RDS_C02_LX',
         'L1_RDS_C03_L2',
         'L1_RDS_R_L1',
         'L1_RDS_R_L3',
         'L1_RDS_R_L4',
         'PEM_RDS_A6',
         'RDS_R_L1',
         'RDS_R_L2',
         'RDS_R_L3',
         'TESTPEM_RDS_A6']
        )r=   c                s   g | ]}  |r|qS r   )r;   )r<   type_)r>   r   r   r?      s    z-HTTPConnection.find_types.<locals>.<listcomp>)r   Zfind_types_pathr@   r,   rA   rB   r2   )r   r=   rC   pathZtypelistr   )r>   r   
find_types   s    !
zHTTPConnection.find_typesc             C   s<   t |||ptd|ptd}| |}tttj|S )a  Query the LDR for times for which files are avaliable.

        Parameters
        ----------
        site : `str`
            single-character name of site to match

        frametype : `str`
            name of frametype to match

        gpsstart : `int`
            GPS start time of query

        gpsend : `int`
            GPS end time of query

        Returns
        -------
        segments : `ligo.segments.segmentlist`
            the list of `[start, stop)` intervals for which files are
            available.
        r   g    eA)r   Zfind_times_pathintr,   r   segmentlistmapsegment)r   r=   	frametypegpsstartgpsendrF   rI   r   r   r   
find_times   s    

zHTTPConnection.find_timesfileerrorc             C   s   t |}| j|||dS )a  Query the LDR host for a single filename.

        Parameters
        ----------
        framefile : `str`
            base name of file to match

        urltype : `str`, optional
            file scheme to search for, one of ``'file'``, ``'gsiftp'``, or
            `None`, default: 'file'

        on_missing : `str`
            what to do when the requested file isn't found, one of:

            - ``'warn'``: print a warning (default),
            - ``'error'``: raise a `RuntimeError`, or
            - ``'ignore'``: do nothing

        Returns
        -------
        urls : `list` of `str`
            a list of structured file paths for all instances of ``filename``.
        )r.   r5   )r   Zfind_url_pathr8   )r   Z	framefileurltyper5   rF   r   r   r   find_url   s    
zHTTPConnection.find_urlc             O   s   t dt | j||S )zBDEPRECATED, use :meth:`~HTTPConnection.find_url` instead.
        z#find_frame() was renamed find_url())r   r   r   rS   )r   argsr   r   r   r   
find_frame;  s    zHTTPConnection.find_framec             C   s    t j|||d}| j|||dS )aQ  Query for the most recent file of a given type.

        Parameters
        ----------
        site : `str`
            single-character name of site to match

        frametype : `str`
            name of frametype to match

        urltype : `str`, optional
            file scheme to search for, one of 'file', 'gsiftp', or
            `None`, default: 'file'

        on_missing : `str`, optional
            what to do when the requested frame isn't found, one of:

            - ``'warn'`` print a warning (default), or
            - ``'error'``: raise a `RuntimeError`, or
            - ``'ignore'``: do nothing

        Returns
        -------
        latest : `list` with one `str`
            the URLs of the latest file found (all file types)

        Raises
        ------
        RuntimeError
            if no frames are found
        )rR   )r.   r5   )r   Zfind_latest_pathr8   )r   r=   rL   rR   r5   rF   r   r   r   find_latestB  s     zHTTPConnection.find_latestr   c             C   s   t j||||||d}| |}	|dkr,|	S t||}
ttt|	 }t|
g|  }|sh|	S dd	tt
| }|dkrt| |	S t|dS )a  Find all files of the given type in the [start, end) GPS interval.

        site : `str`
            single-character name of site to match

        frametype : `str`
            name of frametype to match

        gpsstart : `int`
            integer GPS start time of query

        gpsend : `int`
            integer GPS end time of query

        match : `str`, `re.Pattern`, optional
            regular expression to match against

        urltype : `str`, optional
            file scheme to search for, one of 'file', 'gsiftp', or
            `None`, default: 'file'

        on_gaps : `str`, optional
            what to do when the requested frame isn't found, one of:

            - ``'warn'`` print a warning (default), or
            - ``'error'``: raise a `RuntimeError`, or
            - ``'ignore'``: do nothing

        Returns
        -------
        cache : `list` of `str`
            the list of discovered file URLs
        )rR   rC   r-   zMissing segments: 
%s
r   N)r   Zfind_urls_pathr8   r   rK   rI   rJ   r
   Zcoalescejoinstrr   r   r4   )r   r=   rL   rM   rN   rC   rR   Zon_gapsrF   r6   spanZseglistmissingmsgr   r   r   	find_urlse  s(    $

zHTTPConnection.find_urlsc             O   s   t dt | j||S )zCDEPRECATED, use :meth:`~HTTPConnection.find_urls` instead.
        z)find_frame_urls() was renamed find_urls())r   r   r   r]   )r   rT   r   r   r   r   find_frame_urls  s    zHTTPConnection.find_frame_urls)Nr-   )N)NN)NN)rP   rQ   )rP   rQ   )NrP   r   )__name__
__module____qualname____doc__socket_GLOBAL_DEFAULT_TIMEOUTr   r&   r,   r8   r:   rD   rG   rO   rS   rU   rV   r]   r^   r   r   r   r   r   (   s   "
-

(
 

$
?c               @   s   e Zd ZdZdddZdS )r   a  Connect to a GWDataFind host using HTTPS.

    .. warning::

        This class is deprecated and will be removed in a future release.
        Use the functions from the :ref:`gwdatafind-top-api` instead.

    This requires a valid X509 credential registered with the remote host.

    Parameters
    ----------
    host : `str`
        the name of the server with which to connect.

    port : `int`, optional
        the port on which to connect.

    kwargs
        other keywords are passed directly to `http.client.HTTPSConnection`
    Nc             K   s,   |dkrt  }tjj| |fd|i| dS )z!Create a new connection.
        Nr   )r	   r   r   r   )r   r   r   r   r   r   r   r     s    zHTTPSConnection.__init__)NN)r_   r`   ra   rb   r   r   r   r   r   r     s   )rb   rA   rc   r   httpr   r   jsonr   urllib.errorr   urllib.parser   Zligor    r   utilsr	   r
   
__author____all__r   r   r   r   r   r   <module>   s"      