def get_feed_statuses(self, feed, post_number_limit, date_filters, use_app_token): """ Returns a Dict object of feed ID. and retrieved status objects. :param use_app_token: """ if feed.feed_type == 'PP': try: # Set facebook graph access token to most up-to-date user token in db token = User_Token_Model.objects.first() self.graph.access_token = token.token except AttributeError: # Fallback: Set facebook graph access token to app access token self.graph.access_token = facebook.get_app_access_token( settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) if feed.requires_user_token: # If the Feed is set to require a user-token, and none exist in our db, the feed is skipped. print 'feed %d requires user token, skipping.' % feed.id data_dict = {'feed_id': feed.id, 'statuses': []} return data_dict # Get the data using the pre-set token if use_app_token: self.graph.access_token = facebook.get_app_access_token( settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) return { 'feed_id': feed.id, 'statuses': self.fetch_status_objects_from_feed(feed.vendor_id, post_number_limit, date_filters) } elif feed.feed_type == 'UP': # feed_type == 'UP' - User Profile # Set facebook graph access token to user access token token = User_Token_Model.objects.filter( feeds__id=feed.id).order_by('-date_of_creation').first() if not token: print 'No Token found for User Profile %s' % feed return {'feed_id': feed.id, 'statuses': []} else: print 'using token by user_id: %s' % token.user_id self.graph.access_token = token.token return { 'feed_id': feed.id, 'statuses': self.fetch_status_objects_from_feed( feed.vendor_id, post_number_limit, date_filters) } else: # Deprecated or malfunctioning profile ('NA', 'DP') print 'Profile %s is of type %s, skipping.' % (feed.id, feed.feed_type) return {'feed_id': feed.id, 'statuses': []}
def authenticate(cls, app, type_auth=None, app_user=None): if app.community.type == 'page': if not app.community.token: token = cls.get_long_lived_page_token( app.app_id, app.app_secret, app.app_access_token, app.community.external_id) app.community.token = token app.community.save() else: token = app.community.token else: # community type = group if type_auth == 'write': # User access_token code = cls.get_code(app.app_id, app.app_secret, app.redirect_uri, app_user.access_token) graph = facebook.GraphAPI(app_user.access_token) access_token_info = graph.get_access_token_from_code( code, app.redirect_uri, app.app_id, app.app_secret) token = access_token_info['access_token'] app_user.access_token = token app_user.access_token_exp = calculate_token_expiration_time( access_token_info['expires_in']) app_user.save() else: if app.app_access_token: token = app.app_access_token else: token = facebook.get_app_access_token( app.app_id, app.app_secret) app.app_access_token = token app.save() cls.graph = facebook.GraphAPI(token)
def get_events_for_group(group_id, max_results, since, until=None): access_token = facebook.get_app_access_token(\ current_app.config["FB_APP_ID"],\ current_app.config["FB_APP_SECRET"]) modifiers = {"since": since} if until: modifiers["until"] = until graph_api = facebook.GraphAPI(access_token=access_token) raw_events = graph_api.get_object(("%s/events" % group_id), **modifiers) events = [] cursor = 0 while cursor < max_results: try: for event in raw_events["data"]: if cursor >= max_results: break events.append(event) cursor += 1 if cursor < max_results: raw_events = requests.get(raw_events["paging"]["next"]).json() except KeyError: break return events
def get_graph_client(self): """ Get an instance of the Graph API client """ return facebook.GraphAPI( facebook.get_app_access_token(self.app_id, self.secret) )
def get_feed_data(self, feed): """ Returns a Dict object of feed ID. and retrieved feed data. """ if feed.feed_type == 'UP': # User Profile # Set facebook graph access token to user access token token = User_Token_Model.objects.all().order_by('-date_of_creation').first() if token: print 'token is: %s' % token.token self.graph.access_token = token.token else: print Exception('No User Access Token was found in the database!') #TODO:Write as a real exception data_dict = {'feed_id': feed.id, 'data': self.fetch_user_profile_object_by_feed_id(feed.vendor_id)} pprint(data_dict) # Transform data to fit existing public page data_dict['data'][0]['fan_count'] = 0 data_dict['data'][0]['talking_about_count'] = 0 data_dict['data'][0]['about'] = '' data_dict['data'][0]['page_url'] = data_dict['data'][0]['profile_url'] data_dict['data'][0]['website'] = data_dict['data'][0]['profile_url'] data_dict['data'][0]['pic_large'] = data_dict['data'][0]['pic_big'] data_dict['data'][0]['birthday'] = data_dict['data'][0]['birthday_date'] return data_dict else: # 'PP - Public Page' # Set facebook graph access token to app access token self.graph.access_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) data_dict = {'feed_id': feed.id, 'data': self.fetch_page_object_by_feed_id(feed.vendor_id)} return data_dict
def handle(self, *args, **options): feeds_statuses = [] self.graph.access_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) if len(args) == 0: for feed in facebook_feed_model.objects.all(): feeds_statuses.append(self.get_feed_statuses(feed)) elif len(args) == 1: feed_id = int(args[0]) try: feed = facebook_feed_model.objects.get(pk=feed_id) except facebook_feed_model.DoesNotExist: raise CommandError('Feed "%s" does not exist' % feed_id) feeds_statuses.append(self.get_feed_statuses(feed)) else: raise CommandError("Please enter an id") # Insert to databse for feed_statuses in feeds_statuses: for status in feed_statuses["statuses"]: self.insert_status_post_to_db(status, feed_statuses["feed_id"]) self.stdout.write("Successfully fetched all")
def facebook_graph_api(): """ Returns the result from calling Facebook's Graph API with the app's access token. """ return facebook.GraphAPI( facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET))
def __init__(self): self.access_token = get_app_access_token(FACEBOOK_APP_ID, FACEBOOK_SECRET_ID) self.graph = facebook.GraphAPI(self.access_token) self.obj_name = None self.obj_type = None self.time_handler = TimeHandler()
def get(self): import facebook access_token = facebook.get_app_access_token(APP_ID, APP_SECRET) graph = facebook.GraphAPI(access_token) result = graph.request("/ntuoss/events", { "since": 0, "fields": ["name", "cover", "picture", "start_time", "location"] }) events = result['data'] return_event_list = [] for event in events: if "cover" in event: cover = event['cover']['source'] else: cover = None return_event_list.append({ "id": event['id'], "name": event['name'], "cover": cover, "picture": event['picture']['data']['url'], "location": event['location'], "start_time": event['start_time'] }) import json return_object = { "status": 0, "data": return_event_list } self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(return_object))
def authenticate(cls, app, type_auth=None, app_user=None): if app.community.type == 'page': if not app.community.token: token = cls.get_long_lived_page_token(app.app_id, app.app_secret, app.app_access_token, app.community.external_id) app.community.token = token app.community.save() else: token = app.community.token else: # community type = group if type_auth == 'write': # User access_token code = cls.get_code(app.app_id, app.app_secret, app.redirect_uri, app_user.access_token) os.system('echo "' +str(os.path.dirname(inspect.getfile(facebook))) + '" > prueba.txt') #os.system('echo "' +str(type(facebook)) + '" > prueba.txt') #access_token = cls.get_long_lived_access_token(app.app_id, app.app_secret, app.app_access_token)['access_token'] graph = facebook.GraphAPI(app_user.access_token) access_token_info = graph.get_access_token_from_code(code, app.redirect_uri, app.app_id, app.app_secret) token = access_token_info['access_token'] os.system('echo "' +str(token) + '" > prueba.txt') app_user.access_token = token app_user.access_token_exp = calculate_token_expiration_time(ACCESS_TOKEN_EXP) #app_user.access_token_exp = calculate_token_expiration_time(access_token_info['expires_in']) app_user.save() else: if app.app_access_token: token = app.app_access_token else: token = facebook.get_app_access_token(app.app_id, app.app_secret) app.app_access_token = token app.save() cls.graph = facebook.GraphAPI(token)
def callback(self, request): """ Called from the Service when the user accept to activate it """ try: # finally we save the user auth token # As we already stored the object ServicesActivated # from the UserServiceCreateView now we update the same # object to the database so : # 1) we get the previous objet us = UserService.objects.get( user=request.user, name=ServicesActivated.objects.get(name='ServiceFacebook')) # 2) then get the token access_token = facebook.get_app_access_token( app_secret=self.consumer_secret, app_id=self.app_id) us.token = access_token # 3) and save everything us.save() except KeyError: return '/' return 'facebook/callback.html'
def status_update(request, status_id): status = Facebook_Status.objects.get(status_id=status_id) try: update_status_command = updatestatus.Command() update_status_command.graph.access_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) status_response_dict = update_status_command.fetch_status_object_data(status_id) response_data = dict() response_data['likes'] = status_response_dict['likes']['summary']['total_count'] response_data['comments'] = status_response_dict['comments']['summary']['total_count'] response_data['shares'] = status_response_dict['shares']['count'] response_data['id'] = status.status_id try: status.like_count = int(response_data['likes']) status.comment_count = int(response_data['comments']) status.share_count = int(response_data['shares']) status.save() finally: return HttpResponse(json.dumps(response_data), content_type="application/json") finally: response_data = dict() response_data['likes'] = "{:,}".format(status.like_count) response_data['comments'] = "{:,}".format(status.comment_count) response_data['shares'] = "{:,}".format(status.share_count) response_data['id'] = status.status_id return HttpResponse(json.dumps(response_data), content_type="application/json")
def status_update(request, status_id): status = Facebook_Status.objects.get(status_id=status_id) url = "https://graph.facebook.com/" url += str(status.status_id) url += "?access_token=" + facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) url += "&fields=shares,likes.limit(1).summary(true),comments.limit(1).summary(true)" try: responseText = urllib2.urlopen(url).read() responseJson = json.loads(responseText) response_data = dict() response_data['likes'] = responseJson['likes']['summary']['total_count'] response_data['comments'] = responseJson['comments']['summary']['total_count'] response_data['shares'] = responseJson['shares']['count'] response_data['id'] = status.status_id try: status.like_count = int(response_data['likes']) status.comment_count = int(response_data['comments']) status.share_count = int(response_data['shares']) status.save() finally: return HttpResponse(json.dumps(response_data), content_type="application/json") finally: response_data = dict() response_data['likes'] = status.like_count response_data['comments'] = status.comment_count response_data['shares'] = status.share_count response_data['id'] = status.status_id return HttpResponse(json.dumps(response_data), content_type="application/json")
def authenticate(cls, app, type_auth=None, app_user=None): if app.community.type == 'page': if not app.community.token: token = cls.get_long_lived_page_token(app.app_id, app.app_secret, app.app_access_token, app.community.external_id) app.community.token = token app.community.save() else: token = app.community.token else: # community type = group if type_auth == 'write': # User access_token code = cls.get_code(app.app_id, app.app_secret, app.redirect_uri, app_user.access_token) graph = facebook.GraphAPI(app_user.access_token) access_token_info = graph.get_access_token_from_code(code, app.redirect_uri, app.app_id, app.app_secret) token = access_token_info['access_token'] app_user.access_token = token app_user.access_token_exp = calculate_token_expiration_time(access_token_info['expires_in']) app_user.save() else: if app.app_access_token: token = app.app_access_token else: token = facebook.get_app_access_token(app.app_id, app.app_secret) app.app_access_token = token app.save() cls.graph = facebook.GraphAPI(token)
def run_multithread_tasks(num_threaded, posts_ids, revoke_token_interval): token_interval_counter = 0 def run_thread(thread_name): global result global new_access_token while posts_ids: target_post = posts_ids.pop() print "%s: deal with %s" % (thread_name, target_post) attended_users = get_attended_user(target_post, new_access_token) result += attended_users def check_thread(): print "Remaining: {0}, Result: {1}".format(len(posts_ids), len(result)) for n in range(num_threaded): thread.start_new_thread(run_thread, ("Thread-%s"%n, )) while posts_ids: time.sleep(5) check_thread() token_interval_counter += 1 if token_interval_counter > revoke_token_interval: token_interval_counter = 0 new_access_token = facebook.get_app_access_token(APP_ID, APP_SECRET)
def status_update(request, status_id): status = Facebook_Status.objects_no_filters.get(status_id=status_id) response = HttpResponse(content_type="application/json", status=200) response_data = dict() response_data['id'] = status.status_id try: if status.needs_refresh: update_status_command = updatestatus.Command() update_status_command.graph.access_token = facebook.get_app_access_token( settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) status_response_dict = update_status_command.fetch_status_object_data( status_id) or {} response_data['likes'] = getattr( getattr(getattr(status_response_dict, 'likes', 0), 'summary', 0), 'total_count', 0) response_data['comments'] = getattr( getattr(getattr(status_response_dict, 'comments', 0), 'summary', 0), 'total_count', 0) response_data['shares'] = getattr( getattr(status_response_dict, 'shares', 0), 'count', 0) try: update_status_command.update_status_object_in_db( retrieved_status_data=status_response_dict, status_object=status, options={ 'force-update': True, 'force-attachment-update': True }) finally: response.status_code = 200 except KeyError as e: response.status_code = 500 except GraphAPIError as e: response.status_code = 504 except ValueError as e: raise e except Exception as e: print 'status_update error:', e raise finally: format_int_or_null = lambda x: 0 if not x else "{:,}".format(x) response_data['likes'] = format_int_or_null(status.like_count) response_data['comments'] = format_int_or_null(status.comment_count) response_data['shares'] = format_int_or_null(status.share_count) response_data['id'] = status.status_id response.content = json.dumps(response_data) return response
def __init__(self, **kwargs): self.__dict__.update(kwargs) # code='AQClMjoXlFTLq_WjjDHOq04qCPERDlDHrFOks4GpRCF4R7ED9889leLdVbUEVV6zZUzssJsY8009KTwpgMuvmqs2KBsOtoPhNNt6-tFXQZ9JkKSRRFVmPX--iS6-O8RKHfH9On2I-KaGS-tYeyqd3tmFxrR9ayGQhzsY8XvbyB6pxV8a5xOfYHOemaK8X-T2UyIy4QBsm87sTgKXvJ2Iygv-KgY4xKSTdFjqGhkf9gUWhjn7dARwu9P4Emjjpq6Whs2g5BTGlZppgekoe1fZqwwtRshJUvi4XKF3d-1uE97Kd7Nk-8ddH1qS7DZHr9t6-TAxoceKHHP6c7NmqDC1XVS6#_=_' # self.token = facebook.get_access_token_from_code(code, 'http://fb-parser.int/', config.config['id'], config.config['secret']) self.token = facebook.get_app_access_token(config.app_config['id'], config.app_config['secret']) pprint.pprint(self.token) self.graph = facebook.GraphAPI(self.token) self.profile = self.graph.get_object(self.username)
def test_fql(self): graph = facebook.GraphAPI(access_token=facebook.get_app_access_token(self.app_id, self.secret), version=2.0) # Ensure that version is below 2.1. Facebook has stated that FQL is # not present in this or future versions of the Graph API. if graph.get_version() < 2.1: # This is a tautology, but we are limited in what information # we can retrieve with a proper OAuth access token. fql_result = graph.fql("SELECT app_id from application where app_id = %s" % self.app_id) self.assertEqual(fql_result["data"][0]["app_id"], str(self.app_id))
def get_feed_statuses(self, feed, post_number_limit, date_filters, use_app_token): """ Returns a Dict object of feed ID. and retrieved status objects. :param use_app_token: """ if feed.feed_type == 'PP': try: # Set facebook graph access token to most up-to-date user token in db token = User_Token_Model.objects.first() self.graph.access_token = token.token except AttributeError: # Fallback: Set facebook graph access token to app access token self.graph.access_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) if feed.requires_user_token: # If the Feed is set to require a user-token, and none exist in our db, the feed is skipped. print 'feed %d requires user token, skipping.' % feed.id data_dict = {'feed_id': feed.id, 'statuses': []} return data_dict # Get the data using the pre-set token if use_app_token: self.graph.access_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) return {'feed_id': feed.id, 'statuses': self.fetch_status_objects_from_feed(feed.vendor_id, post_number_limit, date_filters)} elif feed.feed_type == 'UP': # feed_type == 'UP' - User Profile # Set facebook graph access token to user access token token = User_Token_Model.objects.filter(feeds__id=feed.id).order_by('-date_of_creation').first() if not token: print 'No Token found for User Profile %s' % feed return {'feed_id': feed.id, 'statuses': []} else: print 'using token by user_id: %s' % token.user_id self.graph.access_token = token.token return {'feed_id': feed.id, 'statuses': self.fetch_status_objects_from_feed(feed.vendor_id, post_number_limit, date_filters)} else: # Deprecated or malfunctioning profile ('NA', 'DP') print 'Profile %s is of type %s, skipping.' % (feed.id, feed.feed_type) return {'feed_id': feed.id, 'statuses': []}
def get_posts(self, page_id, last_access): """ Obtain all posts made by other users on a wall """ access_token = facebook.get_app_access_token(self.app_id, self.app_secret) timestamp = calendar.timegm(last_access.timetuple()) graph = facebook.GraphAPI(access_token) query = ('SELECT actor_id, message, created_time FROM stream ' 'WHERE type < 0 AND source_id=%s ' 'AND created_time >= %s' % (page_id, timestamp)) return graph.fql(query)
def make_batch_request(cls, app, batch): if not app.app_access_token: access_token = facebook.get_app_access_token(app.app_id, app.app_secret) else: access_token = app.app_access_token ret = cls.graph.request(cls.graph.version + "/", post_args={'batch': json.dumps(batch), 'access_token': access_token, 'include_headers': 'false'}, method='POST') return ret
def test_fql(self): graph = facebook.GraphAPI(access_token=facebook.get_app_access_token( self.app_id, self.secret), version=2.0) # Ensure that version is below 2.1. Facebook has stated that FQL is # not present in this or future versions of the Graph API. if graph.get_version() < 2.1: # This is a tautology, but we are limited in what information # we can retrieve with a proper OAuth access token. fql_result = graph.fql( "SELECT app_id from application where app_id = %s" % self.app_id) self.assertEqual(fql_result["data"][0]["app_id"], str(self.app_id))
def connect_to_facebook(self): """Use the app keys in the settings to connect to the facebook graph api.""" try: access_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET) graph = facebook.GraphAPI(access_token) except urllib2.HTTPError: raise CommandError("Bad Facebook app id or secret key.") except urllib2.URLError: raise CommandError("Couldn't connect to facebook. You're probably offline.") return graph
def get_feed_data(self, feed, is_insist): """ Returns a Dict object of feed ID. and retrieved feed data. """ if feed.feed_type == 'UP': # User Profile data_dict = {'feed_id': feed.id, 'data': {}} return data_dict # Set facebook graph access token to user access token token = User_Token_Model.objects.all().order_by('-date_of_creation').first() if token: print 'token is: %s' % token.token self.graph.access_token = token.token else: print 'No User Access Token was found in the database, skipping' data_dict = {'feed_id': feed.id, 'data': {}} return data_dict # print Exception('No User Access Token was found in the database!') # TODO:Write as a real exception data_dict = {'feed_id': feed.id, 'data': self.fetch_user_profile_object_by_feed_id(feed.vendor_id, is_insist)} pprint(data_dict) # Transform data to fit existing public page data_dict['data']['username'] = ''.join( (data_dict['data']['first_name'], data_dict['data']['last_name'])).lower() data_dict['data']['likes'] = 0 data_dict['data']['talking_about_count'] = 0 data_dict['data']['about'] = '' return data_dict elif feed.feed_type == 'PP': # 'PP - Public Page' try: # Set facebook graph access token to most up-to-date user token in db token = User_Token_Model.objects.first() self.graph.access_token = token.token except: # Fallback: Set facebook graph access token to app access token self.graph.access_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) if feed.requires_user_token: # If the Feed is set to require a user-token, and none exist in our db, the feed is skipped. print 'feed %d requires user token, skipping.' % feed.id data_dict = {'feed_id': feed.id, 'data': {}} return data_dict # Get the data using the pre-set token data_dict = {'feed_id': feed.id, 'data': self.fetch_public_page_object_by_feed_id(feed.vendor_id, is_insist)} return data_dict else: # Deprecated or malfunctioning profile ('NA', 'DP') print 'Profile %s is of type %s, skipping.' % (feed.id, feed.feed_type) data_dict = {'feed_id': feed.id, 'data': {}} return data_dict
def status_update(request, status_id): status = Facebook_Status.objects_no_filters.get(status_id=status_id) response = HttpResponse(content_type="application/json", status=200) response_data = dict() response_data['id'] = status.status_id try: if status.needs_refresh: update_status_command = updatestatus.Command() update_status_command.graph.access_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) status_response_dict = update_status_command.fetch_status_object_data(status_id) or {} response_data['likes'] = getattr(getattr(getattr(status_response_dict, 'likes', 0), 'summary', 0), 'total_count', 0) response_data['comments'] = getattr(getattr(getattr(status_response_dict, 'comments', 0), 'summary', 0), 'total_count', 0) response_data['shares'] = getattr(getattr(status_response_dict, 'shares', 0), 'count', 0) try: update_status_command.update_status_object_in_db(retrieved_status_data=status_response_dict, status_object=status, options={'force-update': True, 'force-attachment-update': True}) finally: response.status_code = 200 except KeyError as e: response.status_code = 500 except GraphAPIError as e: response.status_code = 504 except ValueError as e: raise e except Exception as e: print 'status_update error:', e raise finally: format_int_or_null = lambda x: 0 if not x else "{:,}".format(x) response_data['likes'] = format_int_or_null(status.like_count) response_data['comments'] = format_int_or_null(status.comment_count) response_data['shares'] = format_int_or_null(status.share_count) response_data['id'] = status.status_id response.content = json.dumps(response_data) return response
def status_update(request, status_id): status = Facebook_Status.objects.get(status_id=status_id) response = HttpResponse(content_type="application/json") response_data = dict() response_data['id'] = status.status_id try: update_status_command = updatestatus.Command() update_status_command.graph.access_token = facebook.get_app_access_token( settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) status_response_dict = update_status_command.fetch_status_object_data( status_id) response_data['likes'] = getattr( getattr(getattr(status_response_dict, 'likes', None), 'summary', None), 'total_count', None) response_data['comments'] = getattr( getattr(getattr(status_response_dict, 'comments', None), 'summary', None), 'total_count', None) response_data['shares'] = getattr( getattr(status_response_dict, 'shares', None), 'count', None) try: status.like_count = int(response_data['likes']) status.comment_count = int(response_data['comments']) status.share_count = int(response_data['shares']) status.save() # print 'saved data to db' finally: format_int_or_null = lambda x: 0 if not x else "{:,}".format(x) response_data['likes'] = format_int_or_null(status.like_count) response_data['comments'] = format_int_or_null( status.comment_count) response_data['shares'] = format_int_or_null(status.share_count) response_data['id'] = status.status_id response.status_code = 200 except KeyError as e: response.status_code = 500 except GraphAPIError as e: response.status_code = 504 except ValueError as e: raise e finally: # print 'response is:', response_data response.content = json.dumps(response_data) return response
def __init__(self, person, uri_path, from_date = datetime.datetime.now(), to_date = None, limit = 25): self.person = person self.limit = limit self.uri_path = uri_path self.graph = facebook.GraphAPI(facebook.get_app_access_token(APP_ID, APP_SECRET), timeout = 20) self.id = self._get_id() self.until = None self._main_query = True self.from_date = from_date self.to_date = to_date self._day_shift = 90 #advance in the posts self._next_page()
def index(request): app_id = '238712782964401' # hasadna-OpenNewMedia-Pilot app_secret = '2914f1c0116fc917ad452a698834b92b' access_token = facebook.get_app_access_token(app_id, app_secret) graph = facebook.GraphAPI(access_token=access_token) list_of_pages = get_list_of_pages(number_of_pages=3) list_of_messages = [get_random_status_message(graph, page_id) for page_id in list_of_pages] context = {'list_of_messages': list_of_messages} return render(request, 'index.html', context)
def delete_subscription_real_time_updates(cls, app, data): if not app.app_access_token: access_token = facebook.get_app_access_token(app.app_id, app.app_secret) else: access_token = app.app_access_token data.update({'access_token': access_token}) url = cls.api_real_time_subscription.format(app.app_id) resp = requests.delete(url=url, data=data) resp_text = json.loads(resp.text) if resp.status_code and not 200 <= resp.status_code < 300: raise ConnectorError(cls._get_req_error_msg(resp_text)) else: return resp_text
def make_batch_request(cls, app, batch): if not app.app_access_token: access_token = facebook.get_app_access_token( app.app_id, app.app_secret) else: access_token = app.app_access_token ret = cls.graph.request(cls.graph.version + "/", post_args={ 'batch': json.dumps(batch), 'access_token': access_token, 'include_headers': 'false' }, method='POST') return ret
def delete_subscription_real_time_updates(cls, app, data): if not app.app_access_token: access_token = facebook.get_app_access_token( app.app_id, app.app_secret) else: access_token = app.app_access_token data.update({'access_token': access_token}) url = cls.api_real_time_subscription.format(app.app_id) resp = requests.delete(url=url, data=data) resp_text = json.loads(resp.text) if resp.status_code and not 200 <= resp.status_code < 300: raise ConnectorError(cls._get_req_error_msg(resp_text)) else: return resp_text
def handle(self, *args, **options): """ Executes fetchfeed manage.py command. Receives either one feed ID and retrieves Statuses for that feed, or no feed ID and therefore retrieves all Statuses for all the feeds. """ feeds_statuses = [] # Initialize facebook graph access tokens self.graph.access_token = facebook.get_app_access_token( settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) if options['initial']: fql_limit = DEFAULT_STATUS_SELECT_LIMIT_FOR_INITIAL_RUN else: fql_limit = DEFAULT_STATUS_SELECT_LIMIT_FOR_REGULAR_RUN print 'Variable fql_limit set to: {0}.'.format(fql_limit) # Case no args - fetch all feeds if len(args) == 0: for feed in Facebook_Feed_Model.objects.all(): self.stdout.write('Working on feed: {0}.'.format(feed.pk)) feeds_statuses.append(self.get_feed_statuses(feed, fql_limit)) self.stdout.write('Successfully fetched all') # Case arg exists - fetch feed by id supplied elif len(args) == 1: feed_id = int(args[0]) try: feed = Facebook_Feed_Model.objects.get(pk=feed_id) self.stdout.write( 'Successfully fetched feed id {0}'.format(feed_id)) except Facebook_Feed_Model.DoesNotExist: raise CommandError('Feed "%s" does not exist' % feed_id) feeds_statuses.append(self.get_feed_statuses(feed, fql_limit)) # Case invalid args else: raise CommandError('Please enter a valid feed id') # Insert fetched statuses to database for feed_statuses in feeds_statuses: for status in feed_statuses['statuses']: self.insert_status_object_to_db(status, feed_statuses['feed_id']) self.stdout.write('Successfully saved all statuses to db.')
def index(request): app_id = '238712782964401' # hasadna-OpenNewMedia-Pilot app_secret = '2914f1c0116fc917ad452a698834b92b' access_token = facebook.get_app_access_token(app_id, app_secret) graph = facebook.GraphAPI(access_token=access_token) list_of_pages = get_list_of_pages(number_of_pages=3) list_of_messages = [ get_random_status_message(graph, page_id) for page_id in list_of_pages ] context = {'list_of_messages': list_of_messages} return render(request, 'index.html', context)
def get_facebook_data(self, instance, fql): try: auth_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET) graph = facebook.GraphAPI(auth_token) if instance.count > 0: limit = ' limit %s' % instance.count else: limit = '' fql += limit query = graph.fql(fql % {'uid': instance.user_id}) return query except URLError: # Can't access facebook, return an empty response return []
def update_friends(self): self.friends.clear() app_key = settings.SOCIAL_AUTH_FACEBOOK_APP_KEY app_secret = settings.SOCIAL_AUTH_FACEBOOK_APP_SECRET token = facebook.get_app_access_token(app_key, app_secret) graph = facebook.GraphAPI(token) info = graph.get_connections(self.uid, 'friends') while True: self._update_raw_friends(info.get('data')) has_next = 'paging' in info and 'next' in info['paging'] if not has_next: break next_url = info['paging']['next'] info = json.loads(requests.get(next_url).text)
def fetch_comments_data(self, status, limit): """ Returns a Dict object with Status data, by Status ID, empty Dict if not working, None if status deleted. :param limit: """ status_dict = dict() is_skip = False if status.feed.feed_type == 'PP': try: # Set facebook graph access token to most up-to-date user token in db token = User_Token.objects.first() self.graph.access_token = token.token except AttributeError: # exception - trying to set an empty token (NoneType) as graph.access_token # Fallback: Set facebook graph access token to app access token self.graph.access_token = facebook.get_app_access_token( settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) if status.feed.requires_user_token: # If the Status's Feed is set to require a user-token, and none exist in our db, the feed is skipped. print 'feed %d requires user token, skipping.' % status.id is_skip = True # Get the data using the pre-set token elif status.feed.feed_type == 'UP': # feed_type == 'UP' - User Profile # Set facebook graph access token to user access token token = User_Token.objects.filter( feeds__id=status.id).order_by('-date_of_creation').first() if not token: print 'No Token found for User Profile %s' % status is_skip = True else: print 'using token by user_id: %s' % token.user_id self.graph.access_token = token.token else: # Deprecated or malfunctioning profile ('NA', 'DP') print 'Profile %s is of type %s, skipping.' % (status.id, status.feed_type) is_skip = True if not is_skip: status_dict = self.fetch_status_object_data( status.status_id, limit) return status_dict
def status_update(request, status_id): status = Facebook_Status.objects_no_filters.get(status_id=status_id) response = HttpResponse(content_type="application/json") response_data = dict() response_data['id'] = status.status_id try: update_status_command = updatestatus.Command() update_status_command.graph.access_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) status_response_dict = update_status_command.fetch_status_object_data(status_id) response_data['likes'] = getattr(getattr(getattr(status_response_dict, 'likes', None), 'summary', None), 'total_count', None) response_data['comments'] = getattr(getattr(getattr(status_response_dict, 'comments', None), 'summary', None), 'total_count', None) response_data['shares'] = getattr(getattr(status_response_dict, 'shares', None), 'count', None) try: status.like_count = int(response_data['likes']) status.comment_count = int(response_data['comments']) status.share_count = int(response_data['shares']) status.save() # print 'saved data to db' finally: format_int_or_null = lambda x: 0 if not x else "{:,}".format(x) response_data['likes'] = format_int_or_null(status.like_count) response_data['comments'] = format_int_or_null(status.comment_count) response_data['shares'] = format_int_or_null(status.share_count) response_data['id'] = status.status_id response.status_code = 200 except KeyError as e: response.status_code = 500 except GraphAPIError as e: response.status_code = 504 except ValueError as e: raise e finally: # print 'response is:', response_data response.content = json.dumps(response_data) return response
def handle(self, *args, **options): """ Executes fetchfeed manage.py command. Receives either one feed ID and retrieves Statuses for that feed, or no feed ID and therefore retrieves all Statuses for all the feeds. """ feeds_statuses = [] # Initialize facebook graph access tokens self.graph.access_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) if options["initial"]: fql_limit = DEFAULT_STATUS_SELECT_LIMIT_FOR_INITIAL_RUN else: fql_limit = DEFAULT_STATUS_SELECT_LIMIT_FOR_REGULAR_RUN print "Variable fql_limit set to: {0}.".format(fql_limit) # Case no args - fetch all feeds if len(args) == 0: for feed in Facebook_Feed_Model.objects.all(): self.stdout.write("Working on feed: {0}.".format(feed.pk)) feeds_statuses.append(self.get_feed_statuses(feed, fql_limit)) self.stdout.write("Successfully fetched all") # Case arg exists - fetch feed by id supplied elif len(args) == 1: feed_id = int(args[0]) try: feed = Facebook_Feed_Model.objects.get(pk=feed_id) self.stdout.write("Successfully fetched feed id {0}".format(feed_id)) except Facebook_Feed_Model.DoesNotExist: raise CommandError('Feed "%s" does not exist' % feed_id) feeds_statuses.append(self.get_feed_statuses(feed, fql_limit)) # Case invalid args else: raise CommandError("Please enter a valid feed id") # Insert fetched statuses to database for feed_statuses in feeds_statuses: for status in feed_statuses["statuses"]: self.insert_status_object_to_db(status, feed_statuses["feed_id"]) self.stdout.write("Successfully saved all statuses to db.")
def fetch_comments_data(self, status, limit): """ Returns a Dict object with Status data, by Status ID, empty Dict if not working, None if status deleted. :param limit: """ status_dict = dict() is_skip = False if status.feed.feed_type == 'PP': try: # Set facebook graph access token to most up-to-date user token in db token = User_Token.objects.first() self.graph.access_token = token.token except AttributeError: # exception - trying to set an empty token (NoneType) as graph.access_token # Fallback: Set facebook graph access token to app access token self.graph.access_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) if status.feed.requires_user_token: # If the Status's Feed is set to require a user-token, and none exist in our db, the feed is skipped. print 'feed %d requires user token, skipping.' % status.id is_skip = True # Get the data using the pre-set token elif status.feed.feed_type == 'UP': # feed_type == 'UP' - User Profile # Set facebook graph access token to user access token token = User_Token.objects.filter(feeds__id=status.id).order_by('-date_of_creation').first() if not token: print 'No Token found for User Profile %s' % status is_skip = True else: print 'using token by user_id: %s' % token.user_id self.graph.access_token = token.token else: # Deprecated or malfunctioning profile ('NA', 'DP') print 'Profile %s is of type %s, skipping.' % (status.id, status.feed_type) is_skip = True if not is_skip: status_dict = self.fetch_status_object_data(status.status_id, limit) return status_dict
def daily_user_update_connections(): app_access_token = facebook.get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET) graph = facebook.GraphAPI(app_access_token) #Get active users actives = User.objects.filter(type=User.ACTIVE) errors = 0 for active in actives: try: _id = active._id friends = graph.get_connections(_id, "friends").get('data') logger.warning("daily_user_update_connections user_id:%s 2" % _id) social.ensure_exists(_id, active.network) logger.warning("daily_user_update_connections user_id:%s 3" % _id) new_friends = {f['id'] : f for f in friends} r = update_friends_async(_id, [friend['id'] for friend in friends]) logger.warning("daily_user_update_connections user_id:%s 4" % _id) #Get the people who are on keen around me and figure out their mutual relations users = col_get(USER_, {'network' : active.network}) logger.warning("daily_user_update_connections user_id:%s 5" % _id) user_ids = [u.get('_id') for u in users] #make sure the update_friends has finished dr = DummyRequest() dr.session = {} user = User.get_by_id(_id) rms = social.get_relation_mutuals_cache_v2(dr, user, user_ids, force_reload=True, check_cache_only=False) logger.warning("daily_user_update_connections user_id:%s 6" % _id) #try to get friends then run check_friends alg # try: # friends = graph.get_connections(active._id, "friends").get('data') ## print friends['data'] # new_friends = {} # for friend in friends: # id_ = friend['id'] # f = {'name' : friend.get('name', ''), 'id' : id_, 'city_id' : '', 'city_name' : ''} # new_friends[id_] = f # new_friend_ids = active.check_friends(new_friends) except facebook.GraphAPIError: #Maybe the user has uninstalled us frorm fb errors += 1 return "Completed daily user update connections for %s users, with %s facebook graph errors" % (str(len(actives)), str(errors))
def handle(self, *args, **options): """ Executes fetchperson manage.py command. Receives either one feed ID and retrieves the relevant page's data, and updates them in the db, or no feed ID and therefore retrieves data for all the feeds. """ feeds_data = [] # Initialize facebook graph access tokens self.graph.access_token = facebook.get_app_access_token( settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) # Case no args - fetch all feeds if len(args) == 0: for feed in Facebook_Feed_Model.objects.all(): self.stdout.write('Working on feed: {0}.'.format(feed.pk)) feeds_data.append(self.get_feed_data(feed)) self.stdout.write('Successfully fetched all') # Case arg exists - fetch feed by id supplied elif len(args) == 1: feed_id = int(args[0]) try: feed = Facebook_Feed_Model.objects.get(pk=feed_id) self.stdout.write( 'Successfully fetched feed id {0}'.format(feed_id)) except Facebook_Feed_Model.DoesNotExist: raise CommandError('Feed "%s" does not exist' % feed_id) feeds_data.append(self.get_feed_data(feed)) # Case invalid args else: raise CommandError('Please enter a valid feed id') # Update fetched data to feed in database for feed_data in feeds_data: self.update_feed_data_to_db(feed_data['data'], feed_data['feed_id']) self.stdout.write('Successfully saved all statuses to db.')
def _request_and_advance(self, path, post_args): #get the data try: data = self.graph.request(path, post_args) except GraphAPIError: self.graph.access_token = facebook.get_app_access_token(APP_ID, APP_SECRET) data = self.graph.request(path, post_args) except URLError: #retry data = self.graph.request(path, post_args) #the actual results if data.has_key('data'): self._list = data['data'] #until will change if data.has_key('paging'): next_url = data['paging']['next'] self.until = self._get_until(next_url) else: self._list = None
def main(): print "Please note that this program will not fail gracefully if you enter the wrong Facebook app information." klassif_username = raw_input("Enter your username for Klassif.io: \n") klassif_password = raw_input("Enter your password for Klassif.io: \n") add_authentication(klassif_username, klassif_password) mode = raw_input("Do you want to enter posts manually or pull them from public Facebook posts? Enter manual or auto: \n") if mode == "auto": app_id = raw_input("Enter the app id of your Facebook app: \n") app_secret = raw_input("Enter the app secret of your Facebook app: \n") print "Getting Facebook access token" access_token = facebook.get_app_access_token(app_id, app_secret) print "Done." search_term = raw_input("Enter a search term to use to find public Facebook posts: \n") run_post_classifying_loop(access_token, search_term) elif mode == "manual": run_manual_classify_loop() else: print "Invalid mode. Goodbye."
def subscribe_real_time_updates(cls, app, data): cls.authenticate(app) url = cls.api_app_page_subscription.format(app.community.external_id) data_token = ({'access_token': app.community.token}) resp = requests.post(url=url, data=data_token) resp_text = json.loads(resp.text) if resp.status_code and not 200 <= resp.status_code < 300: raise ConnectorError(cls._get_req_error_msg(resp_text)) else: if not app.app_access_token: access_token = facebook.get_app_access_token(app.app_id, app.app_secret) else: access_token = app.app_access_token data.update({'access_token': access_token}) url = cls.api_real_time_subscription.format(app.app_id) resp = requests.post(url=url, data=data) resp_text = json.loads(resp.text) if resp.status_code and not 200 <= resp.status_code < 300: raise ConnectorError(cls._get_req_error_msg(resp_text)) else: return resp_text
def subscribe_real_time_updates(cls, app, data): cls.authenticate(app) url = cls.api_app_page_subscription.format(app.community.external_id) data_token = ({'access_token': app.community.token}) resp = requests.post(url=url, data=data_token) resp_text = json.loads(resp.text) if resp.status_code and not 200 <= resp.status_code < 300: raise ConnectorError(cls._get_req_error_msg(resp_text)) else: if not app.app_access_token: access_token = facebook.get_app_access_token( app.app_id, app.app_secret) else: access_token = app.app_access_token data.update({'access_token': access_token}) url = cls.api_real_time_subscription.format(app.app_id) resp = requests.post(url=url, data=data) resp_text = json.loads(resp.text) if resp.status_code and not 200 <= resp.status_code < 300: raise ConnectorError(cls._get_req_error_msg(resp_text)) else: return resp_text
def main(): auth = tweepy.OAuthHandler(consumer_key, consumer_secret) redir_url = auth.get_authorization_url() print('Go here on your browser:\n' + redir_url) pin = raw_input('PIN: ') tw = auth.get_access_token(pin) fb = facebook.get_app_access_token(app_id, app_secret) print('== Twitter ==') print('consumer_key: ' + consumer_key) print('consumer_secret: ' + consumer_secret) print('access_token: ' + tw[0]) print('access_token_secret: ' + tw[1]) print('') print('== Facebook ==') print('app_id: ' + app_id) print('app_secret: ' + app_secret) print('app_access_token: ' + fb) print('') print('Don\'t share these with anybody!')
def test_get_app_access_token(self): token = facebook.get_app_access_token(self.app_id, self.secret) # Since "unicode" does not exist in Python 3, we cannot check # the following line with flake8 (hence the noqa comment). assert (isinstance(token, str) or isinstance(token, unicode)) # noqa
def crunch_post_and_write(self, obj_name, multiple_flag): self.reset() self.obj_name = obj_name graph = facebook.GraphAPI( get_app_access_token(FACEBOOK_APP_ID, FACEBOOK_SECRET_ID)) field_names = ['count', 'id', 'name'] with open(self.generate_path(self.post_id, "likes", multiple_flag), 'wb') as csvfile: csv_writer = csv.DictWriter(csvfile, field_names) csv_writer.writeheader() while True: while True: try: if self.next_page is not None: post_object = graph.get_object( self.post_id + '/likes', limit=2500, after=self.next_page, fields="id, name") break else: post_object = graph.get_object(self.post_id + '/likes', limit=2500, fields="id, name") break except KeyError: print "No likes!" break except facebook.GraphAPIError: print "Facebook Timed Out, retrying after 10 seconds." time.sleep(5.0) continue if not post_object['data']: print "End of list for post " + self.post_id + "!" print "There were {} likes!".format(self.object_count) return self.object_count try: self.next_page = post_object['paging']['cursors']['after'] except KeyError: print "No 'after' paging detected. End of list?" likes_from_post = post_object['data'] # Write to the CSV for liker in likes_from_post: try: csv_writer.writerow({ 'count': self.object_count, 'id': liker['id'], 'name': liker['name'] }) except UnicodeEncodeError: # Weird symbols in FB Name. reformed_name = ''.join(i for i in liker['name'] if ord(i) < 128) csv_writer.writerow({ 'count': self.object_count, 'id': liker['id'], 'name': reformed_name }) finally: self.object_count += 1
def __setup_fb(self): self.fb_app_token = facebook.get_app_access_token(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET) self.graph = facebook.GraphAPI(self.fb_app_token, version="2.1") self.rest_url = "http://api.facebook.com/restserver.php?method=links.getStats&urls="
def test_get_app_access_token(self): token = facebook.get_app_access_token(self.app_id, self.secret) assert(isinstance(token, str) or isinstance(token, unicode))
+ "Displays the list of aliases and their respective facebook page" bot.sendMessage(user, helpMessage) # Handle all messages def handle(msg): if "text" in msg: text = msg["text"] if text[0] == "/": user = msg["from"] split = text.strip().split(" ") cmd = split[0][1:] args = split[1:] command(user["id"], cmd, args) # Create our bot instance with our token, passed as a system argument bot = telepot.Bot(key) accesstoken = facebook.get_app_access_token(fbid, fbsecret) graph = facebook.GraphAPI(access_token=accesstoken) # Tell the bot to call handle() when a message is received bot.notifyOnMessage(handle) print "Running..." # This keeps the program running. Idk what the significance of the 10 is, just based on example docs while 1: time.sleep(30) # maybe change processPages()
def get_feed_data(self, feed, is_insist): """ Returns a Dict object of feed ID. and retrieved feed data. """ if feed.feed_type == 'UP': # User Profile data_dict = {'feed_id': feed.id, 'data': {}} return data_dict # Set facebook graph access token to user access token token = None if feed.tokens.all(): token = feed.tokens.order_by('-date_of_creation').first() elif feed.requires_user_token: print feed.tokens.all() print 'feed requires user token' pass elif User_Token.objects.all(): print 'feed does not require a particular user token.' token = User_Token.objects.all().order_by( '-date_of_creation').first() print 'token is: %s.' % token if token: print 'token is: %s' % token.token self.graph.access_token = token.token else: print 'No User Access Token was found in the database, skipping' data_dict = {'feed_id': feed.id, 'data': {}} return data_dict # print Exception('No User Access Token was found in the database!') # TODO:Write as a real exception data_dict = { 'feed_id': feed.id, 'data': self.fetch_user_profile_object_by_feed_id( feed.vendor_id, is_insist) } pprint(data_dict) # Transform data to fit existing public page data_dict['data']['username'] = ''.join( (data_dict['data']['first_name'], data_dict['data']['last_name'])).lower() data_dict['data']['likes'] = 0 data_dict['data']['talking_about_count'] = 0 data_dict['data']['about'] = '' return data_dict elif feed.feed_type == 'PP': # 'PP - Public Page' try: # Set facebook graph access token to most up-to-date user token in db token = User_Token.objects.first() self.graph.access_token = token.token except: # Fallback: Set facebook graph access token to app access token self.graph.access_token = facebook.get_app_access_token( settings.FACEBOOK_APP_ID, settings.FACEBOOK_SECRET_KEY) if feed.requires_user_token: # If the Feed is set to require a user-token, and none exist in our db, the feed is skipped. print 'feed %d requires user token, skipping.' % feed.id data_dict = {'feed_id': feed.id, 'data': {}} return data_dict # Get the data using the pre-set token data_dict = { 'feed_id': feed.id, 'data': self.fetch_public_page_object_by_feed_id( feed.vendor_id, is_insist) } return data_dict else: # Deprecated or malfunctioning profile ('NA', 'DP') print 'Profile %s is of type %s, skipping.' % (feed.id, feed.feed_type) data_dict = {'feed_id': feed.id, 'data': {}} return data_dict
def __init__(self, start_page_id=0): self.start_page_id = start_page_id self.graph.access_token = facebook.get_app_access_token( '1379244598975239', 'cf601ab7afd846d736601704787435fe') self.job_regexes = map(compile, self.job_regexes)
import facebook as fbsdk from socialfeedsparser.contrib.parsers import ChannelParser, PostParser from .settings import FACEBOOK_CLIENT_ID, FACEBOOK_CLIENT_SECRET FACEBOOK_ACCESS_TOKEN = fbsdk.get_app_access_token( FACEBOOK_CLIENT_ID, FACEBOOK_CLIENT_SECRET) class FacebookSource(ChannelParser): """ Collect class for Facebook. """ name = 'Facebook' slug = 'facebook' def get_messages_user(self, feed_id, count=20): """ Return posts from user or page feed. :param feed_id: id of the page or user to parse. :type item: str :param count: number of items to retrieve (default 20). :type item: int """ return self.get_api().get_connections(feed_id.encode('utf-8'), 'feed')['data'] def get_messages_search(self, search):
def __init__(self): self.posts = list() self.users = dict() self.access_token = get_app_access_token(FACEBOOK_APP_ID, FACEBOOK_SECRET_ID) self.chdir = Chdir()
def get(self, request, format=None): try: page = int(request.GET.get('page')) mode = request.GET.get('mode') except: return HttpResponseBadRequest() items_per_page = 10 if page == 1: items_per_page *= 2 else: page += 1 all_members = ghp_members() if request.user.is_authenticated(): client = request.user.client all_members = ghp_members().exclude(pk=client.pk) if mode == 'favorites': client_content_type = get_person_content_type('client') favorite_ids = HealingPersonStatus.objects.filter( client=client, status=HealingPersonStatus.FAVORITE, person_content_type=client_content_type).values_list( 'person_object_id', flat=True) all_members = all_members.filter(id__in=favorite_ids) elif mode == 'urgent': urgent_ids = GhpSettings.objects.filter(urgent=True).values_list( 'user', flat=True) all_members = all_members.filter(user__in=urgent_ids) elif mode == 'facebook': try: fb_id = request.user.userassociation_set.get( service='facebook').identifier[3:] facebook_key = settings.OAUTH_ACCESS_SETTINGS['facebook'][ 'keys'] token = facebook.get_app_access_token(facebook_key['KEY'], facebook_key['SECRET']) except UserAssociation.DoesNotExist: token = '' if token: graph = facebook.GraphAPI(token) friends = graph.get_connections( id=fb_id, connection_name='friends')['data'] friends = ['fb-' + friend['id'] for friend in friends] users = UserAssociation.objects.filter( identifier__in=friends).values_list('user_id', flat=True) all_members = Client.objects.filter(user__in=users) else: return Response( render_to_string('phonegap/link_with_facebook.html')) members = all_members[(page - 1) * items_per_page:page * items_per_page] is_last_page = all_members.count() < items_per_page * page return Response( render_to_string( 'phonegap/list_contents.html', { 'members': members, 'next_page': page + 1, 'is_last_page': is_last_page, 'mode': mode }))
def test_get_app_access_token(self): assert (isinstance( facebook.get_app_access_token(self.app_id, self.secret), str))
def get_app_access_token(self): return facebooklib.get_app_access_token(self._app_id, self._app_secret)