Exemple #1
0
def all_processor_line_families(request):
    url = reverse('solonotebooks.cotizador.views_notebooks.processor_line')
    return HttpResponsePermanentRedirect(url)
Exemple #2
0
def document(request, document_slug, document_locale):
    """
    View a wiki document.
    """
    # PUT requests go to the write API.
    if request.method == 'PUT':
        if (not request.authkey and not request.user.is_authenticated()):
            raise PermissionDenied
        return _document_PUT(request, document_slug, document_locale)

    fallback_reason = None
    slug_dict = split_slug(document_slug)

    # Is there a document at this slug, in this locale?
    doc, fallback_reason = _get_doc_and_fallback_reason(
        document_locale, document_slug)

    if doc is None:
        # Possible the document once existed, but is now deleted.
        # If so, show that it was deleted.
        deletion_log_entries = DocumentDeletionLog.objects.filter(
            locale=document_locale, slug=document_slug)
        if deletion_log_entries.exists():
            return _document_deleted(request, deletion_log_entries)

        # We can throw a 404 immediately if the request type is HEAD.
        # TODO: take a shortcut if the document was found?
        if request.method == 'HEAD':
            raise Http404

        # Check if we should fall back to default locale.
        fallback_doc, fallback_reason, redirect_url = _default_locale_fallback(
            request, document_slug, document_locale)
        if fallback_doc is not None:
            doc = fallback_doc
            if redirect_url is not None:
                return redirect(redirect_url)
        else:
            # If a Document is not found, we may 404 immediately based on
            # request parameters.
            if (any([
                    request.GET.get(param, None)
                    for param in ('raw', 'include', 'nocreate')
            ]) or not request.user.is_authenticated()):
                raise Http404

            # The user may be trying to create a child page; if a parent exists
            # for this document, redirect them to the "Create" page
            # Otherwise, they could be trying to create a main level doc.
            create_url = _document_redirect_to_create(document_slug,
                                                      document_locale,
                                                      slug_dict)
            return redirect(create_url)

    # We found a Document. Now we need to figure out how we're going
    # to display it.

    # If we're a redirect, and redirecting hasn't been disabled, redirect.

    # Obey explicit redirect pages:
    # Don't redirect on redirect=no (like Wikipedia), so we can link from a
    # redirected-to-page back to a "Redirected from..." link, so you can edit
    # the redirect.
    redirect_url = (None if request.GET.get('redirect') == 'no' else
                    doc.get_redirect_url())

    if redirect_url and redirect_url != doc.get_absolute_url():
        url = urlparams(redirect_url, query_dict=request.GET)
        # TODO: Re-enable the link in this message after Django >1.5 upgrade
        # Redirected from <a href="%(url)s?redirect=no">%(url)s</a>
        messages.add_message(
            request,
            messages.WARNING,
            mark_safe(
                ugettext(u'Redirected from %(url)s') %
                {"url": request.build_absolute_uri(doc.get_absolute_url())}),
            extra_tags='wiki_redirect')
        return HttpResponsePermanentRedirect(url)

    # Read some request params to see what we're supposed to do.
    rendering_params = {}
    for param in ('raw', 'summary', 'include', 'edit_links'):
        rendering_params[param] = request.GET.get(param, False) is not False
    rendering_params['section'] = request.GET.get('section', None)
    rendering_params['render_raw_fallback'] = False
    rendering_params['use_rendered'] = kumascript.should_use_rendered(
        doc, request.GET)

    # Get us some HTML to play with.
    doc_html, ks_errors, render_raw_fallback = _get_html_and_errors(
        request, doc, rendering_params)
    rendering_params['render_raw_fallback'] = render_raw_fallback
    toc_html = None

    # Start parsing and applying filters.
    if not doc.is_template:
        if doc.show_toc and not rendering_params['raw']:
            toc_html = doc.get_toc_html()
        else:
            toc_html = None
        doc_html = _filter_doc_html(request, doc, doc_html, rendering_params)

    # If we're doing raw view, bail out to that now.
    if rendering_params['raw']:
        return _document_raw(request, doc, doc_html, rendering_params)

    # Get the SEO summary
    seo_summary = ''
    if not doc.is_template:
        seo_summary = doc.get_summary_text()

    # Get the additional title information, if necessary.
    seo_parent_title = _get_seo_parent_title(slug_dict, document_locale)

    # Retrieve pre-parsed content hunks
    if doc.is_template:
        quick_links_html, zone_subnav_html = None, None
        body_html = doc_html
    else:
        quick_links_html = doc.get_quick_links_html()
        zone_subnav_html = doc.get_zone_subnav_html()
        body_html = doc.get_body_html()

    share_text = ugettext('I learned about %(title)s on MDN.') % {
        "title": doc.title
    }

    contributors = doc.contributors
    contributors_count = len(contributors)
    has_contributors = contributors_count > 0

    # Bundle it all up and, finally, return.
    context = {
        'document': doc,
        'document_html': doc_html,
        'toc_html': toc_html,
        'quick_links_html': quick_links_html,
        'zone_subnav_html': zone_subnav_html,
        'body_html': body_html,
        'contributors': contributors,
        'contributors_count': contributors_count,
        'contributors_limit': 6,
        'has_contributors': has_contributors,
        'fallback_reason': fallback_reason,
        'kumascript_errors': ks_errors,
        'render_raw_fallback': rendering_params['render_raw_fallback'],
        'seo_summary': seo_summary,
        'seo_parent_title': seo_parent_title,
        'share_text': share_text,
        'search_url': referrer_url(request) or '',
    }
    response = render(request, 'wiki/document.html', context)
    return _set_common_headers(doc, rendering_params['section'], response)
