示例#1
0
def comments(page):
    objects = StoryComment.select(lambda x: x.story_published)
    filter_deleted = current_user.is_staff and request.args.get('deleted') == '1'
    if filter_deleted:
        objects = objects.filter(lambda x: x.deleted).order_by(StoryComment.last_deleted_at.desc())
    else:
        objects = objects.filter(lambda x: not x.deleted).order_by(StoryComment.id.desc())

    page_obj = Paginator(page, objects.count(), per_page=current_app.config['COMMENTS_COUNT']['stream'])
    objects = [('story', x) for x in page_obj.slice_or_404(objects)]

    comment_votes_cache = Story.bl.select_comment_votes(
        current_user._get_current_object(),
        [x[1].id for x in objects]
    ) if current_user.is_authenticated else {}

    return render_template(
        'stream/comments.html',
        page_title='Лента комментариев',
        tab='story',
        comments=objects,
        filter_deleted=filter_deleted,
        with_target_link=True,
        comment_votes_cache=comment_votes_cache,
        page_obj=page_obj,
        robots_noindex=True,
        **cached_lists([x[1].story.id for x in objects])
    )
示例#2
0
def ajax_author_dashboard(page):
    if not current_user.is_authenticated:
        abort(403)

    comments_list = StoryComment.bl.select_by_story_author(current_user)
    comments_list = comments_list.order_by(StoryComment.id.desc())
    comments_count = comments_list.count()

    paged = Paginator(
        number=page,
        total=comments_count,
        per_page=current_app.config['COMMENTS_COUNT']['author_page'],
    )  # TODO: restore orphans?
    comments = paged.slice(comments_list)
    if not comments and page != 1:
        abort(404)

    data = {
        'comments': comments,
        'page_obj': paged,
        'comments_short': True,
    }
    data.update(cached_lists([x.story.id for x in comments]))

    return jsonify({
        'success': True,
        'link': url_for('author.info', comments_page=page),
        'comments_count': comments_count,
        'comments_list': render_template('includes/story_comments_list.html', **data),
        'pagination': render_template('includes/comments_pagination_author_dashboard.html', **data),
    })
示例#3
0
def comments(page):
    objects = StoryComment.select(lambda x: x.story_published)
    filter_deleted = current_user.is_staff and request.args.get(
        'deleted') == '1'
    if filter_deleted:
        objects = objects.filter(lambda x: x.deleted).order_by(
            StoryComment.last_deleted_at.desc())
    else:
        objects = objects.filter(lambda x: not x.deleted).order_by(
            StoryComment.id.desc())

    page_obj = Paginator(
        page,
        objects.count(),
        per_page=current_app.config['COMMENTS_COUNT']['stream'])
    objects = [('story', x) for x in page_obj.slice_or_404(objects)]

    comment_votes_cache = Story.bl.select_comment_votes(
        current_user._get_current_object(),
        [x[1].id for x in objects]) if current_user.is_authenticated else {}

    return render_template('stream/comments.html',
                           page_title='Лента комментариев',
                           tab='story',
                           comments=objects,
                           filter_deleted=filter_deleted,
                           with_target_link=True,
                           comment_votes_cache=comment_votes_cache,
                           page_obj=page_obj,
                           robots_noindex=True,
                           **cached_lists([x[1].story.id for x in objects]))
示例#4
0
def tag_index(tag_name, page):
    iname = normalize_tag(tag_name)
    if not iname:
        abort(404)
    tag = Tag.get(iname=iname)
    if tag and tag.is_alias_for is not None:
        if tag.is_alias_for.is_alias_for:
            raise RuntimeError('Tag alias {} refers to another alias {}!'.format(tag.id, tag.is_alias_for.id))
        tag = tag.is_alias_for
    if not tag or tag.is_blacklisted:
        abort(404)
    if tag.iname != tag_name:
        return redirect(url_for('tags.tag_index', tag_name=tag.iname, page=page))

    objects = Story.bl.select_by_tag(tag, user=current_user._get_current_object())
    objects = objects.prefetch(Story.characters, Story.contributors, StoryContributor.user, Story.tags, StoryTag.tag, Tag.category)
    objects = objects.order_by(Story.first_published_at.desc(), Story.id.desc())

    page_obj = Paginator(page, objects.count(), per_page=current_app.config['STORIES_COUNT']['stream'])
    objects = page_obj.slice_or_404(objects)

    return render_template(
        'tags/tag_index.html',
        page_title=tag.name,
        tag=tag,
        aliases=[x.name for x in Tag.bl.get_aliases_for([tag])[tag.id]],
        category=tag.category,
        stories=objects,
        page_obj=page_obj,
        **cached_lists([x.id for x in objects])
    )
