예제 #1
0
def test_pageurl():
    purl = paginate.PageURL("/articles", {})
    eq_(purl(2), "/articles?page=2")
    purl = paginate.PageURL("/articles", {"foo": "bar"})
    eq_(purl(2), "/articles?foo=bar&page=2")
    params = {"foo": "bar", "page": "1"}
    purl = paginate.PageURL("/articles", params)
    eq_(purl(2), "/articles?foo=bar&page=2")
예제 #2
0
def report_list(request):
    current_status = status_filters[request.matched_route.name]
    current_page = int(request.GET.get("page", 1))
    reports = Session.query(PromptReport).order_by(
        PromptReport.created.desc(),
    ).filter(PromptReport.status == current_status).options(
        joinedload(PromptReport.reporting_user),
        joinedload(PromptReport.reported_user),
    ).limit(25).offset((current_page-1)*25).all()
    # 404 on empty pages.
    if current_page!=1 and len(reports)==0:
        raise HTTPNotFound
    report_count = Session.query(func.count('*')).select_from(PromptReport).filter(PromptReport.status == current_status).scalar()
    paginator = paginate.Page(
        [],
        page=current_page,
        items_per_page=25,
        item_count=report_count,
        url=paginate.PageURL(
            request.route_path("admin_report_list"),
            { "page": current_page }
        ),
    )
    return {
        "PromptReport": PromptReport,
        "reports": reports,
        "paginator": paginator,
        "prompt_categories": prompt_categories,
        "prompt_levels": prompt_levels,
    }
예제 #3
0
파일: main.py 프로젝트: opaquebox/TAnon
def view_log(chat=None):

    try:
        log = g.mysql.query(Log).filter(Log.url == chat).one()
    except NoResultFound:
        abort(404)

    current_page = request.args.get('page') or log.page_count
    mode = request.args.get('mode') or 'normal'

    try:
        log_page = g.mysql.query(LogPage).filter(
            and_(LogPage.log_id == log.id,
                 LogPage.number == current_page)).one()
    except NoResultFound:
        abort(404)

    url_generator = paginate.PageURL(url_for('view_log', chat=chat),
                                     {'page': current_page})

    # It's only one row per page and we want to fetch them via both log id and
    # page number rather than slicing, so we'll just give it an empty list and
    # override the count.
    paginator = paginate.Page([],
                              page=current_page,
                              items_per_page=1,
                              item_count=log.page_count,
                              url=url_generator)

    # Pages end with a line break, so the last line is blank.
    lines = log_page.content.split('\n')[0:-1]
    lines = filter(lambda x: x is not None,
                   map(lambda _: parse_line(_, 0), lines))

    for line in lines:
        line['datetime'] = datetime.datetime.fromtimestamp(line['timestamp'])

    return render_template(
        'log.html',
        chat=chat,
        lines=lines,
        current_page=current_page,
        mode=mode,
        paginator=paginator,
    )