def legacy_project_detail(request, username, project_slug):
    return HttpResponsePermanentRedirect(
        reverse(project_detail, kwargs={
            'project_slug': project_slug,
        }))
Exemple #4
0
    def form_valid(self,form):
        Blog = form.save(commit=False)
        Blog.author = self.request.user
        Blog.save()

        return HttpResponsePermanentRedirect(self.request.POST.get('next', '/'))
Exemple #5
0
def mindtouch_file_redirect(request, file_id, filename):
    """Redirect an old MindTouch file URL to a new kuma file URL."""
    attachment = get_object_or_404(Attachment, mindtouch_attachment_id=file_id)
    return HttpResponsePermanentRedirect(attachment.get_file_url())
Exemple #6
0
 def get(self, request, *args, **kwargs):
     path = kwargs.get('path', '')
     return HttpResponsePermanentRedirect('/p/' + path)
Exemple #7
0
 def redirect_trailing_period(request):
     response = get_response(request)
     if response.status_code == 404 and request.path.endswith("."):
         return HttpResponsePermanentRedirect(request.path.rstrip("."))
     return response
Exemple #8
0
def index(request):
    return HttpResponsePermanentRedirect('login/')
Exemple #9
0
 def get(self, request):
     logout(request)
     return HttpResponsePermanentRedirect(reverse('index'))
Exemple #10
0
def notebook_details(request, notebook_id):
    product = Product.objects.get(pk=notebook_id)
    url = reverse('solonotebooks.cotizador.views.product_details',
                  kwargs={'product_url': product.url})
    return HttpResponsePermanentRedirect(url)
Exemple #11
0
 def func_wrapper(request):
     if request.user.is_anonymous:
         return HttpResponsePermanentRedirect('/login/')
     else:
         return func(request)
Exemple #12
0
def store_notebook_redirect(request, store_notebook_id):
    url = reverse('solonotebooks.cotizador.views.store_product_redirect',
                  args=[store_notebook_id])
    return HttpResponsePermanentRedirect(url)
Exemple #13
0
def video_card_line(request):
    url = reverse('solonotebooks.cotizador.views_notebooks.video_card_line')
    return HttpResponsePermanentRedirect(url)
