Пример #1
0
    def load_photos(self, album):
        url = '%s/photos' % album.identifier

        api = GraphAPI(self.token)

        photos = []
        result = api.request(url)
        until_re = re.compile('until=(\d+)')

        while result and result['data']:
            for item in result['data']:
                image_url = self.get_absolute_url(item['source'])
                thumb = self.get_thumb_url(item['source'])
                server = '%d' in self.thumbor_server and self.thumbor_server % random.choice([1,2,3]) or self.thumbor_server
                photo = Photo(url=image_url, title='name' in item and item['name'] or '',
                          thumbnail=join(server.rstrip('/'), thumb.lstrip('/')),
                          width=int(item['width']), height=int(item['height']))
                photos.append(photo)
 
            if 'paging' in result:
                match = until_re.search(result['paging']['next'])
                if match:
                    until = match.groups()[0]
                    result = api.request(url, {'limit': 25, 'until': until})
                else:
                    result = None
            else:
                result = None
        return photos
Пример #2
0
    def load_albums(self):
        albums = []
        api = GraphAPI(self.token)

        result = api.request('me/albums')
        until_re = re.compile('until=(\d+)')

        while result['data']:
            for item in result['data']:
                album = Album(identifier=item['id'], url=item['link'], title=item['name'])
                albums.append(album)
            until = until_re.search(result['paging']['next']).groups()[0]
            result = api.request('me/albums', {'limit': 25, 'until': until})

        return albums
Пример #3
0
def facebook_get_email(access_token):  # pragma: no cover
    try:
        graph = GraphAPI(access_token=access_token)
        data = graph.request('/me?fields=email')
        return data.get('email')
    except GraphAPIError:
        return None
Пример #4
0
    def get_medias_from_album_id(self, album_id):
        data = {'results': []}

        access_token = self.get_access_token()

        api = GraphAPI(access_token)

        results = api.request('%s/photos' % smart_str(album_id), args={'fields':'id,name,picture,source,images,link,from'})
        result = results['data']

        data['index'] = {
            'total_results': len(result),
            'items_per_page': self.NB_RESULTS_PER_PAGE
        }

        for r in result:
            print r
            data['results'].append({
                'id': r['id'],
                'name': r.get('name',''),
                'image_url': r['source'],
                'image_url_tn': r['picture'],
                'description': '',
                'permalink_url': r['link'],
                'user_name': r['from']['name'],
                'user_url': 'http://www.facebook.com/'+r['from']['id']
            })
        return data
Пример #5
0
    def search_by_username(self, user, page=1):
        data = {'results': []}

        access_token = self.get_access_token()

        api = GraphAPI(access_token)

        results = api.request('%s/photos' % smart_str(user), args={'fields':'id,picture,source,images, link, from'})
        result = results['data']

        data['index'] = {
            'total_results': len(result),
            'items_per_page': self.NB_RESULTS_PER_PAGE
        }

        for r in result:
            data['results'].append({
                'id': r['id'],
                'name': '',
                'image_url': r['source'],
                'image_url_tn': r['picture'],
                'description': '',
                'permalink_url': r['link'],
                'user_name': r['from']['name'],
                'user_url': 'http://www.facebook.com/%s' % smart_str(user)
            })
        return data
Пример #6
0
    def search_albums_by_username(self, user, page=1):
        data = {'results': []}

        access_token = self.get_access_token()

        api = GraphAPI(access_token)

        results = api.request('%s/albums' % smart_str(user), args={'fields':'id,name,link,from,cover_photo'})
        result = results['data']

        data['index'] = {
            'total_results': len(result),
            'items_per_page': self.NB_RESULTS_PER_PAGE
        }
        
        for r in result:
            file = urllib.urlopen("https://graph.facebook.com/%s/picture?" % r['id']
                                    + urllib.urlencode({'access_token': access_token}))
            image_url = file.url
            file.close()

            data['results'].append({
                'id': r['id'],
                'name': r.get('name', ''),
                'image_url': image_url,
                'image_url_tn': image_url,
                'description': '',
                'permalink_url': r['link'],
                'user_name': r['from']['name'],
                'user_url': r['from']['id']
            })
        return data
