def preview_snippet(request): """ Build a snippet using info from the POST parameters, and preview that snippet on a mock about:home page. """ try: template_id = int(request.POST.get('template_id', None)) except (TypeError, ValueError): return HttpResponseBadRequest() template = get_object_or_none(SnippetTemplate, id=template_id) data = request.POST.get('data', None) # Validate that data is JSON. try: json.loads(data) except (TypeError, ValueError): data = None # If your parameters are wrong, I have no sympathy for you. if data is None or template is None: return HttpResponseBadRequest() # Build a snippet that isn't saved so we can render it. snippet = Snippet(template=template, data=data) if strtobool(request.POST.get('activity_stream', 'false')): template_name = 'base/preview_as.jinja' preview_client = Client(5, 'Firefox', '57.0', 'default', 'default', 'en-US', 'release', 'default', 'default', 'default') else: template_name = 'base/preview.jinja' preview_client = Client(4, 'Firefox', '24.0', 'default', 'default', 'en-US', 'release', 'default', 'default', 'default') skip_boilerplate = request.POST.get('skip_boilerplate', 'false') skip_boilerplate = strtobool(skip_boilerplate) if skip_boilerplate: template_name = 'base/preview_without_shell.jinja' return render( request, template_name, { 'snippets_json': json.dumps([snippet.to_dict()]), 'client': preview_client, 'preview': True, 'current_firefox_major_version': util.current_firefox_major_version(), })
def fetch_json_snippets(request, **kwargs): statsd.incr('serve.json_snippets') client = Client(**kwargs) matching_snippets = (JSONSnippet.objects.filter( disabled=False).match_client(client).filter_by_available()) return HttpResponse(json.dumps(matching_snippets, cls=JSONSnippetEncoder), content_type='application/json')
def fetch_json_snippets(request, **kwargs): client = Client(**kwargs) matching_snippets = (JSONSnippet.cached_objects.filter( disabled=False).match_client(client).order_by( 'priority').filter_by_available()) return HttpResponse(json.dumps(matching_snippets, cls=SnippetEncoder), mimetype='application/json')
def fetch_snippet_pregen_bundle(request, **kwargs): statsd.incr('serve.bundle_pregen') client = Client(**kwargs) product = 'Firefox' channel = client.channel.lower() channel = next( (item for item in CHANNELS if channel.startswith(item)), None) or 'release' locale = client.locale.lower() # Distribution populated by client's distribution if it starts with # `experiment-`. Otherwise default to `default`. # # This is because non-Mozilla distributors of Firefox (e.g. Linux # Distributions) override the distribution field with their identification. # We want all Firefox clients to get the default bundle for the locale / # channel combination, unless they are part of an experiment. distribution = client.distribution.lower() if distribution.startswith('experiment-'): distribution = distribution[11:] else: distribution = 'default' filename = (f'{settings.MEDIA_BUNDLES_PREGEN_ROOT}/{product}/{channel}/' f'{locale}/{distribution}.json') full_url = urljoin(settings.CDN_URL or settings.SITE_URL, urlparse(default_storage.url(filename)).path) # Remove AWS S3 parameters full_url = full_url.split('?')[0] return HttpResponseRedirect(full_url)
def fetch_snippet_bundle(request, **kwargs): """ Return one of the following responses: - 200 with empty body when the bundle is empty - 302 to a bundle URL after generating it if not cached. """ statsd.incr('serve.snippets') client = Client(**kwargs) if client.startpage_version == 6: bundle = ASRSnippetBundle(client) else: bundle = SnippetBundle(client) if bundle.empty: statsd.incr('bundle.empty') if client.startpage_version == 6: # Return valid JSON for Activity Stream Router return HttpResponse(status=200, content='{}', content_type='application/json') # This is not a 204 because Activity Stream expects content, even if # it's empty. return HttpResponse(status=200, content='') elif bundle.cached: statsd.incr('bundle.cached') else: statsd.incr('bundle.generate') bundle.generate() return HttpResponseRedirect(bundle.url)
def fetch_pregenerated_snippets(request, **kwargs): """ Return a redirect to a pre-generated bundle of snippets for the client. If the bundle in question is expired, re-generate it. """ client = Client(**kwargs) bundle = SnippetBundle(client) if bundle.expired: bundle.generate() return HttpResponseRedirect(bundle.url)
def _build_client(self, **client_attrs): params = {'startpage_version': '4', 'name': 'Firefox', 'version': '23.0a1', 'appbuildid': '20130510041606', 'build_target': 'Darwin_Universal-gcc3', 'locale': 'en-US', 'channel': 'release', 'os_version': 'Darwin 10.8.0', 'distribution': 'default', 'distribution_version': 'default_version'} params.update(client_attrs) return Client(**params)
def fetch_snippets(request, **kwargs): client = Client(**kwargs) matching_snippets = (Snippet.cached_objects.filter( disabled=False).match_client(client).order_by( 'priority').select_related('template').filter_by_available()) return render( request, 'base/fetch_snippets.html', { 'snippets': matching_snippets, 'client': client, 'current_time': strftime('%Y-%m-%dT%H:%M:%SZ', gmtime()), 'locale': client.locale, })
def fetch_render_snippets(request, **kwargs): """Fetch snippets for the client and render them immediately.""" client = Client(**kwargs) matching_snippets = (Snippet.cached_objects.filter( disabled=False).match_client(client).order_by( 'priority').select_related('template').filter_by_available()) response = render(request, 'base/fetch_snippets.html', { 'snippets': matching_snippets, 'client': client, 'locale': client.locale, }) # ETag will be a hash of the response content. response['ETag'] = hashlib.sha256(response.content).hexdigest() patch_vary_headers(response, ['If-None-Match']) return response
def fetch_snippets(request, **kwargs): """ Return one of the following responses: - 204 with the bundle is empty - 302 to a bundle URL after generating it if not cached. """ statsd.incr('serve.snippets') client = Client(**kwargs) bundle = SnippetBundle(client) if bundle.empty: statsd.incr('bundle.empty') return HttpResponse(status=204) elif bundle.cached: statsd.incr('bundle.cached') else: statsd.incr('bundle.generate') bundle.generate() return HttpResponseRedirect(bundle.url)
def show_snippet(request, snippet_id, uuid=False): preview_client = Client('4', 'Firefox', '24.0', 'default', 'default', 'en-US', 'release', 'default', 'default', 'default') if uuid: snippet = get_object_or_404(Snippet, uuid=snippet_id) else: snippet = get_object_or_404(Snippet, pk=snippet_id) if snippet.disabled and not request.user.is_authenticated(): raise Http404() template = 'base/preview.jinja' if snippet.on_startpage_5: template = 'base/preview_as.jinja' return render(request, template, { 'snippets_json': json.dumps([snippet.to_dict()]), 'client': preview_client, 'preview': True, 'current_firefox_major_version': util.current_firefox_major_version(), })
def fetch_snippets(request, **kwargs): """ Return one of the following responses: - 204 with the bundle is empty - 302 to a bundle URL after generating it if not cached. """ statsd.incr('serve.snippets') client = Client(**kwargs) bundle = SnippetBundle(client) if bundle.empty: statsd.incr('bundle.empty') # This is not a 204 because Activity Stream expects content, even if # it's empty. return HttpResponse(status=200, content='') elif bundle.cached: statsd.incr('bundle.cached') else: statsd.incr('bundle.generate') bundle.generate() return HttpResponseRedirect(bundle.url)
def _client(self, **kwargs): client_kwargs = dict((key, '') for key in Client._fields) client_kwargs.update(kwargs) return Client(**client_kwargs)
else: return fetch_render_snippets(request, **kwargs) @cache_control(public=True, max_age=HTTP_MAX_AGE) @access_control(max_age=HTTP_MAX_AGE) def fetch_json_snippets(request, **kwargs): client = Client(**kwargs) matching_snippets = (JSONSnippet.cached_objects.filter( disabled=False).match_client(client).order_by( 'priority').filter_by_available()) return HttpResponse(json.dumps(matching_snippets, cls=SnippetEncoder), mimetype='application/json') PREVIEW_CLIENT = Client('4', 'Firefox', '24.0', 'default', 'default', 'en-US', 'release', 'default', 'default', 'default') @xframe_allow @csrf_exempt @permission_required('base.change_snippet') def preview_snippet(request): """ Build a snippet using info from the POST parameters, and preview that snippet on a mock about:home page. """ try: template_id = int(request.POST.get('template_id', None)) except (TypeError, ValueError): return HttpResponseBadRequest()
def _client(self, **kwargs): client_kwargs = dict((key, '') for key in Client._fields) client_kwargs['startpage_version'] = 4 client_kwargs.update(kwargs) return Client(**client_kwargs)