def getGraphPost(request, postID): require_persistent_graph(request) context = RequestContext(request) graph = request.facebook postDict = graph.get(postID) return HttpResponse(json.dumps(postDict, ensure_ascii=False), mimetype="application/json")
def home(request): require_persistent_graph(request) context = RequestContext(request) print 'homepage yo' graph = request.facebook return render_to_response('home.html', context)
def getProfilePicture(request): require_persistent_graph(request) context = RequestContext(request) print 'getting profile picture yo' graph = request.facebook url = graph.get('me/picture', redirect = 0, height = 50, width = 50, type = 'normal') # print url return HttpResponse(json.dumps(url, ensure_ascii=False), mimetype="application/json")
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\ 'and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: require_persistent_graph(request) logger.info('trying to connect using facebook') graph = get_persistent_graph(request) if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: warn_message = u'Incomplete profile data encountered '\ u'with error %s' % e.message.decode('utf-8', 'replace') send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) if action is CONNECT_ACTIONS.CONNECT: messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: response = backend.post_registration_redirect(request, user) return response else: if 'attempt' in request.GET: return next_redirect(request, next_key=['error_next', 'next'], additional_params=dict(fb_error_or_cancel=1)) else: logger.info('Facebook authentication needed for connect, ' \ 'raising an error') raise OpenFacebookException('please authenticate') return next_redirect(request)
def reindex(request): require_persistent_graph(request) context = RequestContext(request) print 'reindexing yo' graph = request.facebook user = request.user buildIndex(graph, user) # saveUserPosts(graph, user) return HttpResponse("Done yo!")
def getProfilePicture(request): require_persistent_graph(request) context = RequestContext(request) print 'getting profile picture yo' graph = request.facebook url = graph.get('me/picture', redirect=0, height=50, width=50, type='normal') # print url return HttpResponse(json.dumps(url, ensure_ascii=False), mimetype="application/json")
def page_tab(request): ''' Example of a canvas page. Canvas pages require redirects to work using javascript instead of http headers The facebook required and facebook required lazy decorator abstract this away ''' context = RequestContext(request) facebook = require_persistent_graph(request) likes = facebook.get('me/likes')['data'] context['likes'] = likes from user.models import FacebookPageTab signed_request = request.REQUEST.get('signed_request') data = facebook.prefetched_data page_id = data['page']['id'] defaults = dict(created_by_user=data['user_id']) tab, created = FacebookPageTab.objects.get_or_create(page_id=page_id, defaults=defaults) context['facebook'] = facebook raise Exception, tab return render_to_response('django_facebook/page_tab.html', context) """ #NOT USED ATM
def table_user_friends_batch(request): ''' I am using batch queries, let us taste performance gain ''' graph = require_persistent_graph(request) query_dict = {} for friend in FacebookFriend.objects.all()[:100]: # Conclusion 100 batched queries at a time are enough for a while # My current problem is not to use broker, so deferring it. What I can do with data and for the problem is the question. query_dict[friend.id] = FacebookUser.fql_query("WHERE uid=%d" % friend.uid2) response_dataset = graph.batch_fql(query_dict) for response_data in response_dataset.values(): try: response_data_dict = response_data[0] data_dict = FacebookUser.prepare_dict(response_data_dict) facebook_user = FacebookUser(user=request.user, **data_dict) facebook_user.save() except IndexError: logger.info("A user query returned no information") #pp.pprint(response_data) return HttpResponse( "<h2>Step 3. Congratulations! You have downloaded profiles of your first hundred friends. Don't believe me ? You can always look at these profiles using django's admin interface. Just don't forget to login into admin using different browser not messing up with this session. Now we will download 'like' table, click here : <a href='%s'>/table/table_like</a>." % reverse('fbschema_table_like'))
def authenticate(self, fn, request, *args, **kwargs): redirect_uri = self.get_redirect_uri(request) oauth_url = get_oauth_url( self.scope_list, redirect_uri, extra_params=self.extra_params) graph = None try: # call get persistent graph and convert the # token with correct redirect uri graph = require_persistent_graph( request, redirect_uri=redirect_uri) # Note we're not requiring a persistent graph here # You should require a persistent graph in the view when you start using this response = self.execute_view( fn, request, graph=graph, *args, **kwargs) except open_facebook_exceptions.OpenFacebookException, e: permission_granted = has_permissions(graph, self.scope_list) if permission_granted: # an error if we already have permissions # shouldn't have been caught # raise to prevent bugs with error mapping to cause issues raise elif request.REQUEST.get('attempt') == '1': # Doing a redirect could end up causing infinite redirects # If Facebook is somehow not giving permissions # Time to show an error page response = self.authentication_failed( fn, request, *args, **kwargs) else: response = self.oauth_redirect(oauth_url, redirect_uri, e)
def authenticate(self, fn, request, *args, **kwargs): redirect_uri = self.get_redirect_uri(request) oauth_url = get_oauth_url(self.scope_list, redirect_uri, extra_params=self.extra_params) graph = None try: # call get persistent graph and convert the # token with correct redirect uri graph = require_persistent_graph(request, redirect_uri=redirect_uri) # Note we're not requiring a persistent graph here # You should require a persistent graph in the view when you start using this response = self.execute_view(fn, request, graph=graph, *args, **kwargs) except open_facebook_exceptions.OpenFacebookException, e: permission_granted = has_permissions(graph, self.scope_list) if permission_granted: # an error if we already have permissions # shouldn't have been caught # raise to prevent bugs with error mapping to cause issues raise elif request.REQUEST.get('attempt') == '1': # Doing a redirect could end up causing infinite redirects # If Facebook is somehow not giving permissions # Time to show an error page response = self.authentication_failed(fn, request, *args, **kwargs) else: response = self.oauth_redirect(oauth_url, redirect_uri, e)
def fb_group_post(request, item, fb_group): graph = require_persistent_graph(request) if graph.is_authenticated(): facebook = FacebookUserConverter(graph) response = facebook.set_fb_group(item, fb_group) return response return None
def _connect(request, facebook_login): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) if facebook_login: logger.info('trying to connect using Facebook') graph = require_persistent_graph(request) authenticated = False if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) authenticated = facebook.is_authenticated() if authenticated: logger.info('Facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) except facebook_exceptions.AlreadyConnectedError, e: user_ids = [u.id for u in e.users] ids_string = ','.join(map(str, user_ids)) return error_next_redirect( request, additional_params=dict(already_connected=ids_string)) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect( request, user) #compatibility for Django registration backends which return redirect tuples instead of a response if not isinstance(response, HttpResponse): to, args, kwargs = response response = redirect(to, *args, **kwargs) return response
def logged_home(request): graph = require_persistent_graph(request) #print graph.fql("SELECT uid2 FROM friend WHERE uid1 IN ( SELECT uid FROM user WHERE uid=me() )"); return render_to_response('home/logged-home.html', { 'graph': graph, 'profile_pic': graph.my_image_url }, context_instance=RequestContext(request))
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\ 'and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: logger.info('trying to connect using facebook') graph = require_persistent_graph(request) if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) except facebook_exceptions.AlreadyConnectedError, e: user_ids = [u.id for u in e.users] ids_string = ','.join(map(str, user_ids)) return next_redirect(request, next_key=['error_next', 'next'], additional_params=dict(already_connected=ids_string)) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect(request, user) #compatability for django registration backends which return tuples instead of a response #alternatively we could wrap django registration backends, but that would be hard to understand response = response if isinstance(response, HttpResponse) else redirect(response) return response
def table_notification(request): ''' table notification ''' context_model = FacebookNotification graph = require_persistent_graph(request) response_data = graph.fql(context_model.fql_query_me()) context_model.save_update_delete(request, response_data, stream_nature=True) return HttpResponse("<h2>Step 9. Facebook deletes all notifications older than 7 days, we have downloaded all available. But we can download all your shared links on facebook from 'link' FQL table ! Click here - : <a href='%s'>/table/table_link</a>." % reverse('fbschema_table_link'))
def table_album(request): ''' table album ''' context_model = FacebookAlbum graph = require_persistent_graph(request) response_data = graph.fql(context_model.fql_query_me()) context_model.save_update_delete(request, response_data) return HttpResponse("<h2>Step 5. We have downloaded your album information. Now we do the same for your first hundred friends i.e. we are downloading album information of your first hundred friends ( Not all at once ). Click here to start with 'album' FQL table for your friends' albums : <a href='%s'>/table/table_album_friends_batch</a>." % reverse('fbschema_table_album_friends_batch'))
def table_stream(request): ''' table stream ''' context_model = FacebookStream graph = require_persistent_graph(request) response_data = graph.fql(context_model.fql_query_me()) context_model.save_update_delete(request, response_data, stream_nature=True) return HttpResponse("<h2>Successfully done. Do checkout the project on github and help me to implement more fql tables and do more awesome things with locally hosted fql tables.")
def _wrapped_view(request, *args, **kwargs): oauth_url, redirect_uri = get_oauth_url(request, scope_list, extra_params=extra_params) try: # call get persistent graph and convert the # token with correct redirect uri require_persistent_graph(request, redirect_uri=redirect_uri) return view_func(request, *args, **kwargs) except open_facebook_exceptions.OpenFacebookException, e: if test_permissions(request, scope_list, redirect_uri): # an error if we already have permissions # shouldn't have been caught # raise to prevent bugs with error mapping to cause issues raise else: logger.info(u'requesting access with redirect uri: %s, error was %s', redirect_uri, e) response = response_redirect(oauth_url, canvas=canvas) return response
def table_link_save_update(request): ''' table link : Save update ''' context_model = FacebookLink graph = require_persistent_graph(request) response_data = graph.fql(context_model.fql_query_me()) context_model.save_update_delete(request, response_data) return HttpResponse("<h2>Step 10. Now to download all shared links by your friends (3 at a time) ! Click here - : <a href='%s'>/table/table_link_friends_batch</a>." % reverse('fbschema_table_link_friends_batch'))
def query(request): require_persistent_graph(request) context = RequestContext(request) print 'querying yo' # print response response = {} if request.POST: formDict = request.POST if formDict['query']: query = formDict['query'] print 'getting more' response = _query(query, request.user) else: response = {'error' : "Enter a search term", "count":0} else: response = {'error' : "Invalid Request, please refresh the page.", "count":0} return HttpResponse(json.dumps(response, ensure_ascii=False), mimetype="application/json")
def table_album(request): ''' table album ''' context_model = FacebookAlbum graph = require_persistent_graph(request) response_data = graph.fql(context_model.fql_query_me()) context_model.save_update_delete(request, response_data) return HttpResponse( "<h2>Step 5. We have downloaded your album information. Now we do the same for your first hundred friends i.e. we are downloading album information of your first hundred friends ( Not all at once ). Click here to start with 'album' FQL table for your friends' albums : <a href='%s'>/table/table_album_friends_batch</a>." % reverse('fbschema_table_album_friends_batch'))
def canvas(request): ''' Example of a canvas page. Canvas pages require redirects to work using javascript instead of http headers The facebook required and facebook required lazy decorator abstract this away ''' context = RequestContext(request) fb = require_persistent_graph(request) likes = fb.get('me/likes')['data'] context['likes'] = likes return render_to_response('django_facebook/canvas.html', context)
def table_link_save_update(request): ''' table link : Save update ''' context_model = FacebookLink graph = require_persistent_graph(request) response_data = graph.fql(context_model.fql_query_me()) context_model.save_update_delete(request, response_data) return HttpResponse( "<h2>Step 10. Now to download all shared links by your friends (3 at a time) ! Click here - : <a href='%s'>/table/table_link_friends_batch</a>." % reverse('fbschema_table_link_friends_batch'))
def table_user(request): ''' To Fetch, Parse and Store user table data ''' graph = require_persistent_graph(request) response_data = graph.fql(FacebookUser.fql_query('WHERE uid=me()')) response_data_dict = response_data[0] data_dict = FacebookUser.prepare_dict(response_data_dict) facebook_user = FacebookUser( user=request.user, **data_dict ) facebook_user.save() return HttpResponse("<h2>Step 1. Successfully downloaded 'user' table. Now to download 'friend' table click here : <a href='%s'>/table/friend</a></h2> " % reverse('fbschema_table_friend'))
def canvas(request): """ Example of a canvas page. Canvas pages require redirects to work using javascript instead of http headers The facebook required and facebook required lazy decorator abstract this away """ context = RequestContext(request) fb = require_persistent_graph(request) likes = fb.get("me/likes")["data"] context["likes"] = likes return render_to_response("django_facebook/canvas.html", context)
def table_stream(request): ''' table stream ''' context_model = FacebookStream graph = require_persistent_graph(request) response_data = graph.fql(context_model.fql_query_me()) context_model.save_update_delete(request, response_data, stream_nature=True) return HttpResponse( "<h2>Successfully done. Do checkout the project on github and help me to implement more fql tables and do more awesome things with locally hosted fql tables." )
def table_like(request): ''' User Likes ''' graph = require_persistent_graph(request) response_data = graph.fql(FacebookLike.fql_query('WHERE user_id=me()')) for response_data_dict in response_data: data_dict = FacebookLike.prepare_dict(response_data_dict, request) print data_dict facebook_like = FacebookLike(**data_dict) facebook_like.save() return HttpResponse("<h2>Step 4. We have downloaded your like table. Facebook doesn't allow you to download your friends like information without their permission. Now we will start downloading 'album' table. First all your albums, click here to start with 'album' FQL table : <a href='%s'>/table/table_album</a>." % reverse('fbschema_table_album'))
def table_notification(request): ''' table notification ''' context_model = FacebookNotification graph = require_persistent_graph(request) response_data = graph.fql(context_model.fql_query_me()) context_model.save_update_delete(request, response_data, stream_nature=True) return HttpResponse( "<h2>Step 9. Facebook deletes all notifications older than 7 days, we have downloaded all available. But we can download all your shared links on facebook from 'link' FQL table ! Click here - : <a href='%s'>/table/table_link</a>." % reverse('fbschema_table_link'))
def table_friend(request): ''' To Fetch, Parse and Store user table data ''' graph = require_persistent_graph(request) response_data = graph.fql(FacebookFriend.fql_query('WHERE uid1=me()')) print("Hello") for response_data_dict in response_data: data_dict = FacebookFriend.prepare_dict(response_data_dict) facebook_friend = FacebookFriend( user=request.user, **data_dict ) facebook_friend.save() return HttpResponse("<h2>Step 2. Successfully downloaded 'friend' table. Now we will download all friends' profiles and store them in facebook_user table. Importing all friends in a single request will throw facebookapi timeout error, hence we do 100 at a time. To start it click here : <a href='%s'>/table/user_friends_batch</a>. You can always look at your command terminal while django's testserver is printing mysterious things, it just feels good. " % reverse('fbschema_table_user_friends_batch'))
def table_user(request): ''' To Fetch, Parse and Store user table data ''' graph = require_persistent_graph(request) response_data = graph.fql(FacebookUser.fql_query('WHERE uid=me()')) response_data_dict = response_data[0] data_dict = FacebookUser.prepare_dict(response_data_dict) facebook_user = FacebookUser(user=request.user, **data_dict) facebook_user.save() return HttpResponse( "<h2>Step 1. Successfully downloaded 'user' table. Now to download 'friend' table click here : <a href='%s'>/table/friend</a></h2> " % reverse('fbschema_table_friend'))
def table_like(request): ''' User Likes ''' graph = require_persistent_graph(request) response_data = graph.fql(FacebookLike.fql_query('WHERE user_id=me()')) for response_data_dict in response_data: data_dict = FacebookLike.prepare_dict(response_data_dict, request) print data_dict facebook_like = FacebookLike(**data_dict) facebook_like.save() return HttpResponse( "<h2>Step 4. We have downloaded your like table. Facebook doesn't allow you to download your friends like information without their permission. Now we will start downloading 'album' table. First all your albums, click here to start with 'album' FQL table : <a href='%s'>/table/table_album</a>." % reverse('fbschema_table_album'))
def query(request): require_persistent_graph(request) context = RequestContext(request) print 'querying yo' # print response response = {} if request.POST: formDict = request.POST if formDict['query']: query = formDict['query'] print 'getting more' response = _query(query, request.user) else: response = {'error': "Enter a search term", "count": 0} else: response = { 'error': "Invalid Request, please refresh the page.", "count": 0 } return HttpResponse(json.dumps(response, ensure_ascii=False), mimetype="application/json")
def authenticate(self, fn, request, *args, **kwargs): redirect_uri = self.get_redirect_uri(request) oauth_url = get_oauth_url( self.scope_list, redirect_uri, extra_params=self.extra_params) graph = None try: # call get persistent graph and convert the # token with correct redirect uri graph = require_persistent_graph( request, redirect_uri=redirect_uri) # Note we're not requiring a persistent graph here # You should require a persistent graph in the view when you start # using this facebook = OpenFacebook(graph.access_token) user = facebook.get('me') email = user.get('email') user_model = get_user_model() user = user_model.objects.filter(email=email) a = 0 if user: response = self.execute_view( fn, request, graph=graph, *args, **kwargs) else: response = HttpResponse("Voce nao tem permissao para acessar o sistema<br>Para ter acesso repasse esse email para o administrador: " + email) except open_facebook_exceptions.OpenFacebookException as e: permission_granted = has_permissions(graph, self.scope_list) if permission_granted: # an error if we already have permissions # shouldn't have been caught # raise to prevent bugs with error mapping to cause issues a = 0 if a == 0: response = self.authentication_failed( fn, request, *args, **kwargs) else: raise elif request.REQUEST.get('attempt') == '1': # Doing a redirect could end up causing infinite redirects # If Facebook is somehow not giving permissions # Time to show an error page response = self.authentication_failed( fn, request, *args, **kwargs) else: response = self.oauth_redirect(oauth_url, redirect_uri, e) return response
def table_album_friends_batch(request): ''' table album for friends ''' graph = require_persistent_graph(request) query_dict = {} for friend in FacebookFriend.objects.all()[:100]: # 100 query_dict[friend.id] = FacebookAlbum.fql_query("WHERE owner=%d" % friend.uid2) response_dataset = graph.batch_fql(query_dict) for response_data in response_dataset.values(): for response_data_dict in response_data: data_dict = FacebookAlbum.prepare_dict(response_data_dict, request) facebook_album = FacebookAlbum(user=request.user, **data_dict) facebook_album.save() return HttpResponse("<h2>Step 6. Cool! You now have all album information of some of your friends, checkout the django admin or mysql table. Now we will do the same thing with 'photo' table. To start with your own photos information, click here : <a href='%s'>/table/table_photo</a>." % reverse('fbschema_table_photo'))
def table_friend(request): ''' To Fetch, Parse and Store user table data ''' graph = require_persistent_graph(request) response_data = graph.fql(FacebookFriend.fql_query('WHERE uid1=me()')) print("Hello") for response_data_dict in response_data: data_dict = FacebookFriend.prepare_dict(response_data_dict) facebook_friend = FacebookFriend(user=request.user, **data_dict) facebook_friend.save() return HttpResponse( "<h2>Step 2. Successfully downloaded 'friend' table. Now we will download all friends' profiles and store them in facebook_user table. Importing all friends in a single request will throw facebookapi timeout error, hence we do 100 at a time. To start it click here : <a href='%s'>/table/user_friends_batch</a>. You can always look at your command terminal while django's testserver is printing mysterious things, it just feels good. " % reverse('fbschema_table_user_friends_batch'))
def table_photo_friends_batch(request): ''' table photo for friends ''' context_model = FacebookPhoto graph = require_persistent_graph(request) query_dict = {} for friend in FacebookFriend.objects.all()[2:4]: # 2 query_dict[friend.id] = context_model.fql_query_my_friends(friend.uid2) response_dataset = graph.batch_fql(query_dict) for response_data in response_dataset.values(): if response_data: context_model.save_update_delete(request, response_data) return HttpResponse("<h2>Step 8. Now to download 'notification' table. Click here : <a href='%s'>/table/table_notification</a>." % reverse('fbschema_table_notification'))
def table_link_friends_batch(request): ''' table link for friends ''' context_model = FacebookLink graph = require_persistent_graph(request) query_dict = {} for friend in FacebookFriend.objects.all()[:3]: # 3 query_dict[friend.id] = context_model.fql_query_my_friends(friend.uid2) response_dataset = graph.batch_fql(query_dict) for response_data in response_dataset.values(): if response_data: context_model.save_update_delete(request, response_data) return HttpResponse("<h2>Step 11. Finally in this alpha demo we download your stream posts from 'stream' FQL table. Click here - : <a href='%s'>/table/table_stream</a>." % reverse('fbschema_table_stream'))
def table_album_friends_batch(request): ''' table album for friends ''' graph = require_persistent_graph(request) query_dict = {} for friend in FacebookFriend.objects.all()[:100]: # 100 query_dict[friend.id] = FacebookAlbum.fql_query("WHERE owner=%d" % friend.uid2) response_dataset = graph.batch_fql(query_dict) for response_data in response_dataset.values(): for response_data_dict in response_data: data_dict = FacebookAlbum.prepare_dict(response_data_dict, request) facebook_album = FacebookAlbum(user=request.user, **data_dict) facebook_album.save() return HttpResponse( "<h2>Step 6. Cool! You now have all album information of some of your friends, checkout the django admin or mysql table. Now we will do the same thing with 'photo' table. To start with your own photos information, click here : <a href='%s'>/table/table_photo</a>." % reverse('fbschema_table_photo'))
def table_photo_friends_batch(request): ''' table photo for friends ''' context_model = FacebookPhoto graph = require_persistent_graph(request) query_dict = {} for friend in FacebookFriend.objects.all()[2:4]: # 2 query_dict[friend.id] = context_model.fql_query_my_friends(friend.uid2) response_dataset = graph.batch_fql(query_dict) for response_data in response_dataset.values(): if response_data: context_model.save_update_delete(request, response_data) return HttpResponse( "<h2>Step 8. Now to download 'notification' table. Click here : <a href='%s'>/table/table_notification</a>." % reverse('fbschema_table_notification'))
def table_link_friends_batch(request): ''' table link for friends ''' context_model = FacebookLink graph = require_persistent_graph(request) query_dict = {} for friend in FacebookFriend.objects.all()[:3]: # 3 query_dict[friend.id] = context_model.fql_query_my_friends(friend.uid2) response_dataset = graph.batch_fql(query_dict) for response_data in response_dataset.values(): if response_data: context_model.save_update_delete(request, response_data) return HttpResponse( "<h2>Step 11. Finally in this alpha demo we download your stream posts from 'stream' FQL table. Click here - : <a href='%s'>/table/table_stream</a>." % reverse('fbschema_table_stream'))
def search_results(request): facebook = require_persistent_graph(request) search_term = request.POST.get("search_term") search_term = search_term.strip() terms = re.sub("\s+"," ",search_term).split(" ") friend_set = request.user.friends() for term in terms: friend_set = friend_set.filter(name__icontains=term) friends = friend_set.all() url = "https://graph.facebook.com/search?q={}&type=user&access_token={}".format( urllib.quote_plus(search_term), facebook.access_token) result = requests.get(url) users = json.loads(result.content)['data'] return render(request, 'search_results.html', {'users': users})
def table_photo(request): ''' table photo ''' # depends on Album i.e. for a photo its parent album should exist context_model = FacebookPhoto graph = require_persistent_graph(request) response_data = graph.fql(context_model.fql_query_me()) context_model.save_update_delete(request, response_data) ''' graph = require_persistent_graph(request) response_data = graph.fql(FacebookPhoto.fql_query('WHERE owner=me() limit 5000')) for response_data_dict in response_data: data_dict = FacebookPhoto.prepare_dict(response_data_dict, request) #print data_dict facebook_photo = FacebookPhoto(user=request.user, **data_dict) facebook_photo.save() ''' return HttpResponse("<h2>Step 7. Great, now you have all your facebook photos information. We do the same for your friends, and this time we process 2 friends at a time ( have a look in code ) as photo counts can be huge for each friend. Click here : <a href='%s'>/table/table_photo_friends_batch</a>." % reverse('fbschema_table_photo_friends_batch'))
def table_like_friends_batch(request): ''' table_like => me and my friends => my friends in batch queries => table_like_friends_batch Warning: work under construction ''' # OpenFacebookException at /table/like_friends_batch # The indexed user_id queried on must be the logged in user # Note: that means we can fetch user_id[s?] if we have object_id, but we cannot fetch all object_ids for a give user_id [ makes sense ] graph = require_persistent_graph(request) query_dict = {} for friend in FacebookFriend.objects.all()[:100]: query_dict[friend.id] = FacebookLike.fql_query("WHERE user_id=%d" % friend.uid2) response_dataset = graph.batch_fql(query_dict) for response_data in response_dataset.values(): response_data_dict = response_data[0] data_dict = FacebookLike.prepare_dict(response_data_dict, request) facebook_like = FacebookLike(**data_dict) facebook_like.save() return HttpResponse("Hello World")
def table_photo(request): ''' table photo ''' # depends on Album i.e. for a photo its parent album should exist context_model = FacebookPhoto graph = require_persistent_graph(request) response_data = graph.fql(context_model.fql_query_me()) context_model.save_update_delete(request, response_data) ''' graph = require_persistent_graph(request) response_data = graph.fql(FacebookPhoto.fql_query('WHERE owner=me() limit 5000')) for response_data_dict in response_data: data_dict = FacebookPhoto.prepare_dict(response_data_dict, request) #print data_dict facebook_photo = FacebookPhoto(user=request.user, **data_dict) facebook_photo.save() ''' return HttpResponse( "<h2>Step 7. Great, now you have all your facebook photos information. We do the same for your friends, and this time we process 2 friends at a time ( have a look in code ) as photo counts can be huge for each friend. Click here : <a href='%s'>/table/table_photo_friends_batch</a>." % reverse('fbschema_table_photo_friends_batch'))
def page_tab(request): """ Example of a canvas page. Canvas pages require redirects to work using javascript instead of http headers The facebook required and facebook required lazy decorator abstract this away """ context = RequestContext(request) facebook = require_persistent_graph(request) likes = facebook.get("me/likes")["data"] context["likes"] = likes from user.models import FacebookPageTab signed_request = request.REQUEST.get("signed_request") data = facebook.prefetched_data page_id = data["page"]["id"] defaults = dict(created_by_user=data["user_id"]) tab, created = FacebookPageTab.objects.get_or_create(page_id=page_id, defaults=defaults) context["facebook"] = facebook raise Exception, tab return render_to_response("django_facebook/page_tab.html", context)
def page_tab(request): ''' Example of a canvas page. Canvas pages require redirects to work using javascript instead of http headers The facebook required and facebook required lazy decorator abstract this away ''' context = RequestContext(request) facebook = require_persistent_graph(request) likes = facebook.get('me/likes')['data'] context['likes'] = likes from user.models import FacebookPageTab signed_request = request.REQUEST.get('signed_request') data = facebook.prefetched_data page_id = data['page']['id'] defaults = dict(created_by_user=data['user_id']) tab, created = FacebookPageTab.objects.get_or_create(page_id=page_id, defaults=defaults) context['facebook'] = facebook raise Exception, tab return render_to_response('django_facebook/page_tab.html', context)
def table_user_friends_batch(request): ''' I am using batch queries, let us taste performance gain ''' graph = require_persistent_graph(request) query_dict = {} for friend in FacebookFriend.objects.all()[:100]: # Conclusion 100 batched queries at a time are enough for a while # My current problem is not to use broker, so deferring it. What I can do with data and for the problem is the question. query_dict[friend.id] = FacebookUser.fql_query("WHERE uid=%d" % friend.uid2) response_dataset = graph.batch_fql(query_dict) for response_data in response_dataset.values(): try: response_data_dict = response_data[0] data_dict = FacebookUser.prepare_dict(response_data_dict) facebook_user = FacebookUser( user=request.user, **data_dict ) facebook_user.save() except IndexError: logger.info("A user query returned no information") #pp.pprint(response_data) return HttpResponse("<h2>Step 3. Congratulations! You have downloaded profiles of your first hundred friends. Don't believe me ? You can always look at these profiles using django's admin interface. Just don't forget to login into admin using different browser not messing up with this session. Now we will download 'like' table, click here : <a href='%s'>/table/table_like</a>." % reverse('fbschema_table_like'))
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\ 'and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: logger.info('trying to connect using facebook') graph = require_persistent_graph(request) if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) except facebook_exceptions.AlreadyConnectedError, e: user_ids = [u.id for u in e.users] ids_string = ','.join(map(str, user_ids)) return next_redirect( request, next_key=['error_next', 'next'], additional_params=dict(already_connected=ids_string)) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info( request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect( request, user) #compatability for django registration backends which return tuples instead of a response #alternatively we could wrap django registration backends, but that would be hard to understand response = response if isinstance( response, HttpResponse) else redirect(response) return response
def connect(request): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) assert context.get('FACEBOOK_APP_ID'), 'Please specify a facebook app id '\ 'and ensure the context processor is enabled' facebook_login = bool(int(request.REQUEST.get('facebook_login', 0))) if facebook_login: require_persistent_graph(request) logger.info('trying to connect using facebook') graph = get_persistent_graph(request) if graph: logger.info('found a graph object') klass = get_facebook_user_converter_class() facebook = klass(graph) if facebook.is_authenticated(): logger.info('facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info( request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect( request, user) return response else: if 'attempt' in request.GET: return next_redirect( request, next_key=['error_next', 'next'], additional_params=dict(fb_error_or_cancel=1)) else: logger.info('Facebook authentication needed for connect, ' \ 'raising an error') raise OpenFacebookException('please authenticate') #for CONNECT and LOGIN we simple redirect to the next page return next_redirect( request, default=facebook_settings.FACEBOOK_LOGIN_DEFAULT_REDIRECT)
def _connect(request, facebook_login): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) if True: logger.info('trying to connect using Facebook') graph = require_persistent_graph(request) authenticated = False if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) authenticated = facebook.is_authenticated() if authenticated: logger.info('Facebook is authenticated') facebook_data = facebook.facebook_profile_data() #either, login register or connect the user : This is where it interfaces with Django try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) print user print request.user except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e, facebook_data=facebook_data) context['facebook_mode'] = True context['form'] = e.form return render_to_response( facebook_settings.FACEBOOK_REGISTRATION_TEMPLATE, context_instance=context, ) except facebook_exceptions.AlreadyConnectedError, e: user_ids = [u.user_id for u in e.users] ids_string = ','.join(map(str, user_ids)) return error_next_redirect( request, additional_params=dict(already_connected=ids_string)) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality #response = backend.post_registration_redirect( # request, user) return HttpResponseRedirect(reverse('home_logged_home')) #compatibility for Django registration backends which return redirect tuples instead of a response if not isinstance(response, HttpResponse): to, args, kwargs = response response = redirect(to, *args, **kwargs) return response
def getGraphPost (request, postID): require_persistent_graph(request) context = RequestContext(request) graph = request.facebook postDict = graph.get(postID) return HttpResponse(json.dumps(postDict, ensure_ascii=False), mimetype="application/json")
def _connect(request, facebook_login): ''' Handles the view logic around connect user - (if authenticated) connect the user - login - register ''' backend = get_registration_backend() context = RequestContext(request) if facebook_login: logger.info('trying to connect using Facebook') try: graph = require_persistent_graph(request) except: return HttpResponseRedirect('https://www.facebook.com') authenticated = False if graph: logger.info('found a graph object') facebook = FacebookUserConverter(graph) authenticated = facebook.is_authenticated() if authenticated: facebook_data = facebook.facebook_profile_data() #either, login register or connect the user try: action, user = connect_user(request) logger.info('Django facebook performed action: %s', action) except facebook_exceptions.IncompleteProfileError, e: #show them a registration form to add additional data warning_format = u'Incomplete profile data encountered with error %s' warn_message = warning_format % e.message send_warning(warn_message, e=e,facebook_data=facebook_data) context['facebook_mode'] = True m = re.search(r'{(?P<hello>.*)}',str(e).replace('\t','').replace('\n','')) all_d = smart_str(m.group('hello')) #return HttpResponse(all_d) all_data = splitting(all_d) sec = get_random_string(250) all_data['sec'] = sec error = False try: bb = all_data['birthday'].split('/') birthday = bb[2] +'-' + bb[0] + '-' + bb[1] except: error = True ############################################################################### pss = hashlib.sha512(str(all_data['password1'])).hexdigest() #,avatar2=all_data['image'] try: if not error: cix = Account.objects.create(name=all_data['facebook_name'],email=all_data['email'],gender2=all_data['gender'].upper(),facebook_data=str(all_d),secret=sec,password=pss,facebook_page=all_data['link']) else: cix = Account.objects.create(name=all_data['facebook_name'],birthday=birthday,email=all_data['email'],gender2=all_data['gender'].upper(),facebook_data=str(all_d),secret=sec,password=pss,facebook_page=all_data['link']) except IntegrityError: pass try: cix.facebook_data=str(all_d) cix.save() except: pass ##############################################################################3 xt = Account.objects.is_valid3(all_data['email']) if not xt[0]: request.META['authenticated2'] = str(all_data['link']) else: request.META['authenticated2'] = xt[1] #c = { 'form' : all_data } #featured = BaseCourse.objects.filter(featured=True) #c['f1'] = featured[:3] #c['f2'] = featured[3:6] #c['f3'] = featured[6:9] #c['number_of_courses'] = BaseCourse.objects.all().count() return HttpResponseRedirect('/coursewall') except facebook_exceptions.AlreadyConnectedError, e: user_ids = [u.user_id for u in e.users] ids_string = ','.join(map(str, user_ids)) return error_next_redirect( request, additional_params=dict(already_connected=ids_string)) if action is CONNECT_ACTIONS.CONNECT: #connect means an existing account was attached to facebook messages.info(request, _("You have connected your account " "to %s's facebook profile") % facebook_data['name']) elif action is CONNECT_ACTIONS.REGISTER: #hook for tying in specific post registration functionality response = backend.post_registration_redirect( request, user) #compatibility for Django registration backends which return redirect tuples instead of a response if not isinstance(response, HttpResponse): to, args, kwargs = response response = redirect(to, *args, **kwargs) return response