예제 #1
0
def test_content_view_twice(db, create_func, model, feature):
    """
    Two users viewing the same content increments the view count twice.
    """
    user1 = db_utils.create_user()
    user2 = db_utils.create_user()
    thing = create_func()
    assert d.common_view_content(user1, thing, feature)
    assert d.common_view_content(user2, thing, feature)
    assert db.query(model).get(thing).page_views == 2
예제 #2
0
파일: test_define.py 프로젝트: 0x15/weasyl
def test_content_view_same_user_twice(db, create_func, model, feature):
    """
    The same user viewing the same content twice does not increment the view
    count twice.
    """
    user = db_utils.create_user()
    thing = create_func()
    assert d.common_view_content(user, thing, feature)
    assert not d.common_view_content(user, thing, feature)
    assert db.query(model).get(thing).page_views == 1
예제 #3
0
파일: test_define.py 프로젝트: 0x15/weasyl
def test_two_anonymous_content_views(db, create_func, model, feature):
    """
    Two anonymous users coming from different IPs will both increment the view
    count separately.
    """
    thing = create_func()
    d.common_view_content(0, thing, feature)
    web.ctx.env['HTTP_X_FORWARDED_FOR'] = '127.0.0.2'
    assert d.common_view_content(0, thing, feature)
    assert db.query(model).get(thing).page_views == 2
예제 #4
0
def test_content_view_same_user_twice(db, create_func, model, feature):
    """
    The same user viewing the same content twice does not increment the view
    count twice.
    """
    user = db_utils.create_user()
    thing = create_func()
    assert d.common_view_content(user, thing, feature)
    assert not d.common_view_content(user, thing, feature)
    assert db.query(model).get(thing).page_views == 1
예제 #5
0
def test_two_anonymous_content_views(db, create_func, model, feature):
    """
    Two anonymous users coming from different IPs will both increment the view
    count separately.
    """
    thing = create_func()
    d.common_view_content(0, thing, feature)
    get_current_request().client_addr = '127.0.0.2'
    assert d.common_view_content(0, thing, feature)
    assert db.query(model).get(thing).page_views == 2
예제 #6
0
def test_two_anonymous_content_views(db, create_func, model, feature):
    """
    Two anonymous users coming from different IPs will both increment the view
    count separately.
    """
    thing = create_func()
    d.common_view_content(0, thing, feature)
    web.ctx.env['HTTP_X_FORWARDED_FOR'] = '127.0.0.2'
    assert d.common_view_content(0, thing, feature)
    assert db.query(model).get(thing).page_views == 2
예제 #7
0
파일: test_define.py 프로젝트: 0x15/weasyl
def test_content_view_twice(db, create_func, model, feature):
    """
    Two users viewing the same content increments the view count twice.
    """
    user1 = db_utils.create_user()
    user2 = db_utils.create_user()
    thing = create_func()
    assert d.common_view_content(user1, thing, feature)
    assert d.common_view_content(user2, thing, feature)
    assert db.query(model).get(thing).page_views == 2
예제 #8
0
def test_two_anonymous_content_views(db, create_func, model, feature):
    """
    Two anonymous users coming from different IPs will both increment the view
    count separately.
    """
    thing = create_func()
    d.common_view_content(0, thing, feature)
    get_current_request().client_addr = '127.0.0.2'
    assert d.common_view_content(0, thing, feature)
    assert db.query(model).get(thing).page_views == 2
예제 #9
0
파일: test_define.py 프로젝트: 0x15/weasyl
def test_content_view_same_user_twice_clearing_views(db, create_func, model, feature):
    """
    The same user viewing the same content twice *does* increment the view count
    twice iff the `views` table was truncated in between.
    """
    user = db_utils.create_user()
    thing = create_func()
    d.common_view_content(user, thing, feature)
    db.execute(d.meta.tables['views'].delete())
    assert d.common_view_content(user, thing, feature)
    assert db.query(model).get(thing).page_views == 2
예제 #10
0
def test_content_view_same_user_twice_clearing_views(db, create_func, model,
                                                     feature):
    """
    The same user viewing the same content twice *does* increment the view count
    twice iff the `views` table was truncated in between.
    """
    user = db_utils.create_user()
    thing = create_func()
    d.common_view_content(user, thing, feature)
    db.execute(d.meta.tables['views'].delete())
    assert d.common_view_content(user, thing, feature)
    assert db.query(model).get(thing).page_views == 2
