Пример #1
0
def find_by_id(id):
    # @FIXME: make these exceptions specific to the case
    # where they can run successfully but do not find
    # the thing we are looking for. This should be really
    # easy as I think we just need NoResultFound.
    from raggregate.queries import submission
    from raggregate.queries import users
    from raggregate.queries import epistle as epistle_queries

    try:
        return submission.get_story_by_id(id)
    except:
        pass

    if users.get_user_by_id(id):
        return users.get_user_by_id(id)

    try:
        return submission.get_comment_by_id(id)
    except:
        pass

    try:
        return epistle_queries.get_epistle_by_id(id)
    except:
        raise
Пример #2
0
def find_by_id(id):
    # @FIXME: make these exceptions specific to the case
    # where they can run successfully but do not find
    # the thing we are looking for. This should be really
    # easy as I think we just need NoResultFound.
    from raggregate.queries import submission
    from raggregate.queries import users
    from raggregate.queries import epistle as epistle_queries

    try:
        return submission.get_story_by_id(id)
    except:
        pass

    if users.get_user_by_id(id):
        return users.get_user_by_id(id)

    try:
        return submission.get_comment_by_id(id)
    except:
        pass

    try:
        return epistle_queries.get_epistle_by_id(id)
    except:
        raise
Пример #3
0
def follow(request):
    s = request.session
    p = request.session['safe_params']
    message = ''

    if 'logged_in' not in s:
        s['message'] = 'Sorry, you must be logged in to use the follow feature.'
        return {'success': False, 'code': 'ENOLOGIN'}

    if 'follow_id' in p and 'logged_in' in s:
        dbsession = DBSession()
        #@TODO: replace with model-wide method to get logged-in user object
        u = users.get_user_by_id(s['users.id'])
        to_follow = users.get_user_by_id(p['follow_id'])
        op = 'add'
        if 'op' in p:
            op = p['op']
        if to_follow not in u.follows and op == 'add':
            u.follows.append(to_follow)
            del (s['followed_users'])
            dbsession.add(u)
            message = 'Successfully following {0}'.format(
                to_follow.display_name())
        elif to_follow in u.follows and op == 'del':
            u.follows.remove(to_follow)
            del (s['followed_users'])
            dbsession.add(u)
            message = 'Successfully unfollowed {0}'.format(
                to_follow.display_name())
    elif 'logged_in' in s:
        u = users.get_user_by_id(s['users.id'])

    vds = []
    vote_dict = {}

    if u:
        for i in u.follows:
            for story in i.submissions:
                #@FIXME: this is probably quite slow
                vds.append(
                    users.get_user_votes(u.id, "on_submission", story.id))
        for vd in vds:
            if type(vd) == dict:
                vote_dict.update(vd)

    s['message'] = message
    return {'follows': u.follows, 'vote_dict': vote_dict}
Пример #4
0
def get_users_to_notify(parent_id):
    """
    Returns real user objects.
    """
    res = dbsession.query(Notify).filter(Notify.target_id == parent_id).all()
    users = []
    [users.append(user_queries.get_user_by_id(x.user_id)) for x in res]
    return users
Пример #5
0
def get_users_to_notify(parent_id):
    """
    Returns real user objects.
    """
    res = dbsession.query(Notify).filter(Notify.target_id == parent_id).all()
    users = []
    [users.append(user_queries.get_user_by_id(x.user_id)) for x in res]
    return users
