Ejemplo n.º 1
0
        def get_object(*args, **kwargs):
            if fails:
                raise facebook.GraphAPIError("Facebook error")

            return {
                "first_name": overrides.pop("first_name", "Isaac"),
                "last_name": overrides.pop("last_name", "Asimov"),
                "id": overrides.pop("fcb_id", FCB_ID),
                "picture": {
                    "data": {
                        "height":
                        200,
                        "is_silhouette":
                        True,
                        "url":
                        "https://platform-lookaside.fbsbx.com/platform/profilepic/"
                        "?asid=110045436843169"
                        "&height=200"
                        "&width=200"
                        "&ext=1556829832"
                        "&hash=AeSLD93lbSjc5t96",
                        "width":
                        200,
                    },
                },
            }
Ejemplo n.º 2
0
    def put_media(self,
                  mediafile,
                  message=None,
                  album_id=None,
                  mediatype=None,
                  **kwargs):
        """ Uploads a file using multipart/form-data
            mediafile: File like object for the image
            message: Caption for your image
            album_id: On photos, None posts to /me/photos which uses or creates and uses 
                      an album for your application.
            mediatype: one of 'photos' or 'videos' depending on media type
        """
        object = album_id or "me"

        form = MultiPartForm()
        form.add_field('access_token', self.access_token)
        form.add_field('message', message)
        form.add_file('source', mediafile.name, mediafile)
        if kwargs:
            for k, v in kwargs.items():
                form.add_field(k, v)

        request = urllib2.Request('https://graph.facebook.com/%s/%s' %
                                  (object, mediatype))
        body = str(form)
        request.add_header('Content-type', form.get_content_type())
        request.add_header('Content-length', len(body))
        request.add_data(body)

        raw = urllib2.urlopen(request).read()
        logger.debug('facebook response raw (post image): %s' % raw)

        try:
            response = _parse_json(raw)
        except:
            raise facebook.GraphAPIError(
                'GET_GRAPH',
                'Facebook returned bullshit (%s), expected json' % response)
        """ in some cases, response is not an object """
        if response:
            if response.get("error"):
                raise facebook.GraphAPIError(response["error"]["type"],
                                             response["error"]["message"])
        return response
Ejemplo n.º 3
0
def authenticate(app_id, app_secret, code=None, redirect_uri="", type=None):
    access_token = None

    args = {
        'client_id': app_id,
        'client_secret': app_secret,
        'redirect_uri': redirect_uri
    }
    if code: args['code'] = code.replace("\"", "")
    if type: args['type'] = 'client_cred'

    file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" +
                          urllib.urlencode(args))
    raw = file.read()
    file.close()
    logger.debug('Got Graph Response: %s' % raw)
    # The raw response is a urlparsed string (access_token=xxxxxxxx&expires=6295).
    # We convert it to a dict.
    response = urlparse.parse_qs(raw)

    if response == {}:
        # An error occured: The response is a JSON string containing the error.
        try:
            response = _parse_json(raw)
        except ValueError:
            raise facebook.GraphAPIError(
                'AUTHENTICATION ERROR',
                'Facebook returned this: %s. Expected access token.' % raw)
        else:
            if isinstance(response, dict) and response.get("error"):
                # The Code is invalid. Maybe the user logged out of Facebook or removed the app.
                raise facebook.GraphAPIError(response["error"]["type"],
                                             response["error"]["message"])
            else:
                raise facebook.GraphAPIError(
                    'AUTHENTICATION ERROR',
                    'Facebook returned json (%s), expected access_token' %
                    response)

    logger.debug('Authentication Graph Response: %s' % response)
    return response
Ejemplo n.º 4
0
    def get_comments(self,obj_id, graph_obj, limit, delay):
        # to prevent rate limit problems
        time.sleep(delay)
        try:
            comments = graph_obj.request(obj_id + '/?fields=comments')
        except facebook.GraphAPIError():
            logging.error("Graph API comments error", exc_info=True)

        if 'comments' in comments.keys():
            comments = comments['comments']['data']
            for c in comments:
                try:
                    time.sleep(delay)
                    replies= graph_obj.request(c['id'] + '/?fields=comments.limit('+ limit + ')')
                    if 'comments' in replies.keys():
                        c['replies'] = replies['comments']['data']

                except facebook.GraphAPIError():
                    logging.error("Graph API replies error", exc_info=True)

        # print(comments)
        return comments
Ejemplo n.º 5
0
 def get_object(self, object_id, **kwargs):
     if '/picture' in object_id:
         return {}
     if object_id == '/me/accounts':
         return self.ME_ACCOUNT
     for post in self.OBJECTS:
         if post['id'] == object_id:
             if 'fields' in kwargs:
                 return {field: post.get(field, "") for field in kwargs['fields'].split(',') + ['id']}
             else:
                 return post
     raise facebook.GraphAPIError({"error": {"message": "(#803) Some of the aliases you requested do not exist: %s" % object_id,
                                             "type": "OAuthException",
                                             "code": 803}})