예제 #11
0
파일: test_define.py 프로젝트: 0x15/weasyl
def test_anonymous_content_view(db, create_func, model, feature):
    """
    Content viewed anonymously also increments the view count.
    """
    thing = create_func()
    assert d.common_view_content(0, thing, feature)
    assert db.query(model).get(thing).page_views == 1
예제 #12
0
파일: test_define.py 프로젝트: 0x15/weasyl
def test_viewing_own_profile(db):
    """
    Viewing one's own profile does not increment the view count.
    """
    user = db_utils.create_user()
    assert not d.common_view_content(user, user, 'profile')
    assert db.query(users.Profile).get(user).page_views == 0
예제 #13
0
def test_viewing_own_profile(db):
    """
    Viewing one's own profile does not increment the view count.
    """
    user = db_utils.create_user()
    assert not d.common_view_content(user, user, 'profile')
    assert db.query(users.Profile).get(user).page_views == 0
예제 #14
0
def test_anonymous_content_view(db, create_func, model, feature):
    """
    Content viewed anonymously also increments the view count.
    """
    thing = create_func()
    assert d.common_view_content(0, thing, feature)
    assert db.query(model).get(thing).page_views == 1
예제 #15
0
def test_content_view(db, create_func, model, feature):
    """
    Viewing content increments its view count.
    """
    user = db_utils.create_user()
    thing = create_func()
    assert d.common_view_content(user, thing, feature)
    assert db.query(model).get(thing).page_views == 1
예제 #16
0
파일: test_define.py 프로젝트: 0x15/weasyl
def test_content_view(db, create_func, model, feature):
    """
    Viewing content increments its view count.
    """
    user = db_utils.create_user()
    thing = create_func()
    assert d.common_view_content(user, thing, feature)
    assert db.query(model).get(thing).page_views == 1
예제 #17
0
파일: submission.py 프로젝트: Syfaro/weasyl
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,
    }
예제 #18
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,
    }
예제 #19
0
def _select_journal_and_check(userid,
                              journalid,
                              rating=None,
                              ignore=True,
                              anyway=False,
                              increment_views=True):
    """Selects a journal, after checking if the user is authorized, etc.

    Args:
        userid (int): Currently authenticating user ID.
        journalid (int): Character ID to fetch.
        rating (int): Maximum rating to display. Defaults to None.
        ignore (bool): Whether to respect ignored or blocked tags. Defaults to True.
        anyway (bool): Whether ignore checks and display anyway. Defaults to False.
        increment_views (bool): Whether to increment the number of views on the submission. Defaults to True.

    Returns:
        A journal and all needed data as a dict.
    """

    query = d.engine.execute("""
        SELECT jo.userid, pr.username, jo.unixtime, jo.title, jo.content, jo.rating, jo.settings, jo.page_views, pr.config
        FROM journal jo JOIN profile pr ON jo.userid = pr.userid
        WHERE jo.journalid = %(id)s
    """,
                             id=journalid).first()

    if not query:
        # If there's no query result, there's no record, so fast-fail.
        raise WeasylError('journalRecordMissing')
    elif journalid and userid in staff.MODS and anyway:
        pass
    elif not query or 'h' in query.settings:
        raise WeasylError('journalRecordMissing')
    elif query.rating > rating and (
        (userid != query.userid and userid not in staff.MODS)
            or d.is_sfw_mode()):
        raise WeasylError('RatingExceeded')
    elif 'f' in query.settings and not frienduser.check(userid, query.userid):
        raise WeasylError('FriendsOnly')
    elif ignore and ignoreuser.check(userid, query.userid):
        raise WeasylError('UserIgnored')
    elif ignore and blocktag.check(userid, journalid=journalid):
        raise WeasylError('TagBlocked')

    query = dict(query)

    if increment_views and d.common_view_content(userid, journalid, 'journal'):
        query['page_views'] += 1

    return query
