Пример #1
0
def view_event(request, event_id):
    """
    Display single Event page.
    """
    event = get_object_or_404(Event, pk=event_id)

    if not event.visible():
        raise PermissionDenied

    # Caching only responses for anonymous users, as that's the majority of
    # visits and those don't change that much.
    anonymous_user_cache = "anon_event_view_{}".format(event_id)

    if request.user and request.user.is_anonymous:
        cached_response = cache.get(anonymous_user_cache)
        if cached_response is not None:
            cached_response, cache_timestamp = cached_response
            if cache_timestamp <= event.modified_date:
                return cached_response

    entry_ids = Entry.all_visible.filter(event=event).values_list('id',
                                                                  flat=True)
    entries_map = Entry.prefetch_entries(
        entry_ids, show_unapproved=is_contributor(request))

    entries = sorted(entries_map.values(), key=lambda e: e.order)
    sources = list(event.sources_iterator())

    approval_msg = get_config('approval_message')
    if event.review_state == Event.REVIEW_APPROVED:
        approval_explanation = get_config('review_reviewed_explanation')
    elif event.review_state == Event.REVIEW_PENDING:
        approval_explanation = get_config('review_pending_explanation')
    else:
        approval_explanation = ''

    response = render(
        request, 'palanaeum/event.html', {
            'event': event,
            'entries': entries,
            'sources': sources,
            'approval_msg': approval_msg,
            'review_message': approval_explanation
        })

    if request.user and request.user.is_anonymous:
        cache.set(anonymous_user_cache, (response, event.modified_date))

    return response
Пример #2
0
def create_entry_for_snippet(request, snippet_id):
    """
    Create a new entry for snippet and go to edit page.
    If an entry already exists, just go to edit page.
    """
    snippet = get_object_or_404(Snippet, pk=snippet_id)

    if snippet.entry:
        messages.error(request, _("This snippet already has an entry assigned to it."))
        return redirect('edit_entry', entry_id=snippet.entry_id)

    entry = Entry()
    entry.created_by = request.user
    entry.event = snippet.source.event
    entry.date = entry.event.date
    entry.is_approved = False
    entry.set_order_last()
    entry.save()

    snippet.entry = entry
    snippet.save()
    logging.getLogger('palanaeum.staff').info("Assigning snippet %s to entry %s by %s", snippet.id, entry.id,
                                              request.user)
    return redirect('edit_entry', entry_id=snippet.entry_id)
Пример #3
0
def staff_cp_suggestions(request):
    source_suggestions = list(AudioSource.objects.filter(is_approved=False))
    source_suggestions.extend(ImageSource.objects.filter(is_approved=False))

    entry_suggestions_id = Entry.objects.filter(versions__is_approved=False).values_list('id', flat=True)
    entry_suggestions = Entry.prefetch_entries(entry_suggestions_id, show_unapproved=True).values()

    all_suggestions = defaultdict(lambda: defaultdict(list))
    for entry in entry_suggestions:
        all_suggestions[entry.event]['entries'].append(entry)

    for source in source_suggestions:
        all_suggestions[source.event]['sources'].append(source)

    return render(request, 'palanaeum/staff/staff_cp_suggestions.html',
                  {'sources': source_suggestions, 'entries': entry_suggestions,
                   'all_suggestions': dict(all_suggestions),
                   'page': 'suggestions'})
Пример #4
0
def show_collection(request, collection_id):
    """
    Check if user can view this collections and display it.
    """
    collection = get_object_or_404(UsersEntryCollection, pk=collection_id)

    if not (collection.public or collection.user == request.user or request.user.is_superuser):
        messages.error(request, _('You are not allowed to see this collection.'))
        return redirect('index')
    elif collection.user != request.user and request.user.is_superuser:
        messages.info(request, _('You are viewing a private collection as superuser.'))

    entries_ids = collection.entries.all().values_list('id', flat=True)
    entries = Entry.prefetch_entries(entries_ids)
    entries = [entries[eid] for eid in entries_ids]

    return render(request, 'palanaeum/collections/collection.html',
                  {'entries': entries, 'collection': collection,
                   'is_owner': collection.user == request.user})
