def get_friend_event(user, access_token): graph = GraphAPI(access_token) events = graph.get_connections(user['id'], 'events') for event in events['data']: event = EventActions.create(event, user['id']) pass
def get_details_for_profile_from_user(self, requesting_user, **kwargs): ''' For the details, we need: 1. Cover pic 2. Profile pic 3. Location if available More details about usage from core.models ''' access_token = self.social_auth.get( provider="facebook").extra_data.get("access_token") graph = GraphAPI(access_token) details_dict = {} try: info = graph.get_object("me", fields="picture, cover, location") details_dict['picture'] = info.get('picture', {}).get('data', {}).get('url', None) details_dict['cover'] = info.get('cover', {}).get('source', None) details_dict['location'] = info.get('location', {}).get('name', None) return details_dict except: logger.error( "accounts.models.BanyanUser:get_details_for_profile_from_user {}{} access_token:{}" .format(sys.exc_info()[0], sys.exc_info()[1], access_token)) return []
def harvest_facebook_profile(self): harvest_profile_d = Deferred() logging.info('Facebook Service - Getting users Facebook Profile') graph = GraphAPI(self.facebook_access_token_long) profile = graph.get_object("me") timestamp = str(datetime.datetime.now().isoformat('T')).split(".")[0] uniq_id = "facebook_profile_for_me" object_to_insert = { "@id": uniq_id, "app_object": app_id, "timestamp": timestamp, "facebook_profile": profile } #now need to perform the asnc def insert_cb(re): logging.debug( "Facebook Service - Found Facebook Profile information, Added To INDX {0} profile items" .format(len(profile))) harvest_profile_d.callback(True) def insert_cb_fail(re): harvest_profile_d.callback(True) self.insert_object_to_indx(object_to_insert).addCallbacks( insert_cb, insert_cb_fail) return harvest_profile_d
def add_facebook_token(): """Add token to db""" access_token = request.form.get("access_token") facebook_user_id = request.form.get("facebook_user_id") graph = GraphAPI(access_token) app_id = os.environ['FACEBOOK_APP_ID'] app_secret = os.environ['FACEBOOK_APP_SECRET'] extended_token = graph.extend_access_token(app_id, app_secret) final_token = extended_token['access_token'] facebook_info = FacebookInfo.query.filter_by( facebook_user_id=facebook_user_id, user_id=session['user_id']).first() if not facebook_info: facebook_info = FacebookInfo(user_id=session["user_id"], access_token=final_token, facebook_user_id=facebook_user_id) else: facebook_info.access_token = access_token db.session.add(facebook_info) db.session.commit() return "success"
def id2page(iden): token = g.user['access_token'] graph = GraphAPI(token) pages = graph.get_object('me/accounts') for page in pages['data']: if iden == page['id']: return page
def on_authenticate_facebook(self, response): try: access_token, expires_in = \ response['accessToken'], response['expiresIn'] signed_request = parse_signed_request( response['signedRequest'], app.config['FACEBOOK_SECRET'], expires_in ) if not signed_request: return None, None graph = GraphAPI(access_token) profile = graph.get_object('me') user = User.get_by_facebook(profile['id']) if not user or user.status == User.NOT_REGISTERED_YET: if not user: user = User() user.facebook_account = FacebookAccount() user.email = profile['email'] user.facebook_account.name = user.nickname = profile['name'] user.facebook_account.uid = profile['id'] user.status = User.NORMAL db.session.add(user) db.session.commit() self.online_users[self] = self.session['user_id'] = user.id self.facebook_access_token = access_token, signed_request['expires_at'] return None, user.to_json() except GraphAPIError, e: return {'_type': 'GraphAPIError', 'msg': str(GraphAPIError)},
def scrape_facebook(self, profile_filename=None, posts_filename=None): """ Scrape! """ logger.info('Scraping Facebook (start time: %s)' % self.run_time) if profile_filename and posts_filename: with open(profile_filename) as f: profile = json.load(f) with open(posts_filename) as f: api_posts = json.load(f) else: self.graph = GraphAPI(self.access_token) profile = self.graph.get_object(self.user) api_posts = self.graph.get_connections(profile['id'], 'posts') posts = [] for api_post in api_posts['data']: post = Post(api_post, self.run_time) posts.append(post) logger.info('Scraped basic information for %s from Facebook (%s)' % (post.facebook_id, post.headline)) return posts
def get(self): import facebookoauth from facebookoauth import FBUser import pprint, StringIO co2=100 aaa="" pg=self.request.get('pg') if pg: pg = int(pg) else: pg=0 hout = "" prid=self.request.get('id') 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 errorjson = False profile = {'id': 0} try: graph = GraphAPI(access_token) profile = graph.get_object(prid) 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]))
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
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
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
def get(app_name): parser = reqparse.RequestParser() parser.add_argument('id', type=str, location='args', required=True, help='User id cannot be blank') parser.add_argument('access_token', type=str, location='args', required=True) values = parser.parse_args(strict=True) cursor = conn.cursor(pymysql.cursors.DictCursor) cursor.execute("SELECT TOKEN FROM FACEBOOK WHERE USER_ID=%s AND APP=%s;", (values['id'], app_name)) results = cursor.fetchall() cursor.close() if results != (): access_token = results[0]['TOKEN'] try: graph = GraphAPI(access_token=access_token, version=API_VERSION) permissions = graph.get_permissions(user_id=values['id']) except GraphAPIError: logging.info('Expired access token: {}'.format(access_token)) return error_message('GraphAPI', 'Expired Token', 403), 403 if all(x in ['public_profile', 'user_friends'] for x in permissions): logging.info('\'user_friends\' permission denied for user with id: {}'.format(values['id'])) return error_message('Permission', 'User Friends permission', 403), 403 friends_call = 'https://graph.facebook.com/' + values['id'] + '/friends' friends = requests.get(friends_call, params={'access_token': access_token}).json()['data'] logger.info('HTTP GET successfully processed') return {'ack': 'true', 'msg': friends}, 200 else: return {'ack': 'false', 'msg': 'Invalid User'}, 200
def post(self, *args, **kwargs): try: graph = GraphAPI(access_token=self.request.data['access_token'], version=settings.FACEBOOK_APP_VERSION) graph_data = graph.get_object(id='me', fields='email,first_name,last_name') except GraphAPIError: raise ParseError(detail='Invalid Facebook access token') data = { **graph_data, 'password': get_user_model().objects.make_random_password() } user, created = get_user_model().objects.get_or_create( email=data['email']) signup_ser = SignUpSerializer(instance=user, data=data) signup_ser.is_valid(raise_exception=True) user = signup_ser.save(is_active=True) token_ser = JSONWebTokenSerializer(data={ 'email': data['email'], 'password': data['password'] }) token_ser.is_valid(raise_exception=True) HistoryRecord.objects.create_history_record( user, None, HISTORY_RECORD_USER_SIGNUP_FACEBOOK) return Response( {'token': token_ser.object.get('token')}, status=status.HTTP_201_CREATED if created else status.HTTP_200_OK)
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
def fix_facebook_ids(): """ Retroactively adds Facebook IDs to Facebook table """ db = dataset.connect(app_config.POSTGRES_URL) table = db['facebook'] min_created_time_result = list(db.query('select min(created_time) as min_created_time from facebook')) min_created_time = min_created_time_result[0]['min_created_time'] graph = GraphAPI(SECRETS['FACEBOOK_TOKEN']) profile = graph.get_object(FACEBOOK_USER) posts = graph.get_connections(profile['id'], 'posts') done = False while not done: print 'processing batch of 25' for post in posts['data']: created_time = parser.parse(post['created_time'], ignoretz=True) if created_time < min_created_time: done = True break if 'link' not in post.keys(): print 'skipping %s (no link)' % post['id'] continue link = post['link'].split('?')[0] print 'updating %s (%s)' % (link, post['id']) table.update({ 'facebook_id': post['id'], 'link_url': link, }, ['link_url']) posts = requests.get(posts['paging']['next']).json()
def get_current_user(): if session.get('user'): g.user = session.get('user') return result = get_user_from_cookie(cookies=request.cookies, app_id=APP_ID, app_secret=SECRET_KEY) if result: user = User.query.filter(User.id == result['uid']).first() if not user: graph = GraphAPI(result['access_token']) profile = graph.get_object('me?fields=email,first_name,last_name,name,link,id,gender') user = User(id=str(profile['id']), name=profile['name'], first_name=profile['first_name'], last_name=profile['last_name'], email=profile['email'], gender=profile['gender'], link=profile['link'], access_token=result['access_token']) db.session.add(user) elif user.access_token != result['access_token']: user.access_token = result['access_token'] session['user'] = dict(id=user.id, name=user.name, access_token=user.access_token) db.session.commit() g.user = session.get('user', None)
def list_fb_pages(): token = config("FB_PYTHON_ACCESSTOKEN", default=None) if token != None: graph = GraphAPI(token) groups = graph.get_object("me/groups") return groups return []
class FacebookResource: FB_URL_PATTERN = re.compile('(?:(?:http|https)://)?(?:www.)?(mbasic.facebook|m\.facebook|facebook|fb)\.(com|me)/') def __init__(self, app_id, app_secret): self.facebook = GraphAPI() self.facebook.access_token = self.facebook.get_app_access_token(app_id, app_secret) def extract_fanpage_name_from_url(self, url: str): if self.FB_URL_PATTERN.match(url, 0): sub_url = self.FB_URL_PATTERN.sub('', url) return sub_url.rsplit('/', 1)[0].replace('/', '') return url def get_all_posts(self, page_name: str): return self.__get_all_connections(page_name, 'posts') def get_all_comments(self, post_id: str): return self.__get_all_connections(post_id, 'comments') def __get_all_connections(self, id: str, connection: str, **args): assert id is not None assert connection is not None while True: page = self.facebook.get_connections(id, connection, **args) for item in page['data']: yield item next_page = page.get('paging', {}).get('next') if not next_page: return args = parse_qs(urlparse(next_page).query) del args['access_token']
def create_event(request): if 'facebook_id' in request.session: c = {} c['facebook_id'] = request.session['facebook_id'] c['first_name'] = request.session['first_name'] c['last_name'] = request.session['last_name'] facebook_id = request.session['facebook_id'] facebook_user = FacebookUser.objects.filter(facebook_id=facebook_id)[0] if 'loc' in request.session and 'event' in request.session and 'restaurant' in request.session: location = Location.objects.filter(reference=request.session['loc'])[0] event = Event.objects.filter(event_id=request.session['event'])[0] restaurant = Restaurant.objects.filter(reference=request.session['restaurant'])[0] del request.session['loc'] del request.session['event'] del request.session['restaurant'] graph = GraphAPI(request.session['access_token']) event_name = "Trip to " + location.name description = "We will be going to " + location.name + ". " + "We will then be going to " + event.name + ". Then we will eat at " + restaurant.name +". This event has been created with PlanMyNY." sample_event = graph.post('me/events', params={"name":event_name, "description":description, "location":"New York City","start_time":"2014-02-09T16:00-5:00", "end_time":"2014-02-09T23:00-5:00", "privacy_type":"FRIENDS"}) event_id = sample_event['id'] c['event_link'] = "http://www.facebook.com/events/" + event_id trip = Trip.create(facebook_user,location,event,restaurant,c['event_link']) trip.save() return render_to_response("success.html", c) else: return redirect("profile/") else: return redirect("/")
def load_facebook_events(nodes, token=os.environ.get('FACEBOOK_TOKEN')): """ Load events from Facebook pages to the events file. ..important: In order for this function to work, you need to to provide a valid Facebook Graph API token. You can get yours easily on https://developers.facebook.com/tools/explorer :param nodes: Facebook nodes to load public events from. :param token: Facebook Graph API token. """ graph = GraphAPI(access_token=token) with open('data/events.yml', 'r') as events_file: existing_events = yaml.load(events_file) # Get facebook metadata on existing entries facebook_ids = {entry.get('facebook_id') for entry in existing_events} fetched_events = [] for node in nodes: event_node = "{}/events".format(node) # XXX: Ideally we would follow subrequests, but a large limit # should work as a simple solution. node_events = graph.get_object(event_node, limit=1000) for event in node_events['data']: # If event already exists, just ignore if event['id'] in facebook_ids: continue # We need to reshape datetimes to events format format_date = datetime.strptime(event['start_time'], '%Y-%m-%dT%H:%M:%S%z') fetched_events.append({ 'name': event['name'], 'url': 'https://facebook.com/{}'.format(event['id']), 'local': event.get('place', {}).get('name', ''), 'date': format_date.strftime('%d-%m-%Y'), 'facebook_id': str(event['id']) }) # Pretty print new entries on the events file with open('data/events.yml', 'a') as events_file: for entry in fetched_events: events_file.write('\n') yaml.dump([entry], events_file, default_flow_style=False, allow_unicode=True)
def login(request): ret = None if request.method == 'POST': form = FacebookConnectForm(request.POST) if form.is_valid(): token = form.cleaned_data['access_token'] g = GraphAPI(token) data = g.get_object("me") email = valid_email_or_none(data.get('email')) social_id = data['id'] try: account = FacebookAccount.objects.get(social_id=social_id) except FacebookAccount.DoesNotExist: account = FacebookAccount(social_id=social_id) account.link = data['link'] account.name = data['name'] #adding the storing of users accesstoken account.access_token = token if account.pk: account.save() data = dict(email=email,facebook_me=data) ret = complete_social_login(request, data, account) if not ret: ret = render_authentication_error(request) return ret
def sync_facebook(name): #import ipdb; ipdb.set_trace(); try: form_data = json.loads(request.data) except: return response_msg('error', 'data not correct') try: graph = GraphAPI(form_data['access_token']) try: # #import ipdb; ipdb.set_trace(); email = graph.get_object('me', fields='email')['email'] pic = graph.get_object('me/picture', width='400', height='400')['url'] print pic if email != form_data['fb_email']: return response_msg('error', 'incorrect facebook email') except: return response_msg('error', 'data not complete') except: return response_msg('error', 'invalid access token') try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name).update({ 'fb_email': email, 'pic': pic }).run(connection) cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name).run(connection) except: return response_msg('error', 'Could not connect to db') return response_msg('success', 'OK', data=cursor.items[0])
def getcontents(): from re import search result = get_user_from_cookie(cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET) graph = GraphAPI(ACCESS_TOKEN) url = request.form['url'] info = search(r""" ((?<=facebook.com/)(?P<page_name>\w*))/posts/(?P<post_id>\d*$) """, url).groupdict() page_id = graph.get_object(id=info['page_name'], fields=['id'])['id'] full_id = "%s_%s" % (page_id, info['post_id']) print(full_id) post = graph.get_object(id=full_id, fields=['attachments']) #print(post['message']) data = post['attachments']['data'][0] if data['type'] != 'album': return False img_urls = [] for subdata in data['subattachments']['data']: if subdata['type'] == 'photo': img_urls.append(subdata['media']['image']['src']) else: return "Invalid type" print(img_urls) get_contents(img_urls).apply_async()
def room(request, name, slug): """ Show a room. """ if request.user.username == name: c = {} c.update(csrf(request)) context = {"room": get_object_or_404(Call, slug=slug)} #print request.user #template="space/room.html" owner=request.user try: owner.token = UserSocialAuth.objects.get(user__username=owner.username, provider='facebook').extra_data['access_token'] owner.uid = UserSocialAuth.objects.get(user__username=owner.username, provider='facebook').uid graph = GraphAPI(owner.token) friends = graph.get_connections(owner.uid, "friends", fields="installed,id,name")['data'] me = graph.get_object("me") except: uid = '' token = '' friends = '' me = '' return render_to_response('space/room.html',context, RequestContext(request,{'owner': owner, 'me': me})) #return render(request, template, context) else: raise Http404
def get_current_user(): if session.get('user'): g.user = session.get('user') return # Attempt to get the short term access token for the current user. result = get_user_from_cookie(cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET) if result: user = User.query.filter(User.id == result['uid']).first() if not user: graph = GraphAPI(result['access_token']) profile = graph.get_object('me') # Create the user and insert it into the database user = User(id=str(profile['id']), name=profile['name'], profile_url=profile['link'], access_token=result['access_token']) db.session.add(user) elif user.access_token != result['access_token']: user.access_token = result['access_token'] session['user'] = dict(name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token) db.session.commit() g.user = session.get('user', None)
def show_post_form_pages(): """Show posting for for Facebook Pages""" if 'user_id' not in session: flash("You need to be logged in for that!") return redirect('/') user_id = session["user_id"] user = User.query.filter_by(user_id=user_id).first() username = user.username facebook_info = FacebookInfo.query.filter_by(user_id=user_id).first() if not facebook_info: flash("You need to log into Facebook first!") return redirect('/') access_token = facebook_info.access_token api = GraphAPI(access_token) page_response = api.get_connections("me", "accounts") return render_template("post_pages.html", username=username, pages=page_response["data"])
class FacebookAdapter(AbstractAdapter): access_token = "" graph_api = None def __init__(self, params): if "access_token" in params: self.access_token = params["access_token"] self.graph_api = GraphAPI(self.access_token) else: raise LookupError("access_token key was not found in parameter dictionary") pass def getAuthorizedPerson(self): user_object = self.graph_api.get_object("me") return FacebookPerson(self.graph_api, user_object) def getPerson(self, person_id): user_object = self.graph_api.get_object(person_id) return FacebookPerson(self.graph_api, user_object) def getServiceName(self): return "Facebook Social Network" def getServiceDescription(self): pass def getServiceUrl(self): pass
def get_friend_post(user, access_token): graph = GraphAPI(access_token) posts = graph.get_connections(user['id'], 'posts') for post in posts['data']: post = PostActions.create(post, user['id']) pass
def index(name="index", *args, **kawrgs): if request.is_xhr: return "", 400 if g.user: # try: graph = GraphAPI(g.user['access_token']) args = {'fields': 'birthday, name, email'} facebook_friends = graph.get_object('me/friends', **args) user = UserActions.find_by_id(g.user['id']) for facebook_friend in facebook_friends['data']: friend = UserActions.new(facebook_friend) FriendRelationshipActions.create(user, friend) relations = FriendRelationshipActions.find_by_user(user) return render_template("index.html", app_id=app.config["FB_APP_ID"], user=user, relations=relations) # except Exception: # return redirect(url_for('logout')) return render_template("login.html", app_id=app.config["FB_APP_ID"])
def sync_facebook(name): #import ipdb; ipdb.set_trace(); try: form_data = json.loads(request.data) except: return response_msg('error', 'data not correct') try: graph = GraphAPI(form_data['access_token']) try: # #import ipdb; ipdb.set_trace(); email = graph.get_object('me', fields='email')['email'] pic = graph.get_object('me/picture', width='400', height='400')['url'] print pic if email != form_data['fb_email']: return response_msg('error', 'incorrect facebook email') except: return response_msg('error', 'data not complete') except: return response_msg('error', 'invalid access token') try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name ).update({'fb_email': email, 'pic': pic} ).run(connection) cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['username'] == name ).run(connection) except: return response_msg('error', 'Could not connect to db') return response_msg('success', 'OK', data=cursor.items[0])
def check_user_logged_in(): if session.get('user'): g.user = session.get('user') return result = get_user_from_cookie(cookies=request.cookies, app_id=app.config["FB_APP_ID"], app_secret=app.config["FB_APP_SECRET"]) if result: user = UserActions.find_by_id(result['uid']) if not user: graph = GraphAPI(result['access_token']) args = {'fields': 'birthday, name, email'} profile = graph.get_object('me', **args) UserActions.new_facebook_user(profile, result) elif user.access_token != result['access_token']: user.access_token = result['access_token'] user = UserActions.find_by_id(result['uid']) session['user'] = dict(name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token) db.session.commit() g.user = session.get('user', None)
def put_wall_post(request,message): try: graph = GraphAPI(request.user.accesstoken) fb_response = graph.put_wall_post(message) except GraphAPIError as e: print >> sys.stderr, 'Facebook error: %s', (e, ) sys.stderr.flush()
def get_current_user(): if not session.get('user'): result = get_user_from_cookie(cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET) if result: graph = GraphAPI(result['access_token']) profile = graph.get_object('me', fields='link,name,id') access_token = graph.extend_access_token( FB_APP_ID, FB_APP_SECRET)['access_token'] user = User.get_by_id(result['uid']) if not user: user = User.create(id=profile['id'], name=profile['name'], profile_url=profile['link'], access_token=access_token) clear_friends_cache(user) user.add_default_tag() g.new_user = True else: user.access_token = access_token user.update() session['user'] = user.id g.uid = session.get('user') g.user = User.get_by_id(g.uid) if g.uid else None if not g.user: session['user'] = ''
def get_url_info(url): ''' Capture opengraph data from links. It tries to get everything from Facebook. TO DO: Have a default image when no image is found ''' token = settings.FACEBOOK_TOKEN fb_graph = GraphAPI(access_token=token, version='2.10') fb_info = fb_graph.get_object( id=quote(url), fields=['engagement,og_object{image,description,title,updated_time}']) if fb_info: try: return dict(thumbnail=fb_info['og_object']['image'][0]['url'], facebook_shares=fb_info['engagement']['share_count'], title=fb_info['og_object']['title'], description=fb_info['og_object']['description'], source=url.split('/')[2]) except KeyError: from webpreview import web_preview metadata = web_preview(url) return dict(thumbnail=metadata[2], facebook_shares=fb_info['engagement']['share_count'], title=metadata[0], description=metadata[1], source=url.split('/')[2]) else: return dict(thumbnail='', facebook_shares=0, title='', description='', source=url.split('/')[2])
def post_fb_page(message): graph = GraphAPI(config("FB_PYTHON_ACCESSTOKEN", default="TOKKEEEENNNN")) try: graph.put_object("PyJobs", "feed", message=message) except: pass return True
def verify_data(access_token, verification_id): print('VERIFY {}', verification_id) VERIFICATION_ATTR = ['first_name', 'last_name', 'email', 'birthday'] graph = GraphAPI(access_token=access_token, version='2.11') fb_data = graph.get_object(id='me', fields='first_name,last_name,email,birthday') verification = Verification.query.filter_by(id=verification_id).first() result = {} for attr in VERIFICATION_ATTR: result[attr] = getattr(verification, attr) == fb_data[attr] verification.fb_result = json.dumps(result) verification.fb_data = json.dumps(fb_data) fb_picture = graph.get_object(id='me/picture', type='large') filename = '{}/fb_pic_{}.jpg'.format(UPLOAD_FOLDER, verification_id) with open(filename, 'wb') as f: f.write(fb_picture['data']) verification.fb_picture = filename db.session.add(verification) db.session.commit() return verification_id
def scrape(self, user_data): try: oauth = user_data.services['facebook']['access_token'] except KeyError: return False graph = GraphAPI(access_token=oauth) data = { "text": [], "links": [] } posts = [] posts_blob = yield facebook_paginate( graph.get_connections( 'me', 'posts', fields='message, link, created_time' ), max_results=self.num_posts_per_user ) posts, links = self.message_filter(posts_blob) # To do comments we'd have to go through the different posts and look # Scraping the person's feed is another option, but we get more garbage data['text'] = posts data['links'] = links return data
def signup(request): if request.method == "POST": data = json.loads(request.body) try: if data['type'] == 'facebook': try: access_token = request.META['HTTP_FB_ACCESS_TOKEN'] fb_id = data['fb_id'] g_id = -1 try: graph = GraphAPI(access_token) profile = graph.get_object('me', fields='email') fb_graph_id = profile['id'] except GraphAPIError as e: return response('error', e) if fb_id != fb_graph_id: return response("error", "facebook auth failed", ("error_type", "fb_error")) return check_and_add_user(data,fb_id,g_id) except: return response("error", "Incomplete data sent", ("error_type","Incomplete_data")) elif data['type'] == 'google': pass else: return response("error", "Invalid signup type") except: return response("error", "Invalid signup type") else: return response("error", "Not a post request")
def check_user_logged_in(): if session.get('user'): g.user = session.get('user') return result = get_user_from_cookie(cookies=request.cookies, app_id=app.config["FB_APP_ID"], app_secret=app.config["FB_APP_SECRET"]) if result: user = UserActions.find_by_id(result['uid']) if not user: graph = GraphAPI(result['access_token']) args = {'fields': 'birthday, name, email'} profile = graph.get_object('me', **args); UserActions.new_facebook_user(profile, result) elif user.access_token != result['access_token']: user.access_token = result['access_token'] user = UserActions.find_by_id(result['uid']) session['user'] = dict(name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token) db.session.commit() g.user = session.get('user', None)
def get_current_user(): if not session.get('user'): result = get_user_from_cookie(cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET) if result: graph = GraphAPI(result['access_token']) profile = graph.get_object('me', fields='link,name,id') access_token = graph.extend_access_token(FB_APP_ID, FB_APP_SECRET)['access_token'] user = User.get_by_id(result['uid']) if not user: user = User.create(id=profile['id'], name=profile['name'], profile_url=profile['link'], access_token=access_token) clear_friends_cache(user) user.add_default_tag() g.new_user = True else: user.access_token = access_token user.update() session['user'] = user.id g.uid = session.get('user') g.user = User.get_by_id(g.uid) if g.uid else None if not g.user: session['user'] = ''
def validate_fb_email(email, access_token): # check if user is has synced fb email try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['fb_email'] == email).run(connection) except: return response_msg('error', 'Could not connect to db') if len(cursor.items) == 0: return response_msg('error', 'facebook not synced or user not registered') # if user has already synced fb email # check whether access token and email is valid try: graph = GraphAPI(access_token) profile = graph.get_object('me', fields='email') fb_email = profile['email'] except GraphAPIError as e: return response_msg('error', e) except: return response_msg('error', 'Could not connect to facebook') if fb_email == email: return response_msg('success', 'OK') else: return response_msg('error', 'invalid fb details')
def login(request): ret = None if request.method == 'POST': form = FacebookConnectForm(request.POST) if form.is_valid(): try: token = form.cleaned_data['access_token'] g = GraphAPI(token) facebook_me = g.get_object("me") email = valid_email_or_none(facebook_me.get('email')) social_id = facebook_me['id'] try: account = FacebookAccount.objects.get(social_id=social_id) except FacebookAccount.DoesNotExist: account = FacebookAccount(social_id=social_id) data = dict(email=email, facebook_access_token=token, facebook_me=facebook_me) # some facebook accounts don't have this data data.update((k,v) for (k,v) in facebook_me.items() if k in ['username', 'first_name', 'last_name']) # Don't save partial/temporary accounts that haven't # gone through the full signup yet, as there is no # User attached yet. if account.pk: account.sync(data) ret = complete_social_login(request, data, account) except (GraphAPIError, IOError): pass if not ret: ret = render_authentication_error(request) return ret
def validate_fb_email(email, access_token): # check if user is has synced fb email try: connection = get_rdb_conn() cursor = rdb.db(TODO_DB).table('user').filter( rdb.row['fb_email'] == email ).run(connection) except: return response_msg('error', 'Could not connect to db') if len(cursor.items) == 0: return response_msg('error', 'facebook not synced or user not registered') # if user has already synced fb email # check whether access token and email is valid try: graph = GraphAPI(access_token) profile = graph.get_object('me', fields='email') fb_email = profile['email'] except GraphAPIError as e: return response_msg('error', e) except: return response_msg('error', 'Could not connect to facebook') if fb_email == email: return response_msg('success', 'OK') else: return response_msg('error', 'invalid fb details')
def getFBPosts(station,function): """ Gets the most recent posts from a Facebook page since the last run :param station: (int) id of the station :param function: (int) id of the function :return: """ ##Gets the url after the bot has been added url = StationhasBots.query.filter(StationhasBots.fk_radio_station_id==station,StationhasBots.fk_bot_function_id==function).first() # Gets an access token to allow us to fetch information from FB pages r = requests.get('https://graph.facebook.com/oauth/access_token?client_id='+FB_APP_ID+'&client_secret='+FB_APP_SECRET+'&grant_type=client_credentials') access_token = r.text[13:] graph = GraphAPI(access_token) linkCut(url.source_url) profile = graph.get_object(linkCut(url.source_url)) # Gets the last info that was introduced into the database last_bot_info = Bothasinfo.query.filter(Bothasinfo.fk_station_has_bots_radio_station_id == station, Bothasinfo.fk_station_has_bots_bot_function_id == function).order_by(Bothasinfo.created_at.desc()).first() if last_bot_info == None: last_info_date = datetime.now() - timedelta(days=7) else: last_info_date = last_bot_info.created_at posts = graph.get_connections(profile['id'], 'posts') for post in posts['data']: # This condition grants that we only get info from posts if 'message' in post: if datetime.strptime(post['created_time'], "%Y-%m-%dT%H:%M:%S+%f") > last_info_date: info = validate_sms(post['message']) new_info = Bothasinfo(created_at = post['created_time'], fk_station_has_bots_radio_station_id = station , fk_station_has_bots_bot_function_id = function, info = info) db.session.add(new_info) db.session.commit()
def login(request): ret = None if request.method == 'POST': form = FacebookConnectForm(request.POST) if form.is_valid(): token = form.cleaned_data['access_token'] g = GraphAPI(token) facebook_me = g.get_object("me") email = valid_email_or_none(facebook_me.get('email')) social_id = facebook_me['id'] try: account = FacebookAccount.objects.get(social_id=social_id) except FacebookAccount.DoesNotExist: account = FacebookAccount(social_id=social_id) account.link = facebook_me['link'] account.name = facebook_me['name'] if account.pk: account.save() data = dict(email=email, facebook_me=facebook_me) # some facebook accounts don't have this data data.update((k, v) for (k, v) in facebook_me.items() if k in ['username', 'first_name', 'last_name']) ret = complete_social_login(request, data, account) if not ret: ret = render_authentication_error(request) return ret
def profile_handler(request, socket, context, channel): """ Event handler for online status in new users at home. """ usr = User.objects.get(id=request.user.id) usr.is_active = False; usr.save() print str(request.user.first_name)+' '+request.user.last_name+' setting online' try: session, created = Session.objects.get_or_create(id_websocket = request.user.id) if created == False: session.time = True session.save() else: session.time = False session.save() token = UserSocialAuth.objects.get(user__username=request.user.username, provider='facebook').extra_data['access_token'] uid = UserSocialAuth.objects.get(user__username=request.user.username, provider='facebook').uid graph = GraphAPI(token) friends = graph.get_connections(uid, "friends", fields="installed,id,name")['data'] for friend in friends: if friend.get("installed"): social_usr = UserSocialAuth.objects.get(uid=friend.get("id"), provider='facebook') #Searching for the user to call in db dbfriend = User.objects.get(id=social_usr.user_id) if dbfriend.is_active == False: online_message = {"id": str(dbfriend.id), "action": "friend_online", "message": str(request.user.id)} print online_message try: socket.broadcast_channel(online_message, channel='user-'+str(dbfriend.id)) except NoSocket, e: print e except: print "error subscribe"
def signin(): uid = request.args.get('uid', '') print("uid =", uid) query = {'id': uid} user = db.users.find_one(query) print(user) if not user: # Not an existing user so get info requestAccessToken = request.args.get('access_token', '') print("token=", requestAccessToken) graph = GraphAPI(requestAccessToken) profile = graph.get_object('me') if 'link' not in profile: profile['link'] = "" print(profile) # Create the user and insert it into the database db.users.insert({ 'id': uid, 'profile_url': profile['link'], 'created_time': datetime.utcnow, 'name': profile['name'], 'access_token': requestAccessToken }) elif user.access_token != requestAccessToken: # If an existing user, update the access token user.access_token = requestAccessToken response = jsonify({user}) response.status_code = 200 return response
def _send(self): for_voted, email, fb_notification = self._make_template() # Holmes wants to turn this off, at least for now. # self._send_email(for_voted, email) graph = GraphAPI(access_token=settings.FACEBOOK_APP_ACCESS_TOKEN) graph.put_object(self.user.fb_uid, "notifications", href="", template=fb_notification) self._mark_as_notified()
def profile_handler_disconnect(request, socket, context): """ Event handler for offline status in new users at home. """ usr = User.objects.get(id=request.user.id) print str(request.user.first_name)+' '+request.user.last_name+' setting offline' #Handles the error of refreshing the page by using a flag selector in the avalialbe socket table try: session = Session.objects.get(id_websocket = request.user.id) if session.time == False: print "deleting user..." usr.is_active = True; usr.save() session.delete() #Provisional way to alert friends of offline status token = UserSocialAuth.objects.get(user__username=request.user.username, provider='facebook').extra_data['access_token'] uid = UserSocialAuth.objects.get(user__username=request.user.username, provider='facebook').uid graph = GraphAPI(token) friends = graph.get_connections(uid, "friends", fields="installed,id,name")['data'] for friend in friends: if friend.get("installed"): social_usr = UserSocialAuth.objects.get(uid=friend.get("id"), provider='facebook') #Searching for the user to call in db dbfriend = User.objects.get(id=social_usr.user_id) if dbfriend.is_active == False: offline_message = {"id": str(dbfriend.id), "action": "friend_offline", "message": str(request.user.id)} print offline_message try: socket.broadcast_channel(offline_message, channel='user-'+str(dbfriend.id)) except NoSocket, e: print e else:
def login(request): ret = None if request.method == 'POST': form = FacebookConnectForm(request.POST) if form.is_valid(): try: token = form.cleaned_data['access_token'] g = GraphAPI(token) facebook_me = g.get_object("me") email = valid_email_or_none(facebook_me.get('email')) social_id = facebook_me['id'] try: account = FacebookAccount.objects.get(social_id=social_id) except FacebookAccount.DoesNotExist: account = FacebookAccount(social_id=social_id) data = dict(email=email, facebook_access_token=token, facebook_me=facebook_me) # some facebook accounts don't have this data data.update((k, v) for (k, v) in facebook_me.items() if k in ['username', 'first_name', 'last_name']) # Don't save partial/temporary accounts that haven't # gone through the full signup yet, as there is no # User attached yet. if account.pk: account.sync(data) ret = complete_social_login(request, data, account) except (GraphAPIError, IOError): pass if not ret: ret = render_authentication_error(request) return ret
def login(request): ret = None if request.method == 'POST': form = FacebookConnectForm(request.POST) if form.is_valid(): token = form.cleaned_data['access_token'] g = GraphAPI(token) facebook_me = g.get_object("me") email = valid_email_or_none(facebook_me.get('email')) social_id = facebook_me['id'] try: account = FacebookAccount.objects.get(social_id=social_id) except FacebookAccount.DoesNotExist: account = FacebookAccount(social_id=social_id) account.link = facebook_me['link'] account.name = facebook_me['name'] if account.pk: account.save() data = dict(email=email, facebook_me=facebook_me) # some facebook accounts don't have this data data.update((k,v) for (k,v) in facebook_me.items() if k in ['username', 'first_name', 'last_name']) ret = complete_social_login(request, data, account) if not ret: ret = render_authentication_error(request) return ret
def upload_to_albums(facebook_api: facebook.GraphAPI) -> None: """ Uploads a picture from the user to the album the user must select Arguments: facebook_api (object) : facebook api graph """ path = input_user_chat("Please enter the path of your picture: ") if path: albums_id = [] show_albums(facebook_api, albums_id) select = int(input_user_chat("Select the album: ")) - 1 select = validate_number(select, albums_id) caption = input_user_chat("Caption: ") try: facebook_api.put_photo(image = open(path, 'rb'), album_path = albums_id[select - 1] + "/photos", message = caption) print_write_chatbot("The photo has been uploaded successfully!", color = "green", attrs_color = ["bold"]) except Exception as error: write_log(STATUS_FILE, f"There was a problem opening the file, error: {error}", "Exception") print_write_chatbot(f"There was a problem opening the file, error: {error}", color = "red", attrs_color = ["bold"])
def Look_for_comments(vendor): print(vendor['page_id']) graph = GraphAPI(access_token=vendor['access_token']) print('Started at {} ....'.format(last_time_function_ran)) posts = graph.get_connections( id=vendor['page_id'], connection_name='posts', fields='updated_time,comments{message,created_time}') data = posts['data'] for post in data: post_updated_time = datetime.strptime( post['updated_time'], time_format) if post_updated_time > last_time_function_ran: for comment in post['comments']['data']: comment_created_time = datetime.strptime( comment['created_time'], time_format) if not check_for_comments(comment['id'], graph, vendor): print('Found Comment!') msg = ask_wit(comment['message'], vendor) if msg: graph.put_comment(object_id=comment['id'], message=msg) print('Replied to Comment') print('...Finished at {}'.format(last_time_function_ran))
class FbUserApi(object): def __init__(self, access_token): self.graph = GraphAPI(access_token=access_token, version='3.0') def get_profile(self): profile = self.graph.get_connections_with_params( id='me', connection_name='', params='?fields=name,picture.type(large){url}') return profile def get_own_posts(self): posts = self.graph.get_connections_with_params( id='me', connection_name='posts', params='?fields=message&limit=100') posts = posts['data'] posts = list(filter(self.checkPostObj, posts)) posts = list(map(lambda obj: obj['message'], posts)) return posts def getFriendsInfo(self): # Get the user's friends. user_friends = self.graph.get_connections_with_params( id='me', connection_name='friends', params='?fields=picture{url},name') # multiprocessing.cpu_count() friends = Parallel(n_jobs=10, backend='threading')( delayed(self.processFriendInfo)(item) for item in user_friends['data']) return friends def processFriendInfo(self, item): uid = item['id'] profile = {} profile['id'] = uid profile['fullName'] = item['name'] profile['picture'] = item['picture']['data']['url'] posts = self.graph.get_connections_with_params(id=uid, connection_name='posts', params='?limit=50') posts = list(filter(self.checkPostObj, posts['data'])) posts = list(map(lambda obj: obj['message'], posts)) friend = {'profile': profile, 'posts': posts} return friend def checkPostObj(self, x): try: return 'message' in x and \ detect(x['message']) == 'en' and \ len(x['message']) <= 250 except: return False
def get_current_user(): """Set g.user to the currently logged in user. Called before each request, get_current_user sets the global g.user variable to the currently logged in user. A currently logged in user is determined by seeing if it exists in Flask's session dictionary. If it is the first time the user is logging into this application it will create the user and insert it into the database. If the user is not logged in, None will be set to g.user. """ # Set the user in the session dictionary as a global g.user and bail out # of this function early. if session.get('user'): g.user = session.get('user') return # Attempt to get the short term access token for the current user. result = get_user_from_cookie(cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET) # If there is no result, we assume the user is not logged in. if result: # Check to see if this user is already in our database. user = User.query.filter(User.id == result['uid']).first() if not user: # Not an existing user so get info graph = GraphAPI(result['access_token']) extended_token = graph.extend_access_token( app_id=FB_APP_ID, app_secret=FB_APP_SECRET) access_token = extended_token[ 'access_token'] if extended_token else result['access_token'] profile = graph.get_object('me') if 'link' not in profile: profile['link'] = "" # Create the user and insert it into the database user = User(id=str(profile['id']), name=profile['name'], profile_url=profile['link'], access_token=access_token) db.session.add(user) elif user.access_token != result['access_token']: # If an existing user, update the access token user.access_token = result['access_token'] # Add the user to the current session session['user'] = dict(name=user.name, profile_url=user.profile_url, id=user.id, access_token=user.access_token) # Commit changes to the database and set the user as a global g.user db.session.commit() g.user = session.get('user', None)
def __init__(self, fql, access_token, storage=None, prefer_cache=False, store_results=True, override_name=None): self.fql = merge_spaces(fql) self.storage = storage self.prefer_cache = prefer_cache self.store_results = store_results self.graph_api = GraphAPI(access_token) super(FqlTask, self).__init__(override_name)