예제 #20
0
def _select_character_and_check(userid,
                                charid,
                                rating=None,
                                ignore=True,
                                anyway=False,
                                increment_views=True):
    """Selects a character, after checking if the user is authorized, etc.

    Args:
        userid (int): Currently authenticating user ID.
        charid (int): Character ID to fetch.
        rating (int): Maximum rating to display. Defaults to None.
        ignore (bool): Whether to respect ignored or blocked tags. Defaults to True.
        anyway (bool): Whether to ignore checks and display anyway. Defaults to False.
        increment_views (bool): Whether to increment the number of views on the submission. Defaults to True.

    Returns:
        A character and all needed data as a dict.
    """

    query = define.engine.execute("""
        SELECT
            ch.userid, pr.username, ch.unixtime, ch.char_name, ch.age, ch.gender, ch.height, ch.weight, ch.species,
            ch.content, ch.rating, ch.settings, ch.page_views, pr.config
        FROM character ch
            INNER JOIN profile pr USING (userid)
        WHERE ch.charid = %(charid)s
    """,
                                  charid=charid).first()

    if query and userid in staff.MODS and anyway:
        pass
    elif not query or 'h' in query.settings:
        raise WeasylError('characterRecordMissing')
    elif query.rating > rating and (
        (userid != query.userid and userid not in staff.MODS)
            or define.is_sfw_mode()):
        raise WeasylError('RatingExceeded')
    elif 'f' in query.settings and not frienduser.check(userid, query.userid):
        raise WeasylError('FriendsOnly')
    elif ignore and ignoreuser.check(userid, query.userid):
        raise WeasylError('UserIgnored')
    elif ignore and blocktag.check(userid, charid=charid):
        raise WeasylError('TagBlocked')

    query = dict(query)

    if increment_views and define.common_view_content(userid, charid, 'char'):
        query['page_views'] += 1

    return query
예제 #21
0
def _select_character_and_check(userid, charid, rating=None, ignore=True, anyway=False, increment_views=True):
    """Selects a character, after checking if the user is authorized, etc.

    Args:
        userid (int): Currently authenticating user ID.
        charid (int): Character ID to fetch.
        rating (int): Maximum rating to display. Defaults to None.
        ignore (bool): Whether to respect ignored or blocked tags. Defaults to True.
        anyway (bool): Whether to ignore checks and display anyway. Defaults to False.
        increment_views (bool): Whether to increment the number of views on the submission. Defaults to True.

    Returns:
        A character and all needed data as a dict.
    """

    query = define.engine.execute("""
        SELECT
            ch.userid, pr.username, ch.unixtime, ch.char_name, ch.age, ch.gender, ch.height, ch.weight, ch.species,
            ch.content, ch.rating, ch.settings, ch.page_views, pr.config
        FROM character ch
            INNER JOIN profile pr USING (userid)
        WHERE ch.charid = %(charid)s
    """, charid=charid).first()

    if query and userid in staff.MODS and anyway:
        pass
    elif not query or 'h' in query.settings:
        raise WeasylError('characterRecordMissing')
    elif query.rating > rating and ((userid != query.userid and userid not in staff.MODS) or define.is_sfw_mode()):
        raise WeasylError('RatingExceeded')
    elif 'f' in query.settings and not frienduser.check(userid, query.userid):
        raise WeasylError('FriendsOnly')
    elif ignore and ignoreuser.check(userid, query.userid):
        raise WeasylError('UserIgnored')
    elif ignore and blocktag.check(userid, charid=charid):
        raise WeasylError('TagBlocked')

    query = dict(query)

    if increment_views and define.common_view_content(userid, charid, 'char'):
        query['page_views'] += 1

    return query
예제 #22
0
파일: journal.py 프로젝트: Syfaro/weasyl
def _select_journal_and_check(userid, journalid, rating=None, ignore=True, anyway=False, increment_views=True):
    """Selects a journal, after checking if the user is authorized, etc.

    Args:
        userid (int): Currently authenticating user ID.
        journalid (int): Character ID to fetch.
        rating (int): Maximum rating to display. Defaults to None.
        ignore (bool): Whether to respect ignored or blocked tags. Defaults to True.
        anyway (bool): Whether ignore checks and display anyway. Defaults to False.
        increment_views (bool): Whether to increment the number of views on the submission. Defaults to True.

    Returns:
        A journal and all needed data as a dict.
    """

    query = d.engine.execute("""
        SELECT jo.userid, pr.username, jo.unixtime, jo.title, jo.content, jo.rating, jo.settings, jo.page_views, pr.config
        FROM journal jo JOIN profile pr ON jo.userid = pr.userid
        WHERE jo.journalid = %(id)s
    """, id=journalid).first()

    if journalid and userid in staff.MODS and anyway:
        pass
    elif not query or 'h' in query.settings:
        raise WeasylError('journalRecordMissing')
    elif query.rating > rating and ((userid != query.userid and userid not in staff.MODS) or d.is_sfw_mode()):
        raise WeasylError('RatingExceeded')
    elif 'f' in query.settings and not frienduser.check(userid, query.userid):
        raise WeasylError('FriendsOnly')
    elif ignore and ignoreuser.check(userid, query.userid):
        raise WeasylError('UserIgnored')
    elif ignore and blocktag.check(userid, journalid=journalid):
        raise WeasylError('TagBlocked')

    query = dict(query)

    if increment_views and d.common_view_content(userid, journalid, 'journal'):
        query['page_views'] += 1

    return query
