Exemplo n.º 1
0
def details(ds, **args):
    required(['thread'], args)
    optional('related', args, [], ['user', 'forum'])

    conn = ds.get_db()
    db = conn['conn']
    c = db.cursor()
    c.execute(u"""SELECT * FROM thread
               WHERE id = %s""", (args['thread'],))
    thread_data = c.fetchone()
    c.close()
    db.close() #ds.close(conn['id'])

    check_empty(thread_data, u"No thread found with that id")

    make_boolean(['isClosed', 'isDeleted'], thread_data)
    thread_data['date'] = str(thread_data['date'])

    # del thread_data['user_id']
    # del thread_data['forum_id']

    if 'user' in args['related']:
        thread_data['user'] = user.details(ds, user=thread_data['user'])

    if 'forum' in args['related']:
        thread_data['forum'] = forum.details(ds, forum=thread_data['forum'])

    return thread_data
Exemplo n.º 2
0
def list_posts(**data):
    # Приходит forum, а для list_posts нужен thread
    posts = post.list_posts(**data)

    if len(posts) == 0:
        # Знатный костыль, но так требует серв
        return response_error(Codes.ok, "")

    if 'related' in data:
        if 'user' in data['related']:
            for one_post in posts:
                user_data = {'user': one_post['user']}
                one_post['user'] = user.details(**user_data)

        if 'forum' in data['related']:
            for one_post in posts:
                forum_data = {'forum': one_post['forum']}
                one_post['forum'] = details(**forum_data)

        if 'thread' in data['related']:
            for one_post in posts:
                thread_data = {'thread': one_post['thread']}
                one_post['thread'] = thread.details(**thread_data)

    return {
        'code': Codes.ok,
        'response': posts
    }
Exemplo n.º 3
0
def details(id, related):
    thread = sql.select_query(
        'select date, forum, id, isClosed, isDeleted, message, slug, title, user, dislikes, likes, points, posts '
        'FROM thread WHERE id = %s LIMIT 1;', (id, )
    )
    if len(thread) == 0:
        raise Exception('No thread exists with id=' + str(id))
    thread = thread[0]
    thread = {
        'date': str(thread[0]),
        'forum': thread[1],
        'id': thread[2],
        'isClosed': bool(thread[3]),
        'isDeleted': bool(thread[4]),
        'message': thread[5],
        'slug': thread[6],
        'title': thread[7],
        'user': thread[8],
        'dislikes': thread[9],
        'likes': thread[10],
        'points': thread[11],
        'posts': thread[12],
    }

    if "user" in related:
        thread["user"] = user.details(thread["user"])
    if "forum" in related:
        thread["forum"] = forum.details(short_name=thread["forum"], related=[])

    return thread
Exemplo n.º 4
0
def details(ds, **args):
    required(['forum'], args)
    optional('related', args, [], ['user'])

    conn = ds.get_db()
    db = conn['conn']
    c = db.cursor()
    c.execute(u"""SELECT * FROM forum
               WHERE forum.short_name = %s""", (args['forum'],))
    forum_data = c.fetchone()
    c.close()
    db.close() #ds.close(conn['id'])

    check_empty(forum_data, u"No forum found with that short_name")

    email = forum_data['user']
    if 'user' in args['related']:
        user_data = user.details(ds, user=email)
    else:
        user_data = email

    del forum_data['user_id']
    forum_data['user'] = user_data

    return forum_data
Exemplo n.º 5
0
def details(ds, **args):
    required(['post'], args)
    optional('related', args, [], ['user', 'thread', 'forum'])

    conn = ds.get_db()
    db = conn['conn']
    c = db.cursor()
    c.execute(u"""SELECT * FROM post
               WHERE id = %s""", (args['post'],))
    post_data = c.fetchone()
    c.close()
    db.close() #ds.close(conn['id'])

    check_empty(post_data, u"No post found with that id")

    post_data['date'] = str(post_data['date'])
    make_boolean(['isApproved', 'isDeleted', 'isEdited',
                  'isHighlighted', 'isSpam'], post_data)

    thread_id = post_data['thread_id']
    del post_data['user_id']
    del post_data['thread_id']

    if 'user' in args['related']:
        post_data['user'] = user.details(ds, user=post_data['user'])

    if 'thread' in args['related']:
        post_data['thread'] = thread.details(ds, thread=thread_id)
    else:
        post_data['thread'] = thread_id

    if 'forum' in args['related']:
        post_data['forum'] = forum.details(ds, forum=post_data['forum'])

    return post_data
