def fb_login_callback(request): creds = request.META['QUERY_STRING'].split('&') fbtoken = creds[0].split('=')[1] fb_usrid = creds[1].split('=')[1] graph = GraphAPI(fbtoken) utils.get_extended_access_token(fbtoken, app_id, app_secret) return render(request, 'fb_login_request.html')
def extendOauthToken(self): '''this just generates an extended access token so that it lasts 60 days ''' #Returns a tuple with a string describing the extended access token and a datetime instance describing when it expires. extended_oauth_token = utils.get_extended_access_token(oauth_token[0],globalS.dictDb['FACEBOOK_APP_ID'],globalS.dictDb['FACEBOOK_APP_SECRET']) logger.debug('extended_oauth_token:%s',extended_oauth_token) return
def _get_facebook_token(fb_app_id, fb_app_secret): # try to authenticate fb_auth = _authorize_get_response('http://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=http://0.0.0.0:8080/&scope=manage_pages' % fb_app_id) if 'code' not in fb_auth.keys(): abort('Did not receive a token from Facebook! Did you decline authorization?') # get a short-term access token graph = GraphAPI() response = graph.get( path='oauth/access_token', client_id=fb_app_id, client_secret=fb_app_secret, redirect_uri='http://0.0.0.0:8080/', code=fb_auth['code'][0] ) data = parse_qs(response) # extend the token extended_token = utils.get_extended_access_token(data['access_token'][0], fb_app_id, fb_app_secret) graph = GraphAPI(extended_token[0]) # get the accounts associated with the token (list of pages managed by the user) pages = [] accounts = graph.get(path = 'me/accounts') for entry in accounts['data']: pages.append({'value': {'page_id': unicode(entry['id']), 'token': unicode(entry['access_token'])}, 'display': '%s - %s' % (unicode(entry['id']), unicode(entry['name']))}) # get the user's selected page selected_page = _get_user_choice('Select a page from your authorized ones: ', pages) if selected_page: return (selected_page['token'], selected_page['page_id']) else: return (None, None)
def get_token(access_token): global app_id, app_secret try: access_token, oath_access_token_expres_when = utils.get_extended_access_token(access_token, app_id, app_secret) except Exception, e: print "Error while extending access token: ", str(e) exit()
def setLongToken(self, token): """ got this from the following site: http://fearofcoding.blogspot.com/2012/10/python-script-to-fetch-messages-from.html """ lt, expires_at = get_extended_access_token(token, self.app_id, self.app_secret) self.expires = expires_at print "expires : " + str(expires_at) self.long_token = lt self.g = facebook.GraphAPI(self.long_token)
def extendOauthToken(self): '''this just generates an extended access token so that it lasts 60 days ''' #Returns a tuple with a string describing the extended access token and a datetime instance describing when it expires. extended_oauth_token = utils.get_extended_access_token( oauth_token[0], globalS.dictDb['FACEBOOK_APP_ID'], globalS.dictDb['FACEBOOK_APP_SECRET']) logger.debug('extended_oauth_token:%s', extended_oauth_token) return
def facebook_authorized(resp): if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description']) session['oauth_token'] = (resp['access_token'], '') oauth_token = session['oauth_token'] #this just generates an extended access token so that it lasts 60 days extended_oauth_token = utils.get_extended_access_token( oauth_token[0], FACEBOOK_APP_ID, FACEBOOK_APP_SECRET) me = facebook.get('/me') return 'Logged in as id=%s<br> name=%s<br> redirect=%s<br>EXTENDED_OAUTH_TOKEN=%s' % \ (me.data['id'], me.data['name'], request.args.get('next'), extended_oauth_token[0])
def fb_login_callback(request): def fix_name(name): fml = name.split(' ') if len(fml) > 2: fml = [fml[0], fml[2]] name = ' '.join(fml) if len(name) > 15: name = fml[0] return name creds = request.META['QUERY_STRING'].split('&') fbtoken = creds[0].split('=')[1] fb_usrid = creds[1].split('=')[1] extoken = utils.get_extended_access_token(fbtoken, app_id, app_secret) user = FBUserInfo(facebook_id=fb_usrid, oauth_token=extoken) # TODO fbtoken works, but extoken does not--why? graph = GraphAPI(fbtoken) paginator = graph.get('me/posts?fields=likes', page=True) # sort out the favorites counter = {} candidates = [] contacts = [] while len(candidates) < 20: posts = paginator.next()['data'] for post in posts: if 'likes' in post: likes = post['likes']['data'] for like in likes: person = (int(like['id']), like['name']) if person in counter: counter[person] += 1 if counter[person] == 3: candidates.append(person) else: counter[person] = 1 for person in candidates: contact = Contact(facebook_id=person[0], name=fix_name(person[1])) contacts.append(contact) t = loader.get_template('set_contacts.html') c = Context({'contacts': contacts}) return HttpResponse(t.render(c))
def get_long_access_token(): #application_secret_key='0840d857d5a2d153338f8f3197e6f597' #application_id='1685065455105239' #short_lived_access_token='CAAX8jtZCf9NcBABIaLBXiOB2vidhEcW5EHqGnyPonOxTSx0yxeqYUNeUwnsjHOiRM0SJF3Qq4CW7miia5eBFvcGgQkasyBRrkwZAoTcu40jq3OmgcUBEgFWVV3hGOe1p6EdBqM6SHSe0Yqn6Kbi2Kwf2J8eOuWjxgMUA9DiHZC65iGuZAyolihj1T3Lg0dwOohDcL60ZCCwv63PUvbfL7' application_secret_key=settings.FACEBOOK_ACCESS_TOKEN['app_secret'] application_id=settings.FACEBOOK_ACCESS_TOKEN['app_id'] short_lived_access_token=settings.FACEBOOK_ACCESS_TOKEN['short_lived_access_token'] (long_lived_access_token, expires_at)= get_extended_access_token(short_lived_access_token, application_id, application_secret_key) print long_lived_access_token print expires_at #graph = GraphAPI(long_lived_access_token) #print graph.get('/me') data_to_return={} data_to_return['long_lived_access_token']=str(long_lived_access_token) data_to_return['expires_at']=str(expires_at) return data_to_return
def get_long_access_token(): #application_secret_key='0840d857d5a2d153338f8f3197e6f597' #application_id='1685065455105239' #short_lived_access_token='CAAX8jtZCf9NcBABIaLBXiOB2vidhEcW5EHqGnyPonOxTSx0yxeqYUNeUwnsjHOiRM0SJF3Qq4CW7miia5eBFvcGgQkasyBRrkwZAoTcu40jq3OmgcUBEgFWVV3hGOe1p6EdBqM6SHSe0Yqn6Kbi2Kwf2J8eOuWjxgMUA9DiHZC65iGuZAyolihj1T3Lg0dwOohDcL60ZCCwv63PUvbfL7' application_secret_key = settings.FACEBOOK_ACCESS_TOKEN['app_secret'] application_id = settings.FACEBOOK_ACCESS_TOKEN['app_id'] short_lived_access_token = settings.FACEBOOK_ACCESS_TOKEN[ 'short_lived_access_token'] (long_lived_access_token, expires_at) = get_extended_access_token(short_lived_access_token, application_id, application_secret_key) print long_lived_access_token print expires_at #graph = GraphAPI(long_lived_access_token) #print graph.get('/me') data_to_return = {} data_to_return['long_lived_access_token'] = str(long_lived_access_token) data_to_return['expires_at'] = str(expires_at) return data_to_return
def GET(self): user_data = web.input(code=None) if not user_data.code: dialog_url = ('http://www.facebook.com/dialog/oauth?' + 'client_id=' + app_id + '&redirect_uri=http://0.0.0.0:8080/' + '&scope=manage_pages') return '<script>top.location.href="' + dialog_url + '"</script>' else: try: graph = GraphAPI() response = graph.get( path='oauth/access_token', client_id=app_id, client_secret=app_secret, redirect_uri='http://0.0.0.0:8080/', code=user_data.code ) data = parse_qs(response) extended_token = utils.get_extended_access_token(data['access_token'][0], app_id, app_secret) graph = GraphAPI(extended_token[0]) accounts = graph.get(path = 'me/accounts') result = u'<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>' result += u'<body><table width="100%"><thead><td><b>Name</b></td><td><b>Id</b></td><td><b>Access Token</b></td></thead>' for entry in accounts['data']: result += u'<tr><td>' + unicode(entry['name']) + u'</td><td>' result += unicode(entry['id']) + u'</td><td>' + unicode(entry['access_token']) + u'</td></tr>' result += '</table></body></html>' return result except Exception, e: return 'Error: %s' % e
def worker(nq, rq, rtflag, token_file): i = 1 lm = 0 counter = 0 cntl = [] logging.info('worker(' + str(os.getpid()) + '): STARTED - serving request in realtime: ' + str(rtflag)) if not(os.path.isfile(token_file)): logging.info( 'worker(' + str(os.getpid()) + '): waiting for token file: ' + token_file) print 'worker(' + str(os.getpid()) + '): waiting for token file: ' + token_file while (not os.path.isfile(token_file)) and (not os.path.isfile('stop')): time.sleep(1) if os.path.isfile(token_file): fat = open(token_file, 'r') ACCESS_TOKEN = fat.readline() fat.close() tokentime = os.path.getmtime(token_file) logging.info( 'worker(' + str(os.getpid()) + '): read token:' + ACCESS_TOKEN) logging.info('worker(' + str(os.getpid()) + '): fbi.access_token modification time:' + datetime.fromtimestamp(tokentime).strftime(DATE_FMT)) #Get long live accesss token if the token belongs to SMCC application if TOKEN_TYPE == 'FBAPP': time.sleep(random.randint(0,9)) ACCESS_TOKEN = get_extended_access_token( ACCESS_TOKEN, SSO_APP_ID, SSO_SECRET_KEY)[0] # Create a connection to the Graph API with your access token g = facebook.GraphAPI(ACCESS_TOKEN) else: logging.info( 'worker(' + str(os.getpid()) + '): could not find file: ' + token_file) while (not os.path.isfile('stop')): sm = counter + sum_last10(cntl) #sum calls if (not os.path.isfile('stop')) and (not rq.empty()) and sm < MAX_WCALL: nobj = rq.get() counter = counter + 1 pdownload_time = datetime.strptime(nobj.download_time, DATE_FMT).strftime(DATE_FMT) nobj.download_time = datetime.now().strftime(DATE_FMT) try: obj = g.get_object( nobj.ref, metadata=1, limit=100) # ,limit=5000 except Exception as e: logging.error( 'worker(' + str(os.getpid()) + '): g.get_object(' + nobj.ref + ',metadata=1, limit=100)') logging.exception('') nobj.status = 'ERROR' nq.put(nobj) log(nobj) # Quit or wait after errors in GraphAPI connection(expired session, reaching max request limit, etc.) # Waiting for new token if (e.args[0]).encode('latin-1').find('Error validating access token') >= 0: rq.put(nobj) logging.info( 'worker(' + str(os.getpid()) + '): WAITING for valid access token') while (not os.path.isfile('stop')): if os.path.isfile(token_file) and tokentime < os.path.getmtime(token_file): break else: time.sleep(5) if os.path.isfile(token_file): fat = open(token_file, 'r') ACCESS_TOKEN = fat.readline() fat.close() tokentime = os.path.getmtime( token_file) logging.info( 'worker(' + str(os.getpid()) + '): read token:' + ACCESS_TOKEN) logging.info('worker(' + str(os.getpid()) + '): fbi.access_token modification time:' + datetime.fromtimestamp(tokentime).strftime(DATE_FMT)) g = facebook.GraphAPI(ACCESS_TOKEN) else: logging.info( 'worker(' + str(os.getpid()) + '): could not find file: ' + token_file) # Waiting for 2 minutes if (e.args[0]).encode('latin-1').find('Calls to stream have exceeded') >= 0: rq.put(nobj) logging.info( 'worker(' + str(os.getpid()) + '): wait 2 minutes. (GrahAPIError)') i = 0 while i < 120 and (not os.path.isfile('stop')): time.sleep(1) i = i + 1 # Waiting for 2 hours if (e.args[0]).encode('latin-1').find('User request limit reached') >= 0: rq.put(nobj) logging.info( 'worker(' + str(os.getpid()) + '): wait 2 hours. (GrahAPIError)') i = 0 while i < 2 * 60 * 60 and (not os.path.isfile('stop')): time.sleep(1) i = i + 1 else: try: s = json.dumps(obj) except: logging.error( 'Error in JSON.dump for result of g.get_object(' + nobj.ref + ',metadata=1)') nobj.status = 'ERROR' nq.put(nobj) log(nobj) else: nobj.type = nvl(get_type(obj), nobj.type) nobj.id = nvl(get_id(obj), nobj.id) nobj.status = check_result(s) page_status = nobj.status j = 1 postfix = '' # Set priority and calculate expiry time for facebook. expiry_minutes = 0 means no refresh needed # object if nobj.fbo_type == 'fb_object': nobj.priority = DEF_PRIORITY nobj.expiry_time = INF_DATETIME.strftime(DATE_FMT) # Find the current active object, if the object type was set to inactive then the expire time will be infinity for o in objects: if o.obj == nobj.type and o.active == 'Y': nobj.priority = o.priority if o.expiry_minutes <> 0: nobj.expiry_time = (datetime.strptime( nobj.download_time, DATE_FMT) + timedelta(minutes=o.expiry_minutes)).strftime(DATE_FMT) break # Calculate expiry time for facebook edge, priority has # already been set in function. There are only active edge types in the edges. expiry_minutes = 0 means no refresh needed # add_connected_edges() if nobj.fbo_type == 'fb_edge': nobj.expiry_time = INF_DATETIME.strftime(DATE_FMT) # Find the current object for e in edges: if e.obj == nobj.parent_type and e.edge == nobj.type and e.expiry_minutes <> 0: nobj.expiry_time = (datetime.strptime( nobj.download_time, DATE_FMT) + timedelta(minutes=e.expiry_minutes)).strftime(DATE_FMT) break while page_status == 'OK' and (not os.path.isfile('stop')): si = json.dumps(obj, indent=1) s_ready = json.dumps(obj) nobj.response_size = nobj.response_size + len(s_ready) obj['fbi_id'] = nobj.id obj['fbi_object_reference'] = nobj.ref obj['fbi_level'] = nobj.level obj['fbi_fbo_type'] = nobj.fbo_type obj['fbi_object_type'] = nobj.type obj['fbi_page'] = nobj.page obj['fbi_parent_id'] = nobj.parent_id obj['fbi_parent_type'] = nobj.parent_type obj['fbi_root'] = nobj.root obj['fbi_root_type'] = nobj.root_type obj['fbi_download_time'] = str( nobj.download_time) obj['fbi_expiry_time'] = str( nobj.expiry_time) s_ready=json.dumps(obj) #send_file(filename, dir, text) #send_file(nvl(nobj.id, nobj.ref).replace(':','-') + postfix + '_' + nobj.download_time, str(nobj.type), s_ready) save_file(datetime.now().strftime("%Y%m%d%H") + "_" + str(os.getpid()), TEMP_DIR + str(nobj.type).replace(':','-').replace('/','_') + '/', s_ready + "\n") #Save to separated folder if the request was processed by realtime worker process. #Interface must be defined for outside systems instead of the folder. if rtflag == True: save_file(nvl(nobj.id, nobj.ref).replace(':','-').replace('/','_') + postfix + '_' + nobj.download_time, LOCAL_RT_OUTPUT_DIR + str(nobj.type) + '/', s_ready + "\n") if nobj.root_type == 'page': #Different root type means different entry point and different traversal level LEVEL = MTPAGE_LEVEL else: LEVEL = SSOUSER_LEVEL #user level if nobj.level < LEVEL: logging.debug( 'worker(' + str(os.getpid()) + '): call add_connected_objs, object length: ' + str(len(si))) add_connected_objs(si, nobj, nq) #Put only edges into the queue when reaching the max of depth level. if nobj.level < LEVEL + 1 and nobj.type <> 'unknown' and nobj.id <> 'unknown': add_connected_edges(nobj, nq) if SAVE_META: save_meta(obj, get_type(obj)) try: obj = requests.get( obj['paging']['next']).json() except: break # No paging for followings: if nobj.type == 'insights' or nobj.type == 'unknown': break j = j + 1 counter = counter + 1 nobj.page = j postfix = '_' + str(j) s = json.dumps(obj) page_status = check_result(s) if chk_created_date(s,datetime.strptime(pdownload_time, DATE_FMT)) > 0.97: page_status = 'ALREADY_DOWNLOADED' nq.put(nobj) log(nobj) #logging.info( # 'worker(' + str(os.getpid()) + '): processed request: ' + str(i)) #print 'worker(' + str(os.getpid()) + '): processed request: ' + str(i) i = i + 1 m = datetime.now().minute # Count the request for every minute, if the minute changed store into # the list and reset the counter if m <> lm: cntl.insert(0, counter) logging.info( "worker(" + str(os.getpid()) + "): requests processed from starting: " + str(i)) logging.info( "worker(" + str(os.getpid()) + "): requests processed in last minutes: " + str(counter)) logging.info( "worker(" + str(os.getpid()) + "): requests processed in last 10 minutes: " + str(sm)) counter = 0 lm = m # If nothing to do, wait a second if sm >= MAX_WCALL or rq.empty(): #Main loop time.sleep(1) logging.info('worker(' + str(os.getpid()) + '): STOPPED AND QUIT') #Main code return
# coding: utf-8 __author__ = 'edubecks' from facepy.utils import get_extended_access_token from facepy import GraphAPI import settings long_lived_access_token, expires_at = get_extended_access_token(settings.OAUTH_TOKEN, settings.DEV_FB_APP_ID, settings.DEV_FB_APP_SECRET) print long_lived_access_token graph = GraphAPI(long_lived_access_token) print(graph.get('/me'))
#Imports from facepy api from facepy.utils import get_extended_access_token #App key/APP ID and App_secret from https://developers.facebook.com/apps app_id = '' app_secret = '' #1391587941094306 #f26f0ec4dd654de641126a71cf28df7f #Token got by selecting app_name from the drop-down list. short_lived_access_token = "" '''CAATxpFDnE6IBAP24wjRXu298IL4xUoV2UzRPsGed981x2Gf2LRHLwgZBdVWYbZBKyEiW84gRYPbcF8ZAAZBblEa2XZBoKaPiv9aYI8bDrlAN49G3IUsMPpXX8XGZCRVTXn5q6LsP1yklDGIpbZCh1zTLh4u4TUiqfmxHyVg9EFCZB7M6ulMAP39t5niNqA6i6xufmtA2Hs4V8QZDZD''' long_lived_access_token, expires_at = get_extended_access_token( short_lived_access_token, app_id, app_secret) print long_lived_access_token print expires_at
from facepy.utils import get_extended_access_token from facepy import GraphAPI import sys app_id = '763373250416428' app_secret = '1ac36a48bdce4e6425a0962e44c7aec6' short_lived_access_token = "CAAK2SK9sDywBAGaZC5HJAtIdryNqoZAWLTFmYEen9Qjgpo5bCZAg3vEZBROp9rSisWOPCt9kJYJyyqFINOZA6qigoND6TpegProYBChsZAk9dPNNV6SWwHHz0sq0Oaaez29z3Wj7G302ErZBLiiLcvNgkrYwRlP7Sc3l19G4HZCz07PGtDUJk1623HKdB64YX4coOLDZBeebfcJ4xbtD2e1oQ" long_lived_access_token, expires_at = get_extended_access_token( short_lived_access_token, app_id, app_secret) def user_id_to_username(userid): if userid is not None: userid = '/{0}'.format(userid) try: return graph.get(userid)['name'] except (exceptions.FacebookError, exceptions.OAuthError) as e: print e.message + "1" sys.exit(0) graph = GraphAPI(long_lived_access_token) print graph.get('/me') print graph.get('/me/inbox')
def extend_token(self, old_token): application_id = APP_KEY application_secret_key = APP_SECRET long_lived_access_token, expires_at = get_extended_access_token(old_token, application_id, application_secret_key) return long_lived_access_token