Пример #7
0
 def is_token_valid(self, token=''):
     if not token:
         token = self._fb_access_token
     try:
         temp_api = GraphAPI(version=GRAPH_API_VERSION, access_token=token)
         resp = temp_api.request('me/home')
         return True
     except:
         return False
def login():

    client = None

    if not path.exists(cookie('facebook')):

        for i in range(0, 3):
            token = multenterbox("Enter a valid Facebook access token", ['Access Token'], [''])[0]
            try:
                client = GraphAPI(token)
                client.request('me')
                fmutex('facebook').write(token)
                return client
            except GraphAPIError, e:
                print str(e)
                pass

        raise GraphAPIError('Unable to query GraphAPI')
def login():

    client = None

    if not path.exists(cookie('facebook')):

        for i in range(0, 3):
            token = multenterbox("Enter a valid Facebook access token",
                                 ['Access Token'], [''])[0]
            try:
                client = GraphAPI(token)
                client.request('me')
                fmutex('facebook').write(token)
                return client
            except GraphAPIError, e:
                print str(e)
                pass

        raise GraphAPIError('Unable to query GraphAPI')
Пример #10
0
def get_image_url(connection):
    from facebook import GraphAPI
    api = GraphAPI(access_token=connection.access_token, version='2.5')
    try:
        response = api.request('/%s/picture' % connection.provider_user_id,
                               args={'redirect': '1',
                                     'type': 'large'})
        return 'data:%s;base64,%s' % (response['mime-type'],
                                      response['data'].encode('base64'))
    except Exception as exc:
        LOG.error(exc, exc_info=True)
        return ''
Пример #11
0
def magic(oauth, latlong, dist=1000, limit=5, verbose=False):
  g = GraphAPI(oauth)

  # search a bunch of stuff, until no more results
  # https://graph.facebook.com/search?type=location&center=[lat],[long]&distance=[dist]&access_token=[oauth]
  search = []
  params = {"type":"location", "center":latlong, "distance":dist, "access_token":oauth}
  while limit > 0:
    res = g.request("search", params)
    if len(res.keys()) == 0 or not res.get("paging"):
      break
    search += res["data"]
    params = dict(urlparse.parse_qsl(res["paging"]["next"].split("?")[1]))
    limit -= 1

  if verbose == True:
    pp.pprint(search)

  # filter
  places = g.fql("SELECT name, location, type, page_id FROM page where page_id in (%s)" % string.join([i["place"]["id"] for i in search], ", "))
  desired_place_types = ["RESTAURANT/CAFE", "BAR", "CLUB", "FOOD/BEVERAGES", "LOCAL BUSINESS"]
  limit = 1;
  filtered_places = {}
  for i in places:
    if i["type"].upper() in desired_place_types:
      name = i["name"]
      filtered_places[name] = i
      filtered_places[name]["data"] = []
      page = g.get_object(str(i["page_id"]) + "/picture", width="600")
      if page.get("url"):
        filtered_places[name]["photo_url"] = page["url"]
      del i["name"]

  if verbose == True:
    pp.pprint(filtered_places)

  # sort by places
  for i in search:
    if i["place"]["name"] in filtered_places:
      filtered_places[i["place"]["name"]]["data"].append(i)
      del i["place"]

      # get fb picture urls if can
      if i["type"] == "photo":
        photo = g.get_object(i["id"])
        if photo.get("images"):
          i["photo_url"] = photo["images"]

  if verbose == True:
    pp.pprint(filtered_places)

  return filtered_places
