Beispiel #1
0
 def gift(self):
     """Display one gift donation."""
     log_fb_request(request)
     facebook.process_request()
     c.is_app_user = facebook.api_client.added
     
     """
     current_user = None
     if facebook.user:
         log.debug('user: %s' % facebook.user)
         current_user = facebook.user
     elif facebook.canvas_user:
         log.debug('canvas_user: %s' % facebook.canvas_user)
         current_user = facebook.canvas_user
     
     if not facebook.api_client.added:
         c.error_msg = 'You need to add this app before you can send gifts.'
         return render('/facebook/send_gift.tmpl')
     
     current_user = facebook.user
     if not current_user:
         c.error_msg = 'Error getting your user info.'
         return render('/facebook/send_gift.tmpl')
     """
     try:
         gift_id = int(request.params.get('id'))
         
         # get the gift donation info
         c.donation = meta.Session.query(Donation).get(gift_id)
         session = meta.Session()
         c.recipient_id = user_logic.get_network_uid(session, c.donation.recipient_id)
         c.donor_id = user_logic.get_network_uid(session, c.donation.donor_id)
     except Exception, err:
         log.debug(str(err))
         c.error_msg = 'Unable to find that gift.'
Beispiel #2
0
 def invite_sent(self):
     log_fb_request(request)
     facebook.process_request()
     c.is_app_user = facebook.api_client.added
     
     c.invitee_uid = request.params.get('invitee')
     return render('/facebook/invite_sent.tmpl')
Beispiel #3
0
 def multifeed_handler(self):
     """Handles callback for multiFeedStory form submission."""
     log_fb_request(request)
     facebook.process_request()
     c.is_app_user = facebook.api_client.added
     
     donor_fbid = request.POST.get('donor')
     recipient_fbid = request.POST.get('recipient')
     donation_id = request.POST.get('did')
     
     # look up donation in DB
     session = meta.Session()
     donation = session.query(Donation).get(donation_id)
     
     if donation is None:
         err_obj = {"errorCode": 1, "errorTitle" : "Feed Error", "errorMessage" : "Cannot find donation information."}
         return json.dumps(err_obj)
     
     gifthref = "%s/gift?id=%d" % (c.canvas_url, donation.id)
     
     template_data = {}
     template_data['gift'] = donation.gift.name
     template_data['gifthref'] = gifthref
     template_data['charity'] = donation.charity.name
     template_data['charityhref'] = donation.charity.url
     template_data['comments_xid'] = 'wg-gift.%d' % donation.id
     template_data['images'] = [{'src':h.gift_image_url(donation.gift_id), 'href':gifthref},]
     template_data['user_message'] = 'prompt3'
     
     obj = {'content': {'feed': {'template_id':110890046851, 'user_message':'prompt2', 'template_data':template_data}, 'next_fbjs': 'feed_done();'}, 'method':'multiFeedStory', 'user_message':'prompt1'}
     
     log.debug("multifeed_handler response JSON: %s" % json.dumps(obj))
     return json.dumps(obj)
Beispiel #4
0
 def multiuse_return(self):
     log_fb_request(request)
     facebook.process_request()
     c.is_app_user = facebook.api_client.added
     
     try:
         self._validate_cbui_response_signature()
     except Exception, err:
         return(str(err))
Beispiel #5
0
 def setup_multi(self):
     log_fb_request(request)
     facebook.process_request()
     c.is_app_user = facebook.api_client.added
     if not c.is_app_user:
         return '<fb:redirect url="index" />'
     
     c.charities = self._get_active_charities()
     return render('/facebook/setup_multi.tmpl')
