U
    [e?                     @   s   zd dl ZW n ek
r(   d dlZY nX d dlZd dlZd dlZd dlZzd dlmZ	 d dlm
Z
 W n( ek
r   d dlm
Z
 d dl	Z	Y nX d dlmZ d dlZd dlT eeZG dd deZdS )    N)	urlencode)Decimal)*c                   @   s   e Zd Zd!ddZed"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 Zdd Zdd Zdd  Zeee  ZZZdS )(GraphAPIFhttps://graph.facebook.comTNc                 C   s8   || _ t | _|d| _|| _|| _|| _|| _dS )z
        Initialize GraphAPI with an OAuth access token.

        :param oauth_token: A string describing an OAuth access token.
        :param version: A string with version ex. '2.2'.
        /N)	oauth_tokenrequestssessionstripurlverify_ssl_certificate	appsecrettimeoutversion)selfr   r   r   r   r   r    r   R/var/www/html/services/stratfitenv/lib/python3.8/site-packages/facepy/graph_api.py__init__   s    
zGraphAPI.__init__c                 C   s&   ddl m} ||||d}t||dS )z
        Initialize GraphAPI with an OAuth access token for an application.

        :param id: An integer describing a Facebook application.
        :param secret_key: A String describing the Facebook application's secret key.
        r   )get_application_access_token)api_version)r   )Zfacepy.utilsr   r   )r   idZ
secret_keyr   r   access_tokenr   r   r   for_application*   s    zGraphAPI.for_application    c                 K   s,   | j d||||d}|dkr(td| |S )a  
        Get an item from the Graph API.

        :param path: A string describing the path to the item.
        :param page: A boolean describing whether to return a generator that
                     iterates over each page of results.
        :param retry: An integer describing how many times the request may be retried.
        :param options: Graph API parameters such as 'limit', 'offset' or 'since'.

        Floating-point numbers will be returned as :class:`decimal.Decimal`
        instances.

        See `Facebook's Graph API documentation <http://developers.facebook.com/docs/reference/api/>`_
        for an exhaustive list of parameters.
        GET)methodpathdatapageretryFzCould not get "%s"._queryFacebookError)r   r   r    r!   optionsresponser   r   r   get7   s    zGraphAPI.getr   c                 K   s*   | j d|||d}|dkr&td| |S )a  
        Post an item to the Graph API.

        :param path: A string describing the path to the item.
        :param retry: An integer describing how many times the request may be retried.
        :param data: Graph API parameters such as 'message' or 'source'.

        See `Facebook's Graph API documentation <http://developers.facebook.com/docs/reference/api/>`_
        for an exhaustive list of options.
        POSTr   r   r   r!   FzCould not post to "%s"r"   r   r   r!   r   r&   r   r   r   postT   s    zGraphAPI.postc                 K   s*   | j d|||d}|dkr&td| |S )a  
        Delete an item in the Graph API.

        :param path: A string describing the path to the item.
        :param retry: An integer describing how many times the request may be retried.
        :param data: Graph API parameters such as 'main_page_id' or 'location_page_id'.

        See `Facebook's Graph API documentation <http://developers.facebook.com/docs/reference/api/>`_
        for an exhaustive list of parameters.
        DELETEr)   FzCould not delete "%s"r"   r*   r   r   r   deletek   s    zGraphAPI.deleteplacec                 K   s<   |dkrt d| t||df|}| dd|||}|S )a  
        Search for an item in the Graph API.

        :param term: A string describing the search term.
        :param type: A string describing the type of items to search for.
        :param page: A boolean describing whether to return a generator that
                     iterates over each page of results.
        :param retry: An integer describing how many times the request may be retried.
        :param options: Graph API parameters, such as 'center' and 'distance'.

        Supported types are only ``place`` since Graph API 2.0.

        See `Facebook's Graph API documentation <http://developers.facebook.com/docs/reference/api/>`_
        for an exhaustive list of options.
        r.   zNUnsupported type "%s". The only supported type is "place" since Graph API 2.0.)qtyper   search)
ValueErrordictr#   )r   termr0   r    r!   r%   r&   r   r   r   r1      s    zGraphAPI.searchc                 c   s   |D ]}d|krt |d |d< qddd}g }||dD ]}|| jt|d7 }q:t||D ]X\}}|stdV  q`z| |d V  W q` tk
r } z||_|V  W 5 d}~X Y q`X q`dS )	z
        Make a batch request.

        :param requests: A list of dictionaries with keys 'method', 'relative_url' and optionally 'body'.

        Yields a list of responses and/or exceptions.
        body   c                 s   s,   t dt| |D ]}| |||  V  qdS )a4  
            Batches a list into constant size chunks.

            :param complete_list: A input list (not a generator).
            :param n: The size of the chunk.

            Adapted from <http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python>
            r   N)rangelen)Zcomplete_listnir   r   r   _grouper   s    
z GraphAPI.batch.<locals>._grouper2   )batchN)r6   )r   r+   jsondumpszip_parseFacepyErrorrequest)r   r	   rC   r;   	responsesgroupr&   	exceptionr   r   r   r=      s$    	