示例#5
0
def favorites(user_id, page):
    user = Author.get(id=user_id)
    if not user:
        abort(404)

    objects = select(x.story for x in Favorites if x.author == user)
    if not current_user.is_authenticated or (not current_user.is_staff and current_user.id != user.id):
        objects = objects.filter(lambda story: not story.draft and story.approved)
    objects = objects.without_distinct().order_by('-x.id')

    if current_user.is_authenticated and user.id == current_user.id:
        page_title = 'Мое избранное'
    else:
        page_title = 'Избранное автора %s' % user.username

    page_obj = Paginator(page, objects.count(), per_page=10)
    stories = page_obj.slice_or_404(objects)

    data = dict(
        stories=stories,
        page_obj=page_obj,
        page_title=page_title,
        author=user,
    )
    data.update(cached_lists([x.id for x in stories]))

    return render_template('favorites.html', **data)
示例#6
0
def stories(page):
    objects = Story.select_published().filter(lambda x: not x.pinned)
    objects = objects.order_by(Story.first_published_at.desc(),
                               Story.id.desc())
    objects = objects.prefetch(
        Story.characters,
        Story.contributors,
        StoryContributor.user,
        Story.tags,
        StoryTag.tag,
        Tag.category,
    )

    page_obj = IndexPaginator(
        page,
        total=objects.count(),
        per_page=current_app.config['STORIES_COUNT']['stream'],
    )
    objects = page_obj.slice(objects)

    if page == 1:
        pinned_stories = list(
            Story.select_published().filter(lambda x: x.pinned).order_by(
                Story.first_published_at.desc()))
        objects = pinned_stories + objects

    if not objects and page != 1:
        abort(404)

    return render_template('stream/stories.html',
                           page_title='Лента добавлений',
                           stories=objects,
                           page_obj=page_obj,
                           robots_noindex=True,
                           **cached_lists([x.id for x in objects]))
示例#7
0
def ajax_author_overview(user_id, page):
    author = Author.get(id=user_id)
    if not author:
        abort(404)

    comments_list = StoryComment.select(lambda x: x.author == author and not x.deleted and x.story_published)
    comments_list = comments_list.order_by(StoryComment.id.desc())
    comments_count = comments_list.count()

    paged = Paginator(
        number=page,
        total=comments_count,
        per_page=current_app.config['COMMENTS_COUNT']['author_page'],
    )  # TODO: restore orphans?
    comments = paged.slice(comments_list)
    if not comments and page != 1:
        abort(404)

    data = {
        'author': author,
        'comments': comments,
        'page_obj': paged,
        'comments_short': True,
    }
    data.update(cached_lists([x.story.id for x in comments]))

    return jsonify({
        'success': True,
        'link': url_for('author.info', user_id=author.id, comments_page=page),
        'comments_count': comments_count,
        'comments_list': render_template('includes/story_comments_list.html', **data),
        'pagination': render_template('includes/comments_pagination_author_overview.html', **data),
    })