Пример #6
0
def user_info(request):
    import hashlib
    import os
    from raggregate.queries import user_preference as up

    r = request
    ses = request.session
    p = ses['safe_post']

    edit_mode = False
    user_id = None

    if 'user_id' in r.params:
        user_id = r.params['user_id']

    if 'logged_in' in ses and 'user_id' not in r.params:
        user_id = ses['users.id']

    if 'logged_in' in ses and (user_id == str(ses['users.id'])
                               or users.get_user_by_id(
                                   ses['users.id']).is_user_admin()):
        edit_mode = True

    u = users.get_user_by_id(user_id)
    params = up.get_user_prefs(user_id)

    if p and edit_mode:
        dbsession = DBSession()
        u.about_me = p['about_me']
        if p['email'] == "":
            u.email = None
        else:
            u.email = p['email']
        if r.POST['picture'] != '':
            orig_filename = r.POST['picture'].filename
            up_dir = r.registry.settings['user.picture_upload_directory']

            u.picture = users.add_user_picture(orig_filename,
                                               str(u.id)[:7], up_dir,
                                               r.POST['picture'].file)

        dbsession.add(u)

    response = {'edit_mode': edit_mode, 'u': u}
    response.update(params)
    return response
Пример #7
0
def get_new_message_num(id):
    user = users.get_user_by_id(id)
    epistle_num = dbsession.query(Epistle).filter(
        user.id == Epistle.recipient).filter(Epistle.unread == True).count()
    comment_num = dbsession.query(Comment).filter(
        sqlalchemy.and_(user.id == Comment.in_reply_to,
                        user.id != Comment.user_id)).filter(
                            Comment.unread == True).count()
    return epistle_num + comment_num
Пример #8
0
def notify(request):
    from raggregate.queries import notify as notify_queries
    s = request.session
    p = request.session['safe_params']
    u = None
    op = 'add'
    vote_dict = {}

    notifyd = notify_queries.get_notify_by_user_id(s['users.id'])
    notifyd_ids = [
        str(i.target_id)
        for i in notify_queries.get_notify_by_user_id(s['users.id'])
    ]
    if 'target_id' in p and 'logged_in' in s:
        dbsession = DBSession()

        uid = s['users.id']
        to_notify = p['target_id']
        if 'op' in p:
            op = p['op']
        if op == 'add':
            if to_notify not in notifyd_ids:
                notify_queries.create_notify(uid, to_notify, s['users.id'])
            s['message'] = 'Successfully notified'
        elif op == 'del':
            if to_notify in notifyd_ids:
                notify_queries.delete_notify(user_id=uid, target_id=to_notify)
            s['message'] = 'Successfully de-notified'
    elif 'logged_in' in s:
        u = users.get_user_by_id(s['users.id'])

    # the template expects a set of stories to render
    notifyd_stories = [
        submission.get_story_by_id(i.target_id) for i in notifyd
        if i.target_type == 'submission'
    ]
    notifyd_comments = [
        submission.get_comment_by_id(i.target_id) for i in notifyd
        if i.target_type == 'comment'
    ]

    if u:
        vds = []
        for i in notifyd_stories:
            vds.append(
                users.get_user_votes(s['users.id'], "on_submission", i.id))
        for vd in vds:
            if type(vd) == dict:
                vote_dict.update(vd)

    return {
        'notifyd_stories': notifyd_stories,
        'notifyd_comments': notifyd_comments,
        'vote_dict': vote_dict,
    }
Пример #9
0
def ban(event):
    r = event.request
    ip_ban = general.list_bans(ip = r.remote_addr)

    if 'logged_in' in r.session:
        username_ban = general.list_bans(username = users.get_user_by_id(r.session['users.id']).name)
    else:
        username_ban = False

    if ip_ban or username_ban:
        raise httpexceptions.HTTPForbidden
Пример #10
0
def save(request):
    s = request.session
    p = request.session['safe_params']
    u = None
    op = 'add'
    vote_dict = {}

    if 'story_id' in p and 'logged_in' in s:
        dbsession = DBSession()
        u = users.get_user_by_id(s['users.id'])
        to_save = submission.get_story_by_id(p['story_id'])
        if 'op' in p:
            op = p['op']
        if op == 'add':
            if to_save not in u.saved:
                u.saved.append(to_save)
                dbsession.add(u)
            s['message'] = 'Successfully saved {0}'.format(to_save.title)
        elif op == 'del':
            if to_save in u.saved:
                u.saved.remove(to_save)
                dbsession.add(u)
            s['message'] = 'Successfully unsaved {0}'.format(to_save.title)
    elif 'logged_in' in s:
        u = users.get_user_by_id(s['users.id'])

    if u:
        vds = []
        for i in u.saved:
            vds.append(
                users.get_user_votes(s['users.id'], "on_submission", i.id))
        for vd in vds:
            if type(vd) == dict:
                vote_dict.update(vd)

    return {
        'saved': u.saved,
        'vote_dict': vote_dict,
    }
