Пример #1
0
def journals_(request):
    form = request.web_input(userid="", name="", backid=None, nextid=None)
    form.name = request.matchdict.get('name', form.name)
    form.userid = define.get_int(form.userid)

    config = define.get_config(request.userid)
    rating = define.get_rating(request.userid)
    otherid = profile.resolve(request.userid, form.userid, form.name)

    if not otherid:
        raise WeasylError("userRecordMissing")
    elif not request.userid and "h" in define.get_config(otherid):
        return Response(define.errorpage(request.userid, errorcode.no_guest_access))

    userprofile = profile.select_profile(otherid, images=True, viewer=request.userid)
    has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != ''
    page_title = u"%s's journals" % (userprofile['full_name'] if has_fullname else userprofile['username'],)
    page = define.common_page_start(request.userid, title=page_title)

    page.append(define.render('user/journals.html', [
        # Profile information
        userprofile,
        # User information
        profile.select_userinfo(otherid, config=userprofile['config']),
        # Relationship
        profile.select_relation(request.userid, otherid),
        # Journals list
        # TODO(weykent): use select_user_list
        journal.select_list(request.userid, rating, 250, otherid=otherid, config=config),
        # Latest journal
        journal.select_latest(request.userid, rating, otherid=otherid),
    ]))

    return Response(define.common_page_end(request.userid, page))
Пример #2
0
def api_user_gallery_(request):
    userid = profile.resolve_by_login(d.get_sysname(request.matchdict['login']))
    if not userid:
        raise WeasylError('userRecordMissing')

    form = request.web_input(since=None, count=0, folderid=0, backid=0, nextid=0)
    since = None
    try:
        if form.since:
            since = d.parse_iso8601(form.since)
        count = int(form.count)
        folderid = int(form.folderid)
        backid = int(form.backid)
        nextid = int(form.nextid)
    except ValueError:
        raise HTTPUnprocessableEntity(json=_ERROR_UNEXPECTED)
    else:
        count = min(count or 100, 100)

    submissions = submission.select_list(
        request.userid, d.get_rating(request.userid), count + 1,
        otherid=userid, folderid=folderid, backid=backid, nextid=nextid)
    backid, nextid = d.paginate(submissions, backid, nextid, count, 'submitid')

    ret = []
    for sub in submissions:
        if since is not None and since >= sub['unixtime']:
            break
        tidy_submission(sub)
        ret.append(sub)

    return {
        'backid': backid, 'nextid': nextid,
        'submissions': ret,
    }
Пример #3
0
    def GET(self, charid=""):
        form = web.input(charid="", ignore="", anyway="")

        rating = define.get_rating(self.user_id)
        charid = define.get_int(charid) if charid else define.get_int(form.charid)

        try:
            item = character.select_view(
                self.user_id, charid, rating,
                ignore=define.text_bool(form.ignore, True), anyway=form.anyway
            )
        except WeasylError as we:
            if we.value in ("UserIgnored", "TagBlocked"):
                we.errorpage_kwargs['links'] = [
                    ("View Character", "?ignore=false"),
                    ("Return to the Home Page", "/index"),
                ]
            raise

        canonical_url = "/character/%d/%s" % (charid, slug_for(item["title"]))

        page = define.common_page_start(self.user_id, canonical_url=canonical_url, title=item["title"])
        page.append(define.render('detail/character.html', [
            # Profile
            profile.select_myself(self.user_id),
            # Character detail
            item,
            # Violations
            [i for i in macro.MACRO_REPORT_VIOLATION if 2000 <= i[0] < 3000],
        ]))

        return define.common_page_end(self.user_id, page)
Пример #4
0
def journal_(request):
    form = request.web_input(journalid="", ignore="", anyway="")

    rating = define.get_rating(request.userid)
    journalid = define.get_int(request.matchdict.get('journalid', form.journalid))

    try:
        item = journal.select_view(
            request.userid, rating, journalid,
            ignore=define.text_bool(form.ignore, True), anyway=form.anyway
        )
    except WeasylError as we:
        if we.value in ("UserIgnored", "TagBlocked"):
            we.errorpage_kwargs['links'] = [
                ("View Journal", "?ignore=false"),
                ("Return to the Home Page", "/index"),
            ]
        raise

    canonical_url = "/journal/%d/%s" % (journalid, slug_for(item["title"]))

    page = define.common_page_start(request.userid, canonical_url=canonical_url, title=item["title"])
    page.append(define.render('detail/journal.html', [
        # Myself
        profile.select_myself(request.userid),
        # Journal detail
        item,
        # Violations
        [i for i in macro.MACRO_REPORT_VIOLATION if 3000 <= i[0] < 4000],
    ]))

    return Response(define.common_page_end(request.userid, page))
Пример #5
0
def api_user_gallery_(request):
    userid = profile.resolve_by_login(request.matchdict['login'])
    if not userid:
        raise WeasylError('userRecordMissing')

    form = request.web_input(since=None, count=0, folderid=0, backid=0, nextid=0)
    since = None
    try:
        if form.since:
            since = d.parse_iso8601(form.since)
        count = int(form.count)
        folderid = int(form.folderid)
        backid = int(form.backid)
        nextid = int(form.nextid)
    except ValueError:
        raise HTTPUnprocessableEntity(json=_ERROR_UNEXPECTED)
    else:
        count = min(count or 100, 100)

    submissions = submission.select_list(
        request.userid, d.get_rating(request.userid), count + 1,
        otherid=userid, folderid=folderid, backid=backid, nextid=nextid)
    backid, nextid = d.paginate(submissions, backid, nextid, count, 'submitid')

    ret = []
    for sub in submissions:
        if since is not None and since >= sub['unixtime']:
            break
        tidy_submission(sub)
        ret.append(sub)

    return {
        'backid': backid, 'nextid': nextid,
        'submissions': ret,
    }
Пример #6
0
    def GET(self, journalid=""):
        form = web.input(journalid="", ignore="", anyway="")

        rating = define.get_rating(self.user_id)
        journalid = define.get_int(journalid) if journalid else define.get_int(form.journalid)

        try:
            item = journal.select_view(
                self.user_id, rating, journalid,
                ignore=define.text_bool(form.ignore, True), anyway=form.anyway
            )
        except WeasylError as we:
            if we.value in ("UserIgnored", "TagBlocked"):
                we.errorpage_kwargs['links'] = [
                    ("View Journal", "?ignore=false"),
                    ("Return to the Home Page", "/index"),
                ]
            raise

        canonical_url = "/journal/%d/%s" % (journalid, slug_for(item["title"]))

        page = define.common_page_start(self.user_id, options=["pager"], canonical_url=canonical_url, title=item["title"])
        page.append(define.render(template.detail_journal, [
            # Myself
            profile.select_myself(self.user_id),
            # Journal detail
            item,
            # Violations
            [i for i in macro.MACRO_REPORT_VIOLATION if 3000 <= i[0] < 4000],
        ]))

        return define.common_page_end(self.user_id, page)
Пример #7
0
 def GET(self):
     extras = {
         "title": "Streaming",
     }
     rating = define.get_rating(self.user_id)
     return define.webpage(self.user_id, 'etc/streaming.html',
                           [profile.select_streaming(self.user_id, rating, 300, order_by="start_time desc")], **extras)
Пример #8
0
def select_view_api(userid, journalid, anyway=False, increment_views=False):
    rating = d.get_rating(userid)

    journal = _select_journal_and_check(
        userid, journalid,
        rating=rating, ignore=anyway, anyway=anyway, increment_views=increment_views)

    return {
        'journalid': journalid,
        'title': journal['title'],
        'owner': journal['username'],
        'owner_login': d.get_sysname(journal['username']),
        'owner_media': api.tidy_all_media(
            media.get_user_media(journal['userid'])),
        'content': text.markdown(journal['content']),
        'tags': searchtag.select(journalid=journalid),
        'link': d.absolutify_url('/journal/%d/%s' % (journalid, text.slug_for(journal['title']))),
        'type': 'journal',
        'rating': ratings.CODE_TO_NAME[journal['rating']],
        'views': journal['page_views'],
        'favorites': favorite.count(journalid, 'journal'),
        'comments': comment.count(journalid, 'journal'),
        'favorited': favorite.check(userid, journalid=journalid),
        'friends_only': 'f' in journal['settings'],
        'posted_at': d.iso8601(journal['unixtime']),
    }
Пример #9
0
def journals_(request):
    name = request.matchdict.get('name', request.params.get('name', ''))
    userid = define.get_int(request.params.get('userid'))

    rating = define.get_rating(request.userid)
    otherid = profile.resolve(request.userid, userid, name)

    if not otherid:
        raise WeasylError("userRecordMissing")
    elif not request.userid and "h" in define.get_config(otherid):
        raise WeasylError('noGuests')

    userprofile = profile.select_profile(otherid, viewer=request.userid)
    has_fullname = userprofile[
        'full_name'] is not None and userprofile['full_name'].strip() != ''
    page_title = u"%s's journals" % (userprofile['full_name'] if has_fullname
                                     else userprofile['username'], )
    page = define.common_page_start(request.userid, title=page_title)

    page.append(
        define.render(
            'user/journals.html',
            [
                # Profile information
                userprofile,
                # User information
                profile.select_userinfo(otherid, config=userprofile['config']),
                # Relationship
                profile.select_relation(request.userid, otherid),
                # Journals list
                journal.select_list(request.userid, rating, otherid=otherid),
            ]))

    return Response(define.common_page_end(request.userid, page))
Пример #10
0
def offer(userid, submitid, otherid):
    query = d.engine.execute(
        "SELECT userid, rating, settings FROM submission WHERE submitid = %(id)s",
        id=submitid,
    ).first()

    if not query or "h" in query[2]:
        raise WeasylError("Unexpected")
    elif userid != query[0]:
        raise WeasylError("Unexpected")

    # Check collection acceptability
    if otherid:
        rating = d.get_rating(otherid)

        if rating < query[1]:
            raise WeasylError("collectionUnacceptable")
        if "f" in query[2]:
            raise WeasylError("collectionUnacceptable")
        if ignoreuser.check(otherid, userid):
            raise WeasylError("IgnoredYou")
        if ignoreuser.check(userid, otherid):
            raise WeasylError("YouIgnored")
        if blocktag.check(otherid, submitid=submitid):
            raise WeasylError("collectionUnacceptable")

    try:
        d.execute(
            "INSERT INTO collection (userid, submitid, unixtime) VALUES (%i, %i, %i)",
            [otherid, submitid, d.get_time()])
    except PostgresError:
        raise WeasylError("collectionExists")

    welcome.collectoffer_insert(userid, otherid, submitid)
Пример #11
0
def character_(request):
    form = request.web_input(charid="", ignore="", anyway="")

    rating = define.get_rating(request.userid)
    charid = define.get_int(request.matchdict.get('charid', form.charid))

    try:
        item = character.select_view(
            request.userid, charid, rating,
            ignore=form.ignore != 'false', anyway=form.anyway
        )
    except WeasylError as we:
        if we.value in ("UserIgnored", "TagBlocked"):
            we.errorpage_kwargs['links'] = [
                ("View Character", "?ignore=false"),
                ("Return to the Home Page", "/index"),
            ]
        raise

    canonical_url = "/character/%d/%s" % (charid, slug_for(item["title"]))

    page = define.common_page_start(request.userid, canonical_url=canonical_url, title=item["title"])
    page.append(define.render('detail/character.html', [
        # Profile
        profile.select_myself(request.userid),
        # Character detail
        item,
        # Violations
        [i for i in macro.MACRO_REPORT_VIOLATION if 2000 <= i[0] < 3000],
    ]))

    return Response(define.common_page_end(request.userid, page))