示例#8
0
def comments_updates(params):
    comments_html = None
    if not current_user.is_authenticated:
        comments_html = current_app.cache.get('index_comments_html_guest')

    if not comments_html:
        # Старая логика, при которой могли появляться несколько комментариев одной сущности

        # story_comments = StoryComment.select(lambda x: x.story_published and not x.deleted).order_by(StoryComment.id.desc())
        # story_comments = story_comments[:current_app.config['COMMENTS_COUNT']['main']]

        # news_comments = NewsComment.select(lambda x: not x.deleted).order_by(NewsComment.id.desc())
        # news_comments = news_comments[:current_app.config['COMMENTS_COUNT']['main']]

        stories = select(x for x in Story
                         if x.published and x.last_comment_id > 0).order_by(
                             Story.last_comment_id.desc(
                             ))[:current_app.config['COMMENTS_COUNT']['main']]
        story_comment_ids = [x.last_comment_id for x in stories]
        story_comments = StoryComment.select(
            lambda x: x.id in story_comment_ids).order_by(StoryComment.id.desc(
            ))[:current_app.config['COMMENTS_COUNT']['main']]

        news_list = select(
            x for x in NewsItem
            if x.last_comment_id > 0).order_by(NewsItem.last_comment_id.desc(
            ))[:current_app.config['COMMENTS_COUNT']['main']]
        news_comment_ids = [x.last_comment_id for x in news_list]
        news_comments = NewsComment.select(
            lambda x: x.id in news_comment_ids).order_by(NewsComment.id.desc(
            ))[:current_app.config['COMMENTS_COUNT']['main']]

        comments = [('story', x) for x in story_comments]
        comments += [('news', x) for x in news_comments]
        comments.sort(key=lambda x: x[1].date, reverse=True)
        comments = comments[:current_app.config['COMMENTS_COUNT']['main']]

        data = dict(
            comments=comments,
            comments_short=True,
        )

        # Для счётчика непрочитанных комментариев
        data.update(cached_lists([x.id for x in stories]))

        comments_html = render_template('includes/comments_list.html', **data)

        if not current_user.is_authenticated:
            current_app.cache.set('index_comments_html_guest', comments_html,
                                  3600)

    return render_template('sidebar/comments_updates.html',
                           comments_html=comments_html)
示例#9
0
def bookmarks(page):
    objects = select(x.story for x in Bookmark if x.author.id == current_user.id).without_distinct().order_by('-x.id')
    page_obj = Paginator(page, objects.count(), per_page=10)
    stories = page_obj.slice_or_404(objects)

    data = dict(
        stories=stories,
        page_obj=page_obj,
        page_title='Прочитать позже',
    )
    data.update(cached_lists([x.id for x in stories]))

    return render_template('bookmarks.html', **data)
示例#10
0
def index():
    page_title = gettext('Index')

    stories = Story.select_published().filter(lambda x: not x.pinned)
    stories = stories.order_by(Story.first_published_at.desc(),
                               Story.id.desc())
    stories = stories.prefetch(
        Story.characters,
        Story.contributors,
        StoryContributor.user,
        Story.tags,
        StoryTag.tag,
        Tag.category,
    )
    page_obj = IndexPaginator(
        1,
        total=stories.count(),
        per_page=current_app.config['STORIES_COUNT']['stream'],
    )
    stories = page_obj.slice(stories)

    pinned_stories = list(
        Story.select_published().filter(lambda x: x.pinned).order_by(
            Story.first_published_at.desc()))
    stories = pinned_stories + list(stories)

    sidebar_blocks = []
    for block_name in current_app.config['INDEX_SIDEBAR_ORDER']:
        if isinstance(block_name, str):
            params = {}
        else:
            params = dict(block_name[1])
            block_name = block_name[0]

        block_html = current_app.index_sidebar[block_name](params)
        if block_html is not None:
            sidebar_blocks.append(block_html)

    data = {
        'stories': stories,
        'page_obj': page_obj,
        'page_title': page_title,
        'full_title': indextitle(),
        'site_description': sitedescription(),
        'sidebar_blocks': sidebar_blocks,
    }
    data.update(cached_lists([x.id for x in stories]))

    return render_template('index.html', **data)
示例#11
0
def submitted(page):
    if not current_user.is_staff:
        abort(403)
    objects = Story.select_submitted()
    page_obj = Paginator(page, objects.count(), per_page=10)
    stories = page_obj.slice_or_404(objects)

    data = dict(
        stories=stories,
        page_obj=page_obj,
        page_title='Новые поступления',
    )
    data.update(cached_lists([x.id for x in stories]))

    return render_template('submitted.html', **data)
示例#12
0
def stories(page):
    objects = Story.select_published().order_by(Story.first_published_at.desc(), Story.id.desc())
    objects = objects.prefetch(Story.characters, Story.contributors, StoryContributor.user, Story.tags, StoryTag.tag, Tag.category)

    page_obj = Paginator(page, objects.count(), per_page=current_app.config['STORIES_COUNT']['stream'])
    objects = page_obj.slice_or_404(objects)

    return render_template(
        'stream/stories.html',
        page_title='Лента добавлений',
        stories=objects,
        page_obj=page_obj,
        robots_noindex=True,
        **cached_lists([x.id for x in objects])
    )
