³ò
ƒrÓFc           @   sø   d  Z  d Z d d k Z d d k Z d d k Z d d k Z d d k Z d d k Z y d d k l	 Z
 WnI e j
 o= y d d k	 Z
 Wn# e j
 o d d k l
 Z
 n Xn Xe i d ƒ Z d e f d „  ƒ  YZ e d	 „ Z e e d
 „ Z d S(   sK  AtomService provides CRUD ops. in line with the Atom Publishing Protocol.

  AtomService: Encapsulates the ability to perform insert, update and delete
               operations with the Atom Publishing Protocol on which GData is
               based. An instance can perform query, insertion, deletion, and
               update.
s   api.jscudder (Jeffrey Scudder)iÿÿÿÿN(   t   cElementTree(   t   ElementTrees&   http(s)?\://([\w\.-]*)(\:(\d+))?(/.*)?t   AtomServicec           B   s¶   e  Z d  Z d Z e Z e Z e Z d d d „ Z	 e d „ Z
 e d „ Z d „  Z d d e d „ Z d d e d „ Z d d e d d	 „ Z d d e d d
 „ Z d d e d „ Z RS(   s}   Performs Atom Publishing Protocol CRUD operations.
  
  The AtomService contains methods to perform HTTP CRUD operations. 
  iP   c         C   s*   | |  _  | p h  |  _ d |  i d <d S(   si  Creates a new AtomService client.
    
    Args:
      server: string (optional) The start of a URL for the server
              to which all operations should be directed. Example: 
              'www.google.com'
      additional_headers: dict (optional) Any additional HTTP headers which
                          should be included with CRUD operations.
    s   Python Google Data Client Libs
   User-AgentN(   t   servert   additional_headers(   t   selfR   R   (    (    s@   /afs/sipb.mit.edu/project/freeculture/lib/python/atom/service.pyt   __init__:   s    	c         C   s  |  i  } | o d } t } n |  i } |  i } | } t i | ƒ } | d	 j o | | | | f Sn³ | i d ƒ d	 j	 o d } t } n | i d ƒ d	 j o | i d ƒ } n% | i d ƒ } t	 | i d ƒ ƒ } | i d ƒ d	 j	 o | i d ƒ } n d } | | | | f Sd	 S(
   sr   Processes a passed URL.  If the URL does not begin with https?, then
    the default value for self.server is usediP   i   i»  i   i   i   i   t   /N(
   R   t   Falset   portt   sslt	   URL_REGEXt   matcht   Nonet   groupt   Truet   int(   R   t   urlt	   for_proxyR   R	   R
   t   urit   m(    (    s@   /afs/sipb.mit.edu/project/freeculture/lib/python/atom/service.pyt   _ProcessUrlJ   s*    	
		
c         C   sT   t  i d | | f ƒ } | i ƒ  } | o
 d } n d } d | f |  i | <d S(   s6  Sets an Authenticaiton: Basic HTTP header containing plaintext.
    
    The username and password are base64 encoded and added to an HTTP header
    which will be included in each request. Note that your username and 
    password are sent in plaintext.

    Args:
      username: str
      password: str
    s   %s:%ss   Proxy-Authorizationt   Authorizations   Basic %sN(   t   base64t   encodestringt   stripR   (   R   t   usernamet   passwordR   t   base_64_stringt   header_name(    (    s@   /afs/sipb.mit.edu/project/freeculture/lib/python/atom/service.pyt   UseBasicAuthj   s    
c         C   sú  |  i  | ƒ \ } } } } | oÙt i i d ƒ } | o¤|  i  | t ƒ \ } } }	 }
 t i i d ƒ } t i i d ƒ } | o+ t i d | | f ƒ } d | d } n d } d | | f } d	 |  i d
 } | | | d } t i t i	 t i
 ƒ } | i | | f ƒ | i | ƒ d } x. | i d ƒ d j o | | i d ƒ 7} q)W| i ƒ  d } | t d ƒ j o d t | ƒ ‚ n t i | d  d  ƒ } t i | | ƒ } t i d ƒ } | | _ | } t |  _ qðt i | | ƒ } | } nö t i i d ƒ } | oÄ |  i  | t ƒ \ } } }	 }
 t i i d ƒ } t i i d ƒ } | o |  i | | t ƒ n t i | | ƒ } | i d ƒ p> | i d ƒ o d |  i | f } qÔd |  i | f } qðn t i | | ƒ } | } | | f S(   Nt   https_proxys   proxy-usernames   proxy-passwords   %s:%ss   Proxy-authorization: Basic s   
t    s   CONNECT %s:%s HTTP/1.0
s   User-Agent: %s
s
   User-Agents   

iÿÿÿÿi    i   iÈ   s   Error status=t	   localhostt
   http_proxys   http://R   s   http://%s%ss   http://%s/%s(   R   t   ost   environt   getR   R   R   R   t   sockett   AF_INETt   SOCK_STREAMt   connectt   sendallt   findt   recvt   splitt   strR
   R   t   httplibt
   FakeSockett   HTTPConnectiont   sockt	   skip_hostt   HTTPSConnectionR   t
   startswithR   (   R   t   full_uriR   R	   R
   t   partial_urit   proxyt   p_servert   p_portt   p_sslt   p_urit   proxy_usernamet   proxy_passwordt	   user_passt   proxy_authorizationt   proxy_connectt
   user_agentt   proxy_piecest   p_sockt   responset   p_statust	   fake_sockt
   connection(    (    s@   /afs/sipb.mit.edu/project/freeculture/lib/python/atom/service.pyt   _PrepareConnection~   s`    	
c   	      C   sà   t  | | | ƒ } |  i | ƒ \ } } | i | | d |  i ƒt |  i t ƒ o/ x, |  i D] } | i | |  i | ƒ q] Wn t | t ƒ o) x& | D] } | i | | | ƒ q™ Wn | i ƒ  |  i	 o d | _
 n | S(   NR3   i   (   t   BuildUriRI   t
   putrequestR3   t
   isinstanceR   t   dictt	   putheadert
   endheaderst   debugt
   debuglevel(	   R   R   t   http_operationt   extra_headerst
   url_paramst   escape_paramsR6   RH   t   header(    (    s@   /afs/sipb.mit.edu/project/freeculture/lib/python/atom/service.pyt   _CreateConnectionÆ   s    
  

c         C   s%   |  i  | d | | | ƒ } | i ƒ  S(   s;  Query the APP server with the given URI

    The uri is the portion of the URI after the server value 
    (server example: 'www.google.com').

    Example use:
    To perform a query against Google Base, set the server to 
    'base.google.com' and set the uri to '/base/feeds/...', where ... is 
    your query. For example, to find snippets for all digital cameras uri 
    should be set to: '/base/feeds/snippets?bq=digital+camera'

    Args:
      uri: string The query in the form of a URI. Example:
           '/base/feeds/snippets?bq=digital+camera'.
      extra_headers: dicty (optional) Extra HTTP headers to be included
                     in the GET request. These headers are in addition to 
                     those stored in the client's additional_headers property.
                     The client automatically sets the Content-Type and 
                     Authorization headers.
      url_params: dict (optional) Additional URL parameters to be included
                  in the query. These are translated into query arguments
                  in the form '&dict_key=value&...'.
                  Example: {'max-results': '250'} becomes &max-results=250
      escape_params: boolean (optional) If false, the calling code has already
                     ensured that the query will form a valid URL (all
                     reserved characters have been escaped). If true, this
                     method will escape the query and any URL parameters
                     provided.

    Returns:
      httplib.HTTPResponse The server's response to the GET request.
    t   GET(   RW   t   getresponse(   R   R   RS   RT   RU   t   query_connection(    (    s@   /afs/sipb.mit.edu/project/freeculture/lib/python/atom/service.pyt   GetÜ   s    "s   application/atom+xmlc   	      C   s{   t  i | ƒ o t  i | ƒ } n t | ƒ } t | ƒ | d <| | d <|  i | d | | | ƒ } | i | ƒ | i ƒ  S(   s¯  Insert data into an APP server at the given URI.

    Args:
      data: string, ElementTree._Element, or something with a __str__ method 
            The XML to be sent to the uri. 
      uri: string The location (feed) to which the data should be inserted. 
           Example: '/base/feeds/items'. 
      extra_headers: dict (optional) HTTP headers which are to be included. 
                     The client automatically sets the Content-Type,
                     Authorization, and Content-Length headers.
      url_params: dict (optional) Additional URL parameters to be included
                  in the URI. These are translated into query arguments
                  in the form '&dict_key=value&...'.
                  Example: {'max-results': '250'} becomes &max-results=250
      escape_params: boolean (optional) If false, the calling code has already
                     ensured that the query will form a valid URL (all
                     reserved characters have been escaped). If true, this
                     method will escape the query and any URL parameters
                     provided.

    Returns:
      httplib.HTTPResponse Server's response to the POST request.
    s   Content-Lengths   Content-Typet   POST(   R   t	   iselementt   tostringR.   t   lenRW   t   sendRY   (	   R   t   dataR   RS   RT   RU   t   content_typet   data_strt   insert_connection(    (    s@   /afs/sipb.mit.edu/project/freeculture/lib/python/atom/service.pyt   Post  s    
c   	      C   s{   t  i | ƒ o t  i | ƒ } n t | ƒ } t | ƒ | d <| | d <|  i | d | | | ƒ } | i | ƒ | i ƒ  S(   s­  Updates an entry at the given URI.
     
    Args:
      data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The 
            XML containing the updated data.
      uri: string A URI indicating entry to which the update will be applied.
           Example: '/base/feeds/items/ITEM-ID'
      extra_headers: dict (optional) HTTP headers which are to be included.
                     The client automatically sets the Content-Type,
                     Authorization, and Content-Length headers.
      url_params: dict (optional) Additional URL parameters to be included
                  in the URI. These are translated into query arguments
                  in the form '&dict_key=value&...'.
                  Example: {'max-results': '250'} becomes &max-results=250
      escape_params: boolean (optional) If false, the calling code has already
                     ensured that the query will form a valid URL (all
                     reserved characters have been escaped). If true, this
                     method will escape the query and any URL parameters
                     provided.
  
    Returns:
      httplib.HTTPResponse Server's response to the PUT request.
    s   Content-Lengths   Content-Typet   PUT(   R   R]   R^   R.   R_   RW   R`   RY   (	   R   Ra   R   RS   RT   RU   Rb   Rc   t   update_connection(    (    s@   /afs/sipb.mit.edu/project/freeculture/lib/python/atom/service.pyt   Put*  s    
c         C   s%   |  i  | d | | | ƒ } | i ƒ  S(   s  Deletes the entry at the given URI.

    Args:
      uri: string The URI of the entry to be deleted. Example: 
           '/base/feeds/items/ITEM-ID'
      extra_headers: dict (optional) HTTP headers which are to be included.
                     The client automatically sets the Content-Type and
                     Authorization headers.
      url_params: dict (optional) Additional URL parameters to be included
                  in the URI. These are translated into query arguments
                  in the form '&dict_key=value&...'.
                  Example: {'max-results': '250'} becomes &max-results=250
      escape_params: boolean (optional) If false, the calling code has already
                     ensured that the query will form a valid URL (all
                     reserved characters have been escaped). If true, this
                     method will escape the query and any URL parameters
                     provided.

    Returns:
      httplib.HTTPResponse Server's response to the DELETE request.
    t   DELETE(   RW   RY   (   R   R   RS   RT   RU   t   delete_connection(    (    s@   /afs/sipb.mit.edu/project/freeculture/lib/python/atom/service.pyt   DeleteQ  s    N(   t   __name__t
   __module__t   __doc__R	   R   R
   RP   R3   R   R   R   R   RI   R   RW   R[   Re   Rh   Rk   (    (    (    s@   /afs/sipb.mit.edu/project/freeculture/lib/python/atom/service.pyR   ,   s$    	H'&&c   	      C   s‡   t  t i g t | ƒ } g  } |  p h  i ƒ  D]% \ } } | | | ƒ | | ƒ f q1 ~ } g  } | D] } | d i | ƒ qj ~ S(   sì  Convert a dictionary of URL arguments into a URL parameter string.

  Args:
    url_parameters: The dictionaty of key-value pairs which will be converted
                    into URL parameters. For example,
                    {'dry-run': 'true', 'foo': 'bar'}
                    will become ['dry-run=true', 'foo=bar'].

  Returns:
    A list which contains a string for each key-value pair. The strings are
    ready to be incorporated into a URL by using '&'.join([] + parameter_list)
  t   =(   R.   t   urllibt
   quote_plust   boolt   itemst   join(	   t   url_parametersRU   t   transform_opt   _[1]t   paramt   valuet   parameter_tuplest   _[2]t   x(    (    s@   /afs/sipb.mit.edu/project/freeculture/lib/python/atom/service.pyt   DictionaryToParamListm  s    ?c         C   su   t  | | ƒ } | oU |  i d ƒ d j o d i |  g | ƒ } qq d |  d d i g  | ƒ f } n |  } | S(   s)  Converts a uri string and a collection of parameters into a URI.

  Args:
    uri: string
    url_params: dict (optional)
    escape_params: boolean (optional)
    uri: string The start of the desired URI. This string can alrady contain
         URL parameters. Examples: '/base/feeds/snippets', 
         '/base/feeds/snippets?bq=digital+camera'
    url_parameters: dict (optional) Additional URL parameters to be included
                    in the query. These are translated into query arguments
                    in the form '&dict_key=value&...'.
                    Example: {'max-results': '250'} becomes &max-results=250
    escape_params: boolean (optional) If false, the calling code has already
                   ensured that the query will form a valid URL (all
                   reserved characters have been escaped). If true, this
                   method will escape the query and any URL parameters
                   provided.

  Returns:
    string The URI consisting of the escaped URL parameters appended to the
    initial uri string.
  t   ?iÿÿÿÿt   &s   %s%ss   ?%s(   R}   R+   Rt   (   R   RT   RU   t   parameter_listR6   (    (    s@   /afs/sipb.mit.edu/project/freeculture/lib/python/atom/service.pyRJ   ‡  s    %(   Rn   t
   __author__R#   R/   Rp   t   reR   R&   t	   xml.etreeR    R   t   ImportErrort   elementtreet   compileR   t   objectR   R   R}   R   RJ   (    (    (    s@   /afs/sipb.mit.edu/project/freeculture/lib/python/atom/service.pys   <module>   s&   ÿ B