예제 #4
0
def chat_list(request):

    current_page = int(request.GET.get("page", 1))

    if request.matched_route.name.startswith("chat_list_unanswered"):
        current_status = "unanswered"
    elif request.matched_route.name.startswith("chat_list_ongoing"):
        current_status = "ongoing"
    elif request.matched_route.name.startswith("chat_list_ended"):
        current_status = "ended"
    else:
        current_status = None

    if request.matched_route.name.startswith("chat_list_label"):
        current_label = request.matchdict["label"].lower().strip().replace(
            " ", "_")
        if current_label != request.matchdict["label"]:
            raise HTTPFound(
                request.route_path("chat_list_label", label=current_label))
    else:
        current_label = None

    chats = Session.query(ChatUser, Chat, Message).join(Chat).outerjoin(
        Message,
        Message.id == Session.query(func.min(Message.id), ).filter(
            Message.chat_id == Chat.id, ).correlate(Chat),
    ).filter(ChatUser.user_id == request.user.id, )

    chat_count = Session.query(func.count('*')).select_from(ChatUser).filter(
        ChatUser.user_id == request.user.id, )

    if current_status == "unanswered":
        chats = chats.filter(
            and_(
                Chat.last_user_id is not None,
                Chat.last_user_id != request.user.id,
            ))
        chat_count = chat_count.join(Chat).filter(
            and_(
                Chat.last_user_id is not None,
                Chat.last_user_id != request.user.id,
            ))
    elif current_status is not None:
        chats = chats.filter(Chat.status == current_status)
        chat_count = chat_count.join(Chat).filter(
            Chat.status == current_status)

    if current_label is not None:
        label_array = cast([current_label], ARRAY(Unicode(500)))
        chats = chats.filter(ChatUser.labels.contains(label_array))
        chat_count = chat_count.filter(ChatUser.labels.contains(label_array))

    chats = chats.order_by(Chat.updated.desc()).limit(25).offset(
        (current_page - 1) * 25).all()

    # 404 on empty pages, unless it's the first page.
    if current_page != 1 and len(chats) == 0:
        raise HTTPNotFound

    chat_count = chat_count.scalar()

    if request.matchdict.get("fmt") == "json":
        return render_to_response("json", {
            "chats": [{
                "chat_user": chat_user,
                "chat": chat,
                "prompt": prompt,
            } for chat_user, chat, prompt in chats],
            "chat_count":
            chat_count,
        },
                                  request=request)

    paginator = paginate.Page(
        [],
        page=current_page,
        items_per_page=25,
        item_count=chat_count,
        url=paginate.PageURL(
            request.route_path(request.matched_route.name,
                               label=current_label), {"page": current_page}),
    )

    labels = (Session.query(
        func.unnest(ChatUser.labels),
        func.count("*")).filter(ChatUser.user_id == request.user.id).group_by(
            func.unnest(ChatUser.labels)).order_by(
                func.count("*").desc(),
                func.unnest(ChatUser.labels).asc()).all())

    template = "layout2/chat_list.mako" if request.user.layout_version == 2 else "chat_list.mako"
    return render_to_response(template, {
        "chats": chats,
        "paginator": paginator,
        "labels": labels,
        "current_status": current_status,
        "current_label": current_label,
        "symbols": symbols,
    },
                              request=request)