示例#13
0
def chapters(page):
    objects = orm.select(c for c in Chapter if not c.draft and c.story_published and c.order != 1)
    objects = objects.prefetch(Chapter.text, Chapter.story, Story.contributors, StoryContributor.user)
    objects = objects.order_by(Chapter.first_published_at.desc(), Chapter.order.desc())

    page_obj = Paginator(page, objects.count(), per_page=current_app.config['CHAPTERS_COUNT']['stream'])
    objects = page_obj.slice_or_404(objects)

    return render_template(
        'stream/chapters.html',
        page_title='Лента обновлений',
        chapters=objects,
        page_obj=page_obj,
        robots_noindex=True,
        **cached_lists([x.story.id for x in objects])
    )
示例#14
0
def comments_updates(params):
    comments_html = None
    if not current_user.is_authenticated:
        comments_html = current_app.cache.get('index_comments_html_guest')

    if not comments_html:
        # Старая логика, при которой могли появляться несколько комментариев одной сущности

        # story_comments = StoryComment.select(lambda x: x.story_published and not x.deleted).order_by(StoryComment.id.desc())
        # story_comments = story_comments[:current_app.config['COMMENTS_COUNT']['main']]

        # news_comments = NewsComment.select(lambda x: not x.deleted).order_by(NewsComment.id.desc())
        # news_comments = news_comments[:current_app.config['COMMENTS_COUNT']['main']]

        stories = select(x for x in Story if x.published and x.last_comment_id > 0).order_by(Story.last_comment_id.desc())[:current_app.config['COMMENTS_COUNT']['main']]
        story_comment_ids = [x.last_comment_id for x in stories]
        story_comments = StoryComment.select(lambda x: x.id in story_comment_ids).order_by(StoryComment.id.desc())[:current_app.config['COMMENTS_COUNT']['main']]

        news_list = select(x for x in NewsItem if x.last_comment_id > 0).order_by(NewsItem.last_comment_id.desc())[:current_app.config['COMMENTS_COUNT']['main']]
        news_comment_ids = [x.last_comment_id for x in news_list]
        news_comments = NewsComment.select(lambda x: x.id in news_comment_ids).order_by(NewsComment.id.desc())[:current_app.config['COMMENTS_COUNT']['main']]

        comments = [('story', x) for x in story_comments]
        comments += [('news', x) for x in news_comments]
        comments.sort(key=lambda x: x[1].date, reverse=True)
        comments = comments[:current_app.config['COMMENTS_COUNT']['main']]

        data = dict(
            comments=comments,
            comments_short=True,
        )

        # Для счётчика непрочитанных комментариев
        data.update(cached_lists([x.id for x in stories]))

        comments_html = render_template(
            'includes/comments_list.html',
            **data
        )

        if not current_user.is_authenticated:
            current_app.cache.set('index_comments_html_guest', comments_html, 3600)

    return render_template('sidebar/comments_updates.html', comments_html=comments_html)
示例#15
0
def viewed(page):
    views = select(
        (x.story, min(x.id)) for x in StoryView if x.author.id == current_user.id and x.story
    )
    views = views.prefetch(StoryView.story, Story.characters, Story.contributors, StoryContributor.user, Story.tags, StoryTag.tag, Tag.category)
    views = views.order_by(-2)

    page_obj = Paginator(page, views.count(), per_page=10)

    stories = [x[0] for x in page_obj.slice_or_404(views)]

    return render_template(
        'viewed.html',
        stories=stories,
        page_obj=page_obj,
        page_title='Просмотренные рассказы',
        stories_detail_view=True,
        **cached_lists([x.id for x in stories])
    )
示例#16
0
def chapters(page):
    objects = orm.select(c for c in Chapter
                         if not c.draft and c.story_published and c.order != 1)
    objects = objects.prefetch(Chapter.text, Chapter.story, Story.contributors,
                               StoryContributor.user)
    objects = objects.order_by(Chapter.first_published_at.desc(),
                               Chapter.order.desc())

    page_obj = Paginator(
        page,
        objects.count(),
        per_page=current_app.config['CHAPTERS_COUNT']['stream'])
    objects = page_obj.slice_or_404(objects)

    return render_template('stream/chapters.html',
                           page_title='Лента обновлений',
                           chapters=objects,
                           page_obj=page_obj,
                           robots_noindex=True,
                           **cached_lists([x.story.id for x in objects]))