Пример #12
0
def select_view_api(userid, journalid, anyway=False, increment_views=False):
    rating = d.get_rating(userid)

    journal = _select_journal_and_check(
        userid, journalid,
        rating=rating, ignore=anyway, anyway=anyway, increment_views=increment_views)

    return {
        'journalid': journalid,
        'title': journal['title'],
        'owner': journal['username'],
        'owner_login': d.get_sysname(journal['username']),
        'owner_media': api.tidy_all_media(
            media.get_user_media(journal['userid'])),
        'content': text.markdown(journal['content']),
        'tags': searchtag.select(journalid=journalid),
        'link': d.absolutify_url('/journal/%d/%s' % (journalid, text.slug_for(journal['title']))),
        'type': 'journal',
        'rating': ratings.CODE_TO_NAME[journal['rating']],
        'views': journal['page_views'],
        'favorites': favorite.count(journalid, 'journal'),
        'comments': comment.count(journalid, 'journal'),
        'favorited': favorite.check(userid, journalid=journalid),
        'friends_only': 'f' in journal['settings'],
        'posted_at': d.iso8601(journal['unixtime']),
    }
Пример #13
0
    def GET(self, name=""):
        form = web.input(userid="", name="", backid=None, nextid=None)
        form.name = name if name else form.name
        form.userid = define.get_int(form.userid)

        config = define.get_config(self.user_id)
        rating = define.get_rating(self.user_id)
        otherid = profile.resolve(self.user_id, form.userid, form.name)

        if not otherid:
            raise WeasylError("userRecordMissing")
        elif not self.user_id and "h" in define.get_config(otherid):
            return define.errorpage(self.user_id, errorcode.no_guest_access)

        userprofile = profile.select_profile(otherid, images=True, viewer=self.user_id)
        has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != ''
        page_title = u"%s's journals" % (userprofile['full_name'] if has_fullname else userprofile['username'],)
        page = define.common_page_start(self.user_id, title=page_title)

        page.append(define.render(template.user_journals, [
            # Profile information
            userprofile,
            # User information
            profile.select_userinfo(otherid, config=userprofile['config']),
            # Relationship
            profile.select_relation(self.user_id, otherid),
            # Journals list
            # TODO(weykent): use select_user_list
            journal.select_list(self.user_id, rating, 250, otherid=otherid, config=config),
            # Latest journal
            journal.select_latest(self.user_id, rating, otherid=otherid),
        ]))

        return define.common_page_end(self.user_id, page)
Пример #14
0
def streaming_(request):
    rating = define.get_rating(request.userid)
    return Response(
        define.webpage(
            request.userid,
            'etc/streaming.html', (profile.select_streaming(
                request.userid, rating, 300, order_by="start_time desc"), ),
            title="Streaming"))
Пример #15
0
def streaming_(request):
    extras = {
        "title": "Streaming",
    }
    rating = define.get_rating(request.userid)
    return Response(define.webpage(request.userid, 'etc/streaming.html',
                                   [profile.select_streaming(request.userid, rating, 300, order_by="start_time desc")],
                                   **extras))
Пример #16
0
def submissions_(request):
    name = request.matchdict.get('name', request.params.get('name', ''))
    userid = define.get_int(request.params.get('userid'))

    rating = define.get_rating(request.userid)
    otherid = profile.resolve(request.userid, userid, name)
    folderid = define.get_int(request.params.get('folderid')) or None
    backid = request.params.get('backid')
    nextid = request.params.get('nextid')

    if not otherid:
        raise WeasylError("userRecordMissing")
    elif not request.userid and "h" in define.get_config(otherid):
        raise WeasylError('noGuests')

    userprofile = profile.select_profile(otherid, viewer=request.userid)
    has_fullname = userprofile[
        'full_name'] is not None and userprofile['full_name'].strip() != ''
    page_title = u"%s's submissions" % (userprofile['full_name']
                                        if has_fullname else
                                        userprofile['username'], )
    page = define.common_page_start(request.userid, title=page_title)

    url_format = "/submissions/{username}?%s{folderquery}".format(
        username=define.get_sysname(userprofile['username']),
        folderquery="&folderid=%d" % folderid if folderid else "")
    result = pagination.PaginatedResult(submission.select_list,
                                        submission.select_count,
                                        'submitid',
                                        url_format,
                                        request.userid,
                                        rating,
                                        limit=60,
                                        otherid=otherid,
                                        folderid=folderid,
                                        backid=define.get_int(backid),
                                        nextid=define.get_int(nextid),
                                        profile_page_filter=not folderid)

    page.append(
        define.render(
            'user/submissions.html',
            [
                # Profile information
                userprofile,
                # User information
                profile.select_userinfo(otherid, config=userprofile['config']),
                # Relationship
                profile.select_relation(request.userid, otherid),
                # Recent submissions
                result,
                # Folders
                folder.select_list(otherid),
                # Current folder
                folderid,
            ]))

    return Response(define.common_page_end(request.userid, page))
Пример #17
0
def collections_(request):
    form = request.web_input(userid="",
                             name="",
                             backid=None,
                             nextid=None,
                             folderid=None)
    form.name = request.matchdict.get('name', form.name)
    form.userid = define.get_int(form.userid)

    config = define.get_config(request.userid)
    rating = define.get_rating(request.userid)
    otherid = profile.resolve(request.userid, form.userid, form.name)

    if not otherid:
        raise WeasylError("userRecordMissing")
    elif not request.userid and "h" in define.get_config(otherid):
        return Response(
            define.errorpage(request.userid, errorcode.no_guest_access))

    userprofile = profile.select_profile(otherid,
                                         images=True,
                                         viewer=request.userid)
    has_fullname = userprofile[
        'full_name'] is not None and userprofile['full_name'].strip() != ''
    page_title = u"%s's collections" % (userprofile['full_name']
                                        if has_fullname else
                                        userprofile['username'], )
    page = define.common_page_start(request.userid, title=page_title)

    url_format = "/collections?userid={userid}&%s".format(
        userid=userprofile['userid'])
    result = pagination.PaginatedResult(collection.select_list,
                                        collection.select_count,
                                        'submitid',
                                        url_format,
                                        request.userid,
                                        rating,
                                        66,
                                        otherid=otherid,
                                        backid=define.get_int(form.backid),
                                        nextid=define.get_int(form.nextid),
                                        config=config)

    page.append(
        define.render(
            'user/collections.html',
            [
                # Profile information
                userprofile,
                # User information
                profile.select_userinfo(otherid, config=userprofile['config']),
                # Relationship
                profile.select_relation(request.userid, otherid),
                # Collections
                result,
            ]))

    return Response(define.common_page_end(request.userid, page))
Пример #18
0
 def GET(self):
     extras = {
         "title": "Streaming",
     }
     rating = define.get_rating(self.user_id)
     return define.webpage(self.user_id, template.etc_streaming, [
         profile.select_streaming(
             self.user_id, rating, 300, order_by="start_time desc")
     ], **extras)
Пример #19
0
def submission_(request):
    username = request.matchdict.get('name')
    submitid = request.matchdict.get('submitid')

    form = request.web_input(submitid="", ignore="", anyway="")

    rating = define.get_rating(request.userid)
    submitid = define.get_int(submitid) if submitid else define.get_int(form.submitid)

    extras = {
        "pdf": True,
    }

    if define.user_is_twitterbot():
        extras['twitter_card'] = submission.twitter_card(submitid)

    try:
        item = submission.select_view(
            request.userid, submitid, rating,
            ignore=define.text_bool(form.ignore, True), anyway=form.anyway
        )
    except WeasylError as we:
        we.errorpage_kwargs = extras
        if 'twitter_card' in extras:
            extras['options'] = ['nocache']
        if we.value in ("UserIgnored", "TagBlocked"):
            extras['links'] = [
                ("View Submission", "?ignore=false"),
                ("Return to the Home Page", "/index"),
            ]
        raise

    login = define.get_sysname(item['username'])
    canonical_path = request.route_path('submission_detail_profile', name=login, submitid=submitid, slug=slug_for(item['title']))

    if request.GET.get('anyway'):
        canonical_path += '?anyway=true'

    if login != username:
        raise httpexceptions.HTTPMovedPermanently(location=canonical_path)
    extras["canonical_url"] = canonical_path
    extras["title"] = item["title"]

    page = define.common_page_start(request.userid, **extras)
    page.append(define.render('detail/submission.html', [
        # Myself
        profile.select_myself(request.userid),
        # Submission detail
        item,
        # Subtypes
        macro.MACRO_SUBCAT_LIST,
        # Violations
        [i for i in macro.MACRO_REPORT_VIOLATION if 2000 <= i[0] < 3000],
    ]))

    return Response(define.common_page_end(request.userid, page))
Пример #20
0
    def GET(self, name=""):

        form = web.input(userid="", name="", backid=None, nextid=None)
        form.name = name if name else form.name
        form.userid = define.get_int(form.userid)

        config = define.get_config(self.user_id)
        rating = define.get_rating(self.user_id)
        otherid = profile.resolve(self.user_id, form.userid, form.name)

        if not otherid:
            raise WeasylError("userRecordMissing")
        elif not self.user_id and "h" in define.get_config(otherid):
            return define.errorpage(self.user_id, errorcode.no_guest_access)

        userprofile = profile.select_profile(otherid,
                                             images=True,
                                             viewer=self.user_id)
        has_fullname = userprofile[
            'full_name'] is not None and userprofile['full_name'].strip() != ''
        page_title = u"%s's characters" % (userprofile['full_name']
                                           if has_fullname else
                                           userprofile['username'], )
        page = define.common_page_start(self.user_id, title=page_title)

        url_format = "/characters?userid={userid}&%s".format(
            userid=userprofile['userid'])
        result = pagination.PaginatedResult(character.select_list,
                                            character.select_count,
                                            'charid',
                                            url_format,
                                            self.user_id,
                                            rating,
                                            60,
                                            otherid=otherid,
                                            backid=define.get_int(form.backid),
                                            nextid=define.get_int(form.nextid),
                                            config=config)

        page.append(
            define.render(
                template.user_characters,
                [
                    # Profile information
                    userprofile,
                    # User information
                    profile.select_userinfo(otherid,
                                            config=userprofile['config']),
                    # Relationship
                    profile.select_relation(self.user_id, otherid),
                    # Characters list
                    result,
                ]))

        return define.common_page_end(self.user_id, page)