예제 #5
0
def chat(request):

    try:
        chat = Session.query(Chat).filter(
            Chat.url == request.matchdict["url"]).one()
    except NoResultFound:
        raise HTTPNotFound

    own_chat_user = None
    if request.user is not None and request.user.status != "banned":
        try:
            own_chat_user = Session.query(ChatUser).filter(
                and_(
                    ChatUser.chat_id == chat.id,
                    ChatUser.user_id == request.user.id,
                )).one()
        except NoResultFound:
            pass

    continuable = chat.status == "ongoing" and own_chat_user is not None

    # If we can continue the chat and there isn't a page number, show the
    # full chat window.
    if ("page" not in request.GET and continuable):

        own_chat_user.visited = datetime.datetime.now()

        # Test if we came here from the homepage, for automatically resuming the search.
        from_homepage = ("HTTP_REFERER" in request.environ
                         and request.environ["HTTP_REFERER"]
                         == request.route_url("home"))

        message_count = Session.query(
            func.count('*')).select_from(Message).filter(
                Message.chat_id == chat.id, ).scalar()

        if message_count < 30:

            prompt = None
            messages = Session.query(Message).filter(
                Message.chat_id == chat.id, ).order_by(Message.id.asc()).all()

        else:

            prompt = Session.query(Message).filter(
                Message.chat_id == chat.id, ).order_by(Message.id.asc())
            prompt = prompt.options(joinedload(Message.user))
            prompt = prompt.first()

            messages = Session.query(Message).filter(
                Message.chat_id == chat.id, ).order_by(
                    Message.id.desc()).limit(25)
            messages = messages.options(joinedload(Message.user))
            messages = messages.all()
            messages.reverse()

        if request.matchdict.get("fmt") == "json":
            return render_to_response("json", {
                "chat": chat,
                "chat_user": own_chat_user,
                "message_count": message_count,
                "prompt": prompt,
                "messages": messages,
            },
                                      request=request)

        # List users if we're an admin.
        # Get this from both message users and chat users, because the latter is
        # removed if they delete the chat.
        # XXX DON'T REALLY DELETE CHAT USER WHEN DELETING CHATS.
        symbol_users = None
        if request.user is not None and request.user.status == "admin":
            symbol_users = {
                _.symbol: _.user
                for _ in messages if _.user is not None
            }
            for chat_user in Session.query(ChatUser).filter(
                    ChatUser.chat_id == chat.id).options(
                        joinedload(ChatUser.user)):
                symbol_users[chat_user.symbol] = chat_user.user

        template = "layout2/chat.mako" if request.user.layout_version == 2 else "chat.mako"
        return render_to_response(template, {
            "page": "chat",
            "symbols": symbols,
            "preset_colours": preset_colours,
            "chat": chat,
            "own_chat_user": own_chat_user,
            "from_homepage": from_homepage,
            "message_count": message_count,
            "prompt": prompt,
            "messages": messages,
            "symbol_users": symbol_users,
        },
                                  request=request)

    # Otherwise show the archive view.

    # Update the visited time in archive view if the chat is ended.
    # We need to do this because otherwise it's impossible to mark an ended
    # chat as read.
    if chat.status == "ended" and own_chat_user is not None:
        own_chat_user.visited = datetime.datetime.now()

    try:
        current_page = int(request.GET["page"])
    except:
        current_page = 1

    messages = Session.query(Message).filter(Message.chat_id == chat.id, )
    message_count = Session.query(func.count('*')).select_from(Message).filter(
        Message.chat_id == chat.id, )

    # Hide OOC messages if the chat doesn't belong to us.
    # Also don't hide OOC messages for admins.
    if own_chat_user is None and (request.user is None
                                  or request.user.status != "admin"):
        messages = messages.filter(Message.type != "ooc")
        message_count = message_count.filter(Message.type != "ooc")

    # Join users if we're an admin.
    if request.user is not None and request.user.status == "admin":
        messages = messages.options(joinedload(Message.user))

    messages = messages.order_by(Message.id.asc()).limit(25).offset(
        (current_page - 1) * 25).all()
    message_count = message_count.scalar()

    if request.matchdict.get("fmt") == "json":
        return render_to_response("json", {
            "chat": chat,
            "chat_user": own_chat_user,
            "message_count": message_count,
            "messages": messages,
        },
                                  request=request)

    paginator = paginate.Page(
        [],
        page=current_page,
        items_per_page=25,
        item_count=message_count,
        url=paginate.PageURL(
            request.route_path("chat", url=request.matchdict["url"]),
            {"page": current_page}),
    )

    # List users if we're an admin.
    # Get this from both message users and chat users, because the latter is
    # removed if they delete the chat.
    # XXX DON'T REALLY DELETE CHAT USER WHEN DELETING CHATS.
    symbol_users = None
    if request.user is not None and request.user.status == "admin":
        symbol_users = {
            _.symbol: _.user
            for _ in messages if _.user is not None
        }
        for chat_user in Session.query(ChatUser).filter(
                ChatUser.chat_id == chat.id).options(joinedload(
                    ChatUser.user)):
            symbol_users[chat_user.symbol] = chat_user.user

    template = "layout2/chat_archive.mako" if (
        request.user is None
        or request.user.layout_version == 2) else "chat_archive.mako"
    return render_to_response(template, {
        "page": "archive",
        "symbols": symbols,
        "continuable": continuable,
        "chat": chat,
        "own_chat_user": own_chat_user,
        "messages": messages,
        "paginator": paginator,
        "symbol_users": symbol_users,
    },
                              request=request)