Exemple #14
0
def video_card_line_details(request, video_card_line_id):
    url = reverse(
        'solonotebooks.cotizador.views_notebooks.video_card_line_details',
        args=[video_card_line_id])
    url += concat_dictionary(request.GET)
    return HttpResponsePermanentRedirect(url)
Exemple #15
0
 def menu_item_redirect(self, request, pk, action):
     menu_pk = MenuItem.objects.select_related('menu').get(id=pk).menu.id
     return HttpResponsePermanentRedirect(r'../../%d/items/%s/%s/' %
                                          (menu_pk, pk, action))
Exemple #16
0
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.http import HttpResponsePermanentRedirect

urlpatterns = patterns(
    '',
    # Examples:
    url(r'^$', lambda r: HttpResponsePermanentRedirect('admin/')),
    url(r'^courses/', include('courses.urls')),
    url(r'^admin/', include(admin.site.urls)),
)
Exemple #17
0
 def menu_item_change_redirect(self, request, pk):
     menu_pk = MenuItem.objects.select_related('menu').get(id=pk).menu.id
     print(menu_pk)
     return HttpResponsePermanentRedirect(
         r'../../{}/change/'.format(menu_pk))
Exemple #18
0
def newRoot(request):
    try:
        grid_view = reverse('reports_grid_view')
    except NoReverseMatch:
        grid_view = '/grid'
    return HttpResponsePermanentRedirect(grid_view)
Exemple #19
0
from voting.views import vote_on_object

import mysite.account.views
import mysite.profile.views
import mysite.customs.api
import mysite.profile.api
import mysite.missions.svn.views
import mysite.missions.setup.views

from mysite.base.feeds import RecentActivityFeed