Пример #11
0
def fire_to_listeners(parent_id, submitter, new_id, request):
    parent = general.find_by_id(parent_id)
    if isinstance(parent, Submission):
        submission = parent
    if isinstance(parent, Comment):
        submission = submission_queries.get_story_by_id(parent.submission_id)

    submitter = user_queries.get_user_by_id(submitter).display_name()

    users = get_users_to_notify(parent_id)
    for recipient in users:
        if "users.id" in request.session and str(recipient.id) == request.session["users.id"]:
            continue

        if recipient.notify_by_mail:
            send_mail(recipient, submitter, submission, new_id, request)

    return True
Пример #12
0
def fire_to_listeners(parent_id, submitter, new_id, request):
    parent = general.find_by_id(parent_id)
    if isinstance(parent, Submission):
        submission = parent
    if isinstance(parent, Comment):
        submission = submission_queries.get_story_by_id(parent.submission_id)

    submitter = user_queries.get_user_by_id(submitter).display_name()

    users = get_users_to_notify(parent_id)
    for recipient in users:
        if 'users.id' in request.session and str(
                recipient.id) == request.session['users.id']:
            continue

        if recipient.notify_by_mail:
            send_mail(recipient, submitter, submission, new_id, request)

    return True
Пример #13
0
def login(request):
    #@FIXME: this uses a request handling method with success with which I was experimenting
    # it is not used elsewhere and is a pain to read and write
    # success = False causes a page to stop drawing and "error out"
    # some error conditions therefore don't set success to false because it's more convenient
    # to draw the rest of the page.
    #
    # someone should adapt this to be less success-centric and read less branchy.
    s = request.session

    success = True

    # check for facebook login, provided by Facebook's JS SDK
    try:
        fb_cookie = fb.extract_from_cookie(request)
        try:
            u = users.get_user_by_name(fb_cookie['local_username'])
        except sqlalchemy.orm.exc.NoResultFound:
            u = fb.create_local_user(fb_cookie['info'],
                                     fb_cookie['local_username'],
                                     request=request)
        try:
            users.login_user(request, u, None, bypass_password=True)
        except LoginAdapterExc:
            pass
    except LoginAdapterExc:
        pass

    if 'logout' in request.session['safe_params']:
        if 'logged_in' in s:
            del s['logged_in']
            del s['users.id']
            if 'u_fbgraph' in s:
                del s['u_fbgraph']
                del s['u_fbinfo']
            if 'u_twit' in s:
                del s['u_twit']
            s['message'] = "You have been logged out, thanks."
            success = True
        else:
            s['message'] = "You are not logged in."
            success = True
    else:
        logged_in = False
        if 'logged_in' in s:
            s['message'] = "You are already logged in."
            logged_in = True
        else:
            if 'message' not in s:
                if 'last_login_status' in s:
                    s['message'] = s['last_login_status']
                    del s['last_login_status']
                else:
                    s['message'] = "Please log in."
        p = request.session['safe_post']
        prm = request.session['safe_params']
        username = None
        if 'username' in prm:
            username = general.strip_all_html(prm['username'])
        if p:
            dbsession = DBSession()
            if request.session['safe_get']['act'] == 'register':
                if logged_in:
                    try:
                        u = users.get_user_by_id(s['users.id'])
                        if u.temporary:
                            users.create_user(temp_to_perm=True,
                                              extant_id=s['users.id'],
                                              username=username,
                                              password=p['password'],
                                              email=p['email'],
                                              origination='site')
                            s['message'] = "Your anonymous profile has been converted, thanks."
                        else:
                            s['message'] = "You can't register while you're logged in."
                    except sqlalchemy.exc.IntegrityError:
                        s['message'] = "This username is already registered, sorry."
                        dbsession.rollback()
                else:
                    try:
                        users.create_user(username=username,
                                          password=p['password'],
                                          email=p['email'],
                                          origination='site')
                        s['message'] = "Successfully registered."
                        success = True
                    except sqlalchemy.exc.IntegrityError:
                        s['message'] = "This username is already registered, sorry."
                        success = False
                        dbsession.rollback()
            elif request.session['safe_get']['act'] == 'update_pw':
                if p['new_password'] != p['new_password_confirm']:
                    s['message'] = 'New password doesn\'t match confirmation, please try again.'
                else:
                    u = None

                    if s['logged_in_admin']:
                        if 'user_id' in prm:
                            u = users.get_user_by_id(prm['user_id'])

                    if u == None:
                        u = users.get_user_by_id(s['users.id'])

                    if u.verify_pw(p['old_password']) or s['logged_in_admin']:
                        u.password = u.hash_pw(p['new_password'])
                        dbsession.add(u)
                        s['message'] = 'Password updated.'
                        success = True
                    else:
                        s['message'] = 'Old password invalid.'
            elif request.session['safe_get']['act'] == 'forgot_pass':
                user = users.get_user_by_email(p['email'])
                if not user:
                    s['message'] = "That email isn't registered"
                else:
                    s['message'] = "Check your mail for a confirmation message."
                    users.send_lost_password_verify_email(request, user)
            else:
                try:
                    u = users.get_user_by_name(username)
                    try:
                        users.login_user(request, u, p['password'])
                        s['message'] = "Good, logged in"
                        success = True
                        return HTTPFound(request.route_url('post'))
                    except LoginAdapterExc:
                        s['message'] = "Incorrect password."
                        success = False
                except sqlalchemy.orm.exc.NoResultFound:
                    s['message'] = "Sorry, I don't know you."
                    success = False

    return {
        'success': success,
    }