예제 #23
0
파일: profile.py 프로젝트: bubbt/weasyl
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 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.cdnify_url('/static/images/logo-mark-light.svg'),
        }

    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

    statistics, show_statistics = profile.select_statistics(otherid)

    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
                statistics,
                show_statistics,
                # Commission information
                commishinfo.select_list(otherid),
                # Friends
                lambda: frienduser.has_friends(otherid),
            ]))

    return Response(define.common_page_end(request.userid, page))
예제 #24
0
파일: submission.py 프로젝트: Syfaro/weasyl
def select_view(userid, submitid, rating, ignore=True, anyway=None):
    query = d.execute("""
        SELECT
            su.userid, pr.username, su.folderid, su.unixtime, su.title, su.content, su.subtype, su.rating, su.settings,
            su.page_views, su.sorttime, pr.config, fd.title
        FROM submission su
            INNER JOIN profile pr USING (userid)
            LEFT JOIN folder fd USING (folderid)
        WHERE su.submitid = %i
    """, [submitid], options=["single", "list"])

    # Sanity check
    if query and userid in staff.MODS and anyway == "true":
        pass
    elif not query or "h" in query[8]:
        raise WeasylError("submissionRecordMissing")
    elif query[7] > rating and ((userid != query[0] and userid not in staff.MODS) or d.is_sfw_mode()):
        raise WeasylError("RatingExceeded")
    elif "f" in query[8] and not frienduser.check(userid, query[0]):
        raise WeasylError("FriendsOnly")
    elif ignore and ignoreuser.check(userid, query[0]):
        raise WeasylError("UserIgnored")
    elif ignore and blocktag.check(userid, submitid=submitid):
        raise WeasylError("TagBlocked")

    # Get submission filename
    submitfile = media.get_submission_media(submitid).get('submission', [None])[0]

    # Get submission text
    if submitfile and submitfile['file_type'] in ['txt', 'htm']:
        submittext = files.read(submitfile['full_file_path'])
    else:
        submittext = None

    embedlink = d.text_first_line(query[5]) if "v" in query[8] else None

    google_doc_embed = None
    if 'D' in query[8]:
        db = d.connect()
        gde = d.meta.tables['google_doc_embeds']
        q = (sa.select([gde.c.embed_url])
             .where(gde.c.submitid == submitid))
        results = db.execute(q).fetchall()
        if not results:
            raise WeasylError("can't find embed information")
        google_doc_embed = results[0]

    tags, artist_tags = searchtag.select_with_artist_tags(submitid)
    settings = d.get_profile_settings(query[0])

    return {
        "submitid": submitid,
        "userid": query[0],
        "username": query[1],
        "folderid": query[2],
        "unixtime": query[3],
        "title": query[4],
        "content": (d.text_first_line(query[5], strip=True) if "v" in query[8] else query[5]),
        "subtype": query[6],
        "rating": query[7],
        "settings": query[8],
        "page_views": (
            query[9] + 1 if d.common_view_content(userid, 0 if anyway == "true" else submitid, "submit") else query[9]),
        "fave_count": d.execute(
            "SELECT COUNT(*) FROM favorite WHERE (targetid, type) = (%i, 's')",
            [submitid], ["element"]),


        "mine": userid == query[0],
        "reported": report.check(submitid=submitid),
        "favorited": favorite.check(userid, submitid=submitid),
        "friends_only": "f" in query[8],
        "hidden_submission": "h" in query[8],
        "collectors": collection.find_owners(submitid),
        "no_request": not settings.allow_collection_requests,

        "text": submittext,
        "sub_media": media.get_submission_media(submitid),
        "user_media": media.get_user_media(query[0]),
        "submit": submitfile,
        "embedlink": embedlink,
        "embed": embed.html(embedlink) if embedlink is not None else None,
        "google_doc_embed": google_doc_embed,


        "tags": tags,
        "artist_tags": artist_tags,
        "removable_tags": searchtag.removable_tags(userid, query[0], tags, artist_tags),
        "can_remove_tags": searchtag.can_remove_tags(userid, query[0]),
        "folder_more": select_near(userid, rating, 1, query[0], query[2], submitid),
        "folder_title": query[12] if query[12] else "Root",


        "comments": comment.select(userid, submitid=submitid),
    }