urlpatterns = patterns('',
                       # Okay, sometimes people link /, or /) because of bad linkification
                       # if so, just permit it as a redirect.
                       (r'^,$', lambda x: HttpResponsePermanentRedirect('/')),
                       (r'^\)$', lambda x: HttpResponsePermanentRedirect('/')),

                       (r'^\+meta/', 'mysite.base.views.meta'),

                       (r'^\+api/v1/profile/',
                        include(
                            mysite.profile.api.PortfolioEntryResource().urls)),

                       (r'^\+api/v1/delete_user_for_being_spammy/$',
                        mysite.profile.views.delete_user_for_being_spammy),

                       (r'^\+api/v1/customs/',
                        include(
                            mysite.customs.api.TrackerModelResource().urls)),
Exemple #20
0
def single_linky(request, guid):
    """
    Given a Perma ID, serve it up.
    """

    # Create a canonical version of guid (non-alphanumerics removed, hyphens every 4 characters, uppercase),
    # and forward to that if it's different from current guid.
    canonical_guid = Link.get_canonical_guid(guid)

    # We only do the redirect if the correctly-formatted GUID actually exists --
    # this prevents actual 404s from redirecting with weird formatting.
    link = get_object_or_404(Link.objects.all_with_deleted(),
                             guid=canonical_guid)

    if canonical_guid != guid:
        return HttpResponsePermanentRedirect(
            reverse('single_linky', args=[canonical_guid]))

    # Forward to replacement link if replacement_link is set.
    if link.replacement_link_id:
        return HttpResponseRedirect(
            reverse('single_linky', args=[link.replacement_link_id]))

    # If we get an unrecognized archive type (which could be an old type like 'live' or 'pdf'), forward to default version
    serve_type = request.GET.get('type')
    if serve_type is None:
        serve_type = 'source'
    elif serve_type not in valid_serve_types:
        return HttpResponsePermanentRedirect(
            reverse('single_linky', args=[canonical_guid]))

    # serve raw WARC
    if serve_type == 'warc_download':
        if request.user.can_view(link):
            response = StreamingHttpResponse(FileWrapper(
                default_storage.open(link.warc_storage_file()), 1024 * 8),
                                             content_type="application/gzip")
            response[
                'Content-Disposition'] = "attachment; filename=%s.warc.gz" % link.guid
            return response
        else:
            return HttpResponseForbidden('Private archive.')

    # Special handling for private links on Safari:
    # Safari won't let us set the auth cookie for the WARC_HOST domain inside the iframe, unless we've already set a
    # cookie on that domain outside the iframe. So do a redirect to WARC_HOST to set a cookie and then come back.
    # safari=1 in the query string indicates that the redirect has already happened.
    # See http://labs.fundbox.com/third-party-cookies-with-ie-at-2am/
    if link.is_private and not request.GET.get('safari'):
        user_agent = user_agent_parser.ParseUserAgent(
            request.META.get('HTTP_USER_AGENT', ''))
        if user_agent.get('family') == 'Safari':
            return redirect_to_login(
                request.build_absolute_uri(),
                "//%s%s" % (settings.WARC_HOST,
                            reverse('user_management_set_safari_cookie')))

    # handle requested capture type
    if serve_type == 'image':
        capture = link.screenshot_capture
    else:
        capture = link.primary_capture

        # if primary capture did not work, but screenshot did work, forward to screenshot
        if (
                not capture or capture.status != 'success'
        ) and link.screenshot_capture and link.screenshot_capture.status == 'success':
            return HttpResponseRedirect(
                reverse('single_linky', args=[guid]) + "?type=image")

    # If this record was just created by the current user, show them a new record message
    new_record = request.user.is_authenticated() and link.created_by_id == request.user.id and not link.user_deleted \
                 and link.creation_timestamp > timezone.now() - timedelta(seconds=300)

    # Provide the max upload size, in case the upload form is used
    max_size = settings.MAX_ARCHIVE_FILE_SIZE / 1024 / 1024

    protocol = "https://" if settings.SECURE_SSL_REDIRECT else "http://"

    if not link.submitted_description:
        link.submitted_description = "This is an archive of %s from %s" % (
            link.submitted_url,
            link.creation_timestamp.strftime("%A %d, %B %Y"))

    context = {
        'link': link,
        'can_view': request.user.can_view(link),
        'can_edit': request.user.can_edit(link),
        'can_delete': request.user.can_delete(link),
        'can_toggle_private': request.user.can_toggle_private(link),
        'capture': capture,
        'serve_type': serve_type,
        'new_record': new_record,
        'this_page': 'single_link',
        'max_size': max_size,
        'link_url': settings.HOST + '/' + link.guid,
        'protocol': protocol,
    }

    response = render(request, 'archive/single-link.html', context)
    date_header = format_date_time(mktime(link.creation_timestamp.timetuple()))
    link_memento = protocol + settings.HOST + '/' + link.guid
    link_timegate = protocol + settings.WARC_HOST + settings.TIMEGATE_WARC_ROUTE + '/' + link.safe_url
    link_timemap = protocol + settings.WARC_HOST + settings.WARC_ROUTE + '/timemap/*/' + link.safe_url
    response['Memento-Datetime'] = date_header

    link_memento_headers = '<{0}>; rel="original"; datetime="{1}",<{2}>; rel="memento"; datetime="{1}",<{3}>; rel="timegate",<{4}>; rel="timemap"; type="application/link-format"'
    response['Link'] = link_memento_headers.format(link.safe_url, date_header,
                                                   link_memento, link_timegate,
                                                   link_timemap)

    return response
Exemple #21
0
def ticketAuth(request, ticketId):
    """
    Used to authenticate an user via a ticket
    """
    try:
        data = TicketStore.get(ticketId, invalidate=True)

        try:
            # Extract ticket.data from ticket.data storage, and remove it if success
            username = data['username']
            groups = data['groups']
            auth = data['auth']
            realname = data['realname']
            servicePool = data['servicePool']
            password = cryptoManager().decrypt(data['password'])
            transport = data['transport']
        except Exception:
            logger.error('Ticket stored is not valid')
            raise InvalidUserException()

        auth = Authenticator.objects.get(uuid=auth)
        # If user does not exists in DB, create it right now
        # Add user to groups, if they exists...
        grps = []
        for g in groups:
            try:
                grps.append(auth.groups.get(uuid=g))
            except Exception:
                logger.debug('Group list has changed since ticket assignment')

        if len(grps) == 0:
            logger.error('Ticket has no valid groups')
            raise Exception('Invalid ticket authentication')

        usr = auth.getOrCreateUser(username, realname)
        if usr is None or State.isActive(usr.state) is False:  # If user is inactive, raise an exception
            raise InvalidUserException()

        # Add groups to user (replace existing groups)
        usr.groups.set(grps)

        # Force cookie generation
        webLogin(request, None, usr, password)

        request.user = usr  # Temporarily store this user as "authenticated" user, next requests will be done using session
        request.session['ticket'] = '1'  # Store that user access is done using ticket

        logger.debug("Service & transport: {}, {}".format(servicePool, transport))
        for v in DeployedService.objects.all():
            logger.debug("{} {}".format(v.uuid, v.name))

        # Check if servicePool is part of the ticket
        if servicePool is not None:
            # If service pool is in there, also is transport
            res = userServiceManager().getService(request.user, request.ip, 'F' + servicePool, transport, False)
            _x, userService, _x, transport, _x = res

            transportInstance = transport.getInstance()
            if transportInstance.ownLink is True:
                link = reverse('TransportOwnLink', args=('A' + userService.uuid, transport.uuid))
            else:
                link = html.udsAccessLink(request, 'A' + userService.uuid, transport.uuid)

            response = render(
                request,
                theme.template('simpleLauncher.html'),
                {
                    'link': link
                }
            )
        else:
            response = HttpResponsePermanentRedirect(reverse('uds.web.views.index'))

        # Now ensure uds cookie is at response
        getUDSCookie(request, response, True)
        return response
    except ServiceNotReadyError as e:
        return render(
            request,
            theme.template('service_not_ready.html'),
            {
                'fromLauncher': True,
                'code': e.code
            }
        )

    except TicketStore.InvalidTicket:
        return render(
            request,
            theme.template('simpleLauncherAlreadyLaunched.html')
        )
    except Authenticator.DoesNotExist:
        logger.error('Ticket has an non existing authenticator')
        return errors.exceptionView(request, InvalidUserException())
    except DeployedService.DoesNotExist:
        logger.error('Ticket has an invalid Service Pool')
        return errors.exceptionView(request, InvalidServiceException())
    except Exception as e:
        logger.exception('Exception')
        return errors.exceptionView(request, e)
Exemple #22
0
    def get(self, request):
        additional_headers = {}

        # Apache helpfully(!?) unescapes encoded hash characters. If we get one
        # we know that the browser sent a '%23' (or else would have stripped it
        # as a fragment identifier. We replace it with a '%23' so that our URI
        # canonicalisation doesn't get stuck in an endless redirect loop.
        doc_url = request.build_absolute_uri().replace('#', '%23')

        # Given a URL 'http://example.org/doc/foo.bar' we check whether 'foo',
        # has a type (ergo 'bar' is a format), and if not we assume that
        # 'foo.bar' is part of the URI
        for formats in (None, ()):
            uri, format, is_local = doc_backward(doc_url, formats)
            if uri and not IRI.match(uri):
                raise Http404("Invalid IRI")
            if not uri:
                logger.debug("Could not resolve URL to a URI: %r", doc_url)
                raise Http404("Could not resolve URL to a URI")
            types = self.get_types(uri)
            if types:
                break
            doc_url = doc_url.rsplit('.', 1)[0]
        else:
            logger.debug(
                "Resource has no type, so is probably not known in these parts: %r",
                uri)
            raise Http404(
                "Resource has no type, so is probably not known in these parts"
            )

        expected_doc_url = urlparse.urljoin(
            doc_url, doc_forward(uri, request, format=format, described=True))
        if self.check_canonical and expected_doc_url != doc_url:
            logger.debug(
                "Request for a non-canonical doc URL (%r) for %r, redirecting to %r",
                doc_url, uri, expected_doc_url)
            return HttpResponsePermanentRedirect(expected_doc_url)

        doc_uri = rdflib.URIRef(
            doc_forward(uri, request, format=None, described=True))

        self.context.update({
            'subject_uri': uri,
            'doc_uri': doc_uri,
            'format': format,
            'types': types,
            'show_follow_link': not is_local,
            'no_index': not is_local,
            'additional_headers': additional_headers,
        })

        subject_uri, doc_uri = self.context['subject_uri'], self.context[
            'doc_uri']
        types = self.context['types']

        queries, graph = [], rdflib.ConjunctiveGraph()
        for prefix, namespace_uri in NS.iteritems():
            graph.namespace_manager.bind(prefix, namespace_uri)

        graph += ((subject_uri, NS.rdf.type, t) for t in types)
        subject = Resource(subject_uri, graph, self.endpoint)

        for query in subject.get_queries():
            graph += self.endpoint.query(query)
            queries.append(query)

        licenses, datasets = set(), set()
        for graph_name in graph.subjects(NS['ov'].describes):
            graph.add((doc_uri, NS['dcterms'].source, graph_name))
            licenses.update(graph.objects(graph_name, NS['dcterms'].license))
            datasets.update(graph.objects(graph_name, NS['void'].inDataset))

        if len(licenses) == 1:
            for license_uri in licenses:
                graph.add((doc_uri, NS['dcterms'].license, license_uri))

        if not graph:
            logger.debug("Graph for %r was empty; 404ing", uri)
            raise Http404("Graph was empty")

        self.template_name = subject.template_name or self.template_name
        for template_override in self.template_overrides:
            tn, types = template_override[0], template_override[1:]
            if set(subject._graph.objects(
                    subject._identifier, NS.rdf.type)) & set(map(
                        expand, types)):
                self.template_name = tn
                break

        self.context.update({
            'graph':
            graph,
            'subject':
            subject,
            'licenses':
            [Resource(uri, graph, self.endpoint) for uri in licenses],
            'datasets':
            [Resource(uri, graph, self.endpoint) for uri in datasets],
            'queries':
            map(self.endpoint.normalize_query, queries),
            'template_name':
            self.template_name,
        })

        self.set_renderers()

        for doc_rdf_processor in self._doc_rdf_processors:
            additional_context = doc_rdf_processor(self.request, self.context)
            if additional_context:
                self.context.update(additional_context)

        # If no format was given explicitly (i.e. format parameter or
        # extension) we inspect the Content-Type header.
        if not format:
            if request.renderers:
                format = request.renderers[0].format
                expected_doc_url = doc_forward(uri,
                                               request,
                                               format=format,
                                               described=True)
        if expected_doc_url != doc_url:
            additional_headers['Content-Location'] = expected_doc_url

        # NOTE: This getattrs every atttr on subject, so would force
        # memoization on any cached attributes. We call it as late as
        # possible to make sure the graph won't change afterwards, making
        # those cached results incorrect.
        self.conneg += subject

        if self.context['format']:
            try:
                return self.render_to_format(format=format)
            except KeyError:
                raise Http404
        else:
            return self.render()
Exemple #23
0
def product_details(request, slug, product_id, form=None):
    """Product details page.

    The following variables are available to the template:

    product:
        The Product instance itself.

    is_visible:
        Whether the product is visible to regular users (for cases when an
        admin is previewing a product before publishing).

    form:
        The add-to-cart form.

    price_range:
        The PriceRange for the product including all discounts.

    undiscounted_price_range:
        The PriceRange excluding all discounts.

    discount:
        Either a Price instance equal to the discount value or None if no
        discount was available.

    local_price_range:
        The same PriceRange from price_range represented in user's local
        currency. The value will be None if exchange rate is not available or
        the local currency is the same as site's default currency.
    """
    products = products_with_details(user=request.user)
    product = get_object_or_404(products, id=product_id)
    if product.get_slug() != slug:
        return HttpResponsePermanentRedirect(product.get_absolute_url())
    today = datetime.date.today()
    is_visible = (product.available_on is None
                  or product.available_on <= today)
    if form is None:
        form = handle_cart_form(request, product, create_cart=False)[0]
    availability = get_availability(product,
                                    discounts=request.discounts,
                                    local_currency=request.currency)
    product_images = get_product_images(product)
    variant_picker_data = get_variant_picker_data(product, request.discounts,
                                                  request.currency)
    product_attributes = get_product_attributes_data(product)
    # show_variant_picker determines if variant picker is used or select input
    show_variant_picker = all([v.attributes for v in product.variants.all()])
    json_ld_data = product_json_ld(product, product_attributes)
    return TemplateResponse(
        request, 'product/details.html', {
            'is_visible':
            is_visible,
            'form':
            form,
            'availability':
            availability,
            'product':
            product,
            'product_attributes':
            product_attributes,
            'product_images':
            product_images,
            'show_variant_picker':
            show_variant_picker,
            'variant_picker_data':
            json.dumps(variant_picker_data, default=serialize_decimal),
            'json_ld_product_data':
            json.dumps(json_ld_data, default=serialize_decimal)
        })
Exemple #24
0
def home_redirect(request):
    return HttpResponsePermanentRedirect("/")
Exemple #25
0
     problem.problem_submit,
     name='problem_submit'),
 url(
     r'^/rank/',
     paged_list_view(ranked_submission.RankedSubmissions,
                     'ranked_submissions')),
 url(
     r'^/submissions/',
     paged_list_view(submission.ProblemSubmissions,
                     'chronological_submissions')),
 url(
     r'^/submissions/(?P<user>\w+)/',
     paged_list_view(submission.UserProblemSubmissions,
                     'user_submissions')),
 url(
     r'^/$', lambda _, problem: HttpResponsePermanentRedirect(
         reverse('problem_detail', args=[problem]))),
 url(r'^/test_data$',
     ProblemDataView.as_view(),
     name='problem_data'),
 url(r'^/test_data/init$',
     problem_init_view,
     name='problem_data_init'),
 url(r'^/test_data/diff$',
     ProblemSubmissionDiff.as_view(),
     name='problem_submission_diff'),
 url(r'^/data/(?P<path>.+)$',
     problem_data_file,
     name='problem_data_file'),
 url(r'^/tickets$',
     ticket.ProblemTicketListView.as_view(),
     name='problem_ticket_list'),
