def recording(request, id): # Called by Twilio when recording is finished user = None bday = Birthday.objects.get(id=id) if request.method == 'POST': call = bday.call user = call.user social_user = user.social_auth.get(provider='facebook') api = GraphAPI(social_user.extra_data.get('access_token')) number = user.phone recording = Recording(call_sid=request.POST.get('CallSid'), caller=request.POST.get('From'), recipient=request.POST.get('To'), duration=int( request.POST.get('RecordingDuration')), url=request.POST.get('RecordingUrl'), fb_user_name=bday.recipient_fb_name) recording.save() bday.recording = recording bday.save() url = str('http://callfredo.tklapp.com/wishes/') + str( bday.recording.id) + str('/') try: api.put_wall_post("Happy birthday!", profile_id=str(bday.recipient_fb_id), attachment={ 'name': 'Happy birthday!', 'link': str(url), }) except (User.DoesNotExist, GraphAPIError): user = None resp = twiml.Response() if Birthday.objects.filter(call=bday.call, status=0).count() > 0: bday = Birthday.objects.filter(call=bday.call, status=0)[:1].get() with resp.gather(timeout=2, numDigits=1, action="http://callfredo.tklapp.com/phone/press/" + str(bday.id) + "/", method="POST") as g: g.say( "If you want record birthday wishes for %s, press 1. If you want to skip recording, then press 2." % bday.recipient_fb_name) else: resp.say("That is it! All wishes have been posted. Have a nice day!") resp.hangup() return HttpResponse(str(resp), content_type='application/xml')
def put_wall_post(request,message): try: graph = GraphAPI(request.user.accesstoken) fb_response = graph.put_wall_post(message) except GraphAPIError as e: print >> sys.stderr, 'Facebook error: %s', (e, ) sys.stderr.flush()
def post_message(msg, page_token, is_visible): """ Push a post as the page Use published attribute to distinguish between (Un)published posts """ graph = GraphAPI(page_token) att = {'published' : is_visible} return graph.put_wall_post(msg,attachment=att);
def post_to_facebook(message, link=None): """Posts a message to the Facebook page using GraphAPI authenticated via `FACEBOOK_PAGE_ACCESS_TOKEN`. Args: - message: str. The content of the message to be posted on Facebook. - link: str. (Optional) Url of the attachment to be posted along with message. Returns: - None """ graph = GraphAPI(access_token=FACEBOOK_PAGE_ACCESS_TOKEN) attachment = { 'link': link, # link to visit on clicking on the attachment. 'picture': link # link of the attachment to be posted. } graph.put_wall_post(message=message, attachment=attachment)
def recording(request, id): # Called by Twilio when recording is finished user = None bday = Birthday.objects.get(id=id) if request.method == 'POST': call = bday.call user = call.user social_user = user.social_auth.get(provider='facebook') api = GraphAPI(social_user.extra_data.get('access_token')) number = user.phone recording = Recording(call_sid=request.POST.get('CallSid'), caller=request.POST.get('From'), recipient=request.POST.get('To'), duration=int(request.POST.get('RecordingDuration')), url=request.POST.get('RecordingUrl'), fb_user_name=bday.recipient_fb_name) recording.save() bday.recording = recording bday.save() url = str('http://callfredo.tklapp.com/wishes/') + str(bday.recording.id) + str('/') try: api.put_wall_post("Happy birthday!", profile_id=str(bday.recipient_fb_id), attachment={'name': 'Happy birthday!', 'link': str(url), }) except (User.DoesNotExist, GraphAPIError): user = None resp = twiml.Response() if Birthday.objects.filter(call=bday.call, status=0).count()>0: bday = Birthday.objects.filter(call=bday.call, status=0)[:1].get() with resp.gather(timeout=2, numDigits=1, action="http://callfredo.tklapp.com/phone/press/"+str(bday.id)+"/", method="POST") as g: g.say("If you want record birthday wishes for %s, press 1. If you want to skip recording, then press 2." % bday.recipient_fb_name) else: resp.say("That is it! All wishes have been posted. Have a nice day!") resp.hangup() return HttpResponse(str(resp), content_type='application/xml')
def send_to_facebook(user, context={}): """Send a wall post to a user's facebook profile It's run as a daemon, to avoid delaying too much the response time of the original response """ #only leave the facebook attrs: facebook_attrs = ['name', 'link', 'caption', 'description', 'picture'] for e in context.keys(): if e not in facebook_attrs: del context[e] #description="", picture="", link="http://escolarea.com", message="", caption="" if "http://" not in context.get('link', ''): #build the full url context['link'] = u"http://%s%s" % ( unicode(Site.objects.get_current()), context.get('link', '')) access_token = getattr(user.get_profile(), FACEBOOK_ATTR, None) if context and access_token: graph_api = GraphAPI(access_token) graph_api.put_wall_post(message=context.get('message', ''), attachment=context)
class FacebookAdapter(MessageProvider, ImageProvider, VideoProvider): id = 'facebook' name = 'FacebookAdapter' def __init__(self, user, *args, **kwargs): self.user = user self.social_token = SocialToken.objects.filter(app__provider='facebook', account__provider='facebook', account__user=user) self.facebook = GraphAPI(self.social_token.get().token) self.social_app = SocialApp.objects.filter(id=self.social_token.get().app.id) def publish_image(self, image, message='', **kwargs): try: logger.info('trying to update facebook status with an image, for user: %s' % self.user) result = self.facebook.put_photo(open(image.path), message, **kwargs) logger.info(str(result)) return result except Exception as e: logger.error(e) raise e def publish_message(self, message, **kwargs): try: logger.info('trying to update facebook status, for user: %s' % self.user) result = self.facebook.put_wall_post(message) logger.info(str(result)) return result except Exception as e: logger.error(e) raise e def publish_video(self, video, title='', description='', **kwargs): try: logger.info('trying to update facebook status with a video, for user: %s' % self.user) result = self.facebook.put_video(open(video.path), title=title, description=description) logger.info(str(result)) return result except Exception as e: logger.error(e) raise e
def social_action_checkin(track_id,guest_track,landing_site,guest_device): guest_check = Guest.query.filter_by(id=guest_device.guest_id,site_id=landing_site.id).first() if not guest_check : current_app.logger.error('Wifiguest Log - Site ID:%s social_action_checkin called with device not associated to guest for track ID:%s'%(guest_track.site_id,guest_track.id)) return redirect(url_for('guest.multi_login',track_id=track_id),code=302) code = request.args.get('code') access_token = None fb_appid = landing_site.fb_appid or current_app.config['FB_APP_ID'] fb_app_secret = landing_site.fb_app_secret or current_app.config['FB_APP_SECRET'] redirect_uri = url_for('guest.social_action_checkin',track_id=track_id,_external=True) if code: #URL called after OAuth try: at = GraphAPI().get_access_token_from_code(code, redirect_uri, fb_appid, fb_app_secret) access_token = at['access_token'] graph = GraphAPI(access_token) permissions = graph.get_connections("me","permissions") except: current_app.logger.exception('Wifiguest Log - Site ID:%s guest_device MAC:%s social_action_checkin exception while getting access_token redirecting to social_action_checkin %s'%(landing_site.id,guest_track.device_mac,request.url)) return redirect(url_for('guest.social_action_checkin',track_id=track_id),code=302) else: profile_check = Facebookauth.query.filter_by(id=guest_check.fb_profile).first() if not profile_check : current_app.logger.error('Wifiguest Log - Site ID:%s social_action_checkin called with device not associated to profile_check for track ID:%s'%(guest_track.site_id,guest_track.id)) return redirect(url_for('guest.multi_login',track_id=track_id),code=302) try: graph = GraphAPI(profile_check.token) permissions = graph.get_connections("me","permissions") except: current_app.logger.exception('Wifiguest Log - Site ID:%s guest_device MAC:%s social_action_checkin exception while trying to get permissions %s'%(landing_site.id,guest_track.device_mac,request.url)) return redirect(url_for('guest.multi_login',track_id=track_id),code=302) #check if the user has granted publish_permissions publish_permission = False for perm in permissions['data']: if perm.get('permission') == 'publish_actions' and perm.get('status') == 'granted': publish_permission = True if not publish_permission: current_app.logger.debug('Wifiguest Log - Site ID:%s social_action_checkin called without guest giving publish_permission redo Oauth track ID:%s'%(guest_track.site_id,guest_track.id)) params={'client_id':fb_appid,'redirect_uri':redirect_uri,'scope':'publish_actions '} url = 'https://www.facebook.com/dialog/oauth?'+urllib.urlencode(params) return redirect(url,code=302) form1 = CheckinForm() if form1.validate_on_submit(): #try to do checkin try: fb_page = landing_site.fb_page or current_app.config['FB_PAGE_URL'] page_info = graph.get_object(fb_page,fields='description,name,location,picture') print page_info['id'] print graph.put_wall_post(message=form1.message.data,attachment={'place':page_info['id']}) except: current_app.logger.exception('Wifiguest Log - Site ID:%s social_action_checkin exception while checkinfor track ID:%s'%(guest_track.site_id,guest_track.id)) else: guest_check = Guest.query.filter_by(id=guest_device.guest_id,site_id=landing_site.id).first() if not guest_check: current_app.logger.error('Wifiguest Log - Site ID:%s social_action_checkin called with device not associated to guest for track ID:%s'%(guest_track.site_id,guest_track.id)) abort(404) guest_track.fb_posted = 1 guest_check.fb_posted = 1 db.session.commit() if landing_site.auth_fb_like == 1 and guest_check.fb_liked !=1: #redirect to like return redirect(url_for('guest.social_action_like',track_id=guest_track.track_id),code=302) else: guest_track.state = GUESTRACK_SOCIAL_AUTH guest_device.state = DEVICE_AUTH db.session.commit() return redirect(url_for('guest.authorize_guest',track_id=guest_track.track_id),code=302) # show page asking user to checkin current_app.logger.debug('Wifiguest Log - Site ID:%s social_action_checkin new guest show page to checkin for track ID:%s'%(guest_track.site_id,guest_track.id)) landing_page = Landingpage.query.filter_by(id=landing_site.default_landing).first() fb_page = landing_site.fb_page or current_app.config['FB_PAGE_URL'] page_info = graph.get_object(fb_page,fields='location,name') loc = page_info['location'] location = ' %s - %s %s %s'%(page_info.get('name',''),loc.get('street',''),loc.get('city',''),loc.get('country','')) return render_template("guest/%s/fb_checkin.html"%landing_site.template,landing_page = landing_page,font_list=font_list,app_id=fb_appid,track_id=track_id, fb_page=fb_page,location=location,form1=form1)
def fb_checkin(trackid, guesttrack, wifisite, guestdevice, fbconfig, loginauth): '''End point for guest to checkin ''' code = request.args.get('code') access_token = None fb_appid = fbconfig.fb_appid fb_app_secret = fbconfig.fb_app_secret fb_page = fbconfig.fb_page redirect_uri = url_for('unifispot.modules.facebook.fb_checkin', trackid=trackid, _external=True) if code: #URL called after OAuth try: at = GraphAPI().get_access_token_from_code(code, redirect_uri,\ fb_appid, fb_app_secret) access_token = at['access_token'] graph = GraphAPI(access_token) permissions = graph.get_connections("me", "permissions") except: guestlog_exception( 'fb_checkin exception while getting access_token \ redirecting to fb_checkin ', wifisite, guesttrack) #send back to page return redirect(redirect_uri, code=302) else: try: graph = GraphAPI(loginauth.fbtoken) permissions = graph.get_connections("me", "permissions") except: guestlog_exception( 'fb_checkin exception while getting permissions \ redirecting to fb_checkin ', wifisite, guesttrack) return redirect_guest(wifisite, guesttrack) #check if the user has granted publish_permissions publish_permission = False for perm in permissions['data']: if perm.get('permission') == 'publish_actions' and\ perm.get('status') == 'granted': publish_permission = True if not publish_permission: guestlog_warn( 'fb_checkin called without guest giving publish_permission redo Oauth\ fbauth', wifisite, guesttrack) params = { 'client_id': fb_appid, 'redirect_uri': redirect_uri, 'scope': 'publish_actions ' } url = 'https://www.facebook.com/dialog/oauth?' + urllib.urlencode( params) return redirect(url, code=302) checkinform = CheckinForm() if checkinform.validate_on_submit(): #try to do checkin try: page_info = graph.get_object( fb_page, fields='description,name,location,picture') graph.put_wall_post(message=checkinform.message.data, attachment={'place': page_info['id']}) except Exception as e: if 'Duplicate status message' in str(e): guestlog_warn( 'duplicate message exception while doing checkin, \ ask guest to enter some message', wifisite, guesttrack) flash(_('Please enter some message'), 'danger') else: guestlog_exception('exception while doing checkin', wifisite, guesttrack) else: #mark fbauth with checkedin guesttrack.updatestat('fbcheckedin', 1) guest = Guest.query.get(guestdevice.guestid) if not guest: guestlog_warn("no guest associated with guestdevice", wifisite, guesttrack) return redirect_guest(wifisite, guesttrack) guest.fbcheckedin = 1 guest.save() #check if guest needs to be redirected to asklike #page if fbconfig.auth_fb_like and guest.fbliked != 1: return redirect( url_for('unifispot.modules.facebook.fb_like', trackid=trackid)) else: #redirect guest to auth page loginauth.populate_auth_details(fbconfig) loginauth.reset() loginauth.reset_lastlogin() loginauth.state = LOGINAUTH_FIRST loginauth.save() #neither configured, authorize guest guesttrack.state = GUESTTRACK_POSTLOGIN guesttrack.loginauthid = loginauth.id guesttrack.updatestat('auth_facebook', 1) return redirect_guest(wifisite, guesttrack) guestlog_debug('show ask for checkin page', wifisite, guesttrack) landingpage = Landingpage.query.filter_by(siteid=wifisite.id).first() page_info = graph.get_object(fb_page, fields='location,name') loc = page_info['location'] location = ' %s - %s %s %s' % (page_info.get( 'name', ''), loc.get('street', ''), loc.get( 'city', ''), loc.get('country', '')) return render_template("guest/%s/fb_checkin.html" % wifisite.template, landingpage=landingpage, app_id=fb_appid, trackid=trackid, fb_page=fb_page, location=location, checkinform=checkinform)
def post_message(msg): graph = GraphAPI(session['page']['access_token']) att = {} att['published'] = session['visibility'] return graph.put_wall_post(msg,attachment=att);
class FacebookAdapter(MessageProvider, ImageProvider, ActionMessageProvider): id = 'facebook' name = 'FacebookAdapter' def __init__(self, user, *args, **kwargs): self.user = user self.social_token = SocialToken.objects.filter( app__provider='facebook', account__provider='facebook', account__user=user) self.facebook = GraphAPI(self.social_token.get().token) self.social_app = SocialApp.objects.filter( id=self.social_token.get().app.id) def publish_image(self, image, message='', **kwargs): try: logger.info( 'trying to update facebook status with an image, for user: %s' % self.user) result = self.facebook.put_photo(open(image.path), message, **kwargs) logger.info(str(result)) return result except Exception as e: logger.error(e) raise e def publish_message(self, message, **kwargs): """ Attachment: {"name": "Link name" "link": "http://www.example.com/", "caption": "{*actor*} posted a new review", "description": "This is a longer description of the attachment", "picture": "http://www.example.com/thumbnail.jpg"} """ try: logger.info('trying to update facebook status, for user: %s' % self.user) attachment = dict(kwargs.pop('attachment', {})) if 'picture' in attachment: attachment['picture'] = '%s%s' % (attachment.pop( 'domain', ''), attachment['picture'].url) result = self.facebook.put_wall_post(message, attachment) logger.info(str(result)) return result except Exception as e: logger.error(e) raise e def publish_video(self, video, title='', description='', **kwargs): try: logger.info( 'trying to update facebook status with a video, for user: %s' % self.user) result = self.facebook.put_video(open(video.path), title=title, description=description) logger.info(str(result)) return result except Exception as e: logger.error(e) raise e def publish_action_message(self, message, action_info, **kwargs): """ action_info: dictionary with information about the corresponding app activity/action { "link": the url for the app activity/action to point to, "actor": the actor, "action": the action performed by 'actor', "verb": the verbal form to show for the action performed by 'actor', "target": the target of the action, "app": the application name, "domain": the application domain "picture": the picture to show } """ try: logger.info('trying to update facebook status, for user: %s' % self.user) from django.utils.translation import ugettext as _ result = self.facebook.put_wall_post( message, { 'link': action_info.get('link', action_info.get('domain', '')), 'caption': "%s | %s" % (action_info.get( 'app', ''), action_info.get('action', '')), 'description': "%s %s %s %s %s" % (action_info.get('actor', ''), action_info.get( 'verb', ''), action_info.get('target', ''), _(u'using'), action_info.get('app', _(u'application'))), 'picture': "%s%s" % (action_info.get('domain', ''), action_info['picture'].url) if 'picture' in action_info else '' }) logger.info(str(result)) return result except Exception as e: logger.error(e) raise e
def putwall(req,message,attachment): import facebookoauth from facebookoauth import FBUser import pprint, StringIO # prid=self.request.get('id') # prid="me" # args = dict(grant_type="client_credentials", client_id=FACEBOOK_APP_ID, client_secret=FACEBOOK_APP_SECRET) # response = cgi.parse_qs(urllib.urlopen("https://graph.facebook.com/oauth/access_token?" +urllib.urlencode(args)).read()) # access_token = response["access_token"][-1] #print access_token hout = "" user_id = facebookoauth.parse_cookie(req.request.cookies.get("fb_user")) errorjson = False aaa="<h2>wall post</h2>error" profile = {'id': 0} perm_mp=False perm_pa=False permtext="" cmd=req.request.get('cmd') oid=req.request.get('oid') if user_id: fb2_current_user = FBUser.get_by_key_name(user_id) if fb2_current_user and fb2_current_user.login: try: graph = GraphAPI(fb2_current_user.access_token) profile = graph.get_object("me") permissions = graph.request("/v2.1/me/permissions") for item in permissions["data"]: if item["permission"]=="manage_pages" and item["status"] == "granted": perm_mp=True if item["permission"]=="publish_actions" and item["status"] == "granted": perm_pa=True if not perm_mp: permtext = "manage_pages" if not perm_pa: permtext = permtext + " publish_actions" s = StringIO.StringIO() # pprint.pprint(permissions, s) # message = "Zinute patalpinta per\nhttp://www.nerij.us/fbputwall" # attachment = {} # attachment['name'] = "Nerijaus Terebo turinio valdymo sistemele \"Upelis\"" # attachment['caption'] = 'www.upelis.org' # attachment['link'] = 'http://www.upelis.org/' # attachment['picture'] = 'http://www.nerij.us/static/images/upelis116.jpg' # attachment['description'] = 'Turinio valdymo sistemele \"Upelis\" - Python, AppEngine' if cmd =="delperm": # mess = graph.delete_object(oid) # mess = graph.request(oid, post_args={"method": "delete"}) post_args=dict(method = "delete", access_token = fb2_current_user.access_token) post_data = urllib.urlencode(post_args) file = urllib.urlopen("https://graph.facebook.com/me/permissions" , post_data) try: response = json.loads(file.read()) finally: file.close() json.dump(response, s, sort_keys=True, indent=1) #pprint.pprint(response, s) hout=s.getvalue() aaa="<h2>permissions delete - ok </h2><pre>%s</pre>" % (hout) elif not perm_mp or not perm_pa: aaa="<h2>wall post - error - registruodamiesi nepatvirtinot: %s </h2><br><pre>%s</pre>" % (permtext,hout) else: if cmd =="delete": # mess = graph.delete_object(oid) # mess = graph.request(oid, post_args={"method": "delete"}) post_args=dict(method = "delete", access_token = fb2_current_user.access_token) post_data = urllib.urlencode(post_args) file = urllib.urlopen("https://graph.facebook.com/" + oid , post_data) try: response = json.loads(file.read()) finally: file.close() #pprint.pprint(response, s) json.dump(response, s, sort_keys=True, indent=1) hout=s.getvalue() aaa="<h2>wall post delete - ok </h2><pre>%s</pre>" % (hout) elif cmd =="info": mess = graph.request("/me/accounts") #pprint.pprint(mess, s) json.dump(mess, s, sort_keys=True, indent=1) hout=s.getvalue() aaa="<h2>accounts info</h2><p><pre>%s</pre></p>" % (hout) else: mess = graph.put_wall_post(message, attachment=attachment) #pprint.pprint(mess, s) json.dump(mess, s, sort_keys=True, indent=1) hout=s.getvalue() aaa="<h2>wall post - ok </h2><p><a href=\"/fbputwall?cmd=delete&oid=%s\">delete</a></p><pre>%s</pre>" % (mess["id"],hout) except Exception, e: errorjson = True errtext = cgi.escape(str(sys.exc_info()[0])) + ' ' + cgi.escape(str(sys.exc_info()[1])) + ' ' + cgi.escape(str(sys.exc_info()[2])) else: aaa="<h2>wall post</h2>not loged - <a href=\"/auth/login?continue=%s\">login</a>" % (urllib.quote(req.request.uri))
class FacebookAdapter(MessageProvider, ImageProvider, ActionMessageProvider): id = 'facebook' name = 'FacebookAdapter' def __init__(self, user, *args, **kwargs): self.user = user self.social_token = SocialToken.objects.filter(app__provider='facebook', account__provider='facebook', account__user=user) self.facebook = GraphAPI(self.social_token.get().token) self.social_app = SocialApp.objects.filter(id=self.social_token.get().app.id) def publish_image(self, image, message='', **kwargs): try: logger.info('trying to update facebook status with an image, for user: %s' % self.user) result = self.facebook.put_photo(open(image.path), message, **kwargs) logger.info(str(result)) return result except Exception as e: logger.error(e) raise e def publish_message(self, message, **kwargs): """ Attachment: {"name": "Link name" "link": "http://www.example.com/", "caption": "{*actor*} posted a new review", "description": "This is a longer description of the attachment", "picture": "http://www.example.com/thumbnail.jpg"} """ try: logger.info('trying to update facebook status, for user: %s' % self.user) attachment = dict(kwargs.pop('attachment', {})) if 'picture' in attachment: attachment['picture'] = '%s%s' % (attachment.pop('domain', ''), attachment['picture'].url) result = self.facebook.put_wall_post(message, attachment) logger.info(str(result)) return result except Exception as e: logger.error(e) raise e def publish_video(self, video, title='', description='', **kwargs): try: logger.info('trying to update facebook status with a video, for user: %s' % self.user) result = self.facebook.put_video(open(video.path), title=title, description=description) logger.info(str(result)) return result except Exception as e: logger.error(e) raise e def publish_action_message(self, message, action_info, **kwargs): """ action_info: dictionary with information about the corresponding app activity/action { "link": the url for the app activity/action to point to, "actor": the actor, "action": the action performed by 'actor', "verb": the verbal form to show for the action performed by 'actor', "target": the target of the action, "app": the application name, "domain": the application domain "picture": the picture to show } """ try: logger.info('trying to update facebook status, for user: %s' % self.user) from django.utils.translation import ugettext as _ result = self.facebook.put_wall_post( message, { 'link': action_info.get('link', action_info.get('domain', '')), 'caption': "%s | %s" % (action_info.get('app', ''), action_info.get('action', '')), 'description': "%s %s %s %s %s" % ( action_info.get('actor', ''), action_info.get('verb', ''), action_info.get('target', ''), _(u'using'), action_info.get('app', _(u'application')) ), 'picture': "%s%s" % (action_info.get('domain', ''), action_info['picture'].url) if 'picture' in action_info else '' } ) logger.info(str(result)) return result except Exception as e: logger.error(e) raise e