def banner_create(request): form = FacebookBannerInstanceForm(request, request.POST or None) if request.method == 'POST': if not form.is_valid(): return JSONResponse(form.errors, status=400) banner_instance = form.save() # The create form is submitted via an AJAX call. If the user wants to # include their profile picture on a banner, we return a 202 Accepted to # indicate we are processing the image. If they don't, we just return # a 201 Created to signify that the banner instance has been created # and it is safe to continue. if request.POST['next_action'] == 'share': next = absolutify(reverse('facebook.banners.share', args=[banner_instance.id])) else: next = absolutify(reverse('facebook.banner_list')) if form.cleaned_data['use_profile_image']: generate_banner_instance_image.delay(banner_instance.id) payload = { 'check_url': reverse('facebook.banners.create_image_check', args=[banner_instance.id]), 'next': next } return JSONResponse(payload, status=202) # 202 Accepted else: # No processing needed. banner_instance.processed = True banner_instance.save() return JSONResponse({'next': next}, status=201) # 201 Created return render(request, 'facebook/banner_create.html', {'form': form})
def test_cdn(self): with patch.object(settings, 'CDN_DOMAIN', None): url = absolutify('/some/url', cdn=True) eq_(url, 'http://badge.mo.com/some/url') with patch.object(settings, 'CDN_DOMAIN', 'cdn.badge.mo.com'): url = absolutify('/some/url', cdn=True) eq_(url, 'http://cdn.badge.mo.com/some/url')
def render(self): """Render the image grid for the banner selector.""" banner_ids = [ int(banner_id) for banner_id, label in self.choices if banner_id != '' ] banners = dict( (banner.id, banner) for banner in FacebookBanner.objects.filter(id__in=banner_ids)) inputs = [] locale = get_language() for radio_input in self: # Ignore empty choice. # TODO: Could probably use a better workaround. if radio_input.choice_value == '': continue banner = banners[int(radio_input.choice_value)] # Construct image tag. img = '<img%s>' % flatatt( { 'class': 'banner-choice', 'src': absolutify(banner.thumbnail_for_locale(locale).url), 'width': 100, 'height': 72, 'alt': banner.alt_text }) # Add attributes to the input tag. url = banner.image_for_locale(locale).url radio_input.attrs['data-image'] = absolutify(url) if 'id' in self.attrs: label_for = ' for="%s_%s"' % (radio_input.attrs['id'], radio_input.index) else: label_for = '' # Bring it all together! inputs.append('<label%(label_for)s>\n%(input)s\n%(img)s\n' '</label>' % { 'label_for': label_for, 'input': radio_input.tag(), 'img': img }) return mark_safe(u'<ul>\n%s\n</ul>' % u'\n'.join([u'<li>%s</li>' % tag for tag in inputs]))
def test_use_profile_image(self, delay): """ If the user checked `use_profile_image`, create a banner instance, trigger the celery task and return a 202 Accepted. """ banner = FacebookBannerLocaleFactory.create(locale='en-us').banner response = self.banner_create(banner=banner.id, text='asdf', next_action='', use_profile_image=True) # Asserts that banner instance exists. instance = FacebookBannerInstance.objects.get(banner=banner, user=self.user) delay.assert_called_with(instance.id) # Assert response contians the expected links. eq_(response.status_code, 202) response_data = json.loads(response.content) with self.activate('en-US'): eq_(response_data['next'], absolutify(reverse('facebook.banner_list'))) eq_( response_data['check_url'], reverse('facebook.banners.create_image_check', args=[instance.id]))
def banner_share(request, instance_id): banner_instance = get_object_or_404(FacebookBannerInstance, id=instance_id, user=request.user) protocol = 'https' if request.is_secure() else 'http' next = absolutify(reverse('facebook.post_banner_share'), protocol=protocol) return render(request, 'facebook/banner_share.html', {'banner_instance': banner_instance, 'next': next})
def render(self): """Render the image grid for the banner selector.""" banner_ids = [int(banner_id) for banner_id, label in self.choices if banner_id != ''] banners = dict((banner.id, banner) for banner in FacebookBanner.objects.filter(id__in=banner_ids)) inputs = [] locale = get_language() for radio_input in self: # Ignore empty choice. # TODO: Could probably use a better workaround. if radio_input.choice_value == '': continue banner = banners[int(radio_input.choice_value)] # Construct image tag. img = '<img%s>' % flatatt({ 'class': 'banner-choice', 'src': absolutify(banner.thumbnail_for_locale(locale).url), 'width': 100, 'height': 72, 'alt': banner.alt_text }) # Add attributes to the input tag. url = banner.image_for_locale(locale).url radio_input.attrs['data-image'] = absolutify(url) if 'id' in self.attrs: label_for = ' for="%s_%s"' % (radio_input.attrs['id'], radio_input.index) else: label_for = '' # Bring it all together! inputs.append('<label%(label_for)s>\n%(input)s\n%(img)s\n' '</label>' % { 'label_for': label_for, 'input': radio_input.tag(), 'img': img }) return mark_safe(u'<ul>\n%s\n</ul>' % u'\n'.join([u'<li>%s</li>' % tag for tag in inputs]))
def banner_share(request, instance_id): banner_instance = get_object_or_404(FacebookBannerInstance, id=instance_id, user=request.user) protocol = 'https' if request.is_secure() else 'http' next = absolutify(reverse('facebook.post_banner_share'), protocol=protocol) return render(request, 'facebook/banner_share.html', { 'banner_instance': banner_instance, 'next': next })
def gravatar(arg, size=80): if isinstance(arg, User): email = arg.email else: # Treat as email email = arg return '{url}/avatar/{email_hash}?{options}'.format( url=GRAVATAR_URL, email_hash=md5(email.lower()).hexdigest(), options=urllib.urlencode({'s': unicode(size), 'd': absolutify(static('img/avatar.jpg'))}) )
def load_app(request): """ Create or authenticate the Facebook user and direct them to the correct area of the app upon their entry. """ signed_request = request.POST.get('signed_request', None) if signed_request is None: # App wasn't loaded within a canvas, redirect to the home page. return redirect('base.home') decoded_request = decode_signed_request(signed_request, settings.FACEBOOK_APP_SECRET) if decoded_request is None: return redirect('base.home') # If user is using Safari, we need to apply the cookie workaround. useragent = request.META.get('HTTP_USER_AGENT', '') using_safari = 'Safari' in useragent and not 'Chrome' in useragent workaround_applied = SAFARI_WORKAROUND_KEY in request.COOKIES if using_safari and not workaround_applied: return fb_redirect(request, absolutify(reverse('facebook.safari_workaround')), top_window=True) user, created = (FacebookUser.objects. get_or_create_user_from_decoded_request(decoded_request)) if user is None: # User has yet to authorize the app, redirect to the pre-auth promo. return fb_redirect(request, absolutify(reverse('facebook.pre_auth_promo'))) # Attach country data to the user object. This can only be retrieved from # the decoded request, so we add it here and login saves it. user.country = decoded_request['user'].get('country', user.country) # User has been authed, let's log them in. login(request, user) return fb_redirect(request, absolutify(reverse('facebook.banner_list')))
def gravatar(arg, size=80): if isinstance(arg, User): email = arg.email else: # Treat as email email = arg return '{url}/avatar/{email_hash}?{options}'.format( url=GRAVATAR_URL, email_hash=md5(email.lower()).hexdigest(), options=urllib.urlencode({ 's': unicode(size), 'd': absolutify(static('img/avatar.jpg')) }))
def load_app(request): """ Create or authenticate the Facebook user and direct them to the correct area of the app upon their entry. """ signed_request = request.POST.get('signed_request', None) if signed_request is None: # App wasn't loaded within a canvas, redirect to the home page. return redirect('base.home') decoded_request = decode_signed_request(signed_request, settings.FACEBOOK_APP_SECRET) if decoded_request is None: return redirect('base.home') # If user is using Safari, we need to apply the cookie workaround. useragent = request.META.get('HTTP_USER_AGENT', '') using_safari = 'Safari' in useragent and not 'Chrome' in useragent workaround_applied = SAFARI_WORKAROUND_KEY in request.COOKIES if using_safari and not workaround_applied: return fb_redirect(request, absolutify(reverse('facebook.safari_workaround')), top_window=True) user, created = (FacebookUser.objects. get_or_create_user_from_decoded_request(decoded_request)) if user is None: # User has yet to authorize the app, redirect to the pre-auth promo. return fb_redirect(request, absolutify(reverse('facebook.pre_auth_promo'))) # Attach country data to the user object. This can only be retrieved from # the decoded request, so we add it here and login saves it. user.country = decoded_request['user'].get('country', user.country) # User has been authed, let's log them in. login(request, user) return fb_redirect(request, absolutify(reverse('facebook.banner_list')))
def test_no_safari_workaround(self, fb_redirect, update_user_info): """ If the user is not using Safari, do not redirect to the workaround. """ with self.activate('en-US'): workaround_url = absolutify(reverse('facebook.safari_workaround')) fb_redirect.return_value = HttpResponse('blah') payload = create_payload(user_id=1) response = self.load_app(payload, HTTP_USER_AGENT='Safari/5.04 Chrome/7.5') eq_(response, fb_redirect.return_value) ok_(fb_redirect.call_args[0][1] != workaround_url)
def test_no_safari_workaround(self, fb_redirect, update_user_info): """ If the user is not using Safari, do not redirect to the workaround. """ with self.activate('en-US'): workaround_url = absolutify(reverse('facebook.safari_workaround')) fb_redirect.return_value = HttpResponse('blah') payload = create_payload(user_id=1) response = self.load_app(payload, HTTP_USER_AGENT='Safari/5.04 Chrome/7.5') eq_(response, fb_redirect.return_value) ok_(fb_redirect.call_args[0][1] != workaround_url)
def banner_create(request): form = FacebookBannerInstanceForm(request, request.POST or None) if request.method == 'POST': if not form.is_valid(): return JSONResponse(form.errors, status=400) banner_instance = form.save() # The create form is submitted via an AJAX call. If the user wants to # include their profile picture on a banner, we return a 202 Accepted to # indicate we are processing the image. If they don't, we just return # a 201 Created to signify that the banner instance has been created # and it is safe to continue. if request.POST['next_action'] == 'share': next = absolutify( reverse('facebook.banners.share', args=[banner_instance.id])) else: next = absolutify(reverse('facebook.banner_list')) if form.cleaned_data['use_profile_image']: generate_banner_instance_image.delay(banner_instance.id) payload = { 'check_url': reverse('facebook.banners.create_image_check', args=[banner_instance.id]), 'next': next } return JSONResponse(payload, status=202) # 202 Accepted else: # No processing needed. banner_instance.processed = True banner_instance.save() return JSONResponse({'next': next}, status=201) # 201 Created return render(request, 'facebook/banner_create.html', {'form': form})
def test_no_profile_image(self): """ If the user did not check `use_profile_image`, create the banner instance and return a 201 Created. """ banner = FacebookBannerLocaleFactory.create(locale='en-us').banner response = self.banner_create(banner=banner.id, text='asdf', next_action='', use_profile_image=False) ok_(FacebookBannerInstance.objects.filter(banner=banner, user=self.user) .exists()) eq_(response.status_code, 201) response_data = json.loads(response.content) with self.activate('en-US'): eq_(response_data['next'], absolutify(reverse('facebook.banner_list')))
def test_save_and_share(self): """ If the user clicks the `Save and Share` button, the `next` link should point to the share page for the new banner instance. """ banner = FacebookBannerLocaleFactory.create(locale='en-us').banner response = self.banner_create(banner=banner.id, text='asdf', next_action='share', use_profile_image=False) instance = FacebookBannerInstance.objects.get(banner=banner, user=self.user) response_data = json.loads(response.content) with self.activate('en-US'): eq_(response_data['next'], absolutify(reverse('facebook.banners.share', args=[instance.id])))
def test_safari_workaround_done(self, fb_redirect, update_user_info): """ If the user is using Safari and hasthe workaround cookie, do not send them to the workaround page. """ with self.activate('en-US'): workaround_url = absolutify(reverse('facebook.safari_workaround')) fb_redirect.return_value = HttpResponse('blah') payload = create_payload(user_id=1) self.client.cookies[SAFARI_WORKAROUND_KEY] = '1' response = self.load_app(payload, HTTP_USER_AGENT='Safari/5.04') del self.client.cookies[SAFARI_WORKAROUND_KEY] # Ensure that the redirect URL is NOT the safari workaround url eq_(response, fb_redirect.return_value) ok_(fb_redirect.call_args[0][1] != workaround_url)
def test_safari_workaround_done(self, fb_redirect, update_user_info): """ If the user is using Safari and hasthe workaround cookie, do not send them to the workaround page. """ with self.activate('en-US'): workaround_url = absolutify(reverse('facebook.safari_workaround')) fb_redirect.return_value = HttpResponse('blah') payload = create_payload(user_id=1) self.client.cookies[SAFARI_WORKAROUND_KEY] = '1' response = self.load_app(payload, HTTP_USER_AGENT='Safari/5.04') del self.client.cookies[SAFARI_WORKAROUND_KEY] # Ensure that the redirect URL is NOT the safari workaround url eq_(response, fb_redirect.return_value) ok_(fb_redirect.call_args[0][1] != workaround_url)
def test_save_and_share(self): """ If the user clicks the `Save and Share` button, the `next` link should point to the share page for the new banner instance. """ banner = FacebookBannerLocaleFactory.create(locale='en-us').banner response = self.banner_create(banner=banner.id, text='asdf', next_action='share', use_profile_image=False) instance = FacebookBannerInstance.objects.get(banner=banner, user=self.user) response_data = json.loads(response.content) with self.activate('en-US'): eq_( response_data['next'], absolutify( reverse('facebook.banners.share', args=[instance.id])))
def test_no_profile_image(self): """ If the user did not check `use_profile_image`, create the banner instance and return a 201 Created. """ banner = FacebookBannerLocaleFactory.create(locale='en-us').banner response = self.banner_create(banner=banner.id, text='asdf', next_action='', use_profile_image=False) ok_( FacebookBannerInstance.objects.filter(banner=banner, user=self.user).exists()) eq_(response.status_code, 201) response_data = json.loads(response.content) with self.activate('en-US'): eq_(response_data['next'], absolutify(reverse('facebook.banner_list')))
def test_use_profile_image(self, delay): """ If the user checked `use_profile_image`, create a banner instance, trigger the celery task and return a 202 Accepted. """ banner = FacebookBannerLocaleFactory.create(locale='en-us').banner response = self.banner_create(banner=banner.id, text='asdf', next_action='', use_profile_image=True) # Asserts that banner instance exists. instance = FacebookBannerInstance.objects.get(banner=banner, user=self.user) delay.assert_called_with(instance.id) # Assert response contians the expected links. eq_(response.status_code, 202) response_data = json.loads(response.content) with self.activate('en-US'): eq_(response_data['next'], absolutify(reverse('facebook.banner_list'))) eq_(response_data['check_url'], reverse('facebook.banners.create_image_check', args=[instance.id]))
def image_url(self): return absolutify(media('uploads/upgrade/{pk}'.format(pk=self.pk)))
def activation_link(self): return absolutify(reverse('facebook.links.activate', args=[self.activation_code]))
def invite(request): protocol = 'https' if request.is_secure() else 'http' next = absolutify(reverse('facebook.post_invite'), protocol=protocol) return render(request, 'facebook/invite.html', {'next': next})
def link(self): return absolutify(reverse('facebook.banners.link', args=[self.id]))
def invite(request): protocol = 'https' if request.is_secure() else 'http' next = absolutify(reverse('facebook.post_invite'), protocol=protocol) return render(request, 'facebook/invite.html', {'next': next})
def handle(self, old_table_prefix, *args, **kwargs): cursor = connection.cursor() # Categories # Cannot use bulk_create due to django-mptt. cursor.execute('SELECT id, name FROM {0}badges_category'.format(old_table_prefix)) for row in cursor.fetchall(): Category.objects.create(id=row[0], name=row[1]) subcategory_to_category = {} cursor.execute('SELECT id, name, parent_id FROM {0}badges_subcategory' .format(old_table_prefix)) for row in cursor.fetchall(): category = Category.objects.create(name=row[1], parent_id=row[2]) subcategory_to_category[row[0]] = category.id # Banners cursor.execute('SELECT subcategory_id, name, href, displayed, id FROM {0}badges_badge' .format(old_table_prefix)) banners = [ ImageBanner( id=row[4], category_id=subcategory_to_category[row[0]], name=row[1], destination=row[2], visible=row[3] ) for row in cursor.fetchall() ] ImageBanner.objects.bulk_create(banners, batch_size=1000) # Banner Images cursor.execute('SELECT id, banner_id, color, locale, image FROM {0}banners_bannerimage' .format(old_table_prefix)) variations = [ ImageBannerVariation( id=row[0], banner_id=row[1], color=row[2], locale=row[3], image=row[4], ) for row in cursor.fetchall() ] ImageBannerVariation.objects.bulk_create(variations, batch_size=1000) # Links! (this is the big one) content_type = ContentType.objects.get_for_model(ImageBannerVariation) cursor.execute("""SELECT badgeinstance.id, badgeinstance.user_id, badgeinstance.badge_id, badgeinstance.clicks, bannerinstance.image_id, badge.href, bannerimage.image, bannerimage.id, badgeinstance.created FROM {0}badges_badgeinstance AS badgeinstance LEFT JOIN {0}banners_bannerinstance AS bannerinstance ON bannerinstance.badgeinstance_ptr_id = badgeinstance.id LEFT JOIN {0}badges_badge AS badge ON badgeinstance.badge_id = badge.id LEFT JOIN {0}banners_bannerimage AS bannerimage ON bannerinstance.image_id = bannerimage.id WHERE badgeinstance.user_id in (SELECT id from auth_user) """.format(old_table_prefix)) links = [ Link( id=row[0], user_id=row[1], destination=row[5], html=u'<a href="{url}"><img src="{src}" alt="" /></a>'.format( url=absolutify(u'/link/banner/{0}'.format(row[0]), protocol=''), src=absolutify(u'/media/{0}'.format(row[6]), protocol='') ), legacy_banner_instance_id=row[0], legacy_banner_image_id=row[4], aggregate_link_clicks=row[3], banner_variation_id=row[7], banner_variation_content_type=content_type, created=row[8] ) for row in cursor.fetchall() ] Link.objects.bulk_create(links, batch_size=1000)
def handle(self, old_table_prefix, *args, **kwargs): cursor = connection.cursor() # Categories # Cannot use bulk_create due to django-mptt. cursor.execute( 'SELECT id, name FROM {0}badges_category'.format(old_table_prefix)) for row in cursor.fetchall(): Category.objects.create(id=row[0], name=row[1]) subcategory_to_category = {} cursor.execute( 'SELECT id, name, parent_id FROM {0}badges_subcategory'.format( old_table_prefix)) for row in cursor.fetchall(): category = Category.objects.create(name=row[1], parent_id=row[2]) subcategory_to_category[row[0]] = category.id # Banners cursor.execute( 'SELECT subcategory_id, name, href, displayed, id FROM {0}badges_badge' .format(old_table_prefix)) banners = [ ImageBanner(id=row[4], category_id=subcategory_to_category[row[0]], name=row[1], destination=row[2], visible=row[3]) for row in cursor.fetchall() ] ImageBanner.objects.bulk_create(banners, batch_size=1000) # Banner Images cursor.execute( 'SELECT id, banner_id, color, locale, image FROM {0}banners_bannerimage' .format(old_table_prefix)) variations = [ ImageBannerVariation( id=row[0], banner_id=row[1], color=row[2], locale=row[3], image=row[4], ) for row in cursor.fetchall() ] ImageBannerVariation.objects.bulk_create(variations, batch_size=1000) # Links! (this is the big one) content_type = ContentType.objects.get_for_model(ImageBannerVariation) cursor.execute("""SELECT badgeinstance.id, badgeinstance.user_id, badgeinstance.badge_id, badgeinstance.clicks, bannerinstance.image_id, badge.href, bannerimage.image, bannerimage.id, badgeinstance.created FROM {0}badges_badgeinstance AS badgeinstance LEFT JOIN {0}banners_bannerinstance AS bannerinstance ON bannerinstance.badgeinstance_ptr_id = badgeinstance.id LEFT JOIN {0}badges_badge AS badge ON badgeinstance.badge_id = badge.id LEFT JOIN {0}banners_bannerimage AS bannerimage ON bannerinstance.image_id = bannerimage.id WHERE badgeinstance.user_id in (SELECT id from auth_user) """.format(old_table_prefix)) links = [ Link(id=row[0], user_id=row[1], destination=row[5], html=u'<a href="{url}"><img src="{src}" alt="" /></a>'.format( url=absolutify(u'/link/banner/{0}'.format(row[0]), protocol=''), src=absolutify(u'/media/{0}'.format(row[6]), protocol='')), legacy_banner_instance_id=row[0], legacy_banner_image_id=row[4], aggregate_link_clicks=row[3], banner_variation_id=row[7], banner_variation_content_type=content_type, created=row[8]) for row in cursor.fetchall() ] Link.objects.bulk_create(links, batch_size=1000)
def test_protocol(self): url = absolutify('/some/url', protocol='https') eq_(url, 'https://badge.mo.com/some/url')
def test_basic(self): url = absolutify('/some/url') eq_(url, 'http://badge.mo.com/some/url')
def image_url(self): return absolutify(media('uploads/upgrade/{pk}'.format(pk=self.pk)))
def get_referral_url(self): return absolutify(reverse('links.referral', args=[self.pk]))
def test_relative_protocol(self): """If protocol is a blank string, use a protocol-relative URL.""" url = absolutify('/some/url', protocol='') eq_(url, '//badge.mo.com/some/url')
def activation_link(self): return absolutify( reverse('facebook.links.activate', args=[self.activation_code]))
def link(self): return absolutify(reverse('facebook.banners.link', args=[self.id]))
def get_referral_url(self): return absolutify(reverse("links.referral", args=[self.pk]))