Beispiel #6
0
 def wrap_it_up(self):
     log_fb_request(request)
     facebook.process_request()
     c.is_app_user = facebook.api_client.added
     
     using_multiuse_token = (request.params.get('usemt', 'f') == 't')
     
     session = meta.Session()
     
     if using_multiuse_token:
         # gather information for multi-use token
         multiuse_token_id = request.params.get('mtid')
         if multiuse_token_id is None:
             c.error_msg = 'Token ID is missing.'
             return render('/facebook/wrap_it_up.tmpl')
         multiuse_token = meta.Session.query(MultiUseToken).get(multiuse_token_id)
         if multiuse_token is None:
             c.error_msg = 'Unable to find multi-use token.'
             return render('/facebook/wrap_it_up.tmpl')
         authed_token_id = multiuse_token.token_id
         authed_payment_method = multiuse_token.payment_method
     else:
         # validate and process return response from CBUI
         try:
             self._validate_cbui_response_signature()
         except Exception, err:
             return(str(err))
         
         status = request.GET.get('status')
         log.debug('Return status from CBUI: ' + status)
         
         if 'errorMessage' in request.GET:
             log.error('Error in return from CBUI: ' + request.GET['errorMessage'])
             c.error_msg = 'There was a problem with your payment authorization.'
             return render('/facebook/wrap_it_up.tmpl')
         
         if status == 'A':
             c.error_msg = 'You cancelled the donation.  The gift will not be sent.'
             return render('/facebook/wrap_it_up.tmpl')
         
         if not status in ['SA', 'SB', 'SC']:
             return("status not success")
         
         authed_token_id = request.params.get('tokenID')
         authed_payment_method = {'SA':'ABT', 'SB':'ACH', 'SC':'CC'}[status]
Beispiel #7
0
 def ajax_transaction_status(self):
     """Ajax call from wrap_it_up page to get transaction status."""
     log_fb_request(request)
     facebook.process_request()
     c.is_app_user = facebook.api_client.added
     if not c.is_app_user:
         return self._ajax_fault("not app user!")
     elif facebook.fb_params.get('is_ajax', 0) == 0:
         return self._ajax_fault("not ajax!")
     
     donation_id = request.POST.get('did')
     if donation_id is None:
         return self._ajax_fault("need to specify donation ID")
     
     # look up donation in DB
     session = meta.Session()
     donation = session.query(Donation).get(donation_id)
     
     obj = {}
     obj['error'] = False
     obj['transactionStatus'] = donation.transaction_status
     return json.dumps(obj)
Beispiel #8
0
 def sent(self):
     log_fb_request(request)
     facebook.process_request()
     c.is_app_user = facebook.api_client.added
     
     if not c.is_app_user:
         c.error_msg = 'You must authorize We Give before you can view your sent gifts.'
         return(c.error_msg)
     
     current_user = facebook.user
     if not current_user:
         c.error_msg = 'Error getting your user info.'
         return(c.error_msg)
     
     session = meta.Session()
     
     fb_user = user_logic.get_fb_userpersona(session, current_user)
     if fb_user is None or fb_user.user is None:
         c.error_msg = 'You need to authorize the We Give app before you can view your sent gifts.'
         return(c.error_msg)
     
     c.sent_gifts = user_logic.decorate_with_fb_uid(fb_user.user.sent_gifts, 'recipient_id')
     
     return render('/facebook/sent.tmpl')
Beispiel #9
0
 def allgifts(self):
     log_fb_request(request)
     facebook.process_request()
     c.is_app_user = facebook.api_client.added
     
     c.recipient_id = request.params.get('uid')
     if not c.recipient_id:
         c.error_msg = 'No user specified'
         return(c.error_msg)
     
     session = meta.Session()
     
     fb_user = user_logic.get_fb_userpersona(session, c.recipient_id)
     if fb_user is None or fb_user.user is None:
         c.error_msg = 'Unable to retrieve user of gifts.'
         return(c.error_msg)
     
     # TODO: add clause for privacy if viewer is also subject
     c.received_gifts = user_logic.decorate_with_fb_uid(fb_user.user.received_gifts, 'donor_id')
     
     if c.recipient_id == facebook.user:
         return render('/facebook/received.tmpl')
     else:
         return render('/facebook/allgifts.tmpl')