示例#17
0
def tag_index(tag_name, page):
    iname = normalize_tag(tag_name)
    if not iname:
        abort(404)
    tag = Tag.get(iname=iname)
    if tag and tag.is_alias_for is not None:
        if tag.is_alias_for.is_alias_for:
            raise RuntimeError(
                'Tag alias {} refers to another alias {}!'.format(
                    tag.id, tag.is_alias_for.id))
        tag = tag.is_alias_for
    if not tag or tag.is_blacklisted:
        abort(404)
    if tag.iname != tag_name:
        return redirect(
            url_for('tags.tag_index', tag_name=tag.iname, page=page))

    objects = Story.bl.select_by_tag(tag,
                                     user=current_user._get_current_object())
    objects = objects.prefetch(Story.characters, Story.contributors,
                               StoryContributor.user, Story.tags, StoryTag.tag,
                               Tag.category)
    objects = objects.order_by(Story.first_published_at.desc(),
                               Story.id.desc())

    page_obj = Paginator(
        page,
        objects.count(),
        per_page=current_app.config['STORIES_COUNT']['stream'])
    objects = page_obj.slice_or_404(objects)

    return render_template(
        'tags/tag_index.html',
        page_title=tag.name,
        tag=tag,
        aliases=[x.name for x in Tag.bl.get_aliases_for([tag])[tag.id]],
        category=tag.category,
        stories=objects,
        page_obj=page_obj,
        **cached_lists([x.id for x in objects]))
示例#18
0
def top(page):
    period = request.args.get('period')
    if period and period.isdigit():
        period = int(period)
    else:
        period = 0

    objects = Story.bl.select_top(period)
    objects = objects.prefetch(Story.characters, Story.contributors, StoryContributor.user, Story.tags, StoryTag.tag, Tag.category)

    page_obj = Paginator(
        page,
        objects.count(),
        per_page=current_app.config['STORIES_COUNT']['stream'],
        view_args={'period': period} if period > 0 else None,
    )

    stories = page_obj.slice_or_404(objects)

    if period == 7:
        page_title = gettext('Top stories for the week')
    elif period == 30:
        page_title = gettext('Top stories for the month')
    elif period == 365:
        page_title = gettext('Top stories for the year')
    elif period == 0:
        page_title = gettext('Top stories for all time')
    else:
        page_title = ngettext('Top stories in %(num)d day', 'Top stories in %(num)d days', period)

    data = dict(
        stories=stories,
        page_obj=page_obj,
        count=objects.count(),
        page_title=page_title,
        period=period,
    )
    data.update(cached_lists([x.id for x in stories]))

    return render_template('stream/stories_top.html', **data)
示例#19
0
def index():
    page_title = gettext('Index')

    categories = []  # list(Category.select())

    pinned_stories = list(
        Story.select_published().filter(lambda x: x.pinned).order_by(Story.first_published_at.desc())
    )

    stories = Story.select_published().filter(lambda x: not x.pinned).order_by(Story.first_published_at.desc())
    stories = stories.prefetch(Story.characters, Story.contributors, StoryContributor.user, Story.tags, StoryTag.tag, Tag.category)
    stories = stories[:max(1, current_app.config['STORIES_COUNT']['main'] - len(pinned_stories))]
    stories = pinned_stories + list(stories)

    sidebar_blocks = []
    for block_name in current_app.config['INDEX_SIDEBAR_ORDER']:
        if isinstance(block_name, str):
            params = {}
        else:
            params = dict(block_name[1])
            block_name = block_name[0]

        block_html = current_app.index_sidebar[block_name](params)
        if block_html is not None:
            sidebar_blocks.append(block_html)

    data = {
        'categories': categories,
        'stories': stories,
        'page_title': page_title,
        'full_title': indextitle(),
        'site_description': sitedescription(),
        'sidebar_blocks': sidebar_blocks,
    }
    data.update(cached_lists([x.id for x in stories]))

    return render_template('index.html', **data)