Пример #12
0
        def do_graph_action():
            graph = GraphAPI(self.access_token)

            #if (e.error_code == 3502
            #    or "An unexpected error has occurred." in e.message):

            try:
                post_data = urllib.urlencode({'quest': quest_url})
                post_data += '&fb:explicitly_shared=true'
                graph.request('me/{}'.format(send_action), post_data=post_data)

                if request:
                    Metrics.share_to_timeline.record(request, quest=quest_url)

                self.delete()
            except GraphAPIError as e:
                if request:
                    Metrics.share_to_timeline_error.record(request, quest=quest_url)

                if fail_silently:
                    client.captureException()
                else:
                    raise e
Пример #13
0
        def do_graph_action():
            graph = GraphAPI(self.access_token)

            #if (e.error_code == 3502
            #    or "An unexpected error has occurred." in e.message):

            try:
                post_data = urllib.urlencode({'quest': quest_url})
                post_data += '&fb:explicitly_shared=true'
                graph.request('me/{}'.format(send_action), post_data=post_data)

                if request:
                    Metrics.share_to_timeline.record(request, quest=quest_url)

                self.delete()
            except GraphAPIError as e:
                if request:
                    Metrics.share_to_timeline_error.record(request,
                                                           quest=quest_url)

                if fail_silently:
                    client.captureException()
                else:
                    raise e
Пример #14
0
  def get(self):
    co2=20
    aaa=""
    pg=self.request.get('pg')
    if pg:
      pg = int(pg)
    else:
      pg=0

    args = dict(grant_type="client_credentials", client_id=FACEBOOK_APP_ID, client_secret=FACEBOOK_APP_SECRET)
    response = cgi.parse_qs(urllib.urlopen("https://graph.facebook.com/oauth/access_token?" +urllib.urlencode(args)).read())
#    response = cgi.parse_qs(urlfetch.fetch("https://graph.facebook.com/oauth/access_token?" +urllib.urlencode(args)).read())
    access_token = response["access_token"][-1]
    #print access_token
    graph = GraphAPI(access_token)
    #profile = graph.get_object(FACEBOOK_ID)
    #print profile
    #friends = graph.get_connections(FACEBOOK_ID, "friends")
    try:
	  friends = graph.request("/v2.3/me/friends")
    except Exception, e:
	  errorjson = True
	  errtext =  cgi.escape(str(sys.exc_info()[0])) + ' ' + cgi.escape(str(sys.exc_info()[1])) + ' ' + cgi.escape(str(sys.exc_info()[2]))
Пример #15
0
 def get_profile_data(self, profile_id):
     fb = FacebookAPI(access_token=self.access_token(), version=API_VERSION)
     profile = fb.request(profile_id)
     return profile
        for i in range(0, 3):
            token = multenterbox("Enter a valid Facebook access token", ['Access Token'], [''])[0]
            try:
                client = GraphAPI(token)
                client.request('me')
                fmutex('facebook').write(token)
                return client
            except GraphAPIError, e:
                print str(e)
                pass

        raise GraphAPIError('Unable to query GraphAPI')

    try:
        client = GraphAPI(file(cookie('facebook')).read())
        client.request('me')
    except GraphAPIError, e:
        unlink(cookie('facebook'))
        return login()
    return client


#access_token = None
#
#class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
#
#    def do_GET(self):
#        global access_token
#        self.send_response(200)
#        self.send_header("Content-type", "text/html")
#        self.end_headers()
Пример #17
0
def get_email(oauth_response):
    from facebook import GraphAPI
    api = GraphAPI(access_token=oauth_response['access_token'], version='2.5')
    response = api.request('/me', args={'fields': 'email'})
    return response['email']