Exemplo n.º 6
0
def listUsers(ds, **args):
    required(['forum'], args)
    optional('since_id', args)
    optional('limit', args)
    optional('order', args, 'desc', ['desc', 'asc'])

    query = StringBuilder()
    query.append(u"""SELECT DISTINCT user FROM post
                     WHERE forum = %s""")
    params = (args['forum'],)

    if args['since_id']:
        query.append(u"""AND id >= %s""")
        params += (args['since_id'],)

    if args['order']:
        query.append(u"""ORDER BY user_id %s""" % args['order'])

    if args['limit']:
        query.append(u"""LIMIT %d""" % int(args['limit']))

    conn = ds.get_db()
    db = conn['conn']
    c = db.cursor()
    c.execute(str(query), params)

    users_list = [user.details(ds, user=u['user']) for u in c]

    c.close()
    db.close() #ds.close(conn['id'])

    return users_list
Exemplo n.º 7
0
def followers_list(email, type, params):
    if type == "follower":
        where = "followee"
    if type == "followee":
        where = "follower"

    query = "SELECT " + type + " FROM follower JOIN user ON user.email = follower." + type + \
            " WHERE " + where + " = %s "

    if "since_id" in params:
        query += " AND user.id >= " + str(params["since_id"])
    if "order" in params:
        query += " ORDER BY user.name " + params["order"]
    else:
        query += " ORDER BY user.name DESC "
    if "limit" in params:
        query += " LIMIT " + str(params["limit"])

    followers_ids_tuple = sql.select_query(query=query, params=(email, ))

    f_list = []
    for id in followers_ids_tuple:
        id = id[0]
        f_list.append(user.details(email=id))

    return f_list
Exemplo n.º 8
0
def details(short_name, related):
    forum = sql.select_query(
        'select id, name, short_name, user FROM forum WHERE short_name = %s LIMIT 1;', (short_name, )
    )
    if len(forum) == 0:
        raise ("No forum with exists short_name=" + short_name)
    forum = forum_description(forum)

    if "user" in related:
        forum["user"] = user.details(forum["user"])
    return forum
Exemplo n.º 9
0
def details(get_resp=False, **data):
    query = """SELECT date, dislikes, forum, id, isApproved,
              isDeleted, isEdited, isHighlighted, isSpam, likes,
              message, parent, likes - dislikes AS points,
              thread, user
              FROM Post WHERE id = %s""" % data['post']

    with closing(cnxpool.get_connection()) as db:
        with closing(db.cursor(dictionary=True)) as cursor:
            try:
                cursor.execute(query)
                post = cursor.fetchone()
            except MysqlException as e:
                if get_resp:
                    return response_error(Codes.unknown_error, e)
                raise e

    if post is None:
        post = {}
    else:
        if 'related' in data:
            if 'user' in data['related']:
                user_data = {'user': post['user']}
                post['user'] = user.details(**user_data)

            if 'forum' in data['related']:
                forum_data = {'forum': post['forum']}
                post['forum'] = forum.details(**forum_data)

            if 'thread' in data['related']:
                thread_data = {'thread': post['thread']}
                post['thread'] = thread.details(**thread_data)

        post['date'] = post['date'].strftime("%Y-%m-%d %H:%M:%S")
        post['isApproved'] = bool(post['isApproved'])
        post['isDeleted'] = bool(post['isDeleted'])
        post['isEdited'] = bool(post['isEdited'])
        post['isHighlighted'] = bool(post['isHighlighted'])
        post['isSpam'] = bool(post['isSpam'])

    if get_resp:
        if len(post) != 0:
            response = {
                'code': Codes.ok,
                'response': post
            }
        else:
            str_err = "Post with id=%s not found" % data['post']
            response = response_error(Codes.not_found, str_err)
        return response

    return post