Пример #14
0
 def authenticated_userid(self, request):
     if not request.session['users.id']:
         return None
     return users.get_user_by_id(request.session['users.id'])
Пример #15
0
def epistle(request):
    message = ''
    dbsession = DBSession()
    s = request.session
    p = request.session['safe_post']

    if 'logged_in' not in s:
        s['message'] = 'Sorry, you must be logged in to use the messaging feature.'
        return {'success': False, 'code': 'ENOLOGIN'}

    if p and 'recipient' in p:
        if p['recipient'] == '' and p['recipient-name'] == '':
            s['message'] = "No recipient provided."
            return {'code': 'ENORECP', 'success': False}
        if p['recipient'] == '':
            # look up recipient-name
            try:
                recp = users.get_user_by_name(p['recipient-name'])
            except sqlalchemy.orm.exc.NoResultFound:
                #@TODO: discuss facebook name sending implications
                s['message'] = "Could not find that user."
                return {'code': 'ENORECP', 'success': False}
        else:
            try:
                recp = users.get_user_by_id(p['recipient'])
            except:
                s['message'] = "Could not find that user."
                return {'code': 'ENORECP', 'success': False}

        if p['subject'] == '':
            subject = None
        else:
            subject = p['subject']

        if 'parent_id' not in p or p['parent_id'] == '':
            parent_id = None
            parent_type = 'epistle'
        else:
            parent_id = p['parent_id']
            parent_obj = general.find_by_id(parent_id)
            if isinstance(parent_obj, Comment):
                parent_type = 'comment'
                c = Comment(parent_obj.submission_id, s['users.id'], parent_obj.id, p['body'], in_reply_to = parent_obj.user_id)
                dbsession.add(c)
            else:
                parent_type = 'reply'

        if parent_type != 'comment':
            ep = Epistle(recp.id, s['users.id'], p['body'], parent=parent_id, parent_type=parent_type, subject=subject)
            dbsession.add(ep)
        message = 'Message sent.'

    box = request.matchdict['box']

    if box == 'in':
        comments = epistle_queries.get_unread_comments_by_user_id(s['users.id'])
    elif box == 'comments':
        comments = epistle_queries.get_read_comments_by_user_id(s['users.id'])
    else:
        comments = []

    if box != 'comments':
        ep = epistle_queries.get_epistle_roots(id=s['users.id'], target=box)
        epistle_children = {}

        for e in ep:
            e_id = str(e.id)
            epistle_children[e_id] = epistle_queries.get_epistle_children(e.id)

        flat_eps = []
        [flat_eps.append(e) for e in _unwrap_list(ep)]
        [flat_eps.append(e) for e in _unwrap_list(epistle_children.values())]

        for e in flat_eps:
            if str(e.recipient) == s['users.id']:
                epistle_queries.mark_epistle_read(e)
            e = _assign_epistle_parent(e)

        for c in comments:
            epistle_queries.mark_comment_read(c)
    else:
        ep = {}
        epistle_children = {}

    return {'epistles': {'roots': ep, 'children': epistle_children}, 'comments': comments, 'success': True, 'code': 0,}