Пример #21
0
    def GET(self, a="", b=None):
        if b is None:
            username, submitid = None, a
        else:
            username, submitid = a, b
        now = time.time()

        form = web.input(submitid="", ignore="", anyway="")

        rating = define.get_rating(self.user_id)
        submitid = define.get_int(submitid) if submitid else define.get_int(form.submitid)

        extras = {
            "pdf": True,
        }

        if define.user_is_twitterbot():
            extras['twitter_card'] = submission.twitter_card(submitid)

        try:
            item = submission.select_view(
                self.user_id, submitid, rating,
                ignore=define.text_bool(form.ignore, True), anyway=form.anyway
            )
        except WeasylError as we:
            we.errorpage_kwargs = extras
            if 'twitter_card' in extras:
                extras['options'] = ['nocache']
            if we.value in ("UserIgnored", "TagBlocked"):
                extras['links'] = [
                    ("View Submission", "?ignore=false"),
                    ("Return to the Home Page", "/index"),
                ]
            raise

        login = define.get_sysname(item['username'])
        if username is not None and login != username:
            raise web.seeother('/~%s/post/%s/%s' % (login, submitid, slug_for(item["title"])))
        extras["canonical_url"] = "/submission/%d/%s" % (submitid, slug_for(item["title"]))
        extras["title"] = item["title"]

        page = define.common_page_start(self.user_id, options=["mediaplayer"], **extras)
        page.append(define.render('detail/submission.html', [
            # Myself
            profile.select_myself(self.user_id),
            # Submission detail
            item,
            # Subtypes
            macro.MACRO_SUBCAT_LIST,
            # Violations
            [i for i in macro.MACRO_REPORT_VIOLATION if 2000 <= i[0] < 3000],
        ]))

        return define.common_page_end(self.user_id, page, now=now)