Пример #18
0
    def aprobar(self, user):
        r = self.recorrido
        if not r.uuid:
            # todavia no existe una version de este recorrido real, que estoy por retirar
            # antes de retirarlo creo su version correspondiente
            rp = RecorridoProposed(recorrido=r,
                                   nombre=r.nombre,
                                   linea=r.linea,
                                   ruta=r.ruta,
                                   sentido=r.sentido,
                                   slug=r.slug,
                                   inicio=r.inicio,
                                   fin=r.fin,
                                   semirrapido=r.semirrapido,
                                   color_polilinea=r.color_polilinea,
                                   pois=r.pois,
                                   descripcion=r.descripcion)
            rp.save(user=user)
            self.parent = rp.uuid
            self.save()

        r.recorrido = self.recorrido
        r.nombre = self.nombre
        r.linea = self.linea
        r.ruta = self.ruta
        r.sentido = self.sentido
        r.inicio = self.inicio
        r.fin = self.fin
        r.semirrapido = self.semirrapido
        r.color_polilinea = self.color_polilinea
        r.pois = self.pois
        r.descripcion = self.descripcion
        r.save()

        try:
            parent = RecorridoProposed.objects.get(uuid=self.parent)
            if parent:
                parent.logmoderacion_set.create(created_by=user, newStatus='R')
        except RecorridoProposed.DoesNotExist:
            pass
        for rp in RecorridoProposed.objects.filter(
                current_status='S',
                recorrido=r.recorrido).exclude(uuid=self.uuid):
            rp.logmoderacion_set.create(created_by=user, newStatus='R')
        self.logmoderacion_set.create(created_by=user, newStatus='S')

        #call_command('crear_thumbs', recorrido_id=self.recorrido.id)

        # Notificacion por facebook
        token = urllib2.urlopen(
            'https://graph.facebook.com/oauth/access_token?client_id=' +
            settings.FACEBOOK_APP_ID + '&client_secret=' +
            settings.FACEBOOK_API_SECRET +
            '&grant_type=client_credentials').read().split('access_token=')[1]
        user = self.get_moderacion_last_user()
        if not user.is_anonymous():
            fb = user.social_auth.filter(provider='facebook')
            if len(fb) != 0:
                from facebook import GraphAPI
                fb_uid = fb[0].uid
                graph = GraphAPI(token)
                graph.request(
                    "/" + fb_uid + "/notifications/",
                    post_args={
                        "template":
                        'Felicitaciones! Un moderador aceptó tu edición en cualbondi',
                        "href":
                        "https://cualbondi.com.ar/revision/" + str(self.id) +
                        "/"
                    })
Пример #19
0
def putwall(req,message,attachment):
    import facebookoauth
    from facebookoauth import FBUser
    import pprint, StringIO

#    prid=self.request.get('id')
#    prid="me"
#    args = dict(grant_type="client_credentials", client_id=FACEBOOK_APP_ID, client_secret=FACEBOOK_APP_SECRET)
#    response = cgi.parse_qs(urllib.urlopen("https://graph.facebook.com/oauth/access_token?" +urllib.urlencode(args)).read())
#    access_token = response["access_token"][-1]
    #print access_token
    hout = ""
    user_id = facebookoauth.parse_cookie(req.request.cookies.get("fb_user"))
    errorjson = False
    aaa="<h2>wall post</h2>error"
    profile = {'id': 0}
    perm_mp=False	
    perm_pa=False	
    permtext=""	
    cmd=req.request.get('cmd')
    oid=req.request.get('oid')
    if user_id:
      fb2_current_user = FBUser.get_by_key_name(user_id)
      if fb2_current_user and fb2_current_user.login:
        try:
            graph = GraphAPI(fb2_current_user.access_token)
            profile = graph.get_object("me")
            permissions = graph.request("/v2.1/me/permissions")
            for item in permissions["data"]:
                if item["permission"]=="manage_pages" and item["status"] == "granted":
                    perm_mp=True	
                if item["permission"]=="publish_actions" and item["status"] == "granted":
                    perm_pa=True	
            if not perm_mp:
                permtext = "manage_pages"
            if not perm_pa:
                permtext = permtext + " publish_actions"
            s = StringIO.StringIO()
#            pprint.pprint(permissions, s)
#            message = "Zinute patalpinta per\nhttp://www.nerij.us/fbputwall"        
#            attachment = {}  
#            attachment['name'] = "Nerijaus Terebo turinio valdymo sistemele \"Upelis\""  
#            attachment['caption'] = 'www.upelis.org'  
#            attachment['link'] = 'http://www.upelis.org/'  
#            attachment['picture'] = 'http://www.nerij.us/static/images/upelis116.jpg'  
#            attachment['description'] = 'Turinio valdymo sistemele \"Upelis\" - Python, AppEngine'  
            if cmd =="delperm":