Пример #16
0
def get_new_message_num(id):
    user = users.get_user_by_id(id)
    epistle_num = dbsession.query(Epistle).filter(user.id == Epistle.recipient).filter(Epistle.unread == True).count()
    comment_num = dbsession.query(Comment).filter(sqlalchemy.and_(user.id == Comment.in_reply_to, user.id != Comment.user_id)).filter(Comment.unread == True).count()
    return epistle_num + comment_num
Пример #17
0
 def authenticated_userid(self, request):
     if not request.session['users.id']:
         return None
     return users.get_user_by_id(request.session['users.id'])
Пример #18
0
def user_session_handler(event):
    s = event['request'].session
    r = event['request']
    e = event
    if 'message' in s:
        e['message'] = s['message']
    else:
        e['message'] = None

    e['template_filters'] = template_filters

    # this could be accessed by the request object, request.static_url()
    # should fixup the first here at least to be normal
    e['static_base'] = static_url("{0}/".format(r.registry.settings['template_static_asset']), r)
    e['static_url'] = static_url

    e['site_name'] = r.registry.settings['site.site_name']

    # export date fuzzing function to templates
    e['fuzzify_date'] = users.fuzzify_date

    e['new_message_num'] = None
    e['karma'] = None
    e['u'] = None
    e['logged_in_admin'] = None
    e['logged_in'] = False

    s['logged_in_admin'] = False

    e['followed_users'] = []

    if 'recent_comments.num' in r.registry.settings:
        e['recent_comments'] = submission.get_recent_comments(r.registry.settings['recent_comments.num'])
    else:
        # use ten as default if server parameter is missing
        e['recent_comments'] = submission.get_recent_comments(10)

    if 'sort' in r.params:
        e['sort'] = r.params['sort']
    else:
        e['sort'] = 'new'

    if 'logged_in' in s:
        #@TODO: implement caching/rate limiting so we don't perform this on every single request anymore
        num = epistle_queries.get_new_message_num(s['users.id'])
        if num == 0:
            s['new_message_num'] = None
            e['new_message_num'] = None
        else:
            s['new_message_num'] = num
            e['new_message_num'] = num
        #@TODO: another calculation that would benefit from caching
        #if 'karma' in s:
        #    e['karma'] = s['karma']
        #    print 'AAAAAAAAAA' + str(s['karma'])
        #else:
        #not caching right now, commenting conditional
        karma = users.get_user_by_id(s['users.id']).update_karma()
        s['karma'] = karma
        e['karma'] = karma

        if 'followed_users' in s and len(s['followed_users']) > 0:
            e['followed_users'] = s['followed_users']
        else:
            s['followed_users'] = users.get_followed_users(s['users.id'])
            e['followed_users'] = s['followed_users']

        u = users.get_user_by_id(s['users.id'])
        e['logged_in_admin'] = u.is_user_admin()
        s['logged_in_admin'] = e['logged_in_admin']
        e['u'] = u
        e['logged_in'] = True
    elif 'logged_in' not in s and r.registry.settings['user.generate_anon_accounts'] == 'true':
        # do not create a new user if we are on the login page
        # this simplifies anon -> permanent transfer
        if r.url.find('login') != -1:
            return
        # create a temporary user if this is a new session
        # all activity will be associated with this user until conversion to real account is performed
        u = User("{0}".format(uuid.UUID(bytes=os.urandom(16))), str(os.urandom(8)), real_name = "Unregistered User", temporary = True)
        dbsession.add(u)
        dbsession.flush()
        s['users.id'] = str(u.id)
        s['users.display_name'] = u.display_name()
        s['logged_in'] = True
        e['logged_in'] = True
