def question_vote(request, question_id): """I have this problem too.""" question = get_object_or_404(Question, pk=question_id) if question.is_locked: raise PermissionDenied if not question.has_voted(request): vote = QuestionVote(question=question) if request.user.is_authenticated(): vote.creator = request.user else: vote.anonymous_id = request.anonymous.anonymous_id vote.save() if "referrer" in request.REQUEST: referrer = request.REQUEST.get("referrer") vote.add_metadata("referrer", referrer) if referrer == "search" and "query" in request.REQUEST: vote.add_metadata("query", request.REQUEST.get("query")) ua = request.META.get("HTTP_USER_AGENT") if ua: vote.add_metadata("ua", ua[:1000]) # 1000 max_length statsd.incr("questions.votes.question") if request.is_ajax(): tmpl = "questions/includes/question_vote_thanks.html" form = WatchQuestionForm(request.user) html = jingo.render_to_string(request, tmpl, {"question": question, "watch_form": form}) return HttpResponse(json.dumps({"html": html})) return HttpResponseRedirect(question.get_absolute_url())
def refund_reason(request, contribution, wizard): if not contribution.can_we_refund(): return http.HttpResponseForbidden() addon = contribution.addon if not 'request' in wizard.get_progress(): return redirect('support', contribution.pk, 'request') if contribution.transaction_id is None: messages.error(request, _('A refund cannot be applied for yet. Please try again later. ' 'If this error persists contact [email protected].')) paypal_log.info('Refund requested for contribution with no ' 'transaction_id: %r' % contribution.pk) return redirect('account.purchases') if contribution.is_instant_refund(): try: paypal.refund(contribution.paykey) except PaypalError: paypal_log.error('Paypal error with refund', exc_info=True) messages.error(request, _('There was an error with your instant ' 'refund.')) return redirect('account.purchases') refund = contribution.enqueue_refund(amo.REFUND_APPROVED_INSTANT) paypal_log.info('Refund %r issued for contribution %r' % (refund.pk, contribution.pk)) # Note: we have to wait for PayPal to issue an IPN before it's # completely refunded. messages.success(request, _('Refund is being processed.')) return redirect('account.purchases') form = forms.ContactForm(request.POST or None) if request.method == 'POST' and form.is_valid(): reason = form.cleaned_data['text'] template = jingo.render_to_string(request, wizard.tpl('emails/refund-request.txt'), context={'product': addon, 'form': form, 'user': request.amo_user, 'contribution': contribution, 'refund_url': contribution.get_absolute_refund_url(), 'refund_reason': reason}) log.info('Refund request sent by user: %s for addon: %s' % (request.amo_user.pk, addon.pk)) # L10n: %s is the app name. support_mail(_(u'New Refund Request for %s' % addon.name), template, sender=settings.NOBODY_EMAIL, recipients=[smart_str(addon.support_email)]) # Add this refund request to the queue. contribution.enqueue_refund(amo.REFUND_PENDING, reason) return redirect(reverse('support', args=[contribution.pk, 'refund-sent'])) return wizard.render(request, wizard.tpl('refund.html'), {'product': addon, 'contribution': contribution, 'form': form, 'title': _('Request Refund')})
def question_vote(request, question_id): """I have this problem too.""" question = get_object_or_404(Question, pk=question_id) if question.is_locked: raise PermissionDenied if not question.has_voted(request): vote = QuestionVote(question=question) if request.user.is_authenticated(): vote.creator = request.user else: vote.anonymous_id = request.anonymous.anonymous_id vote.save() ua = request.META.get('HTTP_USER_AGENT') if ua: vote.add_metadata('ua', ua[:1000]) # 1000 max_length statsd.incr('questions.votes.question') if request.is_ajax(): tmpl = 'questions/includes/question_vote_thanks.html' form = _init_watch_form(request) html = jingo.render_to_string(request, tmpl, {'question': question, 'watch_form': form}) return HttpResponse(json.dumps({'html': html})) return HttpResponseRedirect(question.get_absolute_url())
def refund_reason(request, contribution, wizard): addon = contribution.addon if not 'request' in wizard.get_progress(): return redirect(reverse('users.support', args=[contribution.pk, 'request'])) form = forms.ContactForm(request.POST or None) if request.method == 'POST': if form.is_valid(): # if under 30 minutes, refund # TODO(ashort): add in the logic for under 30 minutes. template = jingo.render_to_string(request, wizard.tpl('emails/refund-request.txt'), context={'addon': addon, 'form': form, 'user': request.amo_user, 'contribution': contribution}) log.info('Refund request sent by user: %s for addon: %s' % (request.amo_user.pk, addon.pk)) # L10n: %s is the addon name. send_mail(_(u'New Refund Request for %s' % addon.name), template, request.amo_user.email, [smart_str(addon.support_email)]) return redirect(reverse('users.support', args=[contribution.pk, 'refund-sent'])) return wizard.render(request, wizard.tpl('refund.html'), {'contribut': addon, 'form': form})
def support_mozilla(request, contribution, wizard): addon = contribution.addon form = forms.ContactForm(request.POST or None) if request.method == "POST" and form.is_valid(): template = jingo.render_to_string( request, wizard.tpl("emails/support-request.txt"), context={"product": addon, "form": form, "contribution": contribution, "user": request.amo_user}, ) log.info("Support request to mozilla by user: %s for addon: %s" % (request.amo_user.pk, addon.pk)) # L10n: %s is the app name. support_mail( _(u"New Support Request for %s" % addon.name), template, sender=request.amo_user.email, recipients=[settings.MARKETPLACE_EMAIL], ) return redirect(reverse("support", args=[contribution.pk, "mozilla-sent"])) return wizard.render( request, wizard.tpl("mozilla.html"), {"product": addon, "contribution": contribution, "form": form, "title": _("Contact Mozilla")}, )
def firefox_footer_links(ctx, channel='release', platform='all'): """ Outputs Firefox footer links :param ctx: context from calling template. :param channel: name of channel: 'release', 'beta' or 'alpha'. :param platform: Target platform: 'desktop', 'android', or 'ios'. :return: The footer links html. """ show_desktop = platform in ['all', 'desktop'] show_android = platform in ['all', 'android'] show_ios = platform in ['all', 'ios'] alt_channel = '' if channel == 'release' else channel # Gather data about the build for each platform builds = [] if show_android: builds = android_builds(channel, builds) data = { 'show_desktop': show_desktop, 'show_android': show_android, 'show_ios': show_ios, 'channel': alt_channel, 'builds': builds, } html = jingo.render_to_string( ctx['request'], 'firefox/includes/firefox-footer-links.html', data) return jinja2.Markup(html)
def rendered_content(self): template = self.template_name if 'user' not in self.context_data: self.context_data['user'] = self._request.user context_instance = self.resolve_context(self.context_data) # Gross, let's figure out if we're in the admin. if getattr(self._request, 'current_app', None) == 'admin': source = loader.render_to_string( template, RequestContext(self._request, context_instance)) template = jingo.get_env().from_string(source) # This interferes with our media() helper. if 'media' in self.context_data: del self.context_data['media'] # ``render_to_string`` only accepts a Template instance or a template name, # not a list. if isinstance(template, (list, tuple)): template = loader.select_template(template) if isinstance(template, Template): template = template.template return jingo.render_to_string( self._request, template, self.context_data)
def render_email(template, context): """Renders a template in the currently set locale.""" req = RequestFactory() req.META = {} req.locale = translation.get_language() return jingo.render_to_string(req, template, context)
def item_description(self, submission): return jingo.render_to_string( self.request, 'demos/feed_item_description.html', dict( request=self.request, submission=submission ) )
def _install_button(context, addon, version=None, show_eula=True, show_contrib=True, show_warning=True, src='', collection=None, size='', detailed=False, mobile=False, impala=False): """If version isn't given, we use the latest version.""" request = context['request'] app, lang = context['APP'], context['LANG'] show_eula = bool(request.GET.get('eula', show_eula)) src = src or context.get('src') or request.GET.get('src', '') collection = ((collection.uuid if hasattr(collection, 'uuid') else None) or collection or context.get('collection') or request.GET.get('collection') or request.GET.get('collection_id') or request.GET.get('collection_uuid')) button = install_button_factory(addon, app, lang, version, show_eula, show_contrib, show_warning, src, collection, size, detailed, impala) installed = (request.user.is_authenticated() and addon.id in request.amo_user.mobile_addons) c = {'button': button, 'addon': addon, 'version': button.version, 'installed': installed} if addon.is_webapp(): template = 'webapps/button.html' elif impala: template = 'addons/impala/button.html' elif mobile: template = 'addons/mobile/button.html' else: template = 'addons/button.html' t = jingo.render_to_string(request, template, c) return jinja2.Markup(t)
def refund_reason(request, contribution, wizard): addon = contribution.addon if not 'request' in wizard.get_progress(): return redirect('users.support', contribution.pk, 'request') if contribution.is_instant_refund(): paypal.refund(contribution.paykey) paypal_log.info('Refund issued for contribution %r' % contribution.pk) # Note: we have to wait for PayPal to issue an IPN before it's # completely refunded. messages.success(request, _('Refund is being processed.')) return redirect('users.purchases') form = forms.ContactForm(request.POST or None) if request.method == 'POST' and form.is_valid(): url = absolutify(urlparams(addon.get_dev_url('issue_refund'), transaction_id=contribution.transaction_id)) template = jingo.render_to_string(request, wizard.tpl('emails/refund-request.txt'), context={'addon': addon, 'form': form, 'user': request.amo_user, 'contribution': contribution, 'refund_url': url}) log.info('Refund request sent by user: %s for addon: %s' % (request.amo_user.pk, addon.pk)) # L10n: %s is the addon name. send_mail(_(u'New Refund Request for %s' % addon.name), template, settings.NOBODY_EMAIL, [smart_str(addon.support_email)]) return redirect(reverse('users.support', args=[contribution.pk, 'refund-sent'])) return wizard.render(request, wizard.tpl('refund.html'), {'form': form})
def email_newsletter_form(ctx, newsletters='mozilla-and-you', title=None, include_country=True, include_language=True, use_thankyou=True, footer=True, process_form=True): request = ctx['request'] context = ctx.get_all() success = bool(ctx.get('success')) if success and not use_thankyou: return form = ctx.get('newsletter_form', None) if not form: form = NewsletterFooterForm(newsletters, get_locale(request)) context.update(dict( id=newsletters, title=title, include_country=include_country, include_language=include_language, use_thankyou=use_thankyou, footer=footer, form=form, success=success, )) html = jingo.render_to_string(request, 'newsletter/includes/form.html', context) return jinja2.Markup(html)
def email_newsletter_form(ctx, newsletters='mozilla-and-you', title=None, include_country=True, include_language=True, details=None, use_thankyou=True, thankyou_head=None, thankyou_content=None, footer=True, process_form=True, include_title=None, submit_text=None): request = ctx['request'] context = ctx.get_all() success = bool(ctx.get('success')) if success and not use_thankyou: return form = ctx.get('newsletter_form', None) if not form: form = NewsletterFooterForm(newsletters, get_locale(request)) context.update(dict( id=newsletters, title=title, include_country=include_country, include_language=include_language, details=details, use_thankyou=use_thankyou, thankyou_head=thankyou_head, thankyou_content=thankyou_content, footer=footer, include_title=include_title if include_title is not None else footer, form=form, submit_text=submit_text, success=success, )) html = jingo.render_to_string(request, 'newsletter/includes/form.html', context) return jinja2.Markup(html)
def test_rtl_dir_attribute(self): """Make sure dir attr is set to 'rtl' when specified as so.""" html = jingo.render_to_string(self.request, self.template, {'dir': 'rtl'}) doc = pq(html) dir_attr = doc('html').attr['dir'] eq_('rtl', dir_attr)
def render(self, name, value, attrs=None): topics_and_subtopics = Topic.objects.all() topics = [t for t in topics_and_subtopics if t.parent_id is None] for topic in topics: self.process_topic(value, topic) topic.my_subtopics = [t for t in topics_and_subtopics if t.parent_id == topic.id] for subtopic in topic.my_subtopics: self.process_topic(value, subtopic) # Create a fake request to make jingo happy. req = RequestFactory() req.META = {} req.locale = settings.WIKI_DEFAULT_LANGUAGE return jingo.render_to_string( req, 'wiki/includes/product_topics_widget.html', { 'topics': topics, 'name': name, })
def submit_form(request, form): form_submitted = True if form.is_valid(): form_error = False data = form.cleaned_data subject = FRAUD_REPORT_EMAIL_SUBJECT % (data['input_url'], data['input_category']) sender = FRAUD_REPORT_EMAIL_FROM to = FRAUD_REPORT_EMAIL_TO msg = jingo.render_to_string(request, 'legal/emails/fraud-report.txt', data) email = EmailMessage(subject, msg, sender, to) attachment = data['input_attachment'] if attachment: email.attach(attachment.name, attachment.read(), attachment.content_type) email.send() else: form_error = True return {'form_submitted': form_submitted, 'form_error': form_error}
def send(request, data): """Forward contributor's email to our contacts. All emails are sent to [email protected] For locales with points of contact, it is also sent to them. For locales without, it is also sent to functional area contacts. """ functional_area = FUNCTIONAL_AREAS_DICT[data['interest']] from_ = '*****@*****.**' subject = 'Inquiry about Mozilla %s' % functional_area.subject msg = jingo.render_to_string(request, 'mozorg/emails/infos.txt', data) headers = {'Reply-To': data['email']} to = ['*****@*****.**'] cc = None if request.locale in LOCALE_CONTACTS: cc = LOCALE_CONTACTS[request.locale] else: cc = functional_area.contacts email = EmailMessage(subject, msg, from_, to, cc=cc, headers=headers) email.send()
def autorespond(request, data): """Send an auto-respond email based on chosen field of interest and locale. You can add localized responses by creating email messages in mozorg/emails/<category.txt> """ functional_area = FUNCTIONAL_AREAS_DICT[data['interest']] subject = 'Inquiry about Mozilla %s' % functional_area.subject to = [data['email']] from_ = '*****@*****.**' headers = {} msg = '' template = 'mozorg/emails/%s.txt' % functional_area.id if request.locale != 'en-US' and request.locale in LOCALE_CONTACTS: template = '%s/templates/%s' % (request.locale, template) reply_to = LOCALE_CONTACTS[request.locale] else: reply_to = functional_area.contacts try: msg = jingo.render_to_string(request, template, data) except TemplateNotFound: # No template found means no auto-response return False # FIXME Why ? msg = msg.replace('\n', '\r\n') headers = {'Reply-To': ','.join(reply_to)} email = EmailMessage(subject, msg, from_, to, headers=headers) email.send()
def watch_question(request, question_id): """Start watching a question for replies or solution.""" question = get_object_or_404(Question, pk=question_id) form = WatchQuestionForm(request.POST) # Process the form if form.is_valid(): if request.user.is_authenticated(): email = request.user.email else: email = form.cleaned_data['email'] event_type = form.cleaned_data['event_type'] create_watch(Question, question.id, email, event_type) # Respond to ajax request if request.is_ajax(): if form.is_valid(): msg = _('You will be notified of updates by email.') return HttpResponse(json.dumps({'message': msg})) if request.POST.get('from_vote'): tmpl = 'questions/includes/question_vote_thanks.html' else: tmpl = 'questions/includes/email_subscribe.html' html = jingo.render_to_string(request, tmpl, {'question': question, 'watch_form': form}) return HttpResponse(json.dumps({'html': html})) # Respond to normal request if form.is_valid(): return HttpResponseRedirect(question.get_absolute_url()) return answers(request, question.id, watch_form=form)
def mobile_download_button(ctx, id, format='large', build=None): if build == 'aurora': android_link = download_urls['aurora-mobile'] version = product_details.mobile_details['alpha_version'] elif build == 'beta': android_link = ('https://market.android.com/details?' 'id=org.mozilla.firefox_beta') version = product_details.mobile_details['beta_version'] else: android_link = ('https://market.android.com/details?' 'id=org.mozilla.firefox') version = product_details.mobile_details['version'] builds = [{'platform': '', 'platform_pretty': 'Android', 'download_link': android_link, 'download_link_direct': android_link}] data = { 'locale_name': 'en-US', 'version': version, 'product': 'firefox-mobile', 'builds': builds, 'id': id } html = jingo.render_to_string(ctx['request'], 'mozorg/download_button_%s.html' % format, data) return jinja2.Markup(html)
def submit_form(request, form): form_submitted = False if form.is_valid(): form_submitted = True form_error = False honeypot = form.cleaned_data.pop('office_fax') if honeypot: form_error = True else: subject = 'Message sent from Privacy Hub' sender = form.cleaned_data['sender'] to = ['yourprivacyis#[email protected]'] msg = jingo.render_to_string(request, 'privacy/includes/email-info.txt', form.cleaned_data) headers = {'Reply-To': sender} email = EmailMessage(subject, msg, sender, to, headers=headers) email.send() else: form_error = True return {'form_submitted': form_submitted, 'form_error': form_error}
def refund_reason(request, contribution, wizard): addon = contribution.addon if not 'request' in wizard.get_progress(): return redirect( reverse('users.support', args=[contribution.pk, 'request'])) form = forms.ContactForm(request.POST or None) if request.method == 'POST': if form.is_valid(): # if under 30 minutes, refund # TODO(ashort): add in the logic for under 30 minutes. template = jingo.render_to_string( request, wizard.tpl('emails/refund-request.txt'), context={ 'addon': addon, 'form': form, 'user': request.amo_user, 'contribution': contribution }) log.info('Refund request sent by user: %s for addon: %s' % (request.amo_user.pk, addon.pk)) # L10n: %s is the addon name. send_mail(_(u'New Refund Request for %s' % addon.name), template, request.amo_user.email, [smart_str(addon.support_email)]) return redirect( reverse('users.support', args=[contribution.pk, 'refund-sent'])) return wizard.render(request, wizard.tpl('refund.html'), { 'contribut': addon, 'form': form })
def test_dir_rtl(self): """Make sure dir attr is set to 'rtl' for RTL language.""" translation.activate('he') self.request.LANGUAGE_CODE = 'he' html = jingo.render_to_string(self.request, self.template) eq_('rtl', pq(html)('html').attr['dir']) translation.deactivate()
def firefox_footer_links(ctx, channel='release', platform='all'): """ Outputs Firefox footer links :param ctx: context from calling template. :param channel: name of channel: 'release', 'beta' or 'alpha'. :param platform: Target platform: 'desktop', 'android', or 'ios'. :return: The footer links html. """ show_desktop = platform in ['all', 'desktop'] show_android = platform in ['all', 'android'] show_ios = platform in ['all', 'ios'] alt_channel = '' if channel == 'release' else channel # Gather data about the build for each platform builds = [] if show_android: builds = android_builds(channel, builds) data = { 'show_desktop': show_desktop, 'show_android': show_android, 'show_ios': show_ios, 'channel': alt_channel, 'builds': builds, } html = jingo.render_to_string(ctx['request'], 'firefox/includes/firefox-footer-links.html', data) return jinja2.Markup(html)
def test_dir_rtl(self): """Make sure dir attr is set to 'rtl' for RTL language.""" translation.activate("he") self.request.LANGUAGE_CODE = "he" html = jingo.render_to_string(self.request, self.template) eq_("rtl", pq(html)("html").attr["dir"]) translation.deactivate()
def rendered_content(self): template = self.template_name if 'user' not in self.context_data: self.context_data['user'] = self._request.user context_instance = self.resolve_context(self.context_data) # Gross, let's figure out if we're in the admin. if getattr(self._request, 'current_app', None) == 'admin': source = loader.render_to_string( template, RequestContext(self._request, context_instance)) template = jingo.get_env().from_string(source) # This interferes with our media() helper. if 'media' in self.context_data: del self.context_data['media'] # ``render_to_string`` only accepts a Template instance or a template name, # not a list. if isinstance(template, (list, tuple)): template = loader.select_template(template) if isinstance(template, Template): template = template.template return jingo.render_to_string(self._request, template, self.context_data)
def render(self, module_context="discovery"): if module_context == "home": self.platform = "ALL" self.version = None c = dict(promo=self, module_context=module_context, descriptions=self.get_descriptions()) if self.collection: c.update(addons=self.get_addons()) return jinja2.Markup(jingo.render_to_string(self.request, self.template, c))
def send_email(self, form): subject = PRESS_INQUIRY_EMAIL_SUBJECT sender = PRESS_INQUIRY_EMAIL_FROM to = PRESS_INQUIRY_EMAIL_TO msg = jingo.render_to_string(self.request, 'press/emails/press-inquiry.txt', form.cleaned_data) email = EmailMessage(subject, msg, sender, to) email.send()
def send_activation_email(self, request, link): """ Send an email to an Affiliates user to confirm that they consent to linking their account with a Facebook account. """ subject = _("Link your Firefox Affiliates account") message = jingo.render_to_string(request, "facebook/link_activation_email.html", {"link": link}) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [link.affiliates_user.email])
def video(ctx, *args, **kwargs): """ HTML5 Video tag helper. Accepted kwargs: prefix, w, h, autoplay, poster, preload, id Use like this: {{ video('http://example.com/myvid.mp4', 'http://example.com/myvid.webm', poster='http://example.com/myvid.jpg', w=640, h=360) }} You can also use a prefix like: {{ video('myvid.mp4', 'myvid.webm', prefix='http://example.com') }} The prefix does not apply to the poster attribute. Finally, MIME type detection happens by file extension. Supported: webm, mp4, ogv. If you want anything else, patches welcome. """ filetypes = ('webm', 'ogv', 'mp4') mime = { 'webm': 'video/webm', 'ogv': 'video/ogg; codecs="theora, vorbis"', 'mp4': 'video/mp4' } videos = {} for v in args: try: ext = v.rsplit('.', 1)[1].lower() except IndexError: # TODO: Perhaps we don't want to swallow this quietly in the future continue if ext not in filetypes: continue videos[ext] = (v if 'prefix' not in kwargs else urlparse.urljoin( kwargs['prefix'], v)) if not videos: return '' # defaults data = { 'w': 640, 'h': 360, 'autoplay': False, 'preload': False, 'id': 'htmlPlayer' } data.update(**kwargs) data.update(filetypes=filetypes, mime=mime, videos=videos) return jinja2.Markup( jingo.render_to_string(ctx['request'], 'mozorg/videotag.html', data))
def send_mail(request, template, subject, emails, context, perm_setting=None): # Link to our newfangled "Account Settings" page. manage_url = absolutify(reverse('account.settings')) + '#notifications' amo_send_mail(subject, jingo.render_to_string(request, template, context), recipient_list=emails, from_email=settings.NOBODY_EMAIL, use_blacklist=False, perm_setting=perm_setting, manage_url=manage_url, headers={'Reply-To': settings.MKT_REVIEWERS_EMAIL})
def download_button(ctx, id, format='large', build=None): locale = ctx['request'].locale def latest(locale): if build == 'aurora': return latest_aurora_version(locale) elif build == 'beta': return latest_beta_version(locale) else: return latest_version(locale) version, platforms = latest(locale) or latest('en-US') # Gather data about the build for each platform builds = [] for platform in ['Windows', 'Linux', 'OS X']: # Fallback to en-US if this platform/version isn't available # for the current locale _locale = locale if platform not in platforms: _locale = 'en-US' # Normalize the platform name platform = 'os_%s' % platform.lower().replace(' ', '') platform_pretty = { 'os_osx': 'Mac OS X', 'os_windows': 'Windows', 'os_linux': 'Linux' }[platform] # And generate all the info download_link = make_download_link('firefox', build, version, platform, locale) download_link_direct = make_download_link('firefox', build, version, platform, locale, True) builds.append({'platform': platform, 'platform_pretty': platform_pretty, 'download_link': download_link, 'download_link_direct': download_link_direct}) # Get the native name for current locale langs = product_details.languages locale_name = langs[locale]['native'] if locale in langs else locale data = { 'locale_name': locale_name, 'version': version, 'product': 'firefox', 'builds': builds, 'id': id } html = jingo.render_to_string(ctx['request'], 'mozorg/download_button_%s.html' % format, data) return jinja2.Markup(html)
def test_template_substitution_crash(): translation.activate('xx') env = get_env() # The localized string has the wrong variable name in it s = '{% trans string="heart" %}Broken {{ string }}{% endtrans %}' template = env.from_string(s) rendered = render_to_string(sentinel.request, template, {}) eq_(rendered, 'Broken heart')
def test_multi_feeds(self): """Ensure that multiple feeds are put into the page when set.""" feed_urls = (("/feed_one", "First Feed"), ("/feed_two", "Second Feed")) doc = pq(jingo.render_to_string(self.request, self.template, {"feeds": feed_urls})) feeds = doc('link[type="application/atom+xml"]') eq_(2, len(feeds)) eq_("First Feed", feeds[0].attrib["title"]) eq_("Second Feed", feeds[1].attrib["title"])
def video(ctx, *args, **kwargs): """ HTML5 Video tag helper. Accepted kwargs: prefix, w, h, autoplay, poster, preload, id Use like this: {{ video('http://example.com/myvid.mp4', 'http://example.com/myvid.webm', poster='http://example.com/myvid.jpg', w=640, h=360) }} You can also use a prefix like: {{ video('myvid.mp4', 'myvid.webm', prefix='http://example.com') }} The prefix does not apply to the poster attribute. Finally, MIME type detection happens by file extension. Supported: webm, mp4, ogv. If you want anything else, patches welcome. """ filetypes = ('webm', 'ogv', 'mp4') mime = {'webm': 'video/webm', 'ogv': 'video/ogg; codecs="theora, vorbis"', 'mp4': 'video/mp4'} videos = {} for v in args: try: ext = v.rsplit('.', 1)[1].lower() except IndexError: # TODO: Perhaps we don't want to swallow this quietly in the future continue if ext not in filetypes: continue videos[ext] = (v if 'prefix' not in kwargs else urlparse.urljoin(kwargs['prefix'], v)) if not videos: return '' # defaults data = { 'w': 640, 'h': 360, 'autoplay': False, 'preload': False, 'id': 'htmlPlayer' } data.update(**kwargs) data.update(filetypes=filetypes, mime=mime, videos=videos) return jinja2.Markup(jingo.render_to_string( ctx['request'], 'mozorg/videotag.html', data))
def helpful_vote(request, document_slug): """Vote for Helpful/Not Helpful document""" if 'revision_id' not in request.POST: return HttpResponseBadRequest() revision = get_object_or_404( Revision, id=smart_int(request.POST['revision_id'])) survey = None if revision.document.category == TEMPLATES_CATEGORY: return HttpResponseBadRequest() if not revision.has_voted(request): ua = request.META.get('HTTP_USER_AGENT', '')[:1000] # 1000 max_length vote = HelpfulVote(revision=revision, user_agent=ua) if 'helpful' in request.POST: vote.helpful = True message = _('Glad to hear it — thanks for the feedback!') else: message = _('Sorry to hear that.') # If user is over the limit, don't save but pretend everything is ok. if not request.limited: if request.user.is_authenticated(): vote.creator = request.user else: vote.anonymous_id = request.anonymous.anonymous_id vote.save() statsd.incr('wiki.vote') # Send a survey if flag is enabled and vote wasn't helpful. if 'helpful' not in request.POST: survey = jingo.render_to_string( request, 'wiki/includes/unhelpful_survey.html', {'vote_id': vote.id}) # Save vote metadata: referrer and search query (if available) for name in ['referrer', 'query', 'source']: val = request.POST.get(name) if val: vote.add_metadata(name, val) else: message = _('You already voted on this Article.') if request.is_ajax(): r = {'message': message} if survey: r.update(survey=survey) return HttpResponse(json.dumps(r)) return HttpResponseRedirect(revision.document.get_absolute_url())