Exemplo n.º 10
0
def details(details_id, related):
    post = post_query(details_id)
    if post is None:
        raise Exception("no post with id = " + details_id)

    if "user" in related:
        post["user"] = user.details(post["user"])
    if "forum" in related:
        post["forum"] = forum.details(short_name=post["forum"], related=[])
    if "thread" in related:
        post["thread"] = thread.details(id=post["thread"], related=[])

    return post
Exemplo n.º 11
0
def posts_list(entity, params, identifier, related=[]):
    query = "SELECT date, dislikes, forum, id, isApproved, isDeleted, isEdited, isHighlighted, isSpam, likes, message, " \
            "parent, points, thread, user FROM post WHERE " + entity + " = %s "

    parameters = [identifier]
    if "since" in params:
        query += " AND date >= %s"
        parameters.append(params["since"])

    query += " ORDER BY date " + params["order"]

    if "limit" in params:
        query += " LIMIT " + str(params["limit"])

    post_ids = sql.select_query(query=query, params=parameters)
    post_list = []
    for post in post_ids:
        pf = {
                'date': str(post[0]),
                'dislikes': post[1],
                'forum': post[2],
                'id': post[3],
                'isApproved': bool(post[4]),
                'isDeleted': bool(post[5]),
                'isEdited': bool(post[6]),
                'isHighlighted': bool(post[7]),
                'isSpam': bool(post[8]),
                'likes': post[9],
                'message': post[10],
                'parent': post[11],
                'points': post[12],
                'thread': post[13],
                'user': post[14],
            }
        if "user" in related:
            pf["user"] = user.details(pf["user"])
        if "forum" in related:
            pf["forum"] = forum.details(short_name=pf["forum"], related=[])
        if "thread" in related:
            pf["thread"] = thread.details(id=pf["thread"], related=[])
        post_list.append(pf)
    return post_list
Exemplo n.º 12
0
def listPosts(**data):
    required(data, ['forum'])
    if 'order' not in data:
        data['order'] = 'desc'
    query = StringToFile.StringToFilefunc()
    params = ()
    query.append("""SELECT * FROM post
                    WHERE thread in (SELECT id FROM thread WHERE forum = %s)""")
    params += (data['forum'],)
    if 'since' in data:
        query.append(""" AND date >= %s""")
        params += (data['since'],)
    query.append(""" ORDER BY date %s""" % data['order'])
    if 'limit' in data:
        query.append(""" LIMIT %s""" % data['limit'])
    db = DBconnect.connect()
    cur = db.cursor()
    cur.execute(str(query), params)
    posts = cur.fetchall()
    cur.close()
    for post in posts:
        post['isApproved'] = bool(post['isApproved'])
        post['isDeleted'] = bool(post['isDeleted'])
        post['isEdited'] = bool(post['isEdited'])
        post['isHighlighted'] = bool(post['isHighlighted'])
        post['isSpam'] = bool(post['isSpam'])
        post['date'] = post['date'].strftime("%Y-%m-%d %H:%M:%S")
        if 'related' in data:
            if 'thread' in data['related']:
                thread_data = {'thread': post['thread']}
                thread_data = thread.details(db, False, **thread_data)
                post['thread'] = thread_data
            if 'user' in data['related']:
                user_data = {'user': post['user']}
                user_data = user.details(db, False, **user_data)
                post['user'] = user_data
            if 'forum' in data['related']:
                forum_data = {'forum': post['forum']}
                forum_data = details(db, False, **forum_data)
                post['forum'] = forum_data
    return posts