示例#20
0
def search_action(postform):
    from mini_fiction.apis.amsphinxql import SphinxError

    if not postform.validate():
        data = {
            'form': postform,
            'page_title': gettext('Search of stories'),
            'robots_noindex': True
        }
        return render_template('search.html', **data)

    try:
        page_current = int(request.args.get('page') or 1)
    except Exception:
        page_current = 1

    query = postform.data['q']
    limit = ((page_current - 1) * current_app.config['SPHINX_CONFIG']['limit'],
             current_app.config['SPHINX_CONFIG']['limit'])
    search_type = postform.data['type']
    sort_type = postform.data['sort']

    data = {
        'page_title': query.strip() or gettext('Search results'),
        'search_type': search_type,
        'robots_noindex': True
    }

    if search_type == 0:
        # if current_user.is_authenticated:
        #     excluded_categories = [x for x in current_user.excluded_categories_list if x not in postform.data['genre']]
        # else:
        excluded_categories = []
        try:
            raw_result, result = Story.bl.search(
                query,
                limit,
                int(sort_type),
                only_published=not current_user.is_authenticated
                or not current_user.is_staff,
                extended_syntax=postform.data.get('extsyntax'),
                character=postform.data['char'],
                # classifier=postform.data['cls'],
                tags=smart_split(postform.data.get('tags', '')),
                exclude_tags=smart_split(postform.data.get('exclude_tags',
                                                           '')),
                # category=postform.data['genre'],
                rating_id=postform.data['rating'],
                original=postform.data['original'],
                finished=postform.data['finished'],
                freezed=postform.data['freezed'],
                min_words=postform.data['min_words'],
                max_words=postform.data['max_words'],
                min_vote_total=current_app.config['MINIMUM_VOTES_FOR_VIEW']
                if int(sort_type) == 3 else None,
                excluded_categories=excluded_categories,
            )
        except SphinxError as exc:
            data = {
                'form': postform,
                'page_title': gettext('Search of stories'),
                'error': 'Кажется, есть синтаксическая ошибка в запросе',
                'error_type': 'syntax'
            }
            if current_app.config['DEBUG'] or current_user.is_superuser:
                data['error'] += ': ' + str(exc)
            return render_template('search.html', **data)

    else:
        try:
            raw_result, result = Chapter.bl.search(
                query,
                limit,
                int(sort_type),
                # TODO: сортировка и для глав тоже
                only_published=not current_user.is_authenticated
                or not current_user.is_staff,
                extended_syntax=postform.data.get('extsyntax'),
                character=postform.data['char'],
                # lassifier=postform.data['cls'],
                tags=smart_split(postform.data.get('tags', '')),
                exclude_tags=smart_split(postform.data.get('exclude_tags',
                                                           '')),
                # category=postform.data['genre'],
                rating_id=postform.data['rating'],
                original=postform.data['original'],
                finished=postform.data['finished'],
                freezed=postform.data['freezed'],
                min_words=postform.data['min_words'],
                max_words=postform.data['max_words'],
                min_vote_total=current_app.config['MINIMUM_VOTES_FOR_VIEW']
                if int(sort_type) == 3 else None,
            )
        except SphinxError as exc:
            data = {
                'form': postform,
                'page_title': gettext('Search of stories'),
                'error': 'Кажется, есть синтаксическая ошибка в запросе',
                'error_type': 'syntax'
            }
            if current_app.config['DEBUG'] or current_user.is_superuser:
                data['error'] += ': ' + str(exc)
            return render_template('search.html', **data)

    pagination = Paginator(
        number=page_current,
        total=int(raw_result['total'] or 0),
        per_page=current_app.config['SPHINX_CONFIG']['limit'])

    data['form'] = postform
    data['pagination'] = pagination
    data['total'] = int(raw_result['total_found'])
    data['result'] = result
    data['weights'] = [(x['id'], x['weight']) for x in raw_result['matches']]

    if search_type == 0:
        data.update(cached_lists([x.id for x in result]))
    else:
        data.update(cached_lists([x[0].story.id for x in result]))

    return render_template('search.html', **data)