Ejemplo n.º 6
0
    def test_login_facebook_fail(self, mocked_facebook):
        """
        Test login Facebook call fails
        """
        url = '/0/chefs/login'

        self.user.fb_access_token = 'TOKEN'
        self.user.save()

        mocked_facebook.side_effect = facebook.GraphAPIError(None)

        data = {'email': '*****@*****.**', 'fb_access_token': 'TOKEN'}
        resp = self.client.post(url, data=data)
        self.assertEqual(resp.status_code, 403)
def test_fetch_restaurants_post_api_error(mock_send_mail):
    mock_graph = mock.MagicMock(facebook.GraphAPI)
    mock_graph.get_object.side_effect = facebook.GraphAPIError('error')
    with pytest.raises(utils.NetworkError):
        utils.fetch_restaurant_posts(mock_graph, 'restaurant')
        mock_send_mail.assert_called_once_with(
            'An error occurred while attempting to fetch facebook posts:error',
            admin_email)

    mock_graph.get_object.side_effect = RequestException
    with pytest.raises(utils.NetworkError):
        utils.fetch_restaurant_posts(mock_graph, 'restaurant')
        mock_send_mail.assert_called_once(
            'An error occurred while attempting to fetch facebook posts:error',
            admin_email)
Ejemplo n.º 8
0
def get_facebook_profile(channel):
    " get facebook profile or None "

    if channel.facebook_access_token:
        graph = facebook_driver.GraphAPI(channel.facebook_access_token,
                                         channel=channel)
        try:
            profile = graph.get_object('me')
            return profile
        except facebook.GraphAPIError as e:
            app.logger.error(e)
            if hasattr(e, 'result') and 'error' in e.result and e.result[
                    'error']['code'] == 190 and e.result['error'][
                        'error_subcode'] == 460:
                reset_account_and_sync(channel)
                raise facebook.GraphAPIError(
                    "Facebook user has changed the password, please relogin")
    return None
Ejemplo n.º 9
0
    def _other_calls(cls, url):
        """Next to calls to Graph API are via requests, as client does not have
        built-in iterator. This is fine as Facebook provides full URL's for paging.
        """
        # Per https://developers.facebook.com/docs/graph-api/using-graph-api:
        # "As a best practice, for large requests use a POST request instead of a GET request
        # and add a method=GET parameter. If you do this, the POST will be interpreted
        # as if it were a GET."
        if re.search("method=GET", url, flags=re.I):
            params = {}
        else:
            params = {"method": "GET"}
        response = requests.post(url, params=params)

        try:
            response.raise_for_status()
        except requests.HTTPError:
            raise facebook.GraphAPIError(response)

        return response.json()
Ejemplo n.º 10
0
    def get_replies(self, post_id, obj_id, graph_obj, limit, delay):
        time.sleep(delay)
        try:
            replies = graph_obj.request(obj_id + '/?fields=comments.limit(' +
                                        limit + ')')
        except facebook.GraphAPIError():
            logging.error("Graph API replies error", exc_info=True)
        else:
            if 'comments' in replies.keys():
                replies = replies['comments']['data']
                for r in replies:
                    r['post_id'] = post_id
                    r['comm_id'] = obj_id
                    r['rep_id'] = r['id']
                    r.pop('id', None)
                    if 'message' in r:
                        r['reply'] = r['message']
                        r.pop('message', None)
            else:
                replies = []

            return replies
Ejemplo n.º 11
0
def get_FQL(fql, access_token=None):
    query = 'https://api.facebook.com/method/fql.query?format=json'

    params = {'query': fql}

    if access_token:
        params.update({'access_token': access_token})

    file = urllib.urlopen(query, urllib.urlencode(params))
    raw = file.read()

    logger.debug('facebook FQL response raw: %s, query: %s, FQL: %s' %
                 (raw, query, fql))

    try:
        response = _parse_json(raw)
    finally:
        file.close()
    if isinstance(response, dict) and response.get('error_code', False):
        raise facebook.GraphAPIError(response['error_code'],
                                     response['error_msg'])
    return response
Ejemplo n.º 12
0
    def get_comments(self, obj_id, graph_obj, limit, delay):
        # to prevent rate limit problems
        time.sleep(delay)
        try:
            comments = graph_obj.request(obj_id + '/?fields=comments.limit(' +
                                         limit + ')')
        except facebook.GraphAPIError():
            logging.error("Graph API comments error", exc_info=True)

        else:
            if 'comments' in comments.keys():
                comments = comments['comments']['data']
                for c in comments:
                    c['post_id'] = obj_id
                    c['comm_id'] = c['id']
                    c.pop('id', None)
                    if 'message' in c:
                        c['comment'] = c['message']
                        c.pop('message', None)
            else:
                comments = []
        # print(comments)
            return comments
Ejemplo n.º 13
0
 def _inner(*args, **kwargs):
     print args, kwargs
     raise facebook.GraphAPIError(resp)