Beispiel #10
0
 def help(self):
     log_fb_request(request)
     facebook.process_request()
     c.is_app_user = facebook.api_client.added
 
     return render('/facebook/help.tmpl')
Beispiel #11
0
    def index(self):
        realstart = start = time.time()
        
        log_fb_request(request)
        log.debug('time to log request: %.3f ms' % ((time.time() - start)*1000.0))
        
        #
        # TODOs for canvas page:
        #  - if not added, show message: "To send a gift, add this application"
        #  - if not added but received gift(s), show gifts and message "Add application and to profile to display gifts"
        #  - if added, and there are pending gifts, show these
        #
        
        current_user = None
        start = time.time()
        facebook.process_request()
        log.debug('time to do facebook.process_request(): %.3f ms' % ((time.time() - start)*1000.0))
        c.is_app_user = facebook.api_client.added
        if facebook.user:
            log.debug('user: %s' % facebook.user)
            current_user = facebook.user
        elif facebook.canvas_user:
            log.debug('canvas_user: %s' % facebook.canvas_user)
            current_user = facebook.canvas_user

        c.just_installed = (request.GET.get('installed') == '1')
        c.gift_count = None
        
        if current_user:
            start = time.time()

            """ Removing unnecessary Facebook API calls
            # TODO: need to handle "URLError: urlopen error" exceptions thrown from api calls
            info = facebook.api_client.users.getInfo([current_user], ['name', 'first_name', 'last_name', 'pic_square', 'locale'])[0]
            log.debug('name: %s, pic: %s, locale: %s' % (info['name'], info['pic_square'], info['locale']) )
            friends = facebook.api_client.friends.get(uid=current_user)
            friends = facebook.api_client.users.getInfo(friends, ['uid', 'name', 'pic_square', 'locale'])
            c.friends = friends
            log.debug('time to make facebook API calls: %.3f ms' % ((time.time() - start)*1000.0))
            """
            
            # TODO: we cannot store the first_name, last_name - the user needs to provide it to us
            # TODO: need a way to map existing Users to Facebook users
            
            start = time.time()
            session = meta.Session()
            
            # Look up current_user in UserPersona table
            #   if exists:
            #     - update 'is_app_user' status?
            #   if not exists:
            #     - add new row in User table (even if it ends up being a dummy)
            #     - add new row in UserPersona table
            fb_user = user_logic.get_fb_userpersona(session, current_user, create_if_missing=True)
            
            # update is_app_user if persisted value is inaccurate
            if fb_user.is_app_user != facebook.api_client.added:
                fb_user.is_app_user = facebook.api_client.added

            session.flush()
            
            if c.just_installed:
                c.gift_count = len(fb_user.user.received_gifts)
            
                fbml_start = time.time()
                if fb_user.is_app_user and not fb_logic.has_profile_fbml(current_user):
                    ALLOW_FBML_INIT_ON_FIRST_VISIT = True
                    if ALLOW_FBML_INIT_ON_FIRST_VISIT:
                        fb_logic.update_user_fbml_by_userpersona(fb_user)
                    else:
                        log.debug("Updating profile FBML on canvas-page views is currently de-fanged, so that I can properly test handling users w/o FBML!")
            
                log.debug('time for has_profile_fbml call: %.3f ms' % ((time.time() - fbml_start)*1000.0))
            
            # will commit new user if call to get_fb_userpersona added row
            session.commit()
        
        # query DB for list of gifts
        gifts_mkey = 'Cols.gifts-page1'
        mc_start = time.time()
        gifts = g.mc.get(gifts_mkey)
        log.debug('time for memcached calls: %.3f ms' % ((time.time() - mc_start)*1000.0))
        if gifts:
            log.debug('got gifts from memcached!')
            c.gifts = gifts
        else:
            gift_q = meta.Session.query(Gift)
            c.gifts = gift_q.filter_by(for_sale=True).order_by(Gift.created)[:18]
            if g.mc.set(gifts_mkey, c.gifts, time=86400):
                log.debug('stored gifts in memcached!')
            else:
                log.debug('unable to store gifts in memcached.  make sure memcached server is running!')
        
        # get list of charities that have registered thru CBUI as payment recipients
        c.charities = self._get_active_charities()
        
        c.preselected_charity_id = None
        c.preselected_charity = None
        if len(c.charities) == 1:
            # TODO: temporary logic until we have more than 1 charity
            c.preselected_charity_id = c.charities[0].id
            c.preselected_charity = c.charities[0]
        else:
            co_param = request.params.get('co')
            if co_param is not None:
                for charity in c.charities:
                    if charity.short_code == co_param:
                        c.preselected_charity_id = charity.id
                        c.preselected_charity = charity
                        break
        log.debug('preselected_charity_id: %s' % c.preselected_charity_id)
        
        log.debug('time for all DB calls: %.3f ms' % ((time.time() - start)*1000.0))
        
        c.form_uuid = uuid.uuid1().hex
        
        # for (offset, item) in enumerate(c.gifts):
        #    do something on item and offset
        # or: list comprehension: [c * i for (i, c) in enumerate(c.gifts)]
        
        log.debug('total time: %.3f ms' % ((time.time() - realstart)*1000.0))
        
        ext_perms = request.params.get('fb_sig_ext_perms', '').split(',')
        c.has_publish_stream = ('publish_stream' in ext_perms)
        c.has_email_perm = ('email' in ext_perms)
        if 'publish_stream' in ext_perms:
            c.show_prompt_perm = False
        elif current_user is not None:
            # show link for Tracy and me
            c.show_prompt_perm = (int(current_user) == 541265766 or int(current_user) == 1004760)
        else:
            c.show_prompt_perm = False
        
        return render('/facebook/index.tmpl')