#                    mess = graph.delete_object(oid)
#                    mess = graph.request(oid, post_args={"method": "delete"})
                post_args=dict(method = "delete", access_token = fb2_current_user.access_token)
                post_data = urllib.urlencode(post_args)
                file = urllib.urlopen("https://graph.facebook.com/me/permissions" , post_data)
                try:
                    response = json.loads(file.read())
                finally:
                    file.close()
                json.dump(response, s, sort_keys=True, indent=1)
                #pprint.pprint(response, s)
                hout=s.getvalue()
                aaa="<h2>permissions delete - ok </h2><pre>%s</pre>" % (hout)			
            elif not perm_mp or not perm_pa:
                aaa="<h2>wall post - error - registruodamiesi nepatvirtinot: %s  </h2><br><pre>%s</pre>" % (permtext,hout)			
            else:
                if cmd =="delete":
#                    mess = graph.delete_object(oid)
#                    mess = graph.request(oid, post_args={"method": "delete"})
                    post_args=dict(method = "delete", access_token = fb2_current_user.access_token)
                    post_data = urllib.urlencode(post_args)
                    file = urllib.urlopen("https://graph.facebook.com/" + oid , post_data)
                    try:
                        response = json.loads(file.read())
                    finally:
                        file.close()
                    #pprint.pprint(response, s)
                    json.dump(response, s, sort_keys=True, indent=1)
                    hout=s.getvalue()
                    aaa="<h2>wall post delete - ok </h2><pre>%s</pre>" % (hout)			
                elif cmd =="info":
                    mess = graph.request("/me/accounts")
                    #pprint.pprint(mess, s)
                    json.dump(mess, s, sort_keys=True, indent=1)
                    hout=s.getvalue()
                    aaa="<h2>accounts info</h2><p><pre>%s</pre></p>" % (hout)			
                else:
                    mess = graph.put_wall_post(message, attachment=attachment)
                    #pprint.pprint(mess, s)
                    json.dump(mess, s, sort_keys=True, indent=1)
                    hout=s.getvalue()
                    aaa="<h2>wall post - ok </h2><p><a href=\"/fbputwall?cmd=delete&oid=%s\">delete</a></p><pre>%s</pre>" % (mess["id"],hout)			
        except Exception, e:
            errorjson = True
            errtext =  cgi.escape(str(sys.exc_info()[0])) + ' ' + cgi.escape(str(sys.exc_info()[1])) + ' ' + cgi.escape(str(sys.exc_info()[2]))
      else:
        aaa="<h2>wall post</h2>not loged - <a href=\"/auth/login?continue=%s\">login</a>" % (urllib.quote(req.request.uri))
Пример #20
0
    def get(self):
        profile = {'id': 0}
        perm_mp=False	
        perm_pa=False	
        permtext=""	
        verification_code = self.request.get("code")
        url = self.request.get("continue")
        if self.request.get("continue"):