Пример #22
0
def select_view_api(userid, submitid, anyway=False, increment_views=False):
    rating = d.get_rating(userid)
    db = d.connect()
    sub = db.query(orm.Submission).get(submitid)
    if sub is None or 'hidden' in sub.settings:
        raise WeasylError("submissionRecordMissing")
    sub_rating = sub.rating.code
    if 'friends-only' in sub.settings and not frienduser.check(userid, sub.userid):
        raise WeasylError("submissionRecordMissing")
    elif sub_rating > rating and userid != sub.userid:
        raise WeasylError("RatingExceeded")
    elif not anyway and ignoreuser.check(userid, sub.userid):
        raise WeasylError("UserIgnored")
    elif not anyway and blocktag.check(userid, submitid=submitid):
        raise WeasylError("TagBlocked")

    description = sub.content
    embedlink = None
    if 'embedded-content' in sub.settings:
        embedlink, _, description = description.partition('\n')
    elif 'gdocs-embed' in sub.settings:
        embedlink = sub.google_doc_embed.embed_url

    views = sub.page_views
    if increment_views and d.common_view_content(userid, submitid, 'submit'):
        views += 1

    return {
        'submitid': submitid,
        'title': sub.title,
        'owner': sub.owner.profile.username,
        'owner_login': sub.owner.login_name,
        'owner_media': api.tidy_all_media(media.get_user_media(sub.userid)),
        'media': api.tidy_all_media(media.get_submission_media(submitid)),
        'description': text.markdown(description),
        'embedlink': embedlink,
        'folderid': sub.folderid,
        'folder_name': sub.folder.title if sub.folderid else None,
        'posted_at': d.iso8601(sub.unixtime),
        'tags': searchtag.select(submitid=submitid),
        'link': d.absolutify_url("/submission/%d/%s" % (submitid, text.slug_for(sub.title))),

        'type': 'submission',
        'subtype': m.CATEGORY_PARSABLE_MAP[sub.subtype // 1000 * 1000],
        'rating': sub.rating.name,

        'views': views,
        'favorites': favorite.count(submitid),
        'comments': comment.count(submitid),
        'favorited': favorite.check(userid, submitid=submitid),
        'friends_only': 'friends-only' in sub.settings,
    }
Пример #23
0
def select_view_api(userid, submitid, anyway=False, increment_views=False):
    rating = d.get_rating(userid)
    db = d.connect()
    sub = db.query(orm.Submission).get(submitid)
    if sub is None or 'hidden' in sub.settings:
        raise WeasylError("submissionRecordMissing")
    sub_rating = sub.rating.code
    if 'friends-only' in sub.settings and not frienduser.check(userid, sub.userid):
        raise WeasylError("submissionRecordMissing")
    elif sub_rating > rating and userid != sub.userid:
        raise WeasylError("RatingExceeded")
    elif not anyway and ignoreuser.check(userid, sub.userid):
        raise WeasylError("UserIgnored")
    elif not anyway and blocktag.check(userid, submitid=submitid):
        raise WeasylError("TagBlocked")

    description = sub.content
    embedlink = None
    if 'embedded-content' in sub.settings:
        embedlink, _, description = description.partition('\n')
    elif 'gdocs-embed' in sub.settings:
        embedlink = sub.google_doc_embed.embed_url

    views = sub.page_views
    if increment_views and d.common_view_content(userid, submitid, 'submit'):
        views += 1

    return {
        'submitid': submitid,
        'title': sub.title,
        'owner': sub.owner.profile.username,
        'owner_login': sub.owner.login_name,
        'owner_media': api.tidy_all_media(media.get_user_media(sub.userid)),
        'media': api.tidy_all_media(media.get_submission_media(submitid)),
        'description': text.markdown(description),
        'embedlink': embedlink,
        'folderid': sub.folderid,
        'folder_name': sub.folder.title if sub.folderid else None,
        'posted_at': d.iso8601(sub.unixtime),
        'tags': searchtag.select(submitid=submitid),
        'link': d.absolutify_url("/submission/%d/%s" % (submitid, text.slug_for(sub.title))),

        'type': 'submission',
        'subtype': m.CATEGORY_PARSABLE_MAP[sub.subtype // 1000 * 1000],
        'rating': sub.rating.name,

        'views': views,
        'favorites': favorite.count(submitid),
        'comments': comment.count(submitid),
        'favorited': favorite.check(userid, submitid=submitid),
        'friends_only': 'friends-only' in sub.settings,
    }
Пример #24
0
def collections_(request):
    name = request.matchdict.get('name', request.params.get('name', ''))
    userid = define.get_int(request.params.get('userid'))

    rating = define.get_rating(request.userid)
    otherid = profile.resolve(request.userid, userid, name)

    backid = request.params.get('backid')
    nextid = request.params.get('nextid')

    if not otherid:
        raise WeasylError("userRecordMissing")
    elif not request.userid and "h" in define.get_config(otherid):
        raise WeasylError('noGuests')

    userprofile = profile.select_profile(otherid, viewer=request.userid)
    has_fullname = userprofile[
        'full_name'] is not None and userprofile['full_name'].strip() != ''
    page_title = u"%s's collections" % (userprofile['full_name']
                                        if has_fullname else
                                        userprofile['username'], )
    page = define.common_page_start(request.userid, title=page_title)

    url_format = "/collections?userid={userid}&%s".format(
        userid=userprofile['userid'])
    result = pagination.PaginatedResult(collection.select_list,
                                        collection.select_count,
                                        'submitid',
                                        url_format,
                                        request.userid,
                                        rating,
                                        limit=66,
                                        otherid=otherid,
                                        backid=define.get_int(backid),
                                        nextid=define.get_int(nextid))

    page.append(
        define.render(
            'user/collections.html',
            [
                # Profile information
                userprofile,
                # User information
                profile.select_userinfo(otherid, config=userprofile['config']),
                # Relationship
                profile.select_relation(request.userid, otherid),
                # Collections
                result,
            ]))

    return Response(define.common_page_end(request.userid, page))
Пример #25
0
def template_fields(userid):
    config = d.get_config(userid)
    rating = d.get_rating(userid)
    submissions = list(filter_submissions(userid, recent_submissions()))
    ret = partition_submissions(submissions)

    return ret + [
        # Recent site news update
        siteupdate.select(),
        # Recent critique submissions
        submission.select_list(userid, rating, 4, options=["critique"], config=config),
        # Currently streaming users
        profile.select_streaming(userid, rating, 4),
        # Recently popular submissions
        list(itertools.islice(filter_submissions(userid, submission.select_recently_popular(), incidence_limit=1), 11)),
    ]
Пример #26
0
def template_fields(userid):
    config = d.get_config(userid)
    rating = d.get_rating(userid)
    submissions = list(filter_submissions(userid, recent_submissions()))
    ret = partition_submissions(submissions)

    return ret + [
        # Recent site news update
        siteupdate.select_last(),
        # Recent critique submissions
        submission.select_list(userid, rating, 4, options=["critique"], config=config),
        # Currently streaming users
        profile.select_streaming(userid, rating, 4),
        # Recently popular submissions
        list(itertools.islice(filter_submissions(userid, submission.select_recently_popular(), incidence_limit=1), 11)),
    ]
Пример #27
0
    def GET(self, journalid=""):
        form = web.input(journalid="", ignore="", anyway="")

        rating = define.get_rating(self.user_id)
        journalid = define.get_int(journalid) if journalid else define.get_int(
            form.journalid)

        try:
            item = journal.select_view(self.user_id,
                                       rating,
                                       journalid,
                                       ignore=define.text_bool(
                                           form.ignore, True),
                                       anyway=form.anyway)
        except WeasylError as we:
            if we.value in ("UserIgnored", "TagBlocked"):
                we.errorpage_kwargs['links'] = [
                    ("View Journal", "?ignore=false"),
                    ("Return to the Home Page", "/index"),
                ]
            raise

        canonical_url = "/journal/%d/%s" % (journalid, slug_for(item["title"]))

        page = define.common_page_start(self.user_id,
                                        options=["pager"],
                                        canonical_url=canonical_url,
                                        title=item["title"])
        page.append(
            define.render(
                template.detail_journal,
                [
                    # Myself
                    profile.select_myself(self.user_id),
                    # Journal detail
                    item,
                    # Violations
                    [
                        i for i in macro.MACRO_REPORT_VIOLATION
                        if 3000 <= i[0] < 4000
                    ],
                ]))

        return define.common_page_end(self.user_id, page)
Пример #28
0
def submissions_(request):
    form = request.web_input(userid="", name="", backid=None, nextid=None, folderid=None)
    form.name = request.matchdict.get('name', form.name)
    form.userid = define.get_int(form.userid)

    config = define.get_config(request.userid)
    rating = define.get_rating(request.userid)
    otherid = profile.resolve(request.userid, form.userid, form.name)
    folderid = define.get_int(form.folderid) or None

    if not otherid:
        raise WeasylError("userRecordMissing")
    elif not request.userid and "h" in define.get_config(otherid):
        return Response(define.errorpage(request.userid, errorcode.no_guest_access))

    userprofile = profile.select_profile(otherid, images=True, viewer=request.userid)
    has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != ''
    page_title = u"%s's submissions" % (userprofile['full_name'] if has_fullname else userprofile['username'],)
    page = define.common_page_start(request.userid, title=page_title)

    url_format = "/submissions/{username}?%s{folderquery}".format(
                 username=define.get_sysname(userprofile['username']),
                 folderquery="&folderid=%d" % folderid if folderid else "")
    result = pagination.PaginatedResult(
        submission.select_list, submission.select_count, 'submitid', url_format, request.userid, rating,
        60, otherid=otherid, folderid=folderid, backid=define.get_int(form.backid),
        nextid=define.get_int(form.nextid), config=config, profile_page_filter=not folderid)

    page.append(define.render('user/submissions.html', [
        # Profile information
        userprofile,
        # User information
        profile.select_userinfo(otherid, config=userprofile['config']),
        # Relationship
        profile.select_relation(request.userid, otherid),
        # Recent submissions
        result,
        # Folders
        folder.select_list(otherid, "sidebar/all"),
        # Current folder
        folderid,
    ]))

    return Response(define.common_page_end(request.userid, page))
Пример #29
0
    def GET(self, name=""):
        form = web.input(userid="", name="", backid=None, nextid=None, folderid=None)
        form.name = name if name else form.name
        form.userid = define.get_int(form.userid)

        config = define.get_config(self.user_id)
        rating = define.get_rating(self.user_id)
        otherid = profile.resolve(self.user_id, form.userid, form.name)
        folderid = define.get_int(form.folderid) or None

        if not otherid:
            raise WeasylError("userRecordMissing")
        elif not self.user_id and "h" in define.get_config(otherid):
            return define.errorpage(self.user_id, errorcode.no_guest_access)

        userprofile = profile.select_profile(otherid, images=True, viewer=self.user_id)
        has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != ''
        page_title = u"%s's submissions" % (userprofile['full_name'] if has_fullname else userprofile['username'],)
        page = define.common_page_start(self.user_id, title=page_title)

        url_format = "/submissions/{username}?%s{folderquery}".format(
                     username=define.get_sysname(userprofile['username']),
                     folderquery="&folderid=%d" % folderid if folderid else "")
        result = pagination.PaginatedResult(
            submission.select_list, submission.select_count, 'submitid', url_format, self.user_id, rating,
            60, otherid=otherid, folderid=folderid, backid=define.get_int(form.backid),
            nextid=define.get_int(form.nextid), config=config, profile_page_filter=not folderid)

        page.append(define.render(template.user_submissions, [
            # Profile information
            userprofile,
            # User information
            profile.select_userinfo(otherid, config=userprofile['config']),
            # Relationship
            profile.select_relation(self.user_id, otherid),
            # Recent submissions
            result,
            # Folders
            folder.select_list(otherid, "sidebar/all"),
            # Current folder
            folderid,
        ]))

        return define.common_page_end(self.user_id, page)
Пример #30
0
def request(userid, submitid, otherid):
    query = d.engine.execute(
        "SELECT userid, rating, settings "
        "FROM submission WHERE submitid = %(submission)s",
        submission=submitid).first()

    rating = d.get_rating(userid)

    if not query or "h" in query.settings:
        raise WeasylError("Unexpected")
    if otherid != query.userid:
        raise WeasylError("Unexpected")

    # not checking for blocktags here because if you want to collect
    # something with a tag you don't like that's your business
    if rating < query.rating:
        raise WeasylError("RatingExceeded")
    if "f" in query.settings:
        raise WeasylError("collectionUnacceptable")
    if ignoreuser.check(otherid, userid):
        raise WeasylError("IgnoredYou")
    if ignoreuser.check(userid, otherid):
        raise WeasylError("YouIgnored")
    if _check_throttle(userid, otherid):
        raise WeasylError("collectionThrottle")

    settings = d.get_profile_settings(otherid)
    if not settings.allow_collection_requests:
        raise WeasylError("Unexpected")

    request_settings = "r"
    try:
        d.engine.execute(
            "INSERT INTO collection (userid, submitid, unixtime, settings) "
            "VALUES (%(userid)s, %(submitid)s, %(now)s, %(settings)s)",
            userid=userid,
            submitid=submitid,
            now=d.get_time(),
            settings=request_settings)
    except PostgresError:
        raise WeasylError("collectionExists")

    welcome.collectrequest_insert(userid, otherid, submitid)
Пример #31
0
def manage_collections_get_(request):
    form = request.web_input(feature="", backid="", nextid="")
    backid = int(form.backid) if form.backid else None
    nextid = int(form.nextid) if form.nextid else None

    config = define.get_config(request.userid)
    rating = define.get_rating(request.userid)

    if form.feature == "pending":
        return Response(
            define.webpage(
                request.userid,
                "manage/collections_pending.html",
                [
                    # Pending Collections
                    collection.select_list(request.userid,
                                           rating,
                                           30,
                                           otherid=request.userid,
                                           backid=backid,
                                           nextid=nextid,
                                           pending=True,
                                           config=config),
                    request.userid
                ],
                title="Pending Collections"))

    return Response(
        define.webpage(
            request.userid,
            "manage/collections_accepted.html",
            [
                # Accepted Collections
                collection.select_list(request.userid,
                                       rating,
                                       30,
                                       otherid=request.userid,
                                       backid=backid,
                                       nextid=nextid,
                                       config=config),
            ],
            title="Accepted Collections"))
Пример #32
0
def select_journals(userid):
    journals = d.engine.execute("""
        SELECT we.welcomeid, we.unixtime, we.otherid, we.targetid, pr.username, jo.title
        FROM welcome we
            INNER JOIN profile pr ON we.otherid = pr.userid
            INNER JOIN journal jo ON we.targetid = jo.journalid
        WHERE
            (we.userid, we.type) = (%(user)s, 1010) AND
            rating <= %(rating)s
        ORDER BY we.unixtime DESC
    """, user=userid, rating=d.get_rating(userid))

    return [{
        "type": 1010,
        "id": j.welcomeid,
        "unixtime": j.unixtime,
        "userid": j.otherid,
        "username": j.username,
        "journalid": j.targetid,
        "title": j.title,
    } for j in journals]
Пример #33
0
    def GET(self):
        form = web.input(feature="", backid="", nextid="")
        backid = int(form.backid) if form.backid else None
        nextid = int(form.nextid) if form.nextid else None

        config = define.get_config(self.user_id)
        rating = define.get_rating(self.user_id)

        if form.feature == "pending":
            return define.webpage(self.user_id, "manage/collections_pending.html", [
                # Pending Collections
                collection.select_list(self.user_id, rating, 30, otherid=self.user_id, backid=backid, nextid=nextid,
                                       pending=True, config=config),
                self.user_id
            ])

        return define.webpage(self.user_id, "manage/collections_accepted.html", [
            # Accepted Collections
            collection.select_list(self.user_id, rating, 30, otherid=self.user_id, backid=backid, nextid=nextid,
                                   config=config),
        ])
Пример #34
0
def manage_collections_get_(request):
    form = request.web_input(feature="", backid="", nextid="")
    backid = int(form.backid) if form.backid else None
    nextid = int(form.nextid) if form.nextid else None

    config = define.get_config(request.userid)
    rating = define.get_rating(request.userid)

    if form.feature == "pending":
        return Response(define.webpage(request.userid, "manage/collections_pending.html", [
            # Pending Collections
            collection.select_list(request.userid, rating, 30, otherid=request.userid, backid=backid, nextid=nextid,
                                   pending=True, config=config),
            request.userid
        ]))

    return Response(define.webpage(request.userid, "manage/collections_accepted.html", [
        # Accepted Collections
        collection.select_list(request.userid, rating, 30, otherid=request.userid, backid=backid, nextid=nextid,
                               config=config),
    ]))
Пример #35
0
    def GET(self, name=""):

        form = web.input(userid="", name="", backid=None, nextid=None)
        form.name = name if name else form.name
        form.userid = define.get_int(form.userid)

        config = define.get_config(self.user_id)
        rating = define.get_rating(self.user_id)
        otherid = profile.resolve(self.user_id, form.userid, form.name)

        if not otherid:
            raise WeasylError("userRecordMissing")
        elif not self.user_id and "h" in define.get_config(otherid):
            return define.errorpage(self.user_id, errorcode.no_guest_access)

        userprofile = profile.select_profile(otherid, images=True, viewer=self.user_id)
        has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != ''
        page_title = u"%s's characters" % (userprofile['full_name'] if has_fullname else userprofile['username'],)
        page = define.common_page_start(self.user_id, title=page_title)

        url_format = "/characters?userid={userid}&%s".format(userid=userprofile['userid'])
        result = pagination.PaginatedResult(
            character.select_list, character.select_count,
            'charid', url_format, self.user_id, rating, 60,
            otherid=otherid, backid=define.get_int(form.backid),
            nextid=define.get_int(form.nextid), config=config)

        page.append(define.render(template.user_characters, [
            # Profile information
            userprofile,
            # User information
            profile.select_userinfo(otherid, config=userprofile['config']),
            # Relationship
            profile.select_relation(self.user_id, otherid),
            # Characters list
            result,
        ]))

        return define.common_page_end(self.user_id, page)
Пример #36
0
    def GET(self):
        form = web.input(feature="", backid="", nextid="")
        backid = int(form.backid) if form.backid else None
        nextid = int(form.nextid) if form.nextid else None

        config = define.get_config(self.user_id)
        rating = define.get_rating(self.user_id)

        if form.feature == "pending":
            return define.webpage(
                self.user_id,
                "manage/collections_pending.html",
                [
                    # Pending Collections
                    collection.select_list(self.user_id,
                                           rating,
                                           30,
                                           otherid=self.user_id,
                                           backid=backid,
                                           nextid=nextid,
                                           pending=True,
                                           config=config),
                    self.user_id
                ])

        return define.webpage(
            self.user_id,
            "manage/collections_accepted.html",
            [
                # Accepted Collections
                collection.select_list(self.user_id,
                                       rating,
                                       30,
                                       otherid=self.user_id,
                                       backid=backid,
                                       nextid=nextid,
                                       config=config),
            ])
Пример #37
0
def filter_submissions(userid, submissions, incidence_limit=3):
    """
    Filters a list of submissions according to the user's preferences and
    optionally limits the number of items returned from one submitter.

    :param userid: The userid to use for blocked tags and rating. Usually the
        viewing user.
    :type userid: int.
    :param submissions: A list of submissions with appropriate fields (rating,
        userid, etc.)
    :type submissions: A list of submission dictionaries.
    :param incidence_limit: The maximum number of submissions to permit from
        one creator. Set to 0 or None for no limit.
    :type incidence_limit: int.
    :return: An iterator over the submissions after filtering by the user's
        settings and incidence limit.
    """
    blocked_tags = ignored_users = set()
    rating = ratings.GENERAL.code
    if userid:
        rating = d.get_rating(userid)
        blocked_tags = blocktag.select_ids(userid)
        ignored_users = set(ignoreuser.cached_list_ignoring(userid))

    submitter_incidence = collections.defaultdict(int)
    for s in submissions:
        if incidence_limit and submitter_incidence[
                s['userid']] >= incidence_limit:
            continue
        if s['rating'] > rating:
            continue
        if s['userid'] in ignored_users:
            continue
        tags = set(s['tags'])
        if blocktag.check_list(s['rating'], tags, blocked_tags):
            continue
        submitter_incidence[s['userid']] += 1
        yield s
Пример #38
0
def select_journals(userid):
    journals = d.engine.execute("""
        SELECT we.welcomeid, we.unixtime, we.otherid, we.targetid, pr.username, jo.title
        FROM welcome we
            INNER JOIN profile pr ON we.otherid = pr.userid
            INNER JOIN journal jo ON we.targetid = jo.journalid
        WHERE
            (we.userid, we.type) = (%(user)s, 1010) AND
            rating <= %(rating)s
        ORDER BY we.unixtime DESC
    """,
                                user=userid,
                                rating=d.get_rating(userid))

    return [{
        "type": 1010,
        "id": j.welcomeid,
        "unixtime": j.unixtime,
        "userid": j.otherid,
        "username": j.username,
        "journalid": j.targetid,
        "title": j.title,
    } for j in journals]
Пример #39
0
def filter_submissions(userid, submissions, incidence_limit=3):
    """
    Filters a list of submissions according to the user's preferences and
    optionally limits the number of items returned from one submitter.

    :param userid: The userid to use for blocked tags and rating. Usually the
        viewing user.
    :type userid: int.
    :param submissions: A list of submissions with appropriate fields (rating,
        userid, etc.)
    :type submissions: A list of submission dictionaries.
    :param incidence_limit: The maximum number of submissions to permit from
        one creator. Set to 0 or None for no limit.
    :type incidence_limit: int.
    :return: An iterator over the submissions after filtering by the user's
        settings and incidence limit.
    """
    blocked_tags = ignored_users = set()
    rating = ratings.GENERAL.code
    if userid:
        rating = d.get_rating(userid)
        blocked_tags = blocktag.select_ids(userid)
        ignored_users = set(ignoreuser.cached_list_ignoring(userid))

    submitter_incidence = collections.defaultdict(int)
    for s in submissions:
        if incidence_limit and submitter_incidence[s['userid']] >= incidence_limit:
            continue
        if s['rating'] > rating:
            continue
        if s['userid'] in ignored_users:
            continue
        tags = set(s['tags'])
        if blocktag.check_list(s['rating'], tags, blocked_tags):
            continue
        submitter_incidence[s['userid']] += 1
        yield s
Пример #40
0
    def GET(self, login):
        userid = profile.resolve_by_login(login)
        if not userid:
            web.ctx.status = '404 Not Found'
            raise WeasylError('userRecordMissing')

        form = web.input(since=None, count=0, folderid=0, backid=0, nextid=0)
        since = None
        try:
            if form.since:
                since = d.parse_iso8601(form.since)
            count = int(form.count)
            folderid = int(form.folderid)
            backid = int(form.backid)
            nextid = int(form.nextid)
        except ValueError:
            web.ctx.status = '422 Unprocessable Entity'
            return json.dumps(_ERROR_UNEXPECTED)
        else:
            count = min(count or 100, 100)

        submissions = submission.select_list(
            self.user_id, d.get_rating(self.user_id), count + 1,
            otherid=userid, folderid=folderid, backid=backid, nextid=nextid)
        backid, nextid = d.paginate(submissions, backid, nextid, count, 'submitid')

        ret = []
        for sub in submissions:
            if since is not None and since >= sub['unixtime']:
                break
            tidy_submission(sub)
            ret.append(sub)

        return json.dumps({
            'backid': backid, 'nextid': nextid,
            'submissions': ret,
        })
Пример #41
0
def collections_(request):
    form = request.web_input(userid="", name="", backid=None, nextid=None,
                             folderid=None)
    form.name = request.matchdict.get('name', form.name)
    form.userid = define.get_int(form.userid)

    config = define.get_config(request.userid)
    rating = define.get_rating(request.userid)
    otherid = profile.resolve(request.userid, form.userid, form.name)

    if not otherid:
        raise WeasylError("userRecordMissing")
    elif not request.userid and "h" in define.get_config(otherid):
        return Response(define.errorpage(request.userid, errorcode.no_guest_access))

    userprofile = profile.select_profile(otherid, images=True, viewer=request.userid)
    has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != ''
    page_title = u"%s's collections" % (userprofile['full_name'] if has_fullname else userprofile['username'],)
    page = define.common_page_start(request.userid, title=page_title)

    url_format = "/collections?userid={userid}&%s".format(userid=userprofile['userid'])
    result = pagination.PaginatedResult(
        collection.select_list, collection.select_count, 'submitid', url_format, request.userid, rating, 66,
        otherid=otherid, backid=define.get_int(form.backid), nextid=define.get_int(form.nextid), config=config)

    page.append(define.render('user/collections.html', [
        # Profile information
        userprofile,
        # User information
        profile.select_userinfo(otherid, config=userprofile['config']),
        # Relationship
        profile.select_relation(request.userid, otherid),
        # Collections
        result,
    ]))

    return Response(define.common_page_end(request.userid, page))
Пример #42
0
def select_view_api(userid, charid, anyway=False, increment_views=False):
    rating = define.get_rating(userid)

    query = _select_character_and_check(
        userid, charid, rating=rating, ignore=anyway,
        anyway=anyway, increment_views=increment_views)

    login = define.get_sysname(query['username'])

    return {
        'charid': charid,
        'owner': query['username'],
        'owner_login': login,
        'owner_media': api.tidy_all_media(
            media.get_user_media(query['userid'])),
        'posted_at': define.iso8601(query['unixtime']),
        'title': query['char_name'],
        'age': query['age'],
        'gender': query['gender'],
        'height': query['height'],
        'weight': query['weight'],
        'species': query['species'],
        'content': text.markdown(query['content']),
        'rating': ratings.CODE_TO_NAME[query['rating']],
        'favorited': favorite.check(userid, charid=charid),
        'views': query['page_views'],
        'friends_only': 'f' in query['settings'],
        'favorites': favorite.count(charid, 'character'),
        'comments': comment.count(charid, 'character'),
        'media': api.tidy_all_media(fake_media_items(
            charid, query['userid'], login, query['settings'])),
        'tags': searchtag.select(charid=charid),
        'type': 'character',
        'link': define.absolutify_url(
            '/character/%d/%s' % (charid, text.slug_for(query['char_name']))),
    }
Пример #43
0
def select_view_api(userid, charid, anyway=False, increment_views=False):
    rating = define.get_rating(userid)

    query = _select_character_and_check(
        userid, charid, rating=rating, ignore=anyway,
        anyway=anyway, increment_views=increment_views)

    login = define.get_sysname(query['username'])

    return {
        'charid': charid,
        'owner': query['username'],
        'owner_login': login,
        'owner_media': api.tidy_all_media(
            media.get_user_media(query['userid'])),
        'posted_at': define.iso8601(query['unixtime']),
        'title': query['char_name'],
        'age': query['age'],
        'gender': query['gender'],
        'height': query['height'],
        'weight': query['weight'],
        'species': query['species'],
        'content': text.markdown(query['content']),
        'rating': ratings.CODE_TO_NAME[query['rating']],
        'favorited': favorite.check(userid, charid=charid),
        'views': query['page_views'],
        'friends_only': 'f' in query['settings'],
        'favorites': favorite.count(charid, 'character'),
        'comments': comment.count(charid, 'character'),
        'media': api.tidy_all_media(fake_media_items(
            charid, query['userid'], login, query['settings'])),
        'tags': searchtag.select(charid=charid),
        'type': 'character',
        'link': define.absolutify_url(
            '/character/%d/%s' % (charid, text.slug_for(query['char_name']))),
    }
Пример #44
0
def streaming_(request):
    rating = define.get_rating(request.userid)
    return Response(define.webpage(request.userid, 'etc/streaming.html',
                                   (profile.select_streaming(request.userid, rating, 300, order_by="start_time desc"),),
                                   title="Streaming"))
Пример #45
0
def select_submissions(userid, limit, backtime=None, nexttime=None):
    if backtime:
        time_filter = "AND unixtime > %(backtime)s"
    elif nexttime:
        time_filter = "AND unixtime < %(nexttime)s"
    else:
        time_filter = ""

    statement = """
        SELECT * FROM (
            SELECT
                20 AS contype,
                ch.charid AS id,
                ch.char_name AS title,
                ch.rating,
                ch.unixtime,
                ch.userid,
                pr.username,
                ch.settings,
                we.welcomeid,
                0 AS subtype,
                array_agg(tags.title) AS tags
            FROM welcome we
                INNER JOIN character ch ON we.targetid = ch.charid
                INNER JOIN profile pr ON ch.userid = pr.userid
                LEFT JOIN searchmapchar AS smc ON ch.charid = smc.targetid
                LEFT JOIN searchtag AS tags USING (tagid)
            WHERE
                we.type = 2050 AND
                we.userid = %(userid)s
            GROUP BY
                ch.charid,
                pr.username,
                we.welcomeid
            UNION SELECT
                40 AS contype,
                su.submitid AS id,
                su.title,
                su.rating,
                su.unixtime,
                we.otherid AS userid,
                pr.username,
                su.settings,
                we.welcomeid,
                su.subtype,
                array_agg(tags.title) AS tags
            FROM welcome we
                INNER JOIN submission su ON we.targetid = su.submitid
                INNER JOIN profile pr ON we.otherid = pr.userid
                LEFT JOIN searchmapsubmit AS sms ON su.submitid = sms.targetid
                LEFT JOIN searchtag AS tags USING (tagid)
            WHERE
                we.type = 2030 AND
                we.userid = %(userid)s
            GROUP BY
                su.submitid,
                pr.username,
                we.welcomeid
            UNION SELECT
                10 AS contype,
                su.submitid AS id,
                su.title,
                su.rating,
                su.unixtime,
                su.userid,
                pr.username,
                su.settings,
                we.welcomeid,
                su.subtype,
                array_agg(tags.title) AS tags
            FROM welcome we
                INNER JOIN submission su ON we.targetid = su.submitid
                INNER JOIN profile pr ON su.userid = pr.userid
                LEFT JOIN searchmapsubmit AS sms ON su.submitid = sms.targetid
                LEFT JOIN searchtag AS tags USING (tagid)
            WHERE
                we.type = 2010 AND
                we.userid = %(userid)s
            GROUP BY
                su.submitid,
                pr.username,
                we.welcomeid
        ) results
        WHERE
            rating <= %(rating)s
            {time_filter}
        ORDER BY unixtime DESC
        LIMIT %(limit)s
    """.format(time_filter=time_filter)

    query = d.engine.execute(
        statement,
        userid=userid,
        rating=d.get_rating(userid),
        nexttime=nexttime,
        backtime=backtime,
        limit=limit,
    )

    results = [{
        "contype": i.contype,
        "submitid" if i.contype != _CONTYPE_CHAR else "charid": i.id,
        "welcomeid": i.welcomeid,
        "title": i.title,
        "rating": i.rating,
        "unixtime": i.unixtime,
        "userid": i.userid,
        "username": i.username,
        "subtype": i.subtype,
        "tags": i.tags,
        "sub_media": _fake_media_items(i),
    } for i in query]

    media.populate_with_submission_media(
        [i for i in results if i["contype"] != _CONTYPE_CHAR])

    return results
Пример #46
0
    def GET(self, name=""):
        def _FEATURE(target):
            if target == "submit":
                return 10
            elif target == "char":
                return 20
            elif target == "journal":
                return 30
            else:
                return 0

        form = web.input(userid="", name="", feature="", backid=None, nextid=None)
        form.name = name if name else form.name
        form.userid = define.get_int(form.userid)

        config = define.get_config(self.user_id)
        rating = define.get_rating(self.user_id)
        otherid = profile.resolve(self.user_id, form.userid, form.name)

        if not otherid:
            raise WeasylError("userRecordMissing")
        elif not self.user_id and "h" in define.get_config(otherid):
            return define.errorpage(self.user_id, errorcode.no_guest_access)
        elif self.user_id != otherid and 'v' in define.get_config(otherid):
            return define.errorpage(
                self.user_id,
                "You cannot view this page because the owner does not allow anyone to see their favorites.")

        userprofile = profile.select_profile(otherid, images=True, viewer=self.user_id)
        has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != ''
        page_title = u"%s's favorites" % (userprofile['full_name'] if has_fullname else userprofile['username'],)
        page = define.common_page_start(self.user_id, title=page_title)

        if form.feature:
            nextid = define.get_int(form.nextid)
            backid = define.get_int(form.backid)
            url_format = (
                "/favorites?userid={userid}&feature={feature}&%s".format(userid=userprofile['userid'], feature=form.feature))
            id_field = form.feature + "id"

            count_function = None
            if form.feature == "submit":
                select_function = favorite.select_submit
                count_function = favorite.select_submit_count
            elif form.feature == "char":
                select_function = favorite.select_char
            elif form.feature == "journal":
                select_function = favorite.select_journal

            faves = pagination.PaginatedResult(
                select_function, count_function,
                id_field, url_format, self.user_id, rating, 60,
                otherid=otherid, backid=backid, nextid=nextid, config=config)
        else:
            faves = {
                "submit": favorite.select_submit(self.user_id, rating, 22, otherid=otherid, config=config),
                "char": favorite.select_char(self.user_id, rating, 22, otherid=otherid, config=config),
                "journal": favorite.select_journal(self.user_id, rating, 22, otherid=otherid, config=config),
            }

        page.append(define.render(template.user_favorites, [
            # Profile information
            userprofile,
            # User information
            profile.select_userinfo(otherid, config=userprofile['config']),
            # Relationship
            profile.select_relation(self.user_id, otherid),
            # Feature
            form.feature,
            # Favorites
            faves,
        ]))

        return define.common_page_end(self.user_id, page)
Пример #47
0
def favorites_(request):
    name = request.matchdict.get('name', request.params.get('name', ''))
    userid = define.get_int(request.params.get('userid'))

    rating = define.get_rating(request.userid)
    otherid = profile.resolve(request.userid, userid, name)

    backid = request.params.get('backid')
    nextid = request.params.get('nextid')

    feature = request.params.get('feature', False)

    # TODO(hyena): Why aren't more of these WeasylErrors?
    if not otherid:
        raise WeasylError("userRecordMissing")
    elif not request.userid and "h" in define.get_config(otherid):
        raise WeasylError('noGuests')
    elif request.userid != otherid and 'v' in define.get_config(otherid):
        raise WeasylError('hiddenFavorites')

    userprofile = profile.select_profile(otherid, viewer=request.userid)
    has_fullname = userprofile[
        'full_name'] is not None and userprofile['full_name'].strip() != ''
    page_title = u"%s's favorites" % (userprofile['full_name'] if has_fullname
                                      else userprofile['username'], )
    page = define.common_page_start(request.userid, title=page_title)

    if feature:
        nextid = define.get_int(nextid)
        backid = define.get_int(backid)
        url_format = ("/favorites?userid={userid}&feature={feature}&%s".format(
            userid=otherid, feature=feature))
        id_field = feature + "id"

        count_function = None
        if feature == "submit":
            select_function = favorite.select_submit
            count_function = favorite.select_submit_count
        elif feature == "char":
            select_function = favorite.select_char
        elif feature == "journal":
            select_function = favorite.select_journal
        else:
            raise httpexceptions.HTTPNotFound()

        faves = pagination.PaginatedResult(select_function,
                                           count_function,
                                           id_field,
                                           url_format,
                                           request.userid,
                                           rating,
                                           limit=60,
                                           otherid=otherid,
                                           backid=backid,
                                           nextid=nextid)
    else:
        faves = {
            "submit":
            favorite.select_submit(request.userid, rating, 22,
                                   otherid=otherid),
            "char":
            favorite.select_char(request.userid, rating, 22, otherid=otherid),
            "journal":
            favorite.select_journal(request.userid,
                                    rating,
                                    22,
                                    otherid=otherid),
        }

    page.append(
        define.render(
            'user/favorites.html',
            [
                # Profile information
                userprofile,
                # User information
                profile.select_userinfo(otherid, config=userprofile['config']),
                # Relationship
                profile.select_relation(request.userid, otherid),
                # Feature
                feature,
                # Favorites
                faves,
            ]))

    return Response(define.common_page_end(request.userid, page))
Пример #48
0
def select_submissions(userid, limit, include_tags, backtime=None, nexttime=None):
    if backtime:
        time_filter = "AND we.unixtime > %(backtime)s"
    elif nexttime:
        time_filter = "AND we.unixtime < %(nexttime)s"
    else:
        time_filter = ""

    if include_tags:
        char_tags_select = ", COALESCE(array_agg(tagid) FILTER (WHERE tagid IS NOT NULL), '{}') AS tags"
        char_tags_join = "LEFT JOIN searchmapchar AS smc ON ch.charid = smc.targetid"
        char_tags_groupby = "GROUP BY ch.charid, pr.username, we.welcomeid"

        submission_tags_select = ", tags"
        submission_tags_join = "INNER JOIN submission_tags USING (submitid)"
    else:
        char_tags_select = char_tags_join = char_tags_groupby = submission_tags_select = submission_tags_join = ""

    statement = """
        SELECT * FROM (
            SELECT
                20 AS contype,
                ch.charid AS id,
                ch.char_name AS title,
                ch.rating,
                we.unixtime,
                ch.userid,
                pr.username,
                ch.settings,
                we.welcomeid,
                0 AS subtype
                {char_tags_select}
            FROM welcome we
                INNER JOIN character ch ON we.targetid = ch.charid
                INNER JOIN profile pr ON ch.userid = pr.userid
                {char_tags_join}
            WHERE
                we.type = 2050 AND
                we.userid = %(userid)s AND
                ch.rating <= %(rating)s
                {time_filter}
            {char_tags_groupby}
            ORDER BY welcomeid DESC LIMIT %(limit)s
        ) t
        UNION ALL SELECT * FROM (
            SELECT
                40 AS contype,
                su.submitid AS id,
                su.title,
                su.rating,
                we.unixtime,
                we.otherid AS userid,
                pr.username,
                su.settings,
                we.welcomeid,
                su.subtype
                {submission_tags_select}
            FROM welcome we
                INNER JOIN submission su ON we.targetid = su.submitid
                INNER JOIN profile pr ON we.otherid = pr.userid
                {submission_tags_join}
            WHERE
                we.type = 2030 AND
                we.userid = %(userid)s AND
                su.rating <= %(rating)s
                {time_filter}
            ORDER BY welcomeid DESC LIMIT %(limit)s
        ) t
        UNION ALL SELECT * FROM (
            SELECT
                10 AS contype,
                su.submitid AS id,
                su.title,
                su.rating,
                we.unixtime,
                su.userid,
                pr.username,
                su.settings,
                we.welcomeid,
                su.subtype
                {submission_tags_select}
            FROM welcome we
                INNER JOIN submission su ON we.targetid = su.submitid
                INNER JOIN profile pr ON su.userid = pr.userid
                {submission_tags_join}
            WHERE
                we.type = 2010 AND
                we.userid = %(userid)s AND
                su.rating <= %(rating)s
                {time_filter}
            ORDER BY welcomeid DESC LIMIT %(limit)s
        ) t
        ORDER BY welcomeid DESC LIMIT %(limit)s
    """.format(
        time_filter=time_filter,
        char_tags_select=char_tags_select,
        char_tags_join=char_tags_join,
        char_tags_groupby=char_tags_groupby,
        submission_tags_select=submission_tags_select,
        submission_tags_join=submission_tags_join,
    )

    query = d.engine.execute(
        statement,
        userid=userid,
        rating=d.get_rating(userid),
        nexttime=nexttime,
        backtime=backtime,
        limit=limit,
    ).fetchall()

    if include_tags:
        all_tags = list(frozenset(chain.from_iterable(i.tags for i in query)))
        tag_map = {t.tagid: t.title for t in d.engine.execute("SELECT tagid, title FROM searchtag WHERE tagid = ANY (%(tags)s)", tags=all_tags)}

        results = [{
            "contype": i.contype,
            "submitid" if i.contype != _CONTYPE_CHAR else "charid": i.id,
            "welcomeid": i.welcomeid,
            "title": i.title,
            "rating": i.rating,
            "unixtime": i.unixtime,
            "userid": i.userid,
            "username": i.username,
            "subtype": i.subtype,
            "tags": [tag_map[tag] for tag in i.tags],
            "sub_media": _fake_media_items(i),
        } for i in query]
    else:
        results = [{
            "contype": i.contype,
            "submitid" if i.contype != _CONTYPE_CHAR else "charid": i.id,
            "welcomeid": i.welcomeid,
            "title": i.title,
            "rating": i.rating,
            "unixtime": i.unixtime,
            "userid": i.userid,
            "username": i.username,
            "subtype": i.subtype,
            "sub_media": _fake_media_items(i),
        } for i in query]

    media.populate_with_submission_media(
        [i for i in results if i["contype"] != _CONTYPE_CHAR])

    return results
Пример #49
0
Файл: api.py Проект: 0x15/weasyl
    def GET(self, login):
        userid = self.user_id
        otherid = profile.resolve_by_login(login)
        user = profile.select_profile(otherid)

        rating = d.get_rating(userid)
        u_config = d.get_config(userid)
        o_config = user.pop('config')
        o_settings = user.pop('settings')

        if not otherid and "h" in o_config:
            return json.dumps({
                "error": {
                    "code": 200,
                    "text": "Profile hidden from unlogged users."
                }})

        user.pop('userid', None)
        user.pop('commish_slots', None)

        user['created_at'] = d.iso8601(user.pop('unixtime'))
        user['media'] = api.tidy_all_media(user.pop('user_media'))
        user['login_name'] = d.get_sysname(user['username'])
        user['profile_text'] = markdown(user['profile_text'])

        folders = folder.select_list(otherid, "api/all")
        if folders:
            old_folders = folders
            folders = list()
            for fldr in (i for i in old_folders if 'parentid' not in i):
                newfolder = {
                    "folder_id": fldr['folderid'],
                    "title": fldr['title']
                }

                if fldr['haschildren']:
                    subfolders = list()
                    for sub in (i for i in old_folders if 'parentid' in i and i['parentid'] == fldr['folderid']):
                        subfolders.append({
                            "folder_id": sub['folderid'],
                            "title": sub['title']
                        })

                    newfolder['subfolders'] = subfolders

                folders.append(newfolder)

        user['folders'] = folders

        commissions = {
            "details": None,
            "price_classes": None,
            "commissions": self.convert_commission_setting(o_settings[0]),
            "trades": self.convert_commission_setting(o_settings[1]),
            "requests": self.convert_commission_setting(o_settings[2])
        }

        commission_list = commishinfo.select_list(otherid)
        if commission_list:
            commissions['details'] = commission_list['content']

            if len(commission_list['class']) > 0:
                classes = list()
                for cclass in commission_list['class']:
                    commission_class = {
                        "title": cclass['title']
                    }

                    if len(commission_list['price']) > 0:
                        prices = list()
                        for cprice in (i for i in commission_list['price'] if i['classid'] == cclass['classid']):
                            if 'a' in cprice['settings']:
                                ptype = 'additional'
                            else:
                                ptype = 'base'

                            price = {
                                "title": cprice['title'],
                                "price_min": self.convert_commission_price(cprice['amount_min'], cprice['settings']),
                                "price_max": self.convert_commission_price(cprice['amount_min'], cprice['settings']),
                                'price_type': ptype
                            }
                            prices.append(price)
                        commission_class['prices'] = prices

                    classes.append(commission_class)
                commissions['price_classes'] = classes

        user['commission_info'] = commissions

        user['relationship'] = profile.select_relation(userid, otherid) if userid else None

        if 'O' in o_config:
            submissions = collection.select_list(
                userid, rating, 11, otherid=otherid, options=["cover"], config=u_config)
            more_submissions = 'collections'
            featured = None
        elif 'A' in o_config:
            submissions = character.select_list(
                userid, rating, 11, otherid=otherid, options=["cover"], config=u_config)
            more_submissions = 'characters'
            featured = None
        else:
            submissions = submission.select_list(
                userid, rating, 11, otherid=otherid, options=["cover"], config=u_config,
                profile_page_filter=True)
            more_submissions = 'submissions'
            featured = submission.select_featured(userid, otherid, rating)

        if submissions:
            submissions = map(tidy_submission, submissions)

        user['recent_submissions'] = submissions
        user['recent_type'] = more_submissions

        if featured:
            featured = tidy_submission(featured)

        user['featured_submission'] = featured

        statistics = profile.select_statistics(otherid)
        if statistics:
            statistics.pop('staff_notes')
        user['statistics'] = statistics

        user_info = profile.select_userinfo(otherid)
        if user_info:
            if not user_info['show_age']:
                user_info['age'] = None
            user_info.pop('show_age', None)
            user_info.pop('birthday', None)
            user_info['location'] = user_info.pop('country', None)
        user['user_info'] = user_info
        user['link'] = d.absolutify_url("/~" + user['login_name'])

        return json.dumps(user)
Пример #50
0
def profile_(request):
    name = request.params.get('name', '')
    name = request.matchdict.get('name', name)
    userid = define.get_int(request.params.get('userid'))

    rating = define.get_rating(request.userid)
    otherid = profile.resolve(request.userid, userid, name)

    if not otherid:
        raise WeasylError("userRecordMissing")

    userprofile = profile.select_profile(otherid, viewer=request.userid)
    is_unverified = otherid != request.userid and not define.is_vouched_for(
        otherid)

    if is_unverified and request.userid not in staff.MODS:
        can_vouch = request.userid != 0 and define.is_vouched_for(
            request.userid)

        return Response(
            define.webpage(
                request.userid,
                "error/unverified.html",
                [request, otherid, userprofile['username'], can_vouch],
            ),
            status=403,
        )

    extras = {
        "canonical_url": "/~" + define.get_sysname(userprofile['username'])
    }

    if not request.userid:
        # Only generate the Twitter/OGP meta headers if not authenticated (the UA viewing is likely automated).
        twit_card = profile.twitter_card(otherid)
        if define.user_is_twitterbot():
            extras['twitter_card'] = twit_card
        # The "og:" prefix is specified in page_start.html, and og:image is required by the OGP spec, so something must be in there.
        extras['ogp'] = {
            'title':
            twit_card['title'],
            'site_name':
            "Weasyl",
            'type':
            "website",
            'url':
            twit_card['url'],
            'description':
            twit_card['description'],
            'image':
            twit_card['image:src'] if 'image:src' in twit_card else
            define.get_resource_url('img/logo-mark-light.svg'),
        }

    if not request.userid and "h" in userprofile['config']:
        raise WeasylError('noGuests')

    has_fullname = userprofile[
        'full_name'] is not None and userprofile['full_name'].strip() != ''
    extras['title'] = u"%s's profile" % (userprofile['full_name']
                                         if has_fullname else
                                         userprofile['username'], )

    page = define.common_page_start(request.userid, **extras)
    define.common_view_content(request.userid, otherid, "profile")

    if 'O' in userprofile['config']:
        submissions = collection.select_list(request.userid,
                                             rating,
                                             11,
                                             otherid=otherid)
        more_submissions = 'collections'
        featured = None
    elif 'A' in userprofile['config']:
        submissions = character.select_list(request.userid,
                                            rating,
                                            11,
                                            otherid=otherid)
        more_submissions = 'characters'
        featured = None
    else:
        submissions = submission.select_list(request.userid,
                                             rating,
                                             11,
                                             otherid=otherid,
                                             profile_page_filter=True)
        more_submissions = 'submissions'
        featured = submission.select_featured(request.userid, otherid, rating)

    if userprofile['show_favorites_bar']:
        favorites = favorite.select_submit(request.userid,
                                           rating,
                                           11,
                                           otherid=otherid)
    else:
        favorites = None

    statistics, show_statistics = profile.select_statistics(otherid)

    page.append(
        define.render(
            'user/profile.html',
            [
                request,
                # Profile information
                userprofile,
                # User information
                profile.select_userinfo(otherid, config=userprofile['config']),
                macro.SOCIAL_SITES,
                # Relationship
                profile.select_relation(request.userid, otherid),
                # Myself
                profile.select_myself(request.userid),
                # Recent submissions
                submissions,
                more_submissions,
                favorites,
                featured,
                # Folders preview
                folder.select_preview(request.userid, otherid, rating),
                # Latest journal
                journal.select_latest(request.userid, rating, otherid=otherid),
                # Recent shouts
                shout.select(request.userid, ownerid=otherid, limit=8),
                # Statistics information
                statistics,
                show_statistics,
                # Commission information
                commishinfo.select_list(otherid),
                # Friends
                lambda: frienduser.has_friends(otherid),
                is_unverified,
            ]))

    return Response(define.common_page_end(request.userid, page))
Пример #51
0
def submission_(request):
    username = request.matchdict.get('name')
    submitid = request.matchdict.get('submitid')

    form = request.web_input(submitid="", ignore="", anyway="")

    rating = define.get_rating(request.userid)
    submitid = define.get_int(submitid) if submitid else define.get_int(form.submitid)

    extras = {}

    if not request.userid:
        # Only generate the Twitter/OGP meta headers if not authenticated (the UA viewing is likely automated).
        twit_card = submission.twitter_card(submitid)
        if define.user_is_twitterbot():
            extras['twitter_card'] = twit_card
        # The "og:" prefix is specified in page_start.html, and og:image is required by the OGP spec, so something must be in there.
        extras['ogp'] = {
            'title': twit_card['title'],
            'site_name': "Weasyl",
            'type': "website",
            'url': twit_card['url'],
            'description': twit_card['description'],
            # >> BUG AVOIDANCE: https://trello.com/c/mBx51jfZ/1285-any-image-link-with-in-it-wont-preview-up-it-wont-show-up-in-embeds-too
            #    Image URLs with '~' in it will not be displayed by Discord, so replace ~ with the URL encoded char code %7E
            'image': twit_card['image:src'].replace('~', '%7E') if 'image:src' in twit_card else define.cdnify_url(
                '/static/images/logo-mark-light.svg'),
        }

    try:
        item = submission.select_view(
            request.userid, submitid, rating,
            ignore=define.text_bool(form.ignore, True), anyway=form.anyway
        )
    except WeasylError as we:
        we.errorpage_kwargs = extras
        if we.value in ("UserIgnored", "TagBlocked"):
            extras['links'] = [
                ("View Submission", "?ignore=false"),
                ("Return to the Home Page", "/index"),
            ]
        raise

    login = define.get_sysname(item['username'])
    canonical_path = request.route_path('submission_detail_profile', name=login, submitid=submitid, slug=slug_for(item['title']))

    if request.GET.get('anyway'):
        canonical_path += '?anyway=true'

    if login != username:
        raise httpexceptions.HTTPMovedPermanently(location=canonical_path)
    extras["canonical_url"] = canonical_path
    extras["title"] = item["title"]

    submission_files = item["sub_media"].get("submission")
    submission_file = submission_files[0] if submission_files else None
    extras["pdf"] = bool(submission_file) and submission_file["file_type"] == "pdf"

    page = define.common_page_start(request.userid, **extras)
    page.append(define.render('detail/submission.html', [
        # Myself
        profile.select_myself(request.userid),
        # Submission detail
        item,
        # Subtypes
        macro.MACRO_SUBCAT_LIST,
        # Violations
        [i for i in macro.MACRO_REPORT_VIOLATION if 2000 <= i[0] < 3000],
    ]))

    return Response(define.common_page_end(request.userid, page))
Пример #52
0
def favorites_(request):
    def _FEATURE(target):
        if target == "submit":
            return 10
        elif target == "char":
            return 20
        elif target == "journal":
            return 30
        else:
            return 0

    form = request.web_input(userid="",
                             name="",
                             feature="",
                             backid=None,
                             nextid=None)
    form.name = request.matchdict.get('name', form.name)
    form.userid = define.get_int(form.userid)

    config = define.get_config(request.userid)
    rating = define.get_rating(request.userid)
    otherid = profile.resolve(request.userid, form.userid, form.name)

    # TODO(hyena): Why aren't more of these WeasylErrors?
    if not otherid:
        raise WeasylError("userRecordMissing")
    elif not request.userid and "h" in define.get_config(otherid):
        return Response(
            define.errorpage(request.userid, errorcode.no_guest_access))
    elif request.userid != otherid and 'v' in define.get_config(otherid):
        return Response(
            define.errorpage(
                request.userid,
                "You cannot view this page because the owner does not allow anyone to see their favorites."
            ))

    userprofile = profile.select_profile(otherid,
                                         images=True,
                                         viewer=request.userid)
    has_fullname = userprofile[
        'full_name'] is not None and userprofile['full_name'].strip() != ''
    page_title = u"%s's favorites" % (userprofile['full_name'] if has_fullname
                                      else userprofile['username'], )
    page = define.common_page_start(request.userid, title=page_title)

    if form.feature:
        nextid = define.get_int(form.nextid)
        backid = define.get_int(form.backid)
        url_format = ("/favorites?userid={userid}&feature={feature}&%s".format(
            userid=userprofile['userid'], feature=form.feature))
        id_field = form.feature + "id"

        count_function = None
        if form.feature == "submit":
            select_function = favorite.select_submit
            count_function = favorite.select_submit_count
        elif form.feature == "char":
            select_function = favorite.select_char
        elif form.feature == "journal":
            select_function = favorite.select_journal
        else:
            raise httpexceptions.HTTPNotFound()

        faves = pagination.PaginatedResult(select_function,
                                           count_function,
                                           id_field,
                                           url_format,
                                           request.userid,
                                           rating,
                                           60,
                                           otherid=otherid,
                                           backid=backid,
                                           nextid=nextid,
                                           config=config)
    else:
        faves = {
            "submit":
            favorite.select_submit(request.userid,
                                   rating,
                                   22,
                                   otherid=otherid,
                                   config=config),
            "char":
            favorite.select_char(request.userid,
                                 rating,
                                 22,
                                 otherid=otherid,
                                 config=config),
            "journal":
            favorite.select_journal(request.userid,
                                    rating,
                                    22,
                                    otherid=otherid,
                                    config=config),
        }

    page.append(
        define.render(
            'user/favorites.html',
            [
                # Profile information
                userprofile,
                # User information
                profile.select_userinfo(otherid, config=userprofile['config']),
                # Relationship
                profile.select_relation(request.userid, otherid),
                # Feature
                form.feature,
                # Favorites
                faves,
            ]))

    return Response(define.common_page_end(request.userid, page))
Пример #53
0
def search_(request):
    rating = define.get_rating(request.userid)

    form = request.web_input(q="", find="", within="", rated=[], cat="", subcat="", backid="", nextid="")

    page = define.common_page_start(request.userid, title="Browse and search")

    if form.q:
        find = form.find

        if find not in ("submit", "char", "journal", "user"):
            find = "submit"

        q = form.q.strip()
        search_query = search.Query.parse(q, find)

        meta = {
            "q": q,
            "find": search_query.find,
            "within": form.within,
            "rated": set('gap') & set(form.rated),
            "cat": int(form.cat) if form.cat else None,
            "subcat": int(form.subcat) if form.subcat else None,
            "backid": int(form.backid) if form.backid else None,
            "nextid": int(form.nextid) if form.nextid else None,
        }

        if search_query.find == "user":
            query = search.select_users(q)
            next_count = back_count = 0
        else:
            search_query.ratings.update(ratings.CHARACTER_MAP[rating_code].code for rating_code in meta["rated"])

            query, next_count, back_count = search.select(
                userid=request.userid,
                rating=rating,
                limit=63,
                search=search_query,
                within=meta["within"],
                cat=meta["cat"],
                subcat=meta["subcat"],
                backid=meta["backid"],
                nextid=meta["nextid"])

        page.append(define.render("etc/search.html", [
            # Search method
            {"method": "search"},
            # Search metadata
            meta,
            # Search results
            query,
            next_count,
            back_count,
            # Submission subcategories
            macro.MACRO_SUBCAT_LIST,
            search.COUNT_LIMIT,
        ]))
    elif form.find:
        query = search.browse(request.userid, rating, 66, form)

        meta = {
            "find": form.find,
            "cat": int(form.cat) if form.cat else None,
        }

        page.append(define.render("etc/search.html", [
            # Search method
            {"method": "browse"},
            # Search metadata
            meta,
            # Search results
            query,
            0,
            0,
        ]))
    else:
        page.append(define.render("etc/search.html", [
            # Search method
            {"method": "summary"},
            # Search metadata
            None,
            # Search results
            {
                "submit": search.browse(request.userid, rating, 22, form, find="submit"),
                "char": search.browse(request.userid, rating, 22, form, find="char"),
                "journal": search.browse(request.userid, rating, 22, form, find="journal"),
            },
        ]))

    return Response(define.common_page_end(request.userid, page, options={'search'}))
Пример #54
0
def favorites_(request):
    def _FEATURE(target):
        if target == "submit":
            return 10
        elif target == "char":
            return 20
        elif target == "journal":
            return 30
        else:
            return 0

    form = request.web_input(userid="", name="", feature="", backid=None, nextid=None)
    form.name = request.matchdict.get('name', form.name)
    form.userid = define.get_int(form.userid)

    config = define.get_config(request.userid)
    rating = define.get_rating(request.userid)
    otherid = profile.resolve(request.userid, form.userid, form.name)

    # TODO(hyena): Why aren't more of these WeasylErrors?
    if not otherid:
        raise WeasylError("userRecordMissing")
    elif not request.userid and "h" in define.get_config(otherid):
        return Response(define.errorpage(request.userid, errorcode.no_guest_access))
    elif request.userid != otherid and 'v' in define.get_config(otherid):
        return Response(define.errorpage(
            request.userid,
            "You cannot view this page because the owner does not allow anyone to see their favorites."))

    userprofile = profile.select_profile(otherid, images=True, viewer=request.userid)
    has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != ''
    page_title = u"%s's favorites" % (userprofile['full_name'] if has_fullname else userprofile['username'],)
    page = define.common_page_start(request.userid, title=page_title)

    if form.feature:
        nextid = define.get_int(form.nextid)
        backid = define.get_int(form.backid)
        url_format = (
            "/favorites?userid={userid}&feature={feature}&%s".format(userid=userprofile['userid'], feature=form.feature))
        id_field = form.feature + "id"

        count_function = None
        if form.feature == "submit":
            select_function = favorite.select_submit
            count_function = favorite.select_submit_count
        elif form.feature == "char":
            select_function = favorite.select_char
        elif form.feature == "journal":
            select_function = favorite.select_journal
        else:
            raise httpexceptions.HTTPNotFound()

        faves = pagination.PaginatedResult(
            select_function, count_function,
            id_field, url_format, request.userid, rating, 60,
            otherid=otherid, backid=backid, nextid=nextid, config=config)
    else:
        faves = {
            "submit": favorite.select_submit(request.userid, rating, 22, otherid=otherid, config=config),
            "char": favorite.select_char(request.userid, rating, 22, otherid=otherid, config=config),
            "journal": favorite.select_journal(request.userid, rating, 22, otherid=otherid, config=config),
        }

    page.append(define.render('user/favorites.html', [
        # Profile information
        userprofile,
        # User information
        profile.select_userinfo(otherid, config=userprofile['config']),
        # Relationship
        profile.select_relation(request.userid, otherid),
        # Feature
        form.feature,
        # Favorites
        faves,
    ]))

    return Response(define.common_page_end(request.userid, page))
Пример #55
0
def profile_(request):
    form = request.web_input(userid="", name="")

    form.name = request.matchdict.get('name', form.name)
    form.userid = define.get_int(form.userid)

    config = define.get_config(request.userid)
    rating = define.get_rating(request.userid)
    otherid = profile.resolve(request.userid, form.userid, form.name)

    if not otherid:
        raise WeasylError("userRecordMissing")

    userprofile = profile.select_profile(otherid,
                                         images=True,
                                         viewer=request.userid)
    extras = {"canonical_url": "/~" + define.get_sysname(form.name)}

    if define.user_is_twitterbot():
        extras['twitter_card'] = profile.twitter_card(otherid)
        extras['options'] = ['nocache']

    if not request.userid and "h" in userprofile['config']:
        return Response(
            define.errorpage(
                request.userid,
                "You cannot view this page because the owner does not allow guests to view their profile.",
                **extras))

    has_fullname = userprofile[
        'full_name'] is not None and userprofile['full_name'].strip() != ''
    extras['title'] = u"%s's profile" % (userprofile['full_name']
                                         if has_fullname else
                                         userprofile['username'], )

    page = define.common_page_start(request.userid, **extras)
    define.common_view_content(request.userid, otherid, "profile")

    if 'O' in userprofile['config']:
        submissions = collection.select_list(request.userid,
                                             rating,
                                             11,
                                             otherid=otherid,
                                             options=["cover"],
                                             config=config)
        more_submissions = 'collections'
        featured = None
    elif 'A' in userprofile['config']:
        submissions = character.select_list(request.userid,
                                            rating,
                                            11,
                                            otherid=otherid,
                                            options=["cover"],
                                            config=config)
        more_submissions = 'characters'
        featured = None
    else:
        submissions = submission.select_list(request.userid,
                                             rating,
                                             11,
                                             otherid=otherid,
                                             options=["cover"],
                                             config=config,
                                             profile_page_filter=True)
        more_submissions = 'submissions'
        featured = submission.select_featured(request.userid, otherid, rating)

    if userprofile['show_favorites_bar']:
        favorites = favorite.select_submit(request.userid,
                                           rating,
                                           11,
                                           otherid=otherid,
                                           config=config)
    else:
        favorites = None

    page.append(
        define.render(
            'user/profile.html',
            [
                # Profile information
                userprofile,
                # User information
                profile.select_userinfo(otherid, config=userprofile['config']),
                macro.SOCIAL_SITES,
                # Relationship
                profile.select_relation(request.userid, otherid),
                # Myself
                profile.select_myself(request.userid),
                # Recent submissions
                submissions,
                more_submissions,
                favorites,
                featured,
                # Folders preview
                folder.select_preview(request.userid, otherid, rating, 3),
                # Latest journal
                journal.select_latest(
                    request.userid, rating, otherid=otherid, config=config),
                # Recent shouts
                shout.select(request.userid, ownerid=otherid, limit=8),
                # Statistics information
                profile.select_statistics(otherid),
                # Commission information
                commishinfo.select_list(otherid),
                # Friends
                frienduser.select(request.userid, otherid, 5, choose=None),
                # Following
                followuser.select_following(request.userid, otherid, choose=5),
                # Followed
                followuser.select_followed(request.userid, otherid, choose=5),
            ]))

    return Response(define.common_page_end(request.userid, page))
Пример #56
0
    def GET(self, name=""):
        now = time.time()

        form = web.input(userid="", name="")
        form.name = name if name else form.name
        form.userid = define.get_int(form.userid)

        config = define.get_config(self.user_id)
        rating = define.get_rating(self.user_id)
        otherid = profile.resolve(self.user_id, form.userid, form.name)

        if not otherid:
            raise WeasylError("userRecordMissing")

        userprofile = profile.select_profile(otherid, images=True, viewer=self.user_id)
        extras = {
            "canonical_url": "/~" + define.get_sysname(form.name)
        }

        if define.user_is_twitterbot():
            extras['twitter_card'] = profile.twitter_card(otherid)
            extras['options'] = ['nocache']

        if not self.user_id and "h" in userprofile['config']:
            return define.errorpage(
                self.user_id,
                "You cannot view this page because the owner does not allow guests to view their profile.",
                **extras)

        has_fullname = userprofile['full_name'] is not None and userprofile['full_name'].strip() != ''
        extras['title'] = u"%s's profile" % (userprofile['full_name'] if has_fullname else userprofile['username'],)

        page = define.common_page_start(self.user_id, **extras)
        define.common_view_content(self.user_id, otherid, "profile")

        if 'O' in userprofile['config']:
            submissions = collection.select_list(
                self.user_id, rating, 11, otherid=otherid, options=["cover"], config=config)
            more_submissions = 'collections'
            featured = None
        elif 'A' in userprofile['config']:
            submissions = character.select_list(
                self.user_id, rating, 11, otherid=otherid, options=["cover"], config=config)
            more_submissions = 'characters'
            featured = None
        else:
            submissions = submission.select_list(
                self.user_id, rating, 11, otherid=otherid, options=["cover"], config=config,
                profile_page_filter=True)
            more_submissions = 'submissions'
            featured = submission.select_featured(self.user_id, otherid, rating)

        if userprofile['show_favorites_bar']:
            favorites = favorite.select_submit(self.user_id, rating, 11, otherid=otherid, config=config)
        else:
            favorites = None

        page.append(define.render(template.user_profile, [
            # Profile information
            userprofile,
            # User information
            profile.select_userinfo(otherid, config=userprofile['config']),
            macro.SOCIAL_SITES,
            # Relationship
            profile.select_relation(self.user_id, otherid),
            # Myself
            profile.select_myself(self.user_id),
            # Recent submissions
            submissions, more_submissions,
            favorites,
            featured,
            # Folders preview
            folder.select_preview(self.user_id, otherid, rating, 3),
            # Latest journal
            journal.select_latest(self.user_id, rating, otherid=otherid, config=config),
            # Recent shouts
            shout.select(self.user_id, ownerid=otherid, limit=8),
            # Statistics information
            profile.select_statistics(otherid),
            # Commission information
            commishinfo.select_list(otherid),
            # Friends
            frienduser.select(self.user_id, otherid, 5, choose=None),
            # Following
            followuser.select_following(self.user_id, otherid, choose=5),
            # Followed
            followuser.select_followed(self.user_id, otherid, choose=5),
        ]))

        return define.common_page_end(self.user_id, page, now=now)