Пример #19
0
def epistle(request):
    message = ''
    dbsession = DBSession()
    s = request.session
    p = request.session['safe_post']

    if 'logged_in' not in s:
        s['message'] = 'Sorry, you must be logged in to use the messaging feature.'
        return {'success': False, 'code': 'ENOLOGIN'}

    if p and 'recipient' in p:
        if p['recipient'] == '' and p['recipient-name'] == '':
            s['message'] = "No recipient provided."
            return {'code': 'ENORECP', 'success': False}
        if p['recipient'] == '':
            # look up recipient-name
            try:
                recp = users.get_user_by_name(p['recipient-name'])
            except sqlalchemy.orm.exc.NoResultFound:
                #@TODO: discuss facebook name sending implications
                s['message'] = "Could not find that user."
                return {'code': 'ENORECP', 'success': False}
        else:
            try:
                recp = users.get_user_by_id(p['recipient'])
            except:
                s['message'] = "Could not find that user."
                return {'code': 'ENORECP', 'success': False}

        if p['subject'] == '':
            subject = None
        else:
            subject = p['subject']

        if 'parent_id' not in p or p['parent_id'] == '':
            parent_id = None
            parent_type = 'epistle'
        else:
            parent_id = p['parent_id']
            parent_obj = general.find_by_id(parent_id)
            if isinstance(parent_obj, Comment):
                parent_type = 'comment'
                c = Comment(parent_obj.submission_id,
                            s['users.id'],
                            parent_obj.id,
                            p['body'],
                            in_reply_to=parent_obj.user_id)
                dbsession.add(c)
            else:
                parent_type = 'reply'

        if parent_type != 'comment':
            ep = Epistle(recp.id,
                         s['users.id'],
                         p['body'],
                         parent=parent_id,
                         parent_type=parent_type,
                         subject=subject)
            dbsession.add(ep)
        message = 'Message sent.'

    box = request.matchdict['box']

    if box == 'in':
        comments = epistle_queries.get_unread_comments_by_user_id(
            s['users.id'])
    elif box == 'comments':
        comments = epistle_queries.get_read_comments_by_user_id(s['users.id'])
    else:
        comments = []

    if box != 'comments':
        ep = epistle_queries.get_epistle_roots(id=s['users.id'], target=box)
        epistle_children = {}

        for e in ep:
            e_id = str(e.id)
            epistle_children[e_id] = epistle_queries.get_epistle_children(e.id)

        flat_eps = []
        [flat_eps.append(e) for e in _unwrap_list(ep)]
        [flat_eps.append(e) for e in _unwrap_list(epistle_children.values())]

        for e in flat_eps:
            if str(e.recipient) == s['users.id']:
                epistle_queries.mark_epistle_read(e)
            e = _assign_epistle_parent(e)

        for c in comments:
            epistle_queries.mark_comment_read(c)
    else:
        ep = {}
        epistle_children = {}

    return {
        'epistles': {
            'roots': ep,
            'children': epistle_children
        },
        'comments': comments,
        'success': True,
        'code': 0,
    }