Пример #5
0
def recent_entries(request):
    """
    Show recent entries, sorted by their assigned date, modification or creation date.
    """
    date_mode = request.GET.get('mode', 'created')

    if date_mode == 'modified':
        entries_ids = Entry.all_visible.order_by('-modified').values_list(
            'id', flat=True)
    elif date_mode == 'recorded':
        entries_ids = EntryVersion.newest.order_by('-entry_date', '-entry_id')\
            .values_list('entry_id', flat=True).distinct()
    else:  # Sort by creation date by default
        entries_ids = Entry.all_visible.order_by('-created').values_list(
            'id', flat=True)

    page_length = UserSettings.get_page_length(request)
    page_num = request.GET.get('page', '1')

    paginator = Paginator(entries_ids, page_length, orphans=page_length // 10)

    try:
        page = paginator.page(page_num)
    except PageNotAnInteger:
        page = paginator.page(1)
    except EmptyPage:
        page = paginator.page(paginator.num_pages)

    to_show = page_numbers_to_show(paginator, page.number)

    entries_map = Entry.prefetch_entries(
        page, show_unapproved=is_contributor(request))
    entries = [entries_map[entry_id] for entry_id in page]

    return render(
        request, 'palanaeum/recent_entries.html', {
            'page_numbers_to_show': to_show,
            'page': page,
            'entries': entries,
            'mode': date_mode,
            'page_params': 'mode={}'.format(date_mode)
        })
Пример #6
0
def create_entry_for_image_source(request, source_id):
    """
    Create an empty Entry for Image Source and assign it to the source.
    """
    img_source = get_object_or_404(ImageSource, pk=source_id)

    entry = Entry()
    entry.event = img_source.event
    entry.date = img_source.event.date
    entry.created_by = request.user
    entry.save()

    img_source.entry = entry
    img_source.save()

    messages.success(request, _('New entry for image source has been created and linked.'))
    logging.getLogger('palanaeum.staff').info("%s created new entry for image %s.", request.user, img_source.id)

    return redirect('edit_entry', entry_id=entry.id)
Пример #7
0
def paginate_search_results(request, search_results: list) -> tuple:
    """
    Preload a page of search results. Return loaded entries, paginator object and page object.
    """
    page_length = UserSettings.get_page_length(request)
    paginator = Paginator(search_results,
                          page_length,
                          orphans=page_length // 10)

    page_num = request.GET.get('page', '1')

    try:
        page = paginator.page(page_num)
    except PageNotAnInteger:
        page = paginator.page(1)
    except EmptyPage:
        page = paginator.page(paginator.num_pages)

    entries_ids = [entry[0] for entry in page]
    entries_map = Entry.prefetch_entries(entries_ids)

    entries = [(entries_map[entry_id], rank) for entry_id, rank in page]

    return entries, paginator, page
Пример #8
0
def save_entry(request):
    """
    Save received entry data.
    """
    if not is_contributor(request):
        raise AjaxException(_('Only contributors can perform this action.'))

    if 'entry_id' not in request.POST or not request.POST['entry_id']:
        entry = Entry()
        event = get_object_or_404(Event, pk=request.POST['event_id'])
        entry.event = event
        entry.date = event.date
        entry.created_by = request.user
        entry.is_approved = False
        entry.set_order_last()
        entry.save()
        entry_version = EntryVersion()
        entry_version.entry = entry
        entry_version.user = request.user
    else:
        entry_id = request.POST['entry_id']
        entry = get_object_or_404(Entry, pk=entry_id)
        event = entry.event
        entry_version = entry.versions.last()
        if entry_version is None:
            entry_version = EntryVersion()
            entry_version.entry = entry
            entry_version.user = request.user

    date_str = request.POST.get('date', event.date.strftime("%Y-%m-%d"))
    if date_str:
        try:
            entry.date = datetime.strptime(date_str, "%Y-%m-%d")
        except ValueError:
            raise AjaxException(_("Unsupported date format. Expected date format is: YYYY-MM-DD."))
    else:
        entry.date = event.date
    entry.paraphrased = bool(request.POST.get('paraphrased', False))
    entry.save()

    entry_version.archive_version()
    entry_version.note = request.POST.get('note', '')
    entry_version.user = request.user
    entry_version.is_approved = False
    entry_version.approved_by = None
    entry_version.approved_date = None
    entry_version.save()

    lines_id_mapping, deleted_lines_ids = _save_entry_lines(request, entry_version)

    # There is a bunch of stuff that only staff can do...
    if request.user.is_staff:
        _save_entry_url_sources(request, entry)
        tags_str = ", ".join(request.POST.getlist('tags[]'))
        entry.update_tags(tags_str)
        entry_version.approve(request.user)

    logging.getLogger('palanaeum.staff').info("Entry %s updated by %s", entry.id, request.user)

    return {'lines_id_mapping': lines_id_mapping, 'deleted_lines': deleted_lines_ids, 'entry_id': entry.id,
            'add_entry_url': reverse('event_add_entry', kwargs={'event_id': event.id})}