Ñò
äÒÔPc           @   s€  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 d d k Z d d k Z d d k	 Z	 d d k
 Z
 y d d k Z WnI e j
 o= y d d k l Z Wn e j
 o d d k Z n Xn Xe i Z y d d k l Z Wn# e j
 o d d k l Z n Xd e f d „  ƒ  YZ d e f d „  ƒ  YZ d	 „  Z d
 „  Z e e d „ Z d „  Z d „  Z d S(   sÌ  Python client library for the Facebook Platform.

This client library is designed to support the Graph API and the
official Facebook JavaScript SDK, which is the canonical way to
implement Facebook authentication. Read more about the Graph API at
http://developers.facebook.com/docs/api. You can download the Facebook
JavaScript SDK at http://github.com/facebook/connect-js/.

If your application is using Google AppEngine's webapp framework, your
usage of this module might look like this:

user = facebook.get_user_from_cookie(self.request.cookies, key, secret)
if user:
    graph = facebook.GraphAPI(user["access_token"])
    profile = graph.get_object("me")
    friends = graph.get_connections("me", "friends")

iÿÿÿÿN(   t
   simplejson(   t   parse_qst   GraphAPIc           B   s³   e  Z d  Z d d d „ Z d „  Z d „  Z d „  Z d „  Z h  d d „ Z	 d „  Z
 d	 „  Z d
 „  Z d „  Z d d d „ Z d „  Z d d d „ Z d d d „ Z d „  Z RS(   sŒ  A client for the Facebook Graph API.

    See http://developers.facebook.com/docs/api for complete
    documentation for the API.

    The Graph API is made up of the objects in Facebook (e.g., people,
    pages, events, photos) and the connections between them (e.g.,
    friends, photo tags, and event RSVPs). This client provides access
    to those primitive types in a generic way. For example, given an
    OAuth access token, this will fetch the profile of the active user
    and the list of the user's friends:

       graph = facebook.GraphAPI(access_token)
       user = graph.get_object("me")
       friends = graph.get_connections(user["id"], "friends")

    You can see a list of all of the objects and connections supported
    by the API at http://developers.facebook.com/docs/reference/api/.

    You can obtain an access token via OAuth or by using the Facebook
    JavaScript SDK. See
    http://developers.facebook.com/docs/authentication/ for details.

    If you are using the JavaScript SDK, you can use the
    get_user_from_cookie() method below to get the OAuth access token
    for the active user from the cookie saved by the SDK.

    c         C   s   | |  _  | |  _ d  S(   N(   t   access_tokent   timeout(   t   selfR   R   (    (    s   facebook.pyt   __init__]   s    	c         K   s   |  i  | | ƒ S(   s'   Fetchs the given object from the graph.(   t   request(   R   t   idt   args(    (    s   facebook.pyt
   get_objecta   s    c         K   s#   d i  | ƒ | d <|  i d | ƒ S(   s¡   Fetchs all of the given object from the graph.

        We return a map from ID to object. If any of the IDs are
        invalid, we raise an exception.
        t   ,t   idst    (   t   joinR   (   R   R   R	   (    (    s   facebook.pyt   get_objectse   s    c         K   s   |  i  | d | | ƒ S(   s(   Fetchs the connections for given object.t   /(   R   (   R   R   t   connection_nameR	   (    (    s   facebook.pyt   get_connectionsn   s    c         K   s/   |  i  p
 t d ‚ |  i | d | d | ƒS(   s]  Writes the given object to the graph, connected to the given parent.

        For example,

            graph.put_object("me", "feed", message="Hello, world")

        writes "Hello, world" to the active user's wall. Likewise, this
        will comment on a the first post of the active user's feed:

            feed = graph.get_connections("me", "feed")
            post = feed["data"][0]
            graph.put_object(post["id"], "comments", message="First!")

        See http://developers.facebook.com/docs/api#publishing for all
        of the supported writeable objects.

        Certain write operations require extended permissions. For
        example, publishing to a user's feed requires the
        "publish_actions" permission. See
        http://developers.facebook.com/docs/publishing/ for details
        about publishing permissions.

        s(   Write operations require an access tokenR   t	   post_args(   R   t   AssertionErrorR   (   R   t   parent_objectR   t   data(    (    s   facebook.pyt
   put_objectr   s    t   mec         C   s   |  i  | d d | | S(   sI  Writes a wall post to the given profile's wall.

        We default to writing to the authenticated user's wall if no
        profile_id is specified.

        attachment adds a structured attachment to the status message
        being posted to the Wall. It should be a dictionary of the form:

            {"name": "Link name"
             "link": "http://www.example.com/",
             "caption": "{*actor*} posted a new review",
             "description": "This is a longer description of the attachment",
             "picture": "http://www.example.com/thumbnail.jpg"}

        t   feedt   message(   R   (   R   R   t
   attachmentt
   profile_id(    (    s   facebook.pyt   put_wall_postŽ   s    c         C   s   |  i  | d d | ƒS(   s+   Writes the given comment on the given post.t   commentsR   (   R   (   R   t	   object_idR   (    (    s   facebook.pyt   put_comment¡   s    c         C   s   |  i  | d ƒ S(   s   Likes the given post.t   likes(   R   (   R   R   (    (    s   facebook.pyt   put_like¥   s    c         C   s   |  i  | d h d d 6ƒd S(   s4   Deletes the object with the given ID from the graph.R   t   deletet   methodN(   R   (   R   R   (    (    s   facebook.pyt   delete_object©   s    c         C   s®   t  i d ƒ } d | | t i h |  i d 6ƒ f } | i d | ƒ | i ƒ  } | i ƒ  } t | ƒ } | o0 t	 | t
 ƒ o  | i d ƒ o t | ƒ ‚ n | i ƒ  d S(   s9   Deletes the Request with the given ID for the given user.s   graph.facebook.coms	   /%s_%s?%sR   t   DELETEt   errorN(   t   httplibt   HTTPSConnectiont   urllibt	   urlencodeR   R   t   getresponset   readt   _parse_jsont
   isinstancet   dictt   gett   GraphAPIErrort   close(   R   t   user_idt
   request_idt   connt   urlt   responseR   (    (    s   facebook.pyt   delete_request­   s    'c      	   K   s  | p d } h |  i  d 6| d 6| d 6} | i | ƒ |  i | ƒ \ } } t i d | d | ƒ}	 |	 i d | ƒ y t i |	 ƒ i ƒ  }
 Wn$ t i j
 o } | i ƒ  }
 n XyG t	 |
 ƒ } | o0 t
 | t ƒ o  | i d ƒ o t | ƒ ‚ n Wn t j
 o |
 } n X| S(	   sú   Uploads an image using multipart/form-data.

        image=File like object for the image
        message=Caption for your image
        album_id=None posts to /me/photos which uses or creates and uses
        an album for your application.

        R   R   t   sourceR   s$   https://graph.facebook.com/%s/photosR   s   Content-TypeR'   (   R   t   updatet   _encode_multipart_formt   urllib2t   Requestt
   add_headert   urlopenR-   t	   HTTPErrorR.   R/   R0   R1   R2   t
   ValueError(   R   t   imageR   t   album_idt   kwargsR   R   t   content_typet   bodyt   reqR   t   eR8   (    (    s   facebook.pyt	   put_photoÂ   s.    	

		c   
      C   s‹  d } d } g  } x1| i  ƒ  D]#\ } } t i d | t | ƒ | f ƒ | p q n | i d | ƒ t | d ƒ om t | i ƒ o] t | d d | ƒ } | i d | | f ƒ | i d	 ƒ | i ƒ  } t i t | ƒ ƒ n | i d
 | ƒ | i d ƒ t	 | t
 ƒ o  t i d ƒ | i d ƒ } n | i | ƒ q W| i d | d ƒ | i d ƒ | i | ƒ } d | }	 |	 | f S(   s%  Encode files as 'multipart/form-data'.

        Fields are a dict of form name-> value. For files, value should
        be a file object. Other file-like objects might work and a fake
        name will be chosen.

        Returns (content_type, body) ready for httplib.HTTP instance.

        s    ----------ThIs_Is_tHe_bouNdaRY_$s   
s   Encoding %s, (%s)%ss   --R-   t   names   %s.jpgs6   Content-Disposition: form-data;name="%s";filename="%s"s   Content-Type: image/jpegs)   Content-Disposition: form-data; name="%s"R   s   Convert to asciit   asciis    multipart/form-data; boundary=%s(   t   itemst   loggingt   debugt   typet   appendt   hasattrt   callableR-   t   getattrR/   t   unicodet   encodeR   (
   R   t   fieldst   BOUNDARYt   CRLFt   Lt   keyt   valuet   filenameRG   RF   (    (    s   facebook.pyR<   í   s6    
   	
c   
   
   C   s  | p h  } |  i  o/ | d j	 o |  i  | d <qF |  i  | d <n | d j o d n t i | ƒ } y4 t i d | d t i | ƒ | d |  i ƒ} Wn t i j
 o' } t | i	 ƒ  ƒ } t
 | ƒ ‚ nY t j
 oL |  i o t i |  i ƒ n t i d | d t i | ƒ | ƒ } n Xz„ | i ƒ  } | i d j o t | i	 ƒ  ƒ } nO | i d j o2 | d }	 h | i	 ƒ  d 6|	 d	 6| i d
 6} n t
 d ƒ ‚ Wd | i ƒ  X| oC t | t ƒ o3 | i d ƒ o# t
 | d d | d d ƒ ‚ n | S(   sÐ   Fetches the given path in the Graph API.

        We translate args to a valid query string. If post_args is
        given, we send a POST request to the given path with the given
        arguments.

        R   s   https://graph.facebook.com/t   ?R   t   textRC   s   content-typeR   s	   mime-typeR7   s   Maintype was not text or imageNR'   RP   R   (   R   t   NoneR*   R+   R=   R@   R   RA   R.   R-   R2   t	   TypeErrort   sockett   setdefaulttimeoutt   infot   maintypeR7   R3   R/   R0   R1   (
   R   t   pathR	   R   t	   post_datat   fileRI   R8   t   fileInfot   mimetype(    (    s   facebook.pyR     sD    
#

'c   
      C   s¶  | p h  } |  i  o/ | d j	 o |  i  | d <qF |  i  | d <n | d j o d n t i | ƒ } t | t ƒ p | | d <d } n | | d <d } d | d <y4 t i d | d	 t i | ƒ | d
 |  i ƒ} WnX t	 j
 oL |  i o t
 i |  i ƒ n t i d | d	 t i | ƒ | ƒ } n Xzn yL | i ƒ  } t | ƒ } t | ƒ t j o d | j o t | ƒ ‚ n Wn t j
 o }	 |	 ‚ n XWd | i ƒ  X| S(   s]   FQL query.

        Example query: "SELECT affiliations FROM user WHERE uid = me()"

        R   t   queriess   fql.multiqueryt   querys	   fql.queryt   jsont   formats    https://api.facebook.com/method/R^   R   t
   error_codeN(   R   R`   R*   R+   R/   t
   basestringR=   R@   R   Ra   Rb   Rc   R-   R.   RP   R0   R2   t	   ExceptionR3   (
   R   Rl   R	   R   Rg   t
   fql_methodRh   t   contentR8   RI   (    (    s   facebook.pyt   fqlE  s@    
#




  c         C   s¼   h | d 6| d 6d d 6|  i  d 6} t i d t i | ƒ ƒ i ƒ  } t | ƒ } d | j o= h | d d d 6} d | j o | d d | d <n | St i | ƒ } t | ƒ ‚ d	 S(
   s±   
        Extends the expiration time of a valid OAuth access token. See
        <https://developers.facebook.com/roadmap/offline-access-removal/
        #extend_token>

        t	   client_idt   client_secrett   fb_exchange_tokent
   grant_types.   https://graph.facebook.com/oauth/access_token?R   i    t   expiresN(	   R   R*   R@   R+   R-   R   Rm   t   loadsR2   (   R   t   app_idt
   app_secretR	   R8   t	   query_strt   result(    (    s   facebook.pyt   extend_access_tokeny  s    	N(   t   __name__t
   __module__t   __doc__R`   R   R
   R   R   R   R   R    R"   R%   R9   RJ   R<   R   Rt   R   (    (    (    s   facebook.pyR   @   s    									+	'14R2   c           B   s   e  Z d  „  Z RS(   c      	   C   s¢   | |  _  y | d |  _ Wn d |  _ n Xy | d |  _ WnJ y | d d |  _ Wq‹ y | d |  _ Wq‡ | |  _ q‡ Xq‹ Xn Xt i |  |  i ƒ d  S(   NRo   R   t   error_descriptionR'   R   t	   error_msg(   R~   RP   R   Rq   R   (   R   R~   (    (    s   facebook.pyR   •  s     	(   R€   R   R   (    (    (    s   facebook.pyR2   ”  s   c         C   sƒ   |  i  d | d ƒ } | p d St | | ƒ } | p d Sy t | d d | | ƒ } Wn t j
 o d SX| d | d <| S(   s„  Parses the cookie set by the official Facebook JavaScript SDK.

    cookies should be a dictionary-like object mapping cookie names to
    cookie values.

    If the user is logged in via Facebook, we return a dictionary with
    the keys "uid" and "access_token". The former is the user's
    Facebook ID, and the latter can be used to make authenticated
    requests to the Graph API. If the user is not logged in, we
    return None.

    Download the official Facebook JavaScript SDK at
    http://github.com/facebook/connect-js/. Read more about Facebook
    authentication at
    http://developers.facebook.com/docs/authentication/.

    t   fbsr_R   t   codeR4   t   uidN(   R1   R`   t   parse_signed_requestt   get_access_token_from_codeR2   (   t   cookiesR{   R|   t   cookiet   parsed_requestR~   (    (    s   facebook.pyt   get_user_from_cookie¯  s    c      	   C   s:  yˆ |  i  d d ƒ } t | d ƒ } t | d ƒ } t i | d d t | ƒ d d ƒ } t i | d d t | ƒ d d ƒ } Wn' t j
 o t St j
 o t SXt | ƒ } | i	 d d ƒ i
 ƒ  d	 j o t S| i d
 ƒ } | i d
 ƒ } t i | d | d t i ƒi ƒ  } | | j o t S| S(   s<   Return dictionary with signed request data.

    We return a dictionary containing the information in the
    signed_request. This includes a user_id if the user has authorised
    your application, as well as any information requested.

    If the signed_request is malformed or corrupted, False is returned.

    t   .i   i    i   t   =i   t	   algorithmR   s   HMAC-SHA256RL   t   msgt	   digestmod(   t   splitt   strt   base64t   urlsafe_b64decodet   lent
   IndexErrort   FalseRa   R.   R1   t   upperRV   t   hmact   newt   hashlibt   sha256t   digest(   t   signed_requestR|   t   lt   encoded_sigt   payloadt   sigR   t   expected_sig(    (    s   facebook.pyRˆ   Ð  s.    
!c         C   s^   d } h |  d 6| d 6} | o d i  | ƒ | d <n | o | | d <n | t i | ƒ S(   Ns&   https://www.facebook.com/dialog/oauth?Ru   t   redirect_uriR   t   scopet   state(   R   R*   R+   (   R{   t
   canvas_urlt   permsR¨   R7   t   kvps(    (    s   facebook.pyt   auth_urlû  s    c         C   s½   h |  d 6| d 6| d 6| d 6} t  i d d t  i | ƒ ƒ i ƒ  } t | ƒ } d | j o= h | d d d 6} d	 | j o | d	 d | d	 <n | St i | ƒ } t | ƒ ‚ d
 S(   s³   Get an access token from the "code" returned from an OAuth dialog.

    Returns a dict containing the user-specific access token and its
    expiration date (if applicable).

    R†   R¦   Ru   Rv   s-   https://graph.facebook.com/oauth/access_tokenR^   R   i    Ry   N(   R*   R@   R+   R-   R   Rm   Rz   R2   (   R†   R¦   R{   R|   R	   R8   R}   R~   (    (    s   facebook.pyR‰     s    
 c         C   sf   h d d 6|  d 6| d 6} t  i d t i | ƒ ƒ } z | i ƒ  i d ƒ d } Wd | i ƒ  X| S(	   s÷   Get the access_token for the app.

    This token can be used for insights and creating test users.

    app_id = retrieved from the developer page
    app_secret = retrieved from the developer page

    Returns the application access_token.

    t   client_credentialsRx   Ru   Rv   s.   https://graph.facebook.com/oauth/access_token?R   i   N(   R=   R@   R*   R+   R-   R“   R3   (   R{   R|   R	   Rh   R~   (    (    s   facebook.pyt   get_app_access_token!  s    

	(   R‚   t   cgit   timeR*   R=   R(   R   R›   R•   RN   Rb   R    Rm   t   ImportErrort   django.utilsRz   R.   t   urlparseR   t   objectR   Rq   R2   R   Rˆ   R`   R¬   R‰   R®   (    (    (    s   facebook.pyt   <module>"   s<   	ÿ U	!	+
	