def is_authenticated(self, request, **kwargs): print "Authentication starting..." # Make sure user supplied access token in request try: if request.method == 'GET': access_token = request.GET['access_token'] elif request.method == 'POST': access_token = request.POST['access_token'] except KeyError: return self._unauthorized() # Authenticate with facebook from open_facebook import OpenFacebook from django_facebook.connect import connect_user print "Authentication token found. Verifying..." facebook = OpenFacebook(access_token) print "Connection to Facebook server in progress..." try: if not facebook or not facebook.is_authenticated(): return self._unauthorized() except: return self._unauthorized() print "Connection established. Authentication successful." # Facebook authenticated, now associate # with own internal user, Creating a new user if # necessary. #action, user = connect_user(request, access_token, facebook) user = facebook.get('me') return user
def share_yap_on_facebook(user,facebook_access_token,yap): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: if user.settings.facebook_account_id != None: name = str(yap.user.first_name) + ' ' + str(yap.user.last_name) + " (@" + str(user.username) + ") posted a yap on Yapster" if user.settings.facebook_page_connection_flag == True: api_url = str(user.settings.facebook_page_id) + '/feed' elif user.settings.facebook_page_connection_flag == False: api_url = str(user.settings.facebook_account_id) + '/feed' url = "http://web.yapster.co/yap/" + str(yap.pk) b = connect_s3(bucket_name="yapsterapp") if yap.picture_flag == True: yap_picture_key = b.get_key(yap.picture_cropped_path) yap_picture_url = yap_picture_key.generate_url(expires_in=600) elif yap.picture_flag == False: yap_picture_key = b.get_key(user.profile.profile_picture_path) yap_picture_url = yap_picture_key.generate_url(expires_in=600) if yap.description != None: fb_share_yap_message = "\"" + str(yap.title.encode('utf-8')) + "\" - " + str(yap.description) + " " + "\n" + str(url) elif yap.description == None: fb_share_yap_message = "\"" + str(yap.title.encode('utf-8')) + "\" " + str(url) fb_share_yap_description = "Listen to this yap - and other yaps from " + str(user.first_name) + " " + str(user.last_name) fb_share_yap = facebook.set(api_url, link=url, picture=yap_picture_url, name=name, description=fb_share_yap_description,message=fb_share_yap_message)['id'] return fb_share_yap else: return "User has not set up a facebook_account_id." else: return "User has not connected their account with Facebook."
def is_authenticated(self, request, **kwargs): """ Authenticate with facebook, and return user upon success. """ # Make sure user supplied access token in request try: access_token = request.GET['access_token'] except KeyError: return self._unauthorized() # Authenticate with facebook from open_facebook import OpenFacebook from django_facebook.connect import connect_user facebook = OpenFacebook(access_token) try: if not facebook or \ not facebook.is_authenticated(): return self._unauthorized() except: return self._unauthorized() # Facebook authenticated, now associate # with own internal user, Creating a new user if # necessary. action, user = connect_user(request, access_token, facebook) request.user = user return True
def share_new_following_story_on_facebook(user,user_followed,facebook_access_token): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_account_id != None: if user.settings.facebook_page_connection_flag == True: story_api_url = str(user.settings.facebook_page_id) + '/yapster_fb:followed' elif user.settings.facebook_page_connection_flag == False: story_api_url = str(user.settings.facebook_account_id) + '/yapster_fb:followed' name = str(user_followed.first_name) + ' ' + str(user_followed.last_name) + ' (@' + str(user_followed.username.encode('utf-8') +')') url = "http://yapster.co" b = connect_s3(bucket_name="yapsterapp") if user_followed.profile.profile_picture_flag == True: user_followed_picture_key = b.get_key(user_followed.profile.profile_picture_cropped_path) user_followed_picture_url = user_followed_picture_key.generate_url(expires_in=600) elif user_followed.profile.profile_picture_flag == False: user_followed_picture_url = None if user.settings.facebook_page_connection_flag == True: object_api_url = str(user.settings.facebook_page_id) + '/objects/yapster_fb:user' elif user.settings.facebook_page_connection_flag == False: object_api_url = str(user.settings.facebook_account_id) + '/objects/yapster_fb:user' description = 'Check out what @' + str(user.username) + ' and @' + str(user_followed.username) + ' have been yapping about and listening to!' user_followed_object = facebook.set(object_api_url, object={"url":url,"image":user_followed_picture_url,"title":name})['id'] fb_share = facebook.set(story_api_url,user=user_followed_object)['id'] return fb_share else: return "User has not set up a facebook_account_id."
def recursive_graph_call(graph_id, *args, **kwargs): ''' response = recursive_graph_call('147863265269488_588392457883231/likes', limit=500) ''' graph = OpenFacebook(settings.FACEBOOK_API_ACCESS_TOKEN) if 'limit' not in kwargs: kwargs['limit'] = 100 response = {} while True: r = graph.get(graph_id, *args, **kwargs) if not response: # first call response = r else: response['data'] += r['data'] if 'paging' in r: kwargs['after'] = r['paging']['cursors']['after'] else: break return response
def post_social(self): if settings.DEBUG: return try: verb = self.get_verb_past() object = self.get_object_singular() if verb == "favourited": action_type = "deepsouthsounds:favourite" if verb == "liked": action_type = "like" if verb == "followed": action_type = "og.follows" else: action_type = "deepsouthsounds:play" if False: social_account = SocialToken.objects.filter( account__user=self.user.user, account__provider='facebook')[0] facebook = OpenFacebook(social_account.token) notification_html = {object: wrap_full(self.get_object_url())} result = facebook.set('me/%s' % action_type, notification_html) print(result) except Exception as ex: print(ex) pass
def share_yap_story_on_facebook(user,facebook_access_token,yap): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: if user.settings.facebook_account_id != None: name = str(yap.title.encode('utf-8')) if user.settings.facebook_page_connection_flag == True: object_api_url = str(user.settings.facebook_page_id) + '/objects/yapster_fb:yap' elif user.settings.facebook_page_connection_flag == False: object_api_url = str(user.settings.facebook_account_id) + '/objects/yapster_fb:yap' url = "http://web.yapster.co/yap/" + str(yap.pk) + '/' b = connect_s3(bucket_name="yapsterapp") if yap.picture_flag == True: yap_picture_key = b.get_key(yap.picture_cropped_path) yap_picture_url = yap_picture_key.generate_url(expires_in=600) elif yap.picture_flag == False: yap_picture_key = b.get_key(user.profile.profile_picture_path) yap_picture_url = yap_picture_key.generate_url(expires_in=600) if yap.description != None: fb_yap = facebook.set(object_api_url, object={"url":url,"image":yap_picture_url,"title":json.dumps(name),"description":json.dumps(yap.description)})['id'] elif yap.description == None: fb_yap = facebook.set(object_api_url, object={"url":url,"image":yap_picture_url,"title":json.dumps(name)})['id'] if user.settings.facebook_page_connection_flag == True: story_api_url = str(user.settings.facebook_page_id) + '/yapster_fb:yapped' elif user.settings.facebook_page_connection_flag == False: story_api_url = str(user.settings.facebook_account_id) + '/yapster_fb:yapped' fb_share_yap = facebook.set(story_api_url,yap=fb_yap)['id'] return fb_share_yap else: return "User has not set up a facebook_account_id." else: return "User has not set up their account with Facebook."
def post_social(self): if settings.DEBUG: return try: verb = self.get_verb_past() object = self.get_object_singular() if verb == "favourited": action_type = "deepsouthsounds:favourite" if verb == "liked": action_type = "like" if verb == "followed": action_type = "og.follows" else: action_type = "deepsouthsounds:play" social_account = SocialToken.objects.filter(account__user=self.user.user, account__provider='facebook')[0] facebook = OpenFacebook(social_account.token) notification_html = { object: wrap_full(self.get_object_url()) } result = facebook.set('me/%s' % action_type, notification_html) print result except Exception, ex: print ex.message pass
def handle(self, app_id, app_secret, facebook_page_id, user_token, *args, **options): # To generate a user_token use https://developers.facebook.com/tools/explorer/ # Select your application and Get Access Token # manage_pages in Extended Permissions must be enabled for this token # facebook_page_id can also be obtained from https://developers.facebook.com/tools/explorer/ # Query for 'me/accounts' and look for the id of your facebook page # Another way to find the id is using http://findmyfacebookid.com/ # There you will only have to enter the url of your page to get the page id h = httplib2.Http("") resp, content = h.request("https://graph.facebook.com/oauth/access_token?client_id" "="+app_id+"&client_secret="+app_secret+"&grant_type=fb_excha" "nge_token&fb_exchange_token="+user_token, "POST") user_token_extended = content[13:] graph = OpenFacebook(user_token_extended) accounts = graph.get('me/accounts') page = filter(lambda page: page['id'] == facebook_page_id, accounts["data"])[0] not_expiring_token = page["access_token"] print not_expiring_token
def send_post(request): if request.POST: user = FacebookProfile.objects.get(user_id=request.user.id) access_token = user.access_token facebook = OpenFacebook(access_token) # facebook.get('me') # info about me message = request.POST.get('post_text') # facebook.set('me/feed', message=message, picture='http://neutr10.com/wp-content/uploads/2016/02/python-snake.jpg') # posted message for me photo_urls = [ 'http://neutr10.com/wp-content/uploads/2016/02/python-snake.jpg', 'http://neutr10.com/wp-content/uploads/2016/02/python-snake.jpg', ] for photo in photo_urls: print facebook.set('me/feed', message=message, picture=photo, url='http://www.me.com', link=photo, caption="") return render(request, 'send_post.html', {'message': 'Success'}) return render(request, 'send_post.html')
def connected_facebook_and_yapster_post_on_facebook(user, facebook_access_token): facebook = OpenFacebook(facebook_access_token) url = "http://yapster.co" name = str(user.first_name) + ' ' + str(user.last_name) + " (@" + str( user.username) + ") just connected Yapster to Facebook!" description = "Click here and download the app to listen to what " + " @" + str( user.username) + " has been yapping about." b = connect_s3(bucket_name="yapsterapp") fb_share_yapster_picture_key = b.get_key( '/yapstersocialmedia/yapster_white_y_green_background') fb_share_yapster_picture_url = fb_share_yapster_picture_key.generate_url( expires_in=600) if user.settings.facebook_connection_flag == True: if user.settings.facebook_page_connection_flag == True: api_url = str(user.settings.facebook_page_id) + '/feed' elif user.settings.facebook_page_connection_flag == False: api_url = str(user.settings.facebook_account_id) + '/feed' facebook_post = facebook.set(api_url, link=url, picture=fb_share_yapster_picture_url, name=name, description=description)['id'] return facebook_post else: return 'User has not setup Facebook Connection'
def getUserInbox(user): access_token = user.access_token facebook = OpenFacebook(access_token) inbox = facebook.get('/me/inbox') inbox2 = facebook.get(inbox['paging']['next'].split("v2.0")[1]) return breadthlooper(inbox,user, facebook)
def fb_image(user): if not user.id: return False facebook = OpenFacebook(user.access_token) img_url = facebook.my_image_url(size="small") return img_url
def get_user_from_id(cls, fb_id, token): print "received post", fb_id, token fb = OpenFacebook(token) data = fb.get("me") print data cls.create(data, token)
def get_context_data(self, **kwargs): fb_user = FacebookCustomUserActive.objects.get(id=self.request.user.id) if fb_user.facebook_id and fb_user.access_token: facebook = OpenFacebook(fb_user.access_token) data = facebook.get('me/photos/uploaded', fields='picture')['data'] else: data = {} kwargs['facebook_photos'] = data return super(CreateFacebookPhoto, self).get_context_data(**kwargs)
def populate_likes(self): assert self.token try: fb = OpenFacebook(self.token) likes = fb.get("me/likes")['data'] for like in likes: Interest.get_or_create(like, self) except Exception, e: logging.exception(e)
def set_page_token(self): token = FacebookAdminToken.objects.last() auth_token = token.access_token graph = OpenFacebook(auth_token) result = graph.get('me/accounts') for row in result['data']: if row['id'] == settings.PAGE_ID: self.page_token = row['access_token'] print('Page Token: ', self.page_token, ' ***') break
def get_all_of_users_facebook_friends_on_yapster(user, facebook_access_token): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: facebook_friends = facebook.get('me/friends', fields="id")['data'] this_users_facebook_friends_on_yapster = [ friend_facebook_id['id'] for friend_facebook_id in facebook_friends if Settings.objects.filter( is_active=True, facebook_account_id=friend_facebook_id['id']).exists() == True ] return this_users_facebook_friends_on_yapster
def post_catch_of_the_week(self): fish = self.queryset.first() graph = OpenFacebook(self.page_token) img_url = '{}{}'.format(settings.BASE_URL, fish.image.url) url = '{}{}'.format(settings.BASE_URL, reverse('fish_enlarge', args=[fish.pk])) message = 'Fish of the week - {} {}kg. '.format( fish.species.name, fish.weight) graph.set('me/feed', picture=img_url, link=url, message=message)
def write_facebook_status(message, link, picture=''): """ Post a link and message to Facebook page or timeline """ link = build_url(link) try: fb = OpenFacebook(settings.FACEBOOK_ACCESS_TOKEN) # request to scrape url first res = fb.set('/', id=link, scrape=True) if res['id']: fb.set('me/feed', message=message, link=link) else: raise except: logger.error('Error when posting to Facebook page')
def create_default_photo(sender, instance, created, **kwargs): if created: logger.info('create_default_photo triggered by {} {}'.format( sender, instance )) facebook = OpenFacebook(instance.user.access_token) data = facebook.get('me', fields='picture.hight(1000).width(1000)') image_url = data.get('picture', {}).get('data', {}).get('url', {}) FacebookPhoto.objects.get_or_create( photo=image_url, order=0, user=instance.user )
def get_playlists(client, username, request): if len(username) > 1: username = username else: print "Whoops, need your username!" print "usage: python user_playlists.py [username]" sys.exit() token = util.prompt_for_user_token(username) if token: sp = spotipy.Spotify(auth=token) playlists = sp.user_playlists(username) print playlists #playlist = sp.user_playlist(username, playlist_id=playlist, fields=None) #print playlist #print playlist['tracks']['total'] limit = 100 #playlist = sp.user_playlist_tracks(username, playlist_id=playlist, fields=None, limit=limit, offset=100) #print playlist #print playlist['next'] i=1 print "Access Token:" me = request.user print me #graph = get_persistent_graph(user2) graph = me.get_offline_graph() print graph access_token = me.access_token print access_token facebook = OpenFacebook(access_token) me = facebook.get('me', fields ='third_party_id') print me print 'got it!' ''' for track in playlist['items']: print str(i) + ' ' + track['track']['name'] + ' ' + track['track']['uri'] if i == limit: print playlist['next'] return i += 1 ''' else: print "Can't get token for", username
def share_yap_story_on_facebook(user, facebook_access_token, yap): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: if user.settings.facebook_account_id != None: name = str(yap.title.encode('utf-8')) if user.settings.facebook_page_connection_flag == True: object_api_url = str( user.settings.facebook_page_id) + '/objects/yapster_fb:yap' elif user.settings.facebook_page_connection_flag == False: object_api_url = str(user.settings.facebook_account_id ) + '/objects/yapster_fb:yap' url = "http://web.yapster.co/yap/" + str(yap.pk) + '/' b = connect_s3(bucket_name="yapster") if yap.picture_flag == True: yap_picture_key = b.get_key(yap.picture_cropped_path) yap_picture_url = yap_picture_key.generate_url(expires_in=600) elif yap.picture_flag == False: yap_picture_key = b.get_key(user.profile.profile_picture_path) yap_picture_url = yap_picture_key.generate_url(expires_in=600) if yap.description != None: fb_yap = facebook.set(object_api_url, object={ "url": url, "image": yap_picture_url, "title": json.dumps(name), "description": json.dumps(yap.description) })['id'] elif yap.description == None: fb_yap = facebook.set(object_api_url, object={ "url": url, "image": yap_picture_url, "title": json.dumps(name) })['id'] if user.settings.facebook_page_connection_flag == True: story_api_url = str( user.settings.facebook_page_id) + '/yapster_fb:yapped' elif user.settings.facebook_page_connection_flag == False: story_api_url = str( user.settings.facebook_account_id) + '/yapster_fb:yapped' fb_share_yap = facebook.set(story_api_url, yap=fb_yap)['id'] return fb_share_yap else: return "User has not set up a facebook_account_id." else: return "User has not set up their account with Facebook."
def get_admin_access_token_complete(request): code = request.GET['code'] graph = OpenFacebook() params = { 'code': code, 'client_id': settings.SOCIAL_AUTH_FACEBOOK_APP_KEY, 'client_secret': settings.SOCIAL_AUTH_FACEBOOK_SECRET, 'redirect_uri': request.build_absolute_uri(reverse('get_admin_access_token_complete')) } resp = graph.get('oauth/access_token', **params) FacebookAdminToken(access_token=resp['access_token']).save() return HttpResponseRedirect('/admin/')
def post_weekly_gallery(self): graph = OpenFacebook(self.page_token) resp = graph.set('me/albums', name='Week {}'.format(timezone.now().strftime('%W')), privacy={'value': 'SELF'}) album_id = resp['id'] # album_id = '1482194405444590' graph_url = '{}/photos'.format(album_id) for fish in self.queryset: img_url = '{}{}'.format(settings.BASE_URL, fish.image.url) url = '{}{}'.format(settings.BASE_URL, reverse('fish_enlarge', args=[fish.pk])) resp = graph.set(graph_url, url=img_url, link=url)
def connected_facebook_and_yapster_post_on_facebook(user,facebook_access_token): facebook = OpenFacebook(facebook_access_token) url = "http://yapster.co" name = str(user.first_name) + ' ' + str(user.last_name) + " (@" + str(user.username) + ") just connected Yapster to Facebook!" description = "Click here and download the app to listen to what " + " @" + str(user.username) + " has been yapping about." b = connect_s3(bucket_name="yapsterapp") fb_share_yapster_picture_key = b.get_key('/yapstersocialmedia/yapster_white_y_green_background') fb_share_yapster_picture_url = fb_share_yapster_picture_key.generate_url(expires_in=600) if user.settings.facebook_connection_flag == True: if user.settings.facebook_page_connection_flag == True: api_url = str(user.settings.facebook_page_id) + '/feed' elif user.settings.facebook_page_connection_flag == False: api_url = str(user.settings.facebook_account_id) + '/feed' facebook_post = facebook.set(api_url,link=url,picture=fb_share_yapster_picture_url,name=name,description=description)['id'] return facebook_post else: return 'User has not setup Facebook Connection'
def is_authenticated(self, request, **kwargs): auth_params = request.META.get('HTTP_X_FACEBOOK_AUTHENTICATION') if auth_params: parts = auth_params.split() if len(parts) == 2: if parts[0] == 'OAuth': access_token = parts[1] facebook = OpenFacebook(access_token) try: if facebook == None or not facebook.is_authenticated(): return self._unauthorized() action, user = connect_user(request, access_token, facebook) request.user = user return True except Exception, err: logger.error('ERROR %s: %s' % (self.__class__.__name__, unicode(err)))
def notify_bidders_thread(**kwargs): auction = kwargs['auction'] text = '' if kwargs['signal'] == 'auction_started': text = u'The auction for a {item} has started. Hurry and go win it!.'.format( item=auction.item.name) if kwargs['signal'] == 'precap_finishing': text = u'The auction for a {item} is about to start. Go play for it!.'.format( item=auction.item.name) for member in auction.bidders.all(): of = OpenFacebook(member.access_token) args = { 'template': text, 'access_token': FacebookAuthorization.get_app_access_token() } destination = '{facebook_id}/notifications'.format( facebook_id=member.facebook_id) response = of.set(destination, **args)
def get_posts_impressions(request): """Get the number of impressions for a post id. Receives the post id as a GET parameter and uses Facebook api to get lifetime impressions. Returns JSON for total lifetime impressions for a post id. """ post_id = request.GET['post_id'] # call facebook api using OpenFacebook api facebook = OpenFacebook(request.user.access_token) impressions = facebook.get('%s/insights/post_impressions_unique' % (post_id)) try: # try getting the impressions from json and return N/A if not found num_impression = impressions['data'][0]['values'][0]['value'] except: num_impression = 'N/A' return JsonResponse({"impressions": num_impression})
def _PostToFB(message): token = getattr(settings, 'FACEBOOK_AUTHENTICATION_TOKEN', "") page = str(getattr(settings, 'FACEBOOK_PAGE_ID', 123)) user_account = OpenFacebook(token) accounts = user_account.get('me/accounts') for x in accounts['data']: if x['id'] == page: page = x break else: # page not found print "Page not found with corresponding ID" return page_graph = OpenFacebook(page['access_token']) result = page_graph.set('me/feed', message=message) print "FB post result:", result
def renew_facebook_admin_token(): current_token = FacebookAdminToken.objects.last() if current_token.obtained > (timezone.now() - timezone.timedelta(days=14)): return # obtained two weeks ago, time to renew params = { 'grant_type': 'fb_exchange_token', 'client_id': settings.SOCIAL_AUTH_FACEBOOK_APP_KEY, 'client_secret': settings.SOCIAL_AUTH_FACEBOOK_SECRET, 'fb_exchange_token': current_token.access_token } graph = OpenFacebook() resp = graph.get('oauth/access_token', **params) FacebookAdminToken(resp['access_token']).save()
def share_new_subscribed_story_on_facebook(user, user_followed, facebook_access_token): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_account_id != None: if user.settings.facebook_page_connection_flag == True: story_api_url = str( user.settings.facebook_page_id) + '/yapster_fb:followed' elif user.settings.facebook_page_connection_flag == False: story_api_url = str( user.settings.facebook_account_id) + '/yapster_fb:followed' name = str(user_followed.first_name) + ' ' + str( user_followed.last_name) + ' (@' + str( user_followed.username.encode('utf-8') + ')') url = "http://yapster.co" b = connect_s3(bucket_name="yapsterapp") if user_followed.profile.profile_picture_flag == True: user_followed_picture_key = b.get_key( user_followed.profile.profile_picture_cropped_path) user_followed_picture_url = user_followed_picture_key.generate_url( expires_in=600) elif user_followed.profile.profile_picture_flag == False: user_followed_picture_url = None if user.settings.facebook_page_connection_flag == True: object_api_url = str( user.settings.facebook_page_id) + '/objects/yapster_fb:user' elif user.settings.facebook_page_connection_flag == False: object_api_url = str( user.settings.facebook_account_id) + '/objects/yapster_fb:user' description = 'Check out what @' + str(user.username) + ' and @' + str( user_followed.username ) + ' have been yapping about and listening to!' user_followed_object = facebook.set(object_api_url, object={ "url": url, "image": user_followed_picture_url, "title": name })['id'] fb_share = facebook.set(story_api_url, user=user_followed_object)['id'] return fb_share else: return "User has not set up a facebook_account_id."
def get_facebook_access_token(request): me = [] if request.method == 'GET': code = request.GET.get('code',None) redirect_uri = "http://localhost:8000%s" % reverse('facebook-access') response=FacebookAuthorization.convert_code(code,redirect_uri =redirect_uri) access_token=response.get('access_token',None) expire = response.get('expires',None) expiration = datetime.datetime.now() + datetime.timedelta(seconds=int(expire)) try: stored_token = FaceBookAcessToken.objects.all()[0] stored_token.access_token=access_token stored_token.expiration=expiration except: stored_token = FaceBookAcessToken(access_token=access_token,expiration=expiration) stored_token.save() facebook=OpenFacebook(access_token) me =facebook.get('me') return render(request,"facebook_access/facebook_access.html", {"me":me,})
def main(): social_datas = Social_Data.objects.filter(active=True) for social_data in social_datas: if social_data.account_type == '0': #facebook graph = OpenFacebook(social_data.account_token) profile = graph.get('me') profile_id = profile['id'] friends = graph.get('me/friends') total_follower = int(friends['summary']['total_count']) social_data.total_follower = total_follower social_data.save() elif social_data.account_type == '1': #twitter api = twitter.Api( consumer_key='zsqVde4f4vkRNopoj8zGvVM7x', consumer_secret= '3pcD1MNmQNyHAZrDjmNQmHdnUNfZywbA4Lbomh3ofxqzO3e6o8', access_token_key=social_data.account_id, access_token_secret=social_data.account_token) social_data.total_follower = api.VerifyCredentials( ).followers_count social_data.save()
def page_listing(request): """Fetches the pages managed by a user and shows it on listing.html page. Uses Facebook API to get the pages for a uset. """ facebook = OpenFacebook(request.user.access_token) details = facebook.get('me/accounts') details_dict = details page_info_list = [] # list containing details of all the pages for entry in details_dict.get('data'): temp_dict = { 'name': entry['name'], 'id': entry['id'], 'category': entry['category'] } page_info_list.append(temp_dict) # render to template return render_to_response('listing.html', locals(), RequestContext(request))
def userListens(access_token, client_username): # Form has username info to get access_token from Spotify username = client_username token = util.prompt_for_user_token(username) sp = spotipy.Spotify(auth=token) graph = OpenFacebook(access_token) if access_token is not None: listen_data = graph.get('me/music.listens') user_listens = [] listens = listen_data['data'] for listen in listens: tmp = [] song_name = listen['data']['song']['title'] client_url = listen['data']['song']['url'] client_unique = re.search('track\/(.*)', client_url).group(1) print client_unique # Get tuneboss track if it exists, othewise create it. try: tb_track = Track.objects.get(client_unique=client_unique) except Track.DoesNotExist: sp_track = sp.track(client_unique) client = Client.objects.get(client_name='Spotify') tb_track = create_track(sp_track, client, username) artist_name = tb_track.artist_name tmp.append(client_unique) tmp.append(song_name) tmp.append(artist_name) if listen['data'].get('playlist'): playlist = listen['data']['playlist']['title'] tmp.append(playlist) user_listens.append(tmp) print(json.dumps(song_name, sort_keys=True, indent=4, separators=(',', ': '))) return user_listens
def share_yap_on_facebook(user, facebook_access_token, yap): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: if user.settings.facebook_account_id != None: name = str(yap.user.first_name) + ' ' + str( yap.user.last_name) + " (@" + str( user.username) + ") posted a yap on Yapster" if user.settings.facebook_page_connection_flag == True: api_url = str(user.settings.facebook_page_id) + '/feed' elif user.settings.facebook_page_connection_flag == False: api_url = str(user.settings.facebook_account_id) + '/feed' url = "http://web.yapster.co/yap/" + str(yap.pk) b = connect_s3(bucket_name="yapster") if yap.picture_flag == True: yap_picture_key = b.get_key(yap.picture_cropped_path) yap_picture_url = yap_picture_key.generate_url(expires_in=600) elif yap.picture_flag == False: yap_picture_key = b.get_key(user.profile.profile_picture_path) yap_picture_url = yap_picture_key.generate_url(expires_in=600) if yap.description != None: fb_share_yap_message = "\"" + str( yap.title.encode('utf-8')) + "\" - " + str( yap.description) + " " + "\n" + str(url) elif yap.description == None: fb_share_yap_message = "\"" + str( yap.title.encode('utf-8')) + "\" " + str(url) fb_share_yap_description = "Listen to this yap - and other yaps from " + str( user.first_name) + " " + str(user.last_name) fb_share_yap = facebook.set(api_url, link=url, picture=yap_picture_url, name=name, description=fb_share_yap_description, message=fb_share_yap_message)['id'] return fb_share_yap else: return "User has not set up a facebook_account_id." else: return "User has not connected their account with Facebook."
def dash(request): """ Show user pics in dashboard """ context = RequestContext(request, {'user': request.user}) # access token from user profile # will be used to access fb user_profile = request.user.get_profile() facebook = OpenFacebook(user_profile.access_token) # get all user uploaded pics from fb photos = facebook.get("me/photos/uploaded", fields='images,album') # logic to get the smallest image # single image and album will be displayed display_photos = [] for photo in photos['data']: sorted_images = sorted(photo['images']) thumbnail = sorted_images[0] large = sorted_images[-1] display_photos.append((photo['album'], thumbnail, large)) context['display_photos'] = display_photos return render_to_response('dash.html', context_instance=context)
def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) user = SocialAccount.objects.get(user=request.user) access_token = SocialToken.objects.get(account_id=user, account__provider='facebook') idUser = user.uid graph = OpenFacebook(access_token=access_token) if graph.is_authenticated(): idPages = (graph.get('me/accounts/')) id_Pages_List = [id['id'] for id in idPages['data']] id_Pages_List = ", ".join(id_Pages_List) id_Page_Access_Token = (graph.get(id_Pages_List, fields='access_token')) id_Page_Access_Token = (id_Page_Access_Token['access_token']) graph = OpenFacebook(access_token=id_Page_Access_Token) feed_url = 'https://graph.facebook.com/'+id_Pages_List+'/feed?message='+post.text+'&access_token='+id_Page_Access_Token feed_Request = requests.post(feed_url) print(feed_Request.status_code) if(feed_Request.status_code == 200): return render(request, 'blog/home.html', {'user': request.user,'access_token': id_Page_Access_Token,'page_id': id_Pages_List }) else: return HttpResponse(feed_Request) print('bad') return render(request, 'blog/loginFacebook.html', {'access_token': access_token, 'idUser': idUser}) else: print('bad') return render(request, 'blog/loginFacebook.html') else: form = PostForm() return render(request, 'blog/add_new_post.html', {'form': form})
def save_post(request): """Saves the post(both published and unpublished) for a specific page. Receives page id, message and a publish-unpublish flag as parameters. Then finds out the page access token for the page and uses it to post as the page. """ if request.POST.get('publish-check'): published = True else: published = False message = request.POST['post-message'] page_id = request.POST['page_id_post'] user_facebook = OpenFacebook(request.user.access_token) response = user_facebook.get('me/accounts') # get page access token for entry in response['data']: if entry['id'] == page_id: page_access_token = entry['access_token'] break facebook = OpenFacebook(page_access_token) facebook.set('%s/feed' % (page_id), message=message, published=published) return redirect('page-posts', page_id)
def get_fb(self, links): from open_facebook import OpenFacebook from . utils import recursive_graph_call graph = OpenFacebook(settings.FACEBOOK_API_ACCESS_TOKEN) ids = set() for link in links: matches = re.match(r'^https?://www.facebook.com/(.*?)/posts/(\d+)$', link) if matches: company_slug = matches.group(1) post_id = matches.group(2) try: company = graph.get(company_slug, fields='id') except OpenFacebookException as e: continue # check post_graph_id = '%s_%s' % (company['id'], post_id) try: post = graph.get(post_graph_id, fields='id') except OpenFacebookException as e: continue # getting likes response = recursive_graph_call(post_graph_id + '/likes', limit=500) for user in response['data']: ids.add(user['id']) # u = self.fb_user(user) # u['like'] = 1 # rows[user['id']] = u # getting shares response = recursive_graph_call(post_graph_id + '/sharedposts', fields='from', limit=500) for share in response['data']: user = share['from'] ids.add(user['id']) # if user['id'] not in rows: # u = self.fb_user(user) # u['share'] = 1 # rows[user['id']] = u # else: # rows[user['id']]['share'] = 1 # getting comments response = recursive_graph_call(post_graph_id + '/comments', fields='from', limit=500) for comment in response['data']: user = comment['from'] ids.add(user['id']) # if user['id'] not in rows: # u = self.fb_user(user) # u['comment'] += 1 # rows[user['id']] = u # else: # rows[user['id']]['comment'] += 1 # else: # rows['errors'] = 'Invalid post link' return ids
def get_fb(links): from open_facebook import OpenFacebook graph = OpenFacebook(settings.FACEBOOK_API_ACCESS_TOKEN) rows = [] for link in links: # https://www.facebook.com/Beelinerus/posts/588392457883231 matches = re.match(r'^https?://www.facebook.com/(.*?)/posts/(\d+)$', link) link = '<a href="{0}">{0}</a>'.format(link) if matches: company_slug = matches.group(1) post_id = matches.group(2) try: company = graph.get(company_slug, fields='id,likes,talking_about_count') except OpenFacebookException as e: rows.append({ 'status': 'error', 'data': [ link, 'Company not found', ] }) continue post_graph_id = '%s_%s' % (company['id'], post_id) try: post = graph.get(post_graph_id, fields='comments.limit(0).summary(true),likes.limit(0).summary(true),shares.limit(0).summary(true)') except OpenFacebookException as e: rows.append({ 'status': 'error', 'data': [ link, 'Post not found', ] }) continue likes = '' shares = '' comments = '' if 'likes' in post: likes = post['likes']['summary']['total_count'] if 'shares' in post: shares = post['shares']['count'] if 'comments' in post: comments = post['comments']['summary']['total_count'] rows.append({ 'status': 'ok', 'data': [ link, company['likes'], company['talking_about_count'], likes, shares, comments, ] }) else: rows.append({ 'status': 'error', 'data': [ link, 'Incorrect url', ] }) return rows
def main(): consumer_key = 'zsqVde4f4vkRNopoj8zGvVM7x', consumer_secret = '3pcD1MNmQNyHAZrDjmNQmHdnUNfZywbA4Lbomh3ofxqzO3e6o8' published_adverts = Published_Adverts.objects.filter(active=True) for published_advert in published_adverts: if published_advert.campaign.campaign_type == '0': account = Social_Data.objects.get( publisher=published_advert.social_data.publisher, account_type='1') api = twitter.Api( consumer_key='zsqVde4f4vkRNopoj8zGvVM7x', consumer_secret= '3pcD1MNmQNyHAZrDjmNQmHdnUNfZywbA4Lbomh3ofxqzO3e6o8', access_token_key=account.account_id, access_token_secret=account.account_token) try: if api.GetRetweets(statusid=published_advert.message_link, count=1)[0].retweeted == False: is_message_none(published_advert.social_data.publisher) except Exception as e: print e elif published_advert.campaign.campaign_type == '1': account = Social_Data.objects.get( publisher=published_advert.social_data.publisher, account_type='1') api = twitter.Api( consumer_key='zsqVde4f4vkRNopoj8zGvVM7x', consumer_secret= '3pcD1MNmQNyHAZrDjmNQmHdnUNfZywbA4Lbomh3ofxqzO3e6o8', access_token_key=account.account_id, access_token_secret=account.account_token) print api.GetStatus(id='565490400102985729').user.id try: if api.GetStatus(id='565490400102985729' ).user.id == api.VerifyCredentials().id: pass else: is_message_none(published_advert.social_data.publisher) except Exception as e: print e elif published_advert.campaign.campaign_type == '2': pass elif published_advert.campaign.campaign_type == '3': account = Social_Data.objects.get( publisher=published_advert.social_data.publisher, account_type='0') print account.account_token facebook = OpenFacebook(account.account_token) print facebook.get('deadspace/')['id'] print facebook.get('me/likes/18523496657') if facebook.get('me/likes/' + str(published_advert.message_link))['data'] == []: is_message_none(published_advert.social_data.publisher) else: account = Social_Data.objects.get( publisher=published_advert.social_data.publisher, account_type='1') api = twitter.Api( consumer_key='zsqVde4f4vkRNopoj8zGvVM7x', consumer_secret= '3pcD1MNmQNyHAZrDjmNQmHdnUNfZywbA4Lbomh3ofxqzO3e6o8', access_token_key=account.account_id, access_token_secret=account.account_token) id_list = api.GetFollowerIDs(user_id=published_advert.message_link) try: if not api.VerifyCredentials().id in id_list: is_message_none(published_advert.social_data.publisher) except Exception as e: print e
def get_spotify_username(request): me = request.user context = {} if me.id is not None: access_token = me.access_token print access_token graph = OpenFacebook(access_token) if access_token is not None: listen_data = graph.get('me/music.listens') user_listens = [] listens = listen_data['data'] for listen in listens: tmp = [] song_name = listen['data']['song']['title'] client_url = listen['data']['song']['url'] client_unique = re.search('track\/(.*)', client_url).group(1) tmp.append(song_name) tmp.append(client_unique) user_listens.append(tmp) print(json.dumps(song_name, sort_keys=True, indent=4, separators=(',', ': '))) context['user_listens'] = user_listens current_user = request.user print 'something' if current_user.id is not None: clientProfiles = current_user.clients.all() if clientProfiles: print clientProfiles else: print "clientProfiles" # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = ClientUsernameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: # Get information from username form username = form.cleaned_data["username"] client_name = form.cleaned_data["client"] # Client object and ID based on client chosen by user client = Client.objects.get(client_name=client_name) client_id = client.id # Check if the user has this a profile for this client, if not create it. try: client = current_user.clients.get(id=client_id) except client.DoesNotExist: new_client_profile = ClientProfile(user=current_user, client=client, username=username) new_client_profile.save() # Get user's playlists - Inside this helper function we will decide whether the data needs to be added to TuneBoss, updated or is already present. playlists = update_user_playlists(client, username, request) context = {} if current_user.id is not None: context['user_clientlists'] = current_user.member_clientlists.all() return render(request, 'home.html', context) # if a GET (or any other method) we'll create a blank form else: form = ClientUsernameForm() if current_user.id is not None: print "current_user " + str(current_user.email) context['user_clientlists'] = current_user.member_clientlists.all() context['form'] = form return render(request, 'home.html', context)
# -*- coding: utf-8 -*- import requests from django.conf import settings settings.configure() from django_facebook import settings as facebook_settings from open_facebook import OpenFacebook from open_facebook.api import FacebookAuthorization import json facebook_settings.FACEBOOK_APP_ID ='611406969009887' facebook_settings.FACEBOOK_APP_SECRET ='6be22272c73f9a90f8ded333fbb0ff4d' access_token=FacebookAuthorization.get_app_access_token() graph=OpenFacebook(access_token) fb_name='HongKongPoliceForce' target=graph.get(fb_name) fields='reactions.limit(100){id,name,type},comments.limit(100){id,name}' id=target['id'] print id posts=graph.get(id+'/posts',limit=100,fields=fields,version='v2.6') def getUrl(url): if '\\' in url: url=eval('u'+"'"+url+"'") url=url.replace('\\','') return url
profile = request.user.get_profile() access_token = getattr(profile, 'access_token', None) if not access_token: if raise_: message = 'Couldnt find an access token in the request or the users profile' raise open_facebook_exceptions.OAuthException(message) else: return None else: if raise_: message = 'Couldnt find an access token in the request or cookies' raise open_facebook_exceptions.OAuthException(message) else: return None graph = OpenFacebook(access_token, parsed_data, expires=expires) #add user specific identifiers if request: _add_current_user_id(graph, request.user) return graph def _add_current_user_id(graph, user): ''' set the current user id, convenient if you want to make sure you fb session and user belong together ''' if graph: graph.current_user_id = None
def get_all_of_users_facebook_friends(user,facebook_access_token): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: facebook_friends = facebook.get('me/friends',fields="id,name,picture")['data'] return facebook_friends
def fb_auth_handler(request): # Retrieve oAuth response response = urlparse(request.get_full_path()) query = parse_qs(response.query) # Handle oAuth initial request error if "error" in query and "access_denied" in query["error"] and \ "user_denied" in query["error_reason"]: try: logger.warning("Facebook returned error: %s" % query["error"]) except KeyError: err_msg = "Please login and allow Facebook to continue." return HttpResponse(json.dumps({"status": "fail", "message": err_msg})) # Recreate the redirect_uri redir_path = request.get_full_path() logger.info("exchanging code for accesstoken...") redirect_uri = request.META['wsgi.url_scheme'] + "://" +\ request.get_host() + reverse("fb_auth_handler") payload = { "client_id": settings.FACEBOOK_APP_ID, "redirect_uri": redirect_uri, "client_secret": settings.FACEBOOK_APP_SECRET, "code": query["code"][0] } xrequest = requests.get("https://graph.facebook.com/oauth/access_token", params=payload) # Handle oAuth secondary request error fbresponse = parse_qs(xrequest.text) if "error" in fbresponse or not len(fbresponse): # TODO: Error handling if "error" in fbresponse: err_msg = "FB returned error: %s" % fbresponse["error"] logger.warning(err_msg) else: err_msg = "User fb token expired." logger.warning(err_msg) return HttpResponse(json.dumps({"status": "fail", "message": err_msg})) # Acquire accesstoken accesstoken = fbresponse["access_token"][0] # Acquire userinfo graph = OpenFacebook(accesstoken) user_data = graph.get('me') user = User.create(user_data, token=accesstoken) if user: request.session['me'] = user.fb_id return redirect("/nearby/") # return HttpResponse(json.dumps({"status": "success", # "data": dict(user)})) else: return HttpResponse(json.dumps({"status": "fail"}))
def get_all_of_users_facebook_friends_on_yapster(user,facebook_access_token): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: facebook_friends = facebook.get('me/friends',fields="id")['data'] this_users_facebook_friends_on_yapster = [friend_facebook_id['id'] for friend_facebook_id in facebook_friends if Settings.objects.filter(is_active=True,facebook_account_id=friend_facebook_id['id']).exists() == True] return this_users_facebook_friends_on_yapster
class FacebookApiExplorer(SocialApi): def get_data(self): self.graph = OpenFacebook(self.credentials['access_token']) feed = self.graph.get('me/posts') self.contents = feed["data"] def process_contents(self): for post in self.contents: post_id = post["id"] identification = re.split("_", post_id) account_id = identification[0] post_id = identification[1] published_at = post["created_time"] published_at = datetime.strptime(published_at[0:10]+' '+published_at[11:19], '%Y-%m-%d %H:%M:%S') published_at = timezone.make_aware(published_at, timezone.get_fixed_timezone(0)) if "link" in post.keys(): original_url = post["link"] else: original_url = "https://www.facebook.com/"+account_id+"/posts/"+post_id def search(parameter): try: return post[parameter] except KeyError: return "" def amount(parameter): try: return self.graph.get(post['id']+'/'+parameter, summary='1')['summary']['total_count'] except KeyError: return 0 text = search("message") video_url = search("source") image_url = search("picture") image_id = search("object_id") post_type = search("type") number_of_likes = amount("likes") number_of_comments = amount("comments") if image_url and image_id: feed = self.graph.get(image_id) try: if post_type == 'video': image_url = sorted(feed['format'], key=lambda k: k['width'], reverse=True)[0]['picture'] else: image_url = sorted(feed['images'], key=lambda k: k['width'], reverse=True)[0]['source'] except KeyError: #Error finding image_url pass new_content = FacebookContent(identifier=post_id, text=text, published_at=published_at, image_url=image_url, original_url=original_url, number_of_comments=number_of_comments, number_of_likes=number_of_likes, video_url=video_url) try: if (text or video_url or image_url) and post_type != 'link': self.update_content(new_content) except Exception as err: print 'Could not save content %s: %s' % (new_content, err)
def get_all_of_users_facebook_friends(user, facebook_access_token): facebook = OpenFacebook(facebook_access_token) if user.settings.facebook_connection_flag == True: facebook_friends = facebook.get('me/friends', fields="id,name,picture")['data'] return facebook_friends
def get_data(self): self.graph = OpenFacebook(self.credentials['access_token']) feed = self.graph.get('me/posts') self.contents = feed["data"]
def registered_facebook(request): global token social_account = None username = '' try: token = request.POST.get('access_token') long_access_token = FacebookAuthorization.extend_access_token(token)['access_token'] print 'long is generated' print long_access_token except Exception as e: print e print "register 1" long_access_token = token print long_access_token try: graph = OpenFacebook(long_access_token) profile = graph.get('me') profile_id = profile['id'] # profile_email = profile['email'] profile_first_name = profile['first_name'] profile_last_name = profile['last_name'] profile_gender = profile['gender'] if profile_gender == 'male': sex = True else: sex = False except Exception as e: print '%s (%s)' % (e.message, type(e)) return HttpResponseRedirect('/sorry/') try: print "1212122asas" social_account = SocialData.objects.filter(account_id=str(profile_id)).all() print social_account print "1" except Exception as e: print "HATA" + e try: print "sss" print "r4" if social_account: print "hesap var" user = User.objects.get(id=social_account[0].user.id) social_network = SocialData.objects.get(user=user.id) username = str(user.username) password = str(user.password) social_network.account_token = long_access_token print username print password print "sss" else: print "Hesap yok" user_auth = User.objects.create_user(profile_id, 'sss', profile_id) user_auth.first_name = profile_first_name user_auth.last_name = profile_last_name print "sss" user_auth.email = "" user_auth.is_staff = False user_auth.is_active = True user_auth.save() print "user kayit oldu" au = Audience.objects.get(id=1) users = Users.objects.create(user_id=user_auth.id, gender=sex, been_id=1, lives_in_id=1) users.save() print "users kayit oldu" social_network = SocialData(user=user_auth, account_type=0, account_id=profile_id, account_token=long_access_token) username = profile_id social_network.save() dada = authenticate(username=username, password=username) if dada is not None: print "ac" if dada.is_active: print "ba" auth_login(request, dada) print "you are login !!!" + "hello " + request.user.username return HttpResponse("true", content_type='application/json') else: print "b" print "a" print "social_network kayıt oldu" return "false" except Exception as e: print e print "register4" return HttpResponseRedirect('/login/')
profile = request.user.get_profile() access_token = getattr(profile, 'access_token', None) if not access_token: if raise_: message = 'Couldnt find an access token in the request or the users profile' raise open_facebook_exceptions.OAuthException(message) else: return None else: if raise_: message = 'Couldnt find an access token in the request or cookies' raise open_facebook_exceptions.OAuthException(message) else: return None graph = OpenFacebook(access_token, signed_data, expires=expires) # add user specific identifiers if request: _add_current_user_id(graph, request.user) return graph def _add_current_user_id(graph, user): ''' set the current user id, convenient if you want to make sure you fb session and user belong together ''' if graph: graph.current_user_id = None