示例#21
0
def search_action(postform):
    from mini_fiction.apis.amsphinxql import SphinxError

    if not postform.validate():
        data = {'form': postform, 'page_title': gettext('Search of stories'), 'robots_noindex': True}
        return render_template('search.html', **data)

    try:
        page_current = int(request.args.get('page') or 1)
    except Exception:
        page_current = 1

    query = postform.data['q']
    limit = ((page_current - 1) * current_app.config['SPHINX_CONFIG']['limit'], current_app.config['SPHINX_CONFIG']['limit'])
    search_type = postform.data['type']
    sort_type = postform.data['sort']

    data = {'page_title': query.strip() or gettext('Search results'), 'search_type': search_type, 'robots_noindex': True}

    if search_type == 0:
        # if current_user.is_authenticated:
        #     excluded_categories = [x for x in current_user.excluded_categories_list if x not in postform.data['genre']]
        # else:
        excluded_categories = []
        try:
            raw_result, result = Story.bl.search(
                query,
                limit,
                int(sort_type),
                only_published=not current_user.is_authenticated or not current_user.is_staff,
                extended_syntax=postform.data.get('extsyntax'),
                character=postform.data['char'],
                # classifier=postform.data['cls'],
                tags=smart_split(postform.data.get('tags', '')),
                exclude_tags=smart_split(postform.data.get('exclude_tags', '')),
                # category=postform.data['genre'],
                rating_id=postform.data['rating'],
                original=postform.data['original'],
                finished=postform.data['finished'],
                freezed=postform.data['freezed'],
                min_words=postform.data['min_words'],
                max_words=postform.data['max_words'],
                min_vote_total=current_app.config['MINIMUM_VOTES_FOR_VIEW'] if int(sort_type) == 3 else None,
                excluded_categories=excluded_categories,
            )
        except SphinxError as exc:
            data = {'form': postform, 'page_title': gettext('Search of stories'), 'error': 'Кажется, есть синтаксическая ошибка в запросе', 'error_type': 'syntax'}
            if current_app.config['DEBUG'] or current_user.is_superuser:
                data['error'] += ': ' + str(exc)
            return render_template('search.html', **data)

    else:
        try:
            raw_result, result = Chapter.bl.search(
                query,
                limit,
                int(sort_type),
                # TODO: сортировка и для глав тоже
                only_published=not current_user.is_authenticated or not current_user.is_staff,
                extended_syntax=postform.data.get('extsyntax'),
                character=postform.data['char'],
                # lassifier=postform.data['cls'],
                tags=smart_split(postform.data.get('tags', '')),
                exclude_tags=smart_split(postform.data.get('exclude_tags', '')),
                # category=postform.data['genre'],
                rating_id=postform.data['rating'],
                original=postform.data['original'],
                finished=postform.data['finished'],
                freezed=postform.data['freezed'],
                min_words=postform.data['min_words'],
                max_words=postform.data['max_words'],
                min_vote_total=current_app.config['MINIMUM_VOTES_FOR_VIEW'] if int(sort_type) == 3 else None,
            )
        except SphinxError as exc:
            data = {'form': postform, 'page_title': gettext('Search of stories'), 'error': 'Кажется, есть синтаксическая ошибка в запросе', 'error_type': 'syntax'}
            if current_app.config['DEBUG'] or current_user.is_superuser:
                data['error'] += ': ' + str(exc)
            return render_template('search.html', **data)

    pagination = Paginator(number=page_current, total=int(raw_result['total'] or 0), per_page=current_app.config['SPHINX_CONFIG']['limit'])

    data['form'] = postform
    data['pagination'] = pagination
    data['total'] = int(raw_result['total_found'])
    data['result'] = result
    data['weights'] = [(x['id'], x['weight']) for x in raw_result['matches']]

    if search_type == 0:
        data.update(cached_lists([x.id for x in result]))
    else:
        data.update(cached_lists([x[0].story.id for x in result]))

    return render_template('search.html', **data)