Exemplo n.º 13
0
def details(db=0, close_db=True, **data):
    required(data, ['post'])
    if db == 0:
        db = DBconnect.connect()
    cur = db.cursor()
    cur.execute("""SELECT * FROM post
                   WHERE id = %s""", (data['post'],))
    post = cur.fetchone()
    cur.close()
    post['date'] = post['date'].strftime("%Y-%m-%d %H:%M:%S")
    if 'related' in data:
        if 'user' in data['related']:
            post['user'] = user.details(db, False, **post)
        if 'thread' in data['related']:
            post['thread'] = thread.details(db, False, **post)
        if 'forum' in data['related']:
            short_name = {'forum': post['forum']}
            post['forum'] = forum.details(db, False, **short_name)
    if close_db:
        db.close()
    return post
Exemplo n.º 14
0
def list_threads(**data):
    threads = thread.list_threads(**data)

    if len(threads) == 0:
        return response_error(Codes.ok, '')

    elif 'related' in data:
        if 'user' in data['related']:
            for one_thread in threads:
                user_data = {'user': one_thread['user']}
                one_thread['user'] = user.details(**user_data)

        if 'forum' in data['related']:
            for one_thread in threads:
                forum_data = {'forum': one_thread['forum']}
                one_thread['forum'] = details(**forum_data)

    return {
        'code': Codes.ok,
        'response': threads
    }
Exemplo n.º 15
0
def thread_list(entity, identifier, related, params):
    query = "SELECT date, forum, id, isClosed, isDeleted, message, slug, title, user, dislikes, likes, points, posts " \
            "FROM thread WHERE " + entity + " = %s "
    parameters = [identifier]

    if "since" in params:
        query += " AND date >= %s"
        parameters.append(params["since"])
    if "order" in params:
        query += " ORDER BY date " + params["order"]
    else:
        query += " ORDER BY date DESC "
    if "limit" in params:
        query += " LIMIT " + str(params["limit"])
    thread_ids_tuple = sql.select_query(query=query, params=parameters)
    thread_list = []
    for thread in thread_ids_tuple:
        thread = {
            'date': str(thread[0]),
            'forum': thread[1],
            'id': thread[2],
            'isClosed': bool(thread[3]),
            'isDeleted': bool(thread[4]),
            'message': thread[5],
            'slug': thread[6],
            'title': thread[7],
            'user': thread[8],
            'dislikes': thread[9],
            'likes': thread[10],
            'points': thread[11],
            'posts': thread[12],
        }
        if "user" in related:
            thread["user"] = user.details(thread["user"])
        if "forum" in related:
            thread["forum"] = forum.details(short_name=thread["forum"], related=[])
        thread_list.append(thread)
    return thread_list
Exemplo n.º 16
0
def listThreads(**data):
    required(data, ['forum'])
    param = 'order'
    if param not in data:
        data[param] = 'desc'

    query = StringToFile.StringToFilefunc()
    params = ()
    query.append("""SELECT * FROM thread
                    WHERE forum = %s""")
    params += (data['forum'],)
    if 'since' in data:
        query.append(""" AND date >= %s""")
        params += (data['since'],)
    query.append(""" ORDER BY date %s""" % data['order'])

    if 'limit' in data:
        query.append(""" LIMIT %s""" % data['limit'])
    db = DBconnect.connect()
    cur = db.cursor()
    cur.execute(str(query), params)
    threads = cur.fetchall()
    cur.close()
    for thread in threads:
        thread['isDeleted'] = bool(thread['isDeleted'])
        thread['isClosed'] = bool(thread['isClosed'])
        thread['date'] = thread['date'].strftime("%Y-%m-%d %H:%M:%S")
        if 'related' in data:
            if 'user' in data['related']:
                user_data = {'user': thread['user']}
                user_data = user.details(db, False, **user_data)
                thread['user'] = user_data
            if 'forum' in data['related']:
                forum_data = {'forum': thread['forum']}
                forum_data = details(db, False, **forum_data)
                thread['forum'] = forum_data
    return threads
