def submit_note(self, note_id, **params): note = db.Note.objects.with_id(note_id) groups_ans = [] tcount = 0 allow_total = 0 for gidx, group in enumerate(note.question_groups): if ('pn-%i' % (gidx + 1)) in params: answers = [] if group.qtype.key!='yes-no': allow_total += 1 for qidx, question in enumerate(group.questions): key = 'pn-%iq%i' % (gidx+1, qidx+1) if key in params: if group.qtype.key=='yes-no': tcount += 1 answers.append((question, params[key])) elif group.qtype.key=='yes-no': answers.append((question, False)) groups_ans.append({'name': group.header, 'type': group.qtype.key, 'answers': answers, 'count': tcount}) note_content = env.get_template('publish.tpl.html').render(answers=groups_ans, note=note, total=tcount, allow_total=allow_total) if 'format' in params: if params['format']=='json': return json.dumps({'data':groups_ans,'html':note_content}) elif params['format'] == 'html': return note_content else: if ('session_id' not in cherrypy.request.cookie.keys()): raise cherrypy.HTTPRedirect(FBApi.authorize_url()) else: fbapi = FBApi(str(cherrypy.request.cookie['session_key'].value)) db.Note.objects(id=note.id).update_one(inc__taken=1) out = json.loads(fbapi.publish_note(note.name, ' '.join(note_content.split()))) if 'id' in out: raise cherrypy.HTTPRedirect('/done?note_id='+out['id']) else: return 'Something went wrong... Email the developers to get this fixed.'
def auth(): f = FacebookAPI(config.API_KEY, config.API_SECRET, config.SITE_URL + "/auth_redirect") auth_url = f.get_auth_url(scope=[ "publish_stream", "read_stream", "status_update", "user_friends", "friends_birthday", "friends_hometown", "friends_location", "user_birthday", "user_hometown", "user_location" ], display='') return redirect(auth_url)
def main(): fb = FacebookAPI() readline.write_history_file(".history") readline.parse_and_bind( 'tab: complete' ) while True: line = raw_input('fbshell>') if line == 'quit': break ret = fb.call(line)
def fetch_threads(page, next_url=None): api = FacebookAPI(page.access_token) data = api.fetch_raw(next_url) if next_url else api.fetch(page.key.id() + '/threads') docs = [] if data.get('paging', {}).get('next'): taskqueue.Queue('facebook').add( taskqueue.Task( url='/worker/fetch_page_threads', params={ 'key': page.key.urlsafe(), 'next_url': data.get('paging').get('next'), } ) ) for thread in data.get('data'): messages = thread.get('messages').get('data') if len(messages) == 0: continue # Let the first message be the 'post'. message = messages.pop() post_model = Post( parent=page.key, is_private=True, is_reply=False, id=message.get('id'), created_time=FacebookAPI.parse_date(message.get('created_time')), from_id=message.get('from').get('id'), from_name=message.get('from').get('name'), message=message.get('message'), author=scan_for_author(message.get('message')), ) post_model.put() docs.append(search.create_document(post_model)) # Let the rest of the messages be replies: for reply in messages: reply_model = Post( parent=post_model.key, is_private=True, is_reply=True, id=reply.get('id'), created_time=FacebookAPI.parse_date(reply.get('created_time')), from_id=reply.get('from').get('id'), from_name=reply.get('from').get('name'), message=reply.get('message'), author=scan_for_author(reply.get('message')), ) reply_model.put() docs.append(search.create_document(reply_model)) search.index(page, docs)
def auth_redirect(): f = FacebookAPI(config.API_KEY, config.API_SECRET, config.SITE_URL + "/auth_redirect") try: access_token = f.get_access_token(request.args.get('code', '')) graph = GraphAPI(access_token['access_token']) id = graph.get('me')['id'] save_user(id, access_token['access_token'], int(int(access_token['expires']) + time.time() - 3600)) session['uid'] = id return redirect('/') except FacebookClientError as e: return 'Authorization Failed:' + str(e)
def home(request): if "facebook_id" in request.session: return redirect("/profile") else: f = FacebookAPI(APP_KEY, APP_SECRET, FACEBOOK_REDIRECT) auth_url = f.get_auth_url(scope=['create_event', 'user_photos', 'user_location']) c = {} c['fb_url'] = auth_url response = requests.get(GEOCODING_STRING_COLUMBIA).json() c['location'] = response['results'][0]['geometry']['location'] c['places'] = get_orbit_data() c['api_key'] = GOOGLE_API_KEY return render_to_response('index.html', c)
def callback(self, error=None, error_reason=None, error_description=None, code=None): if error and error_reason == 'user_denied': return 'Please authorize!' if not code: return 'Error from facebook' fbapi = FBApi(None) out = fbapi.callback(code) obj = db.loadUser(token=fbapi.token, fb=fbapi.me()) cookie = cherrypy.response.cookie cookie['session_id'] = obj.id cookie['session_id']['max-age'] = int(out['expires'][0]) cookie['session_id']['path'] = '/' cookie['session_key'] = obj.code cookie['session_key']['max-age'] = int(out['expires'][0]) cookie['session_key']['path'] = '/' return '''Logged in! Loading...
def login_facebook(request): try: code = request.DATA['code'] except KeyError: ret = produceRetCode("fail", "code required") return Response(ret, status=status.HTTP_202_ACCEPTED) try: f = FacebookAPI(APP_ID, APP_SECRET, uri) res = f.get_access_token(code) # get long term token graph = GraphAPI(res['access_token']) # access GraphAPI of facebook personalInfo = graph.get('me') except Exception: ret = produceRetCode("fail", "facebook api error") return Response(ret, status=status.HTTP_202_ACCEPTED) university = University.objects.get(shortname = "Unknown") major = Major.objects.get(shortname = "Unknown") userData = { "first_name": personalInfo['first_name'], "last_name" : personalInfo['last_name'], "nick_name" : personalInfo['name'], "password" : "Unknown", "gender" : personalInfo['gender'], "image" : "Unknown", "tpa_type" : "facebook", "tpa_id" : "facebook" + personalInfo['id'], "tpa_token" : res['access_token'], "university": university.id, # default university id "major" : major.id, "email" : "*****@*****.**", "phone" : "Unknown" } try: user = User.objects.get(tpa_id=userData['tpa_id']) # user account exist, directly login token = produceLoginToken(userData['tpa_id']) ip = getIP(request) return setUserState(user.id, ip, token) except User.DoesNotExist: # create new account serializer = RegisterSerializer(data=userData) if serializer.is_valid(): serializer.save() user = User.objects.get(tpa_id=userData['tpa_id']) token = produceLoginToken(userData['tpa_id']) ip = getIP(request) return setUserState(user.id, ip, token) else: ret = produceRetCode('fail', 'login data from facebook error', serializer.errors) return Response(ret, status=status.HTTP_202_ACCEPTED)
def process_request(self, request): if request.user and hasattr(request.user, 'social_auth'): social_user = request.user.social_auth.filter( provider='facebook', ).first() if social_user: request.facebook = FacebookAPI(social_user) return None
def facebook_login(request): code = request.GET.get('code') f = FacebookAPI(APP_KEY, APP_SECRET, FACEBOOK_REDIRECT) access_token = f.get_access_token(code) final_access_token = access_token['access_token'] request.session['access_token'] = final_access_token graph = GraphAPI(final_access_token) try: me = graph.get('me') request.session['facebook_id'] = me['id'] request.session['first_name'] = me['first_name'] request.session['last_name'] = me['last_name'] if (len(FacebookUser.objects.filter(facebook_id=me['id'])) == 0): f = FacebookUser.create(me['id'],me['first_name'],me['last_name']) f.save() return redirect('/profile/') except FacebookClientError: return HttpResponse("Sorry, something went wrong.")
def fetch_pages(user): api = FacebookAPI(user.facebook_access_token) pages = api.fetch("me/accounts") for page in pages['data']: m = Page( parent=user.key, id=page['id'], access_token=page['access_token'], name=page['name'], ) m.put() taskqueue.Queue('facebook').add( taskqueue.Task( url='/worker/fetch_page', params={ 'key': m.key.urlsafe(), } ) )
class FacebookHandler(BaseRequestHandler): def __init__(self, request, response): self.initialize(request, response) self.api = FacebookAPI(self.current_user.facebook_access_token) def _set_access_token_from_page(self, page_id): m = Page.get_by_id(page_id, parent=self.current_user.key) self.api.access_token = m.access_token def get_feed(self, page_id): self._set_access_token_from_page(page_id) data = self.api.fetch(page_id + "/feed") self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(data)) def get_threads(self, page_id): self._set_access_token_from_page(page_id) data = self.api.fetch(page_id + "/threads") self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(data))
def fetch_feed(page, next_url=None): api = FacebookAPI(page.access_token) data = api.fetch_raw(next_url) if next_url else api.fetch(page.key.id() + '/feed') docs = [] if data.get('paging', {}).get('next'): taskqueue.Queue('facebook').add( taskqueue.Task( url='/worker/fetch_page_feed', params={ 'key': page.key.urlsafe(), 'next_url': data.get('paging').get('next'), } ) ) for post in data.get('data'): post_model = Post( parent=page.key, id=post.get('id'), created_time=FacebookAPI.parse_date(post.get('created_time')), updated_time=FacebookAPI.parse_date(post.get('updated_time')), from_id=post.get('from').get('id'), from_name=post.get('from').get('name'), from_category=post.get('from').get('category'), message=post.get('message') or post.get('story'), author=scan_for_author(post.get('message')), ) post_model.put() docs.append(search.create_document(post_model)) if not 'comments' in post: continue for comment in post.get('comments').get('data'): comment_model = Post( parent=post_model.key, is_reply=True, id=comment.get('id'), created_time=FacebookAPI.parse_date(comment.get('created_time')), from_id=comment.get('from').get('id'), from_name=comment.get('from').get('name'), from_category=comment.get('from').get('category'), message=comment.get('message'), author=scan_for_author(comment.get('message')), ) comment_model.put() docs.append(search.create_document(comment_model)) search.index(page, docs)
import facebook import requests from facebook import FacebookAPI, GraphAPI from django.http import request f = FacebookAPI(client_id='327860917388003', client_secret='2cfddeec2f1ad7abd1e4c5d103e29451', redirect_uri='http://darthbane.org') auth_url = f.get_auth_url(scope=['publish_stream', 'user_photos', 'user_status']) code = request access_token = f.get_access_token(code) print 'Connect with Facebook via: %s' % auth_url #graph = facebook.GraphAPI("327860917388003|RbeGPTESdoXRubc0SFINQivA5Zo") #profile = graph.get_object("me") ##friends = graph.get_connections("me", "friends") #graph.put_object("me", "feed", message="I am writing on my wall!") def getGenre(): return def getLocation(): return
def get_knowns(self, loading=True): fb = FacebookAPI(access_token=self.access_token(), version=API_VERSION) response = fb.get_connections(id='me', connection_name='friends') knowns = self.fetch_paginated(response, loading) return knowns
def get_profile_data(self, profile_id): fb = FacebookAPI(access_token=self.access_token(), version=API_VERSION) profile = fb.request(profile_id) return profile
import facebook import requests from facebook import FacebookAPI, GraphAPI from django.http import request f = FacebookAPI(client_id='327860917388003', client_secret='2cfddeec2f1ad7abd1e4c5d103e29451', redirect_uri='http://darthbane.org') auth_url = f.get_auth_url( scope=['publish_stream', 'user_photos', 'user_status']) code = request access_token = f.get_access_token(code) print 'Connect with Facebook via: %s' % auth_url #graph = facebook.GraphAPI("327860917388003|RbeGPTESdoXRubc0SFINQivA5Zo") #profile = graph.get_object("me") ##friends = graph.get_connections("me", "friends") #graph.put_object("me", "feed", message="I am writing on my wall!") def getGenre(): return def getLocation(): return
def get_knowns_of(self, profile_id: str, loading=False): fb = FacebookAPI(access_token=self.access_token(), version=API_VERSION) response = fb.get_connections(profile_id, connection_name='friends') knowns = self.fetch_paginated(response, loading) return knowns
def _get_access_token(request): short_lived_token = request.POST.get('authResponse[accessToken]') fb = FacebookAPI(settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET) return fb.get_long_lived_token(short_lived_token)
def __init__(self, request, response): self.initialize(request, response) self.api = FacebookAPI(self.current_user.facebook_access_token)
def connect(self): raise cherrypy.HTTPRedirect(FBApi.authorize_url())