Exemple #26
0
def redirect_to_ad(request, slug):
    ad = get_object_or_404(Ad, slug=slug)
    ad.clicked()
    if not ad.link:
        raise Http404('')
    return HttpResponsePermanentRedirect(ad.link)
Exemple #27
0
def view_video(request, video_id, slug=None):
    video = get_object_or_404(models.Video,
                              pk=video_id,
                              site=request.sitelocation().site)

    if video.status != models.VIDEO_STATUS_ACTIVE and \
            not request.user_is_admin():
        raise Http404

    if slug is not None and request.path != video.get_absolute_url():
        return HttpResponsePermanentRedirect(video.get_absolute_url())

    context = {
        'current_video': video,
        # set edit_video_form to True if the user is an admin for
        # backwards-compatibility
        'edit_video_form': request.user_is_admin()
    }

    if video.categories.count():
        category_obj = None
        referrer = request.META.get('HTTP_REFERER')
        host = request.META.get('HTTP_HOST')
        if referrer and host:
            if referrer.startswith('http://') or \
                    referrer.startswith('https://'):
                referrer = referrer[referrer.index('://') + 3:]
            if referrer.startswith(host):
                referrer = referrer[len(host):]
                try:
                    view, args, kwargs = resolve(referrer)
                except Resolver404:
                    pass
                else:
                    if view == listing_views.category:
                        try:
                            category_obj = models.Category.objects.get(
                                slug=args[0], site=request.sitelocation().site)
                        except models.Category.DoesNotExist:
                            pass
                        else:
                            if not video.categories.filter(
                                    pk=category_obj.pk).count():
                                category_obj = None

        if category_obj is None:
            category_obj = video.categories.all()[0]

        context['category'] = category_obj
        context['popular_videos'] = models.Video.objects.popular_since(
            datetime.timedelta(days=7),
            sitelocation=request.sitelocation(),
            status=models.VIDEO_STATUS_ACTIVE,
            categories__pk=category_obj.pk)
    else:
        context['popular_videos'] = models.Video.objects.popular_since(
            datetime.timedelta(days=7),
            sitelocation=request.sitelocation(),
            status=models.VIDEO_STATUS_ACTIVE)

    if video.voting_enabled():
        import voting
        user_can_vote = True
        if request.user.is_authenticated():
            MAX_VOTES_PER_CATEGORY = getattr(settings,
                                             'MAX_VOTES_PER_CATEGORY', 3)
            max_votes = video.categories.filter(
                contest_mode__isnull=False).count() * MAX_VOTES_PER_CATEGORY
            votes = voting.models.Vote.objects.filter(
                content_type=ContentType.objects.get_for_model(models.Video),
                user=request.user).count()
            if votes >= max_votes:
                user_can_vote = False
        context['user_can_vote'] = user_can_vote
        if user_can_vote:
            if 'category' in context and context['category'].contest_mode:
                context['contest_category'] = context['category']
            else:
                context['contest_category'] = video.categories.filter(
                    contest_mode__isnull=False)[0]

    if request.sitelocation().playlists_enabled:
        # showing playlists
        if request.user.is_authenticated():
            if request.user_is_admin() or \
                    request.sitelocation().playlists_enabled == 1:
                # user can add videos to playlists
                context['playlists'] = Playlist.objects.filter(
                    user=request.user)

        if request.user_is_admin():
            # show all playlists
            context['playlistitem_set'] = video.playlistitem_set.all()
        elif request.user.is_authenticated():
            # public playlists or my playlists
            context['playlistitem_set'] = video.playlistitem_set.filter(
                Q(playlist__status=PLAYLIST_STATUS_PUBLIC)
                | Q(playlist__user=request.user))
        else:
            # just public playlists
            context['playlistitem_set'] = video.playlistitem_set.filter(
                playlist__status=PLAYLIST_STATUS_PUBLIC)

        if 'playlist' in request.GET:
            try:
                playlist = Playlist.objects.get(pk=request.GET['playlist'])
            except (Playlist.DoesNotExist, ValueError):
                pass
            else:
                if playlist.status == PLAYLIST_STATUS_PUBLIC or \
                        request.user_is_admin() or \
                        request.user.is_authenticated() and \
                        playlist.user_id == request.user.pk:
                    try:
                        context['playlistitem'] = video.playlistitem_set.get(
                            playlist=playlist)
                    except PlaylistItem.DoesNotExist:
                        pass

    models.Watch.add(request, video)

    return render_to_response('localtv/view_video.html',
                              context,
                              context_instance=RequestContext(request))
Exemple #28
0
def legacy_build_list(request, username=None, project_slug=None, tag=None):
    return HttpResponsePermanentRedirect(
        reverse(build_list, kwargs={
            'project_slug': project_slug,
        }))
Exemple #29
0
def oldindex(request):
    "Fix for old url of old rsr front that has become the akvo home page"
    return HttpResponsePermanentRedirect('/')
Exemple #30
0
def processor_line_family_details(request, processor_line_family_id):
    url = reverse(
        'solonotebooks.cotizador.views_notebooks.processor_line_details',
        args=[processor_line_family_id])
    url += concat_dictionary(request.GET)
    return HttpResponsePermanentRedirect(url)