#        	args = dict(client_id=FACEBOOK_APP_ID, redirect_uri=self.request.path_url+("?continue=%s" % (urllib.quote(self.request.get("continue")))))
        	args = dict(client_id=FACEBOOK_APP_ID, redirect_uri=self.request.path_url+"?"+urllib.urlencode({'continue':url}), scope='email,manage_pages,publish_actions')
        else:
        	args = dict(client_id=FACEBOOK_APP_ID, redirect_uri=self.request.path_url)
        if self.request.get("code"):
            args["client_secret"] = FACEBOOK_APP_SECRET
            args["code"] = self.request.get("code")
            hout=urllib.urlopen(
                "https://graph.facebook.com/oauth/access_token?" +
                urllib.urlencode(args)).read()
            response = cgi.parse_qs(hout)
            aerr=False
            try:
                access_token = response["access_token"][-1]
            except:
                aerr=True
            # Download the user profile and cache a local instance of the
            # basic profile info
            if not aerr:
                permissions_str=""
                info_str=""
                profile = json.load(urllib.urlopen(
                	"https://graph.facebook.com/me?" +
                	urllib.urlencode(dict(access_token=access_token))))
                if not "email" in profile:
                	profile["email"] = 'none'
                if not profile["id"]==0:
                    try:
                        graph = GraphAPI(access_token)
                        permissions = graph.request("/v2.1/me/permissions")
                        for item in permissions["data"]:
                            if item["permission"]=="manage_pages" and item["status"] == "granted":
                                perm_mp=True	
                            if item["permission"]=="publish_actions" and item["status"] == "granted":
                                perm_pa=True	
                        if not perm_mp:
                            permtext = "manage_pages"
                        if not perm_pa:
                            permtext = permtext + " publish_actions"
#                        s = StringIO.StringIO()
#                        pprint.pprint(permissions["data"], s)
#                        permissions_str=s.getvalue()
                        permissions_str=permissions["data"]
                        if perm_mp and perm_pa:
                            if True:
                                mess = graph.request("/me/accounts")
#                                s1 = StringIO.StringIO()
#                                pprint.pprint(mess, s1)
#                                info_str=s1.getvalue()
                                info_str=mess["data"]
                                aaa=""			
                    except:
                        aaa=""

#import ast
#my_entity_k = db.Key.from_path('MyEntity', your_key_here)
#my_entity = db.get(my_entity_k)
#payload = ast.literal_eval(my_entity.dictionary_string)

                profusername=""
                if "username" in profile:
                	profusername=profile["username"]
                user = FBUser(key_name=str(profile["id"]), id=str(profile["id"]),
                			name=profile["name"], nickname=profusername,
                			email=profile["email"], access_token=access_token, access_token2=access_token,
                			profile_url=profile["link"],login=True,info=str(info_str),perm=str(permissions_str))
                user.put()
                set_cookie(self.response, "fb_user", str(profile["id"]),
                			expires=time.time() + 30 * 86400)
            if aerr:
            	self.response.out.write(hout)
            elif self.request.get("continue"):
            	self.redirect(str(self.request.get("continue")))
            else:
            	self.redirect("/fb")
        else:
            self.redirect(
                "https://graph.facebook.com/oauth/authorize?" +
                urllib.urlencode(args))
Пример #21
0
        code = code[0] if code else None

        if code is None:
            self.wfile.write("Sorry, authentication failed.")
            sys.exit(1)

        response = get_access_token_from_code(code, REDIRECT_URI, APP_ID,
                                              APP_SECRET)

        ACCESS_TOKEN = response['access_token']

        open(LOCAL_FILE, 'w').write(ACCESS_TOKEN)
        self.wfile.write("You have successfully logged in to facebook. "
                         "You can close this window now.")


if __name__ == '__main__':
    if not os.path.exists(LOCAL_FILE):
        print "Logging you in to facebook..."
        webbrowser.open(auth_url(APP_ID, REDIRECT_URI, perms=['read_stream']))

        listen_on = urlparse.urlsplit(REDIRECT_URI)
        httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 8080), RequestHandler)
        while ACCESS_TOKEN is None:
            httpd.handle_request()
    else:
        ACCESS_TOKEN = open(LOCAL_FILE).read()

client = GraphAPI(ACCESS_TOKEN)
print client.request('me/permissions')
Пример #22
0
            self.wfile.write("Sorry, authentication failed.")
            sys.exit(1)

	response = get_access_token_from_code(code, REDIRECT_URI, APP_ID, APP_SECRET)

	ACCESS_TOKEN = response['access_token']

        open(LOCAL_FILE,'w').write(ACCESS_TOKEN)
        self.wfile.write("You have successfully logged in to facebook. "
                         "You can close this window now.")