Exemplo n.º 17
0
def details(get_resp=False, **data):
    query = "SELECT id, name, short_name, user FROM Forum WHERE short_name='%s'"

    with closing(cnxpool.get_connection()) as db:
        with closing(db.cursor(dictionary=True)) as cursor:
            cursor.execute(query % data['forum'])
            forum = cursor.fetchone()
    if forum is not None:
        if ('related' in data) and (data['related'] == 'user'):
            forum['user'] = user.details(**{'user': forum['user']})
    else:
        forum = {}

    if get_resp:
        if len(forum) == 0:
            str_err = "Forum '%s' not found" % data['forum']
            return response_error(Codes.not_found, str_err)
        else:
            return {
                'code': Codes.ok,
                'response': forum
            }

    return forum
Exemplo n.º 18
0
def list(ds, orderby='date', **args):
    semi_required(['forum', 'thread', 'user'], args)
    optional('since', args)
    optional('limit', args)
    optional('order', args, 'desc', ['desc', 'asc'])
    optional('related', args, [], ['user', 'forum', 'thread'])

    query = StringBuilder()
    query.append(u"""SELECT * FROM post""")
    params = ()

    if 'thread' in args['related']:
        query.append(u"""INNER JOIN thread ON post.thread_id = thread.id""")
    if 'forum' in args['related']:
        query.append(u"""INNER JOIN forum ON post.forum = forum.short_name""")

    if 'forum' in args:
        query.append(u"""WHERE post.forum = %s""")
        params += (args['forum'],)

    elif 'thread' in args:
        query.append(u"""WHERE post.thread_id = %s""")
        params += (args['thread'],)

    elif 'user' in args:
        query.append(u"""WHERE post.user = %s""")
        params += (args['user'],)

    if args['since']:
        query.append(u"""AND post.date >= %s""")
        params += (args['since'],)

    if args['order']:
        query.append(u"""ORDER BY post.date %s""" % args['order'])

    if args['limit']:
        query.append(u"""LIMIT %d""" % int(args['limit']))

    conn = ds.get_db()
    db = conn['conn']
    c = db.cursor()
    c.execute(str(query), params)
    posts = c.fetchall()

    c.close()
    db.close() #ds.close(conn['id'])

    posts = __builtin__.list(posts)

    for post in posts:
        if 'forum' in args['related']:
            post['forum'] = {
                'id': post['forum.id'],
                'name': post['name'],
                'short_name': post['short_name'],
                'user': post['forum.user'],
            }

            del post['forum.id']
            del post['name']
            del post['short_name']
            del post['forum.user']
            del post['forum.user_id']

        if 'thread' in args['related']:
            post['thread'] = {
                'id': post['thread.id'],
                'date': date_to_str(post['thread.date']),
                'isClosed': post['isClosed'],
                'isDeleted': post['thread.isDeleted'],
                'title': post['title'],
                'slug': post['slug'],
                'posts': post['posts'],
                'message': post['thread.message'],
                'dislikes': post['thread.dislikes'],
                'likes': post['thread.likes'],
                'points': post['thread.points'],
                'user': post['thread.user'],
                'forum': post['thread.forum']
            }

            del post['thread.id']
            del post['thread.date']
            del post['isClosed']
            del post['thread.isDeleted']
            del post['title']
            del post['slug']
            del post['posts']
            del post['thread.message']
            del post['thread.dislikes']
            del post['thread.likes']
            del post['thread.points']
            del post['thread.user']
            del post['thread.forum']
        else:
            post['thread'] = post['thread_id']

        del post['user_id']
        del post['thread_id']
        post['date'] = date_to_str(post['date'])

        if 'user' in args['related']:
            post['user'] = user.details(ds, user=post['user'])

    # posts = [details(ds, post=row['id'], related=args['related']) for row in c]

    return posts
Exemplo n.º 19
0
def remove_follow(email1, email2):
    sql.update_query('DELETE FROM follower WHERE follower = %s AND followee = %s', (email1, email2, ))
    return user.details(email1)
Exemplo n.º 20
0
def add_follow(email1, email2):
    sql.update_query('INSERT INTO follower (follower, followee) VALUES (%s, %s)', (email1, email2, ))
    return user.details(email1)