Beispiel #12
0
 def process_multi(self):
     log_fb_request(request)
     facebook.process_request()
     c.is_app_user = facebook.api_client.added
     if not c.is_app_user:
         return '<fb:redirect url="index" />'
     
     current_user = facebook.user
     if not current_user:
         return '<fb:redirect url="index" />'
     
     session = meta.Session()
     
     fb_user = user_logic.get_fb_userpersona(session, current_user)
     if fb_user is None:
         return '<fb:redirect url="index" />'
     
     # validate
     total_amount = request.POST.get('total_amount')
     charity_ids = request.POST.getall('charity_val')
     
     if charity_ids is None or len(charity_ids) == 0:
         c.error_msg = 'No charities were specified.'
         return render('/facebook/setup_multi.tmpl')
     
     # save (pending) multi-use token info to DB
     multiuse_token = MultiUseToken(fb_user.user.id, float(total_amount))
     session.add(multiuse_token)
     session.flush()
     caller_ref = 'wgmultiuse_%d_%s' % (multiuse_token.id, uuid.uuid1().hex)
     multiuse_token.caller_reference = caller_ref
     session.commit()
     log_payment_event('APP', 'Created multi-use token', caller_ref=caller_ref, new_status='new')
     
     # compute parameters for request to Co-Branded FPS pages
     reason = 'Authorize multiple donations'
     charity_tokens = []
     for charity_id in charity_ids:
         charity = self._get_charity(charity_id)
         if FPS_PROMO_ACTIVE:
             recipient_token = charity.promo_recipient_token_id
         else:
             recipient_token = charity.recipient_token_id
         charity_tokens.append(recipient_token)
     recipient_token_list = ",".join(charity_tokens)
     
     # info for multi-use token CBUI call:
     #
     # - minimum transaction amount: 1.00
     # - expiration: default 1 year
     # - maximum amount limit: total amount (from user)
     # - recipients: list of tokens from charities
     #
     direct_url = fps_logic.get_multiuse_cbui_url(caller_ref,
                                                  reason,
                                                  total_amount,
                                                  minimum_amount=1.0,
                                                  recipient_token_list=recipient_token_list,
                                                  return_url = c.canvas_url + '/multiuse_return',
                                                  website_desc='We Give Facebook application')
     
     return '<fb:redirect url="%s" />' % direct_url