zGraphAPI.batchc           	         sF  |rFt dd | D }t dd | D }t dd | D }|pLi }fdd  fddfd	d
}|D ]@}t|| tttfrxtdd || D rxd|| ||< qx|dst	j
rdt	|d }nd| }|}jrj|d< jr jr  |d< |r2||||S |||d S dS )a  
        Fetch an object from the Graph API and parse the output, returning a tuple where the first item
        is the object yielded by the Graph API and the second is the URL for the next page of results, or
        ``None`` if results have been exhausted.

        :param method: A string describing the HTTP method.
        :param path: A string describing the object in the Graph API.
        :param data: A dictionary of HTTP GET parameters (for GET requests) or POST data (for POST requests).
        :param page: A boolean describing whether to return an iterator that iterates over each page of results.
        :param retry: An integer describing how many times the request may be retried.
        c                 s   s"   | ]\}}| d d|fV  qdS )Z_sqbro_[Nreplace.0kvr   r   r   	<genexpr>   s    z"GraphAPI._query.<locals>.<genexpr>c                 s   s"   | ]\}}| d d|fV  qdS )Z_sqbrc_]NrH   rJ   r   r   r   rN      s    c                 s   s"   | ]\}}| d d|fV  qdS )__:NrH   rJ   r   r   r   rN      s    c              
      s  |D ]*}|| }t |tttfrt|||< qz| dkrVjj| ||djj	d}| dkri }|D ]}t
|| drf|| ||< qf|D ]}|| qjj| |||jj	d}d|j  krdk rn n|j td	|jW n. tjk
r } zt|W 5 d }~X Y nX |j}t |tr<|j|d
<  fdd t |trx d|}	|	rr|	dd }
nd }
nd }
||
fS )N)r   r,   T)paramsallow_redirectsverifyr   )r(   PUTread)r   filesrT   r   i  iX  z Internal Facebook error occurredheadersc                    sJ   | |kr||  S |  D ],\}}t|tr | |}|dk	r|  S qdS )zX
                Get the the given key anywhere in a nested dictionary.
                N)items
isinstancer3   )needleZhaystackkeyvalueitem
nested_getr   r   r`     s    

z1GraphAPI._query.<locals>.load.<locals>.nested_getpagingnext)rZ   listr3   setr>   r?   r
   rC   r   r   hasattrpopstatus_coderA   contentr$   r	   RequestException	HTTPErrorrX   r'   )r   r   r   r\   r]   r&   rW   rF   resultra   Znext_url)r   r_   r   load   s`            

zGraphAPI._query.<locals>.loadc              
      s`   }z | ||W S  t k
rX } z(td||| |dkrF|d8 }n W 5 d }~X Y qX qd S )Nz*Exception on %s: %s, retries remaining: %sr   r6   )rB   logwarn)r   r   r   Zremaining_retriese)rl   r!   r   r   load_with_retry3  s    
z(GraphAPI._query.<locals>.load_with_retryc                 3   s8   |r4 | ||\}}dD ]}||kr||= q|V  q d S )N)offsetZuntilZsincer   )r   r   r   rk   r\   )rp   r   r   paginateC  s    z!GraphAPI._query.<locals>.paginatec                 S   s   g | ]}t |tjqS r   )rZ   sixstring_types)rK   r^   r   r   r   
<listcomp>P  s     z#GraphAPI._query.<locals>.<listcomp>,r   utf-8r   Zappsecret_proofr   N)r3   rY   rZ   rc   rd   tuplealljoin
startswithrs   PY2	text_typedecode_get_urlr   r   _generate_appsecret_proof)	r   r   r   r   r    r!   rr   r\   r   r   )rl   rp   r!   r   r   r#      s:    L*


zGraphAPI._queryc                 C   sD   t  |jdkr| j}nd}| jr4d|| j|f }nd||f }|S )Nr   z%s/v%s%sz%s%s)urlparsenetlocr   r   )r   r   r   r   r   r   r   g  s    zGraphAPI._get_urlc                 C   sD   i }ddddddddg}d	|kr(|d	 }|D ]}| |||< q,|S )
NmessagecodeZerror_subcodeZerror_user_msgZis_transientZ
error_dataZerror_user_titleZ
fbtrace_iderror)r'   )r   Z	error_objZerror_paramsZerror_fieldsfieldr   r   r   _get_error_paramsw  s      zGraphAPI._get_error_paramsc                 C   s   t |t t kr:z|d}W n tk
r8   | Y S X ztj|td}W n tk
rd   | Y S X t |tkrd|kr|d }|	ddkrt
}nt}|f | |d|krtf | ||S )z
        Parse the response from Facebook's Graph API.

        :param data: A string describing the Graph API's response.
        rw   )parse_floatr   r0   ZOAuthException	error_msg)r0   bytesr~   UnicodeDecodeErrorr>   loadsr   r2   r3   r'   
OAuthErrorr$   r   )r   r   r   rF   r   r   r   rA     s&    

zGraphAPI._parsec                 C   s@   t jr| j}| j}nt| jd}t| jd}t||tj	 S )z
        Returns a SHA256 of the oauth_token signed by appsecret.
        https://developers.facebook.com/docs/graph-api/securing-requests/
        rw   )
rs   r|   r   r   r   hmacnewhashlibsha256	hexdigest)r   r\   r   r   r   r   r     s    z"GraphAPI._generate_appsecret_proof)Fr   TFNN)N)r   Fr   )r   r   )r   )r.   Fr   )NFr   )__name__
__module____qualname__r   classmethodr   r'   r+   r-   r1   r=   r#   r   r   rA   r   r$   r   rj   r   r   r   r   r      s   




2
 /r   )Z
simplejsonr>   ImportErrorr	   r   r   loggingurllib.parseparser   r   urllibdecimalr   rs   Zfacepy.exceptions	getLoggerr   rm   objectr   r   r   r   r   <module>   s$   