示例#22
0
def info(user_id=None, comments_page=1):
    if user_id is not None:
        try:
            user_id = int(user_id)
        except ValueError:
            abort(404)

    data = {}

    if user_id is None:
        if not current_user.is_authenticated:
            abort(403)
        author = current_user._get_current_object()
        comments_list = StoryComment.bl.select_by_story_author(author)
        comments_list = comments_list.order_by(StoryComment.id.desc())
        stories = list(author.stories)
        stories.sort(key=lambda x: x.first_published_at or x.date,
                     reverse=True)
        contributing_stories = list(author.contributing_stories)
        contributing_stories.sort(key=lambda x: x.first_published_at or x.date,
                                  reverse=True)

        data['all_views'] = Story.bl.get_all_views_for_author(author)

        data['page_title'] = gettext('My cabinet')
        template = 'author_dashboard.html'
    else:
        author = Author.get(id=user_id)
        if not author:
            abort(404)
        author_id = author.id  # обход утечки памяти
        comments_list = StoryComment.select(
            lambda x: x.author.id == author_id and not x.deleted and x.
            story_published)
        comments_list = comments_list.order_by(StoryComment.id.desc())
        data['page_title'] = gettext('Author: {author}').format(
            author=author.username)
        stories = list(Story.bl.select_by_author(author,
                                                 for_user=current_user))
        stories.sort(key=lambda x: x.first_published_at or x.date,
                     reverse=True)
        contributing_stories = None
        template = 'author_overview.html'

    comments_count = comments_list.count()
    series = list(author.series)
    paged = Paginator(
        number=comments_page,
        total=comments_count,
        per_page=current_app.config['COMMENTS_COUNT']['author_page'],
        page_arg_name='comments_page',
    )  # TODO: restore orphans?
    comments = paged.slice(comments_list)
    if not comments and comments_page != 1:
        abort(404)

    data.update({
        'author':
        author,
        'is_system_user':
        author.id == current_app.config['SYSTEM_USER_ID'],
        'sub':
        author.bl.get_stories_subscription(current_user._get_current_object()),
        'stories':
        stories,
        'contributing_stories':
        contributing_stories,
        'series':
        series,
        'comments':
        comments,
        'comments_count':
        comments_count,
        'comments_short':
        True,
        'page_obj':
        paged,
    })

    story_ids = set(x.id for x in stories)
    if contributing_stories:
        story_ids |= set(x.id for x in contributing_stories)
    story_ids |= set(x.story.id for x in comments)

    data.update(cached_lists(story_ids))

    return render_template(template, **data)
示例#23
0
def info(user_id=None, comments_page=1):
    if user_id is not None:
        try:
            user_id = int(user_id)
        except ValueError:
            abort(404)

    data = {}

    if user_id is None:
        if not current_user.is_authenticated:
            abort(403)
        author = current_user._get_current_object()
        comments_list = StoryComment.bl.select_by_story_author(author)
        comments_list = comments_list.order_by(StoryComment.id.desc())
        stories = list(author.stories)
        stories.sort(key=lambda x: x.first_published_at or x.date, reverse=True)
        contributing_stories = list(author.contributing_stories)
        contributing_stories.sort(key=lambda x: x.first_published_at or x.date, reverse=True)

        data['all_views'] = Story.bl.get_all_views_for_author(author)

        data['page_title'] = gettext('My cabinet')
        template = 'author_dashboard.html'
    else:
        author = Author.get(id=user_id)
        if not author:
            abort(404)
        author_id = author.id  # обход утечки памяти
        comments_list = StoryComment.select(lambda x: x.author.id == author_id and not x.deleted and x.story_published)
        comments_list = comments_list.order_by(StoryComment.id.desc())
        data['page_title'] = gettext('Author: {author}').format(author=author.username)
        stories = list(Story.bl.select_by_author(author, for_user=current_user))
        stories.sort(key=lambda x: x.first_published_at or x.date, reverse=True)
        contributing_stories = None
        template = 'author_overview.html'

    comments_count = comments_list.count()
    series = list(author.series)
    paged = Paginator(
        number=comments_page,
        total=comments_count,
        per_page=current_app.config['COMMENTS_COUNT']['author_page'],
        page_arg_name='comments_page',
    )  # TODO: restore orphans?
    comments = paged.slice(comments_list)
    if not comments and comments_page != 1:
        abort(404)

    data.update({
        'author': author,
        'is_system_user': author.id == current_app.config['SYSTEM_USER_ID'],
        'sub': author.bl.get_stories_subscription(current_user._get_current_object()),
        'stories': stories,
        'contributing_stories': contributing_stories,
        'series': series,
        'comments': comments,
        'comments_count': comments_count,
        'comments_short': True,
        'page_obj': paged,
    })

    story_ids = set(x.id for x in stories)
    if contributing_stories:
        story_ids |= set(x.id for x in contributing_stories)
    story_ids |= set(x.story.id for x in comments)

    data.update(cached_lists(story_ids))

    return render_template(template, **data)