if __name__ == '__main__':
    if not os.path.exists(LOCAL_FILE):
        print "Logging you in to facebook..."
	webbrowser.open(auth_url(APP_ID, REDIRECT_URI, perms=['read_stream']))

	listen_on = urlparse.urlsplit(REDIRECT_URI)
        httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 8080), RequestHandler)
        while ACCESS_TOKEN is None:
            httpd.handle_request()
    else:
        ACCESS_TOKEN = open(LOCAL_FILE).read()


client = GraphAPI(ACCESS_TOKEN)
print client.request('me/permissions')



            token = multenterbox("Enter a valid Facebook access token",
                                 ['Access Token'], [''])[0]
            try:
                client = GraphAPI(token)
                client.request('me')
                fmutex('facebook').write(token)
                return client
            except GraphAPIError, e:
                print str(e)
                pass

        raise GraphAPIError('Unable to query GraphAPI')

    try:
        client = GraphAPI(file(cookie('facebook')).read())
        client.request('me')
    except GraphAPIError, e:
        unlink(cookie('facebook'))
        return login()
    return client


#access_token = None
#
#class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
#
#    def do_GET(self):
#        global access_token
#        self.send_response(200)
#        self.send_header("Content-type", "text/html")
#        self.end_headers()
def download_ads(page_ids, next_page, country="ALL", pages=False, search=dict()):
    """
    Search parameters
    https://developers.facebook.com/docs/marketing-api/reference/ads_archive/

    Ads available fields
    https://developers.facebook.com/docs/graph-api/reference/archived-ad/
    """

    API_VERSION = app.config["API_VERSION"]
    ADS_PER_PAGE = app.config["ADS_PER_PAGE"]
    PAGES_BETWEEN_STORING = pages or app.config["PAGES_BETWEEN_STORING"]

    graph = GraphAPI(version=API_VERSION)

    args = search
    args["access_token"] = get_long_token()
    args["search_terms"] = ""
    args["ad_type"] = "POLITICAL_AND_ISSUE_ADS"
    args["ad_reached_countries"] = [country]
    args[
        "search_page_ids"
    ] = page_ids  # list of specific page (advertiser) ids if we know them
    args["ad_active_status"] = "ALL"
    args["fields"] = ",".join(
        [
            "ad_creation_time",
            "ad_creative_body",
            "ad_creative_link_caption",
            "ad_creative_link_description",
            "ad_creative_link_title",
            "ad_delivery_start_time",
            "ad_delivery_stop_time",
            "ad_snapshot_url",
            "currency",
            "demographic_distribution",
            "funding_entity",
            "impressions",
            "page_id",
            "page_name",
            "potential_reach",
            "publisher_platforms",
            "region_distribution",
            "spend",
        ]
    )
    args["limit"] = ADS_PER_PAGE
    method = "/ads_archive"
    i = 1
    result = []

    def handleGraphAPIError(e):
        if app.config["FLASK_ENV"] == "development":
            print(e)
        else:
            capture_exception(e)

        next_page = None

        # Code 4 is rate limit. We need to just quit here.
        if e.code == 4:
            raise GraphAPIError

    if next_page == "start":
        try:
            r = graph.request(method, args)
            data = r.get("data", [])
            result.extend(data)
            next_page = r.get("paging", {}).get("next", None)
            # print("-------RESULTS----------", "iterations=", i, "len data=", len(data))

        except GraphAPIError as e:
            handleGraphAPIError(e)

    else:
        while i <= PAGES_BETWEEN_STORING:
            argsi = build_args(ADS_PER_PAGE, url=next_page)
            try:
                # just try accessing some key params
                argsi["search_page_ids"]
                argsi["after"]
            except:
                return result, None

            try:
                r = graph.request(method, argsi)
                data = r.get("data", [])
                result.extend(data)
                next_page = r.get("paging", {}).get("next", None)
                i += 1
                # print("-------RESULTS----------", "iterations=", i, "len data=", len(data))

            except GraphAPIError as e:
                handleGraphAPIError(e)

    return result, next_page