Beispiel #13
0
    def send_gift(self):
        """Render gift preview for user to review and then click 'Continue with donation'"""
        log_fb_request(request)
        facebook.process_request()
        c.is_app_user = facebook.api_client.added
        
        if not c.is_app_user:
            c.error_msg = 'You need to add this app before you can send gifts.'
            return render('/facebook/send_gift.tmpl')
        
        current_user = facebook.user
        if not current_user:
            c.error_msg = 'Error getting your user info.'
            return render('/facebook/send_gift.tmpl')
        
        session = meta.Session()
        
        fb_user = user_logic.get_fb_userpersona(session, current_user)
        if fb_user is None:
            # TODO: make sure use has added app
            # TODO: make sure user exists
            
            c.error_msg = 'You need to add this app before you can send gifts.'
            return render('/facebook/send_gift.tmpl')
        
        # validate
        c.recipient_id = request.POST.get('friend_selector_id')
        charity_id = request.params.get('charity_val')
        gift_id = request.params.get('gift_id')
        c.message = request.params.get('message')
        c.donation_amt = request.params.get('amount','1.00')
        stream_short_msg = request.params.get('stream_short_msg')
        
        form_uuid = request.params.get('uuid')
        # TODO: store & lookup uuid in memcached, to see if user is resubmitting form.  at least log the UUID.

        if c.recipient_id:
            recipient_info = facebook.api_client.users.getInfo([c.recipient_id], ['name', 'pic_square', 'locale'])[0]
            log.debug('recipient name: %s, pic: %s, locale: %s' % (recipient_info['name'], recipient_info['pic_square'], recipient_info['locale']) )
            
            recipient_userpersona = user_logic.get_fb_userpersona(session, c.recipient_id, create_if_missing=True)
        
        gift_q = meta.Session.query(Gift)
        charity_q = meta.Session.query(Charity)

        charity = charity_q.get(charity_id)
        if charity is None:
            c.error_msg = 'Charity not found'
            return render('/facebook/send_gift.tmpl')
        c.charity_name = charity.name
        
        c.gift = gift_q.get(gift_id)
        
        # save (pending) donation info to DB or session or memcache or something
        wg_user_id = fb_user.user.id
        donation = Donation(wg_user_id, recipient_userpersona.user.id, float(c.donation_amt), gift_id, charity_id)
        donation.message = c.message
        if stream_short_msg is not None and stream_short_msg.strip() != '':
            donation.stream_short_msg = stream_short_msg
        session.add(donation)
        session.commit()
        
        # check if user has multi-use token active
        multiuse_token_q = meta.Session.query(MultiUseToken)
        c.multiuse_token = multiuse_token_q.filter_by(user_id=wg_user_id).filter_by(is_active=True).filter(MultiUseToken.est_amount_remaining >= float(c.donation_amt)).first()
        
        # TODO: to prevent form resubmission, commit, then redirect to review_gift page with donation ID??
        
        # compute parameters for request to Co-Branded FPS pages
        c.caller_ref = 'wgdonation_%d_%s' % (donation.id, uuid.uuid1().hex)
        reason = 'Donation to %s' % charity.name
        if FPS_PROMO_ACTIVE:
            recipient_token = charity.promo_recipient_token_id
        else:
            recipient_token = charity.recipient_token_id
        c.direct_url = fps_logic.get_cbui_url(c.caller_ref,
                                              reason,
                                              c.donation_amt,
                                              recipient_token=recipient_token,
                                              website_desc='We Give Facebook application')
        
        log_payment_event('APP', 'Created donation', donation_id=donation.id, caller_ref=c.caller_ref, new_status='new')
        
        return render('/facebook/send_gift.tmpl')