예제 #25
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))
예제 #26
0
def select_view(userid, submitid, rating, ignore=True, anyway=None):
    query = d.engine.execute("""
        SELECT
            su.userid, pr.username, su.folderid, su.unixtime, su.title, su.content, su.subtype, su.rating, su.settings,
            su.page_views, fd.title, su.favorites, su.image_representations
        FROM submission su
            INNER JOIN profile pr USING (userid)
            LEFT JOIN folder fd USING (folderid)
        WHERE su.submitid = %(id)s
    """,
                             id=submitid).first()

    # Sanity check
    if query and userid in staff.MODS and anyway == "true":
        pass
    elif not query or "h" in query[8]:
        raise WeasylError("submissionRecordMissing")
    elif query[7] > rating and (
        (userid != query[0] and userid not in staff.MODS) or d.is_sfw_mode()):
        raise WeasylError("RatingExceeded")
    elif "f" in query[8] and not frienduser.check(userid, query[0]):
        raise WeasylError("FriendsOnly")
    elif ignore and ignoreuser.check(userid, query[0]):
        raise WeasylError("UserIgnored")
    elif ignore and blocktag.check(userid, submitid=submitid):
        raise WeasylError("TagBlocked")

    # Get submission filename
    submitfile = media.get_submission_media(submitid).get(
        'submission', [None])[0]

    # Get submission text
    if submitfile and submitfile['file_type'] in ['txt', 'htm']:
        submittext = files.read(submitfile['full_file_path'])
    else:
        submittext = None

    embedlink = d.text_first_line(query[5]) if "v" in query[8] else None

    google_doc_embed = None
    if 'D' in query[8]:
        db = d.connect()
        gde = d.meta.tables['google_doc_embeds']
        q = (sa.select([gde.c.embed_url]).where(gde.c.submitid == submitid))
        results = db.execute(q).fetchall()
        if not results:
            raise WeasylError("can't find embed information")
        google_doc_embed = results[0]

    tags, artist_tags = searchtag.select_with_artist_tags(submitid)
    settings = d.get_profile_settings(query[0])

    if query[12] is None:
        sub_media = media.get_submission_media(submitid)
    else:
        sub_media = media.deserialize_image_representations(query[12])

    return {
        "submitid":
        submitid,
        "userid":
        query[0],
        "username":
        query[1],
        "folderid":
        query[2],
        "unixtime":
        query[3],
        "title":
        query[4],
        "content": (d.text_first_line(query[5], strip=True)
                    if "v" in query[8] else query[5]),
        "subtype":
        query[6],
        "rating":
        query[7],
        "settings":
        query[8],
        "page_views": (query[9] + 1 if d.common_view_content(
            userid, 0 if anyway == "true" else submitid, "submit") else
                       query[9]),
        "fave_count":
        query[11],
        "mine":
        userid == query[0],
        "reported":
        report.check(submitid=submitid),
        "favorited":
        favorite.check(userid, submitid=submitid),
        "friends_only":
        "f" in query[8],
        "hidden_submission":
        "h" in query[8],
        "collected":
        collection.owns(userid, submitid),
        "no_request":
        not settings.allow_collection_requests,
        "text":
        submittext,
        "sub_media":
        sub_media,
        "user_media":
        media.get_user_media(query[0]),
        "submit":
        submitfile,
        "embedlink":
        embedlink,
        "embed":
        embed.html(embedlink) if embedlink is not None else None,
        "google_doc_embed":
        google_doc_embed,
        "tags":
        tags,
        "artist_tags":
        artist_tags,
        "removable_tags":
        searchtag.removable_tags(userid, query[0], tags, artist_tags),
        "can_remove_tags":
        searchtag.can_remove_tags(userid, query[0]),
        "folder_more":
        select_near(userid, rating, 1, query[0], query[2], submitid),
        "folder_title":
        query[10] if query[10] else "Root",
        "comments":
        comment.select(userid, submitid=submitid),
    }
예제 #27
0
파일: profile.py 프로젝트: 0x15/weasyl
    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)
예제 #28
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))
예제 #29
0
파일: profile.py 프로젝트: Weasyl/weasyl
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 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.cdnify_url('/static/images/logo-mark-light.svg'),
        }

    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

    statistics, show_statistics = profile.select_statistics(otherid)

    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
        statistics,
        show_statistics,
        # Commission information
        commishinfo.select_list(otherid),
        # Friends
        lambda: frienduser.has_friends(otherid),
    ]))

    return Response(define.common_page_end(request.userid, page))