Example #1
0
def view_item(request, submission, revision):
    """
    Shows a submitted item to web users. The ``slug`` is always ignored, but
    appears in the URLs for the sake of search engines. The revision, if
    specified >= 0 will show the particular revision of the item, rather than
    the latest revision (default).
    """
    create_hit(request, submission)
    permalink = settings.SPC['short_URL_root'] + str(submission.id) + '/' + \
                                                  str(revision.rev_id+1) + '/'
    latest_link = settings.SPC['short_URL_root'] + str(submission.id) + '/'


    pageviews = get_pagehits('submission', start_date=datetime.datetime.now()\
                        -datetime.timedelta(days=settings.SPC['hit_horizon']),
                        item_pk=submission.id)

    package_files = []
    if submission.sub_type == 'package':
        # Update the repo to the version required
        submission.fileset.checkout_revision(revision.hash_id)
        package_files = list(submission.fileset.list_iterator())


    return render_to_response('submission/item.html', {},
                              context_instance=RequestContext(request,
                                {'item': revision,
                                 'tag_list': revision.tags.all(),
                                 'permalink': permalink,
                                 'latest_link': latest_link,
                                 'pageviews': pageviews,
                                 'pageview_days': settings.SPC['hit_horizon'],
                                 'package_files': package_files,
                                }))
Example #2
0
def view_item(request, submission, revision):
    """
    Shows a submitted item to web users. The ``slug`` is always ignored, but
    appears in the URLs for the sake of search engines. The revision, if
    specified >= 0 will show the particular revision of the item, rather than
    the latest revision (default).
    """
    create_hit(request, submission)
    permalink = settings.SPC['short_URL_root'] + str(submission.id) + '/' + \
                                                  str(revision.rev_id+1) + '/'
    latest_link = settings.SPC['short_URL_root'] + str(submission.id) + '/'


    pageviews = get_pagehits('submission', start_date=datetime.datetime.now()\
                        -datetime.timedelta(days=settings.SPC['hit_horizon']),
                        item_pk=submission.id)

    package_files = []
    if submission.sub_type == 'package':
        # Update the repo to the version required
        submission.fileset.checkout_revision(revision.hash_id)
        package_files = submission.fileset.list_iterator()

    return render_to_response(
        'submission/item.html', {},
        context_instance=RequestContext(
            request, {
                'item': revision,
                'tag_list': revision.tags.all(),
                'permalink': permalink,
                'latest_link': latest_link,
                'pageviews': pageviews,
                'pageview_days': settings.SPC['hit_horizon'],
                'package_files': package_files,
            }))
Example #3
0
def download_submission(request, submission, revision):

    create_hit(request, submission, extra_info="download")
    if submission.sub_type == 'snippet':
        response = HttpResponse(mimetype="application/x-python")
        fname = submission.slug.replace('-', '_') + '.py'
        response["Content-Disposition"] = "attachment; filename=%s" % fname
        source = Site.objects.get_current().domain + \
                                                 submission.get_absolute_url()
        response.write('# Source: ' + source + '\n\n' + revision.item_code)
        return response

    if submission.sub_type == 'package':
        zip_dir = os.path.join(settings.SPC['ZIP_staging'], 'download')
        ensuredir(zip_dir)
        response = HttpResponse(mimetype="attachment; application/zip")
        zip_name = '%s-%d-%d.zip' % (submission.slug, submission.id,
                                     revision.rev_id_human)
        response['Content-Disposition'] = 'filename=%s' % zip_name
        full_zip_file = os.path.join(zip_dir, zip_name)
        if not os.path.exists(full_zip_file):

            # Set the repo's state to the state when that particular revision
            # existed
            out = submission.fileset.checkout_revision(revision.hash_id)
            if out:
                logger.info('Checked out revision "%s" for rev.id=%d' % \
                            (revision.hash_id, revision.id))
            else:
                logger.error('Could not checked out revision "%s" for '
                             'rev.id=%d' % (revision.hash_id, revision.id))
                return page_404_error(request, ('Could not create the ZIP '
                                                'file. This error has been '
                                                'reported.'))

            zip_f = zipfile.ZipFile(full_zip_file, "w", zipfile.ZIP_DEFLATED)
            src_dir = os.path.join(settings.SPC['storage_dir'],
                                   submission.fileset.repo_path)
            for path, dirs, files in os.walk(src_dir):
                for name in files:
                    file_name = os.path.join(path, name)
                    file_h = open(file_name, "r")
                    zip_f.write(file_name, file_name.partition(src_dir)[2])
                    file_h.close()

            for file_h in zip_f.filelist:
                file_h.create_system = 0

            zip_f.close()

            # Return the repo checkout back to the most recent revision
            out = submission.fileset.checkout_revision(submission.\
                                                       last_revision.hash_id)

        # Return the ZIP file
        zip_data = open(full_zip_file, "rb")
        response.write(zip_data.read())
        zip_data.close()
        return response
Example #4
0
def search(request):
    """
    Calls Haystack, but allows us to first log the search query
    """

    if request.GET['q'].strip() == '':
        return redirect(front_page)

    # Avoid duplicate logging if search request results in more than 1 page
    if 'page' not in request.GET:
        create_hit(request, 'haystack_search', request.GET['q'])
        logger.info('SEARCH [%s]: %s' % (get_IP_address(request),
                                         request.GET['q']))
    return SearchView().__call__(request)
Example #5
0
def search(request):
    """
    Calls Haystack, but allows us to first log the search query
    """

    if request.GET.get('q', '').strip() == '':
        return redirect(front_page)

    # Avoid duplicate logging if search request results in more than 1 page
    if 'page' not in request.GET:
        create_hit(request, 'haystack_search', request.GET['q'])
        logger.info('SEARCH [%s]: %s' % (get_IP_address(request),
                                         request.GET['q']))
    return SearchView().__call__(request)
Example #6
0
def profile_page(request, slug=None, user_id=None):
    """
    Shows the user's profile.
    """
    try:
        if user_id:
            the_user = models.User.objects.get(id=user_id)
            if the_user.is_active:
                return redirect(profile_page, the_user.profile.slug)
        elif slug is None:
            the_user = request.user
        else:
            the_user = models.User.objects.get(profile__slug=slug)
    except ObjectDoesNotExist:
        return page_404_error(request, 'No profile for that user.')

    # Don't show the profile for inactive (unvalidated) users
    if not (the_user.is_active):
        return page_404_error(request, "That user's profile isn't available.")

    # Items created by this user. Use the ``all()`` function first, to prevent
    # unvalidated submissions from showing
    all_revs = Revision.objects.all().filter(created_by=the_user)\
                                                    .order_by('-date_created')

    if the_user == request.user:
        no_entries = 'You have not submitted any entries to SciPy Central.'
    else:
        no_entries = 'This user has not submitted any entries to SciPy Central.'

    permalink = settings.SPC['short_URL_root'] + 'user/' + str(
        the_user.id) + '/'

    create_hit(request, the_user)
    return render_to_response(
        'person/profile.html', {},
        context_instance=RequestContext(
            request, {
                'theuser': the_user,
                'permalink': permalink,
                'entries': paginated_queryset(request, all_revs),
                'no_entries_message': no_entries,
            }))
Example #7
0
def profile_page(request, slug=None, user_id=None):
    """
    Shows the user's profile.
    """
    try:
        if user_id:
            the_user = models.User.objects.get(id=user_id)
            if the_user.is_active:
                return redirect(profile_page, the_user.profile.slug)
        elif slug is None:
            the_user = request.user
        else:
            the_user = models.User.objects.get(profile__slug=slug)
    except ObjectDoesNotExist:
        return page_404_error(request, 'No profile for that user.')

    # Don't show the profile for inactive (unvalidated) users
    if not(the_user.is_active):
        return page_404_error(request, "That user's profile isn't available.")


    # Items created by this user. Use the ``all()`` function first, to prevent
    # unvalidated submissions from showing
    all_revs = Revision.objects.all().filter(created_by=the_user)\
                                                    .order_by('-date_created')

    if the_user == request.user:
        no_entries = 'You have not submitted any entries to SciPy Central.'
    else:
        no_entries = 'This user has not submitted any entries to SciPy Central.'

    permalink = settings.SPC['short_URL_root'] + 'user/' + str(the_user.id) + '/'

    create_hit(request, the_user)
    return render_to_response('person/profile.html', {},
                context_instance=RequestContext(request,
                            {'theuser': the_user,
                             'permalink': permalink,
                             'entries':paginated_queryset(request, all_revs),
                             'no_entries_message': no_entries, }))
Example #8
0
def markup_help(request):
    create_hit(request, 'spc-markup-help')
    return render_to_response('pages/markup-help.html', {},
                              context_instance=RequestContext(request))
Example #9
0
def licence_page(request):
    create_hit(request, 'spc-about-licenses')
    return render_to_response('pages/about-licenses.html', {},
                              context_instance=RequestContext(request))
Example #10
0
def about_page(request):
    create_hit(request, 'spc-about-page')
    return render_to_response('pages/about-page.html', {},
                              context_instance=RequestContext(request))
Example #11
0
def download_submission(request, submission, revision):

    create_hit(request, submission, extra_info="download")
    if submission.sub_type == 'snippet':
        response = HttpResponse(mimetype="application/x-python")
        fname = submission.slug.replace('-', '_') + '.py'
        response["Content-Disposition"] = "attachment; filename=%s" % fname
        source = Site.objects.get_current().domain + \
                                                 submission.get_absolute_url()
        response.write('# Source: ' + source + '\n\n' + revision.item_code)
        return response

    if submission.sub_type == 'package':
        # Checkout the repo to the revision version
        checkout = submission.fileset.checkout_revision(revision.hash_id)
        if not checkout:
            logger.error('Could not checkout revision %s for rev.id %d' %
                         (revision.hash_id, revision.pk))
            return page_404_error('Could not create ZIP file. This error has '
                                  'been reported')
        logger.info('Checkout revision %s for rev.id %d' %
                    (revision.hash_id, revision.pk))

        package_data = StringIO()
        zipf = zipfile.ZipFile(package_data, 'w', zipfile.ZIP_DEFLATED)

        full_repo_path = os.path.abspath(
            os.path.join(settings.SPC['storage_dir'],
                         submission.fileset.repo_path))
        for path, dirs, files in os.walk(full_repo_path):
            # ignore revision backend dir
            if os.path.split(
                    path)[1] == '.' + settings.SPC['revisioning_backend']:
                for entry in dirs[:]:
                    dirs.remove(entry)
                continue

            for name in files:
                full_name = os.path.abspath(os.path.join(path, name))
                zipf.write(full_name, full_name.partition(full_repo_path)[2])

        for name in zipf.filelist:
            name.create_system = 0

        zipf.close()

        package_data.seek(0)

        response = HttpResponse(mimetype='attachment; application/zip')
        response['Content-Disposition'] = 'filename=%s-%d-%d.zip' \
                                          % (submission.slug, submission.pk,
                                             revision.rev_id_human)
        response.write(package_data.read())

        package_data.close()

        # checkout the repo to latest revision
        last_revision = submission.last_revision
        checkout = submission.fileset.checkout_revision(last_revision.hash_id)
        if not checkout:
            logger.error('Could not checkout out revision %s for  rev.id %d' %
                         (last_revision.hash_id, last_revision.pk))

        return response
Example #12
0
def download_submission(request, submission, revision):

    create_hit(request, submission, extra_info="download")
    if submission.sub_type == 'snippet':
        response = HttpResponse(mimetype="application/x-python")
        fname = submission.slug.replace('-', '_') + '.py'
        response["Content-Disposition"] = "attachment; filename=%s" % fname
        source = Site.objects.get_current().domain + \
                                                 submission.get_absolute_url()
        response.write('# Source: ' + source + '\n\n' + revision.item_code)
        return response

    if submission.sub_type == 'package':
        # Checkout the repo to the revision version
        checkout = submission.fileset.checkout_revision(revision.hash_id)
        if not checkout:
            logger.error('Could not checkout revision %s for rev.id %d' 
                         % (revision.hash_id, revision.pk))
            return page_404_error('Could not create ZIP file. This error has '
                                  'been reported')
        logger.info('Checkout revision %s for rev.id %d' % (revision.hash_id, revision.pk))

        package_data = StringIO()
        zipf = zipfile.ZipFile(package_data, 'w', zipfile.ZIP_DEFLATED)

        full_repo_path = os.path.abspath(os.path.join(settings.SPC['storage_dir'],
                                                      submission.fileset.repo_path))
        for path, dirs, files in os.walk(full_repo_path):
            # ignore revision backend dir
            if os.path.split(path)[1] == '.' + settings.SPC['revisioning_backend']:
                for entry in dirs[:]:
                    dirs.remove(entry)
                continue

            for name in files:
                full_name = os.path.abspath(os.path.join(path, name))
                zipf.write(full_name, full_name.partition(full_repo_path)[2])

        for name in zipf.filelist:
            name.create_system = 0

        zipf.close()

        package_data.seek(0)

        response = HttpResponse(mimetype='attachment; application/zip')
        response['Content-Disposition'] = 'filename=%s-%d-%d.zip' \
                                          % (submission.slug, submission.pk, 
                                             revision.rev_id_human)
        response.write(package_data.read())

        package_data.close()

        # checkout the repo to latest revision
        last_revision = submission.last_revision
        checkout = submission.fileset.checkout_revision(last_revision.hash_id)
        if not checkout:
            logger.error('Could not checkout out revision %s for  rev.id %d' 
                         % (last_revision.hash_id, last_revision.pk))

        return response
Example #13
0
def markup_help(request):
    create_hit(request, 'spc-markup-help')
    return render_to_response('pages/markup-help.html', {},
                              context_instance=RequestContext(request))
Example #14
0
def licence_page(request):
    create_hit(request, 'spc-about-licenses')
    return render_to_response('pages/about-licenses.html', {},
                              context_instance=RequestContext(request))
Example #15
0
def about_page(request):
    create_hit(request, 'spc-about-page')
    return render_to_response('pages/about-page.html', {},
                              context_instance=RequestContext(request))