Ejemplo n.º 1
0
def thumbup_chapter(article_id, chapter_id):
    try:
        # access to database
        dynamodb = get_dbresource()
        article_table = dynamodb.Table('articles')
        chapter_table = dynamodb.Table('chapters')
        comment_table = dynamodb.Table('comments')

        response1 = article_table.query(KeyConditionExpression=Key(
            'ArticleID').eq(escape_string(article_id)))
        response2 = chapter_table.query(KeyConditionExpression=Key(
            'ChapterID').eq(escape_string(chapter_id)))
        if response1['Count'] == 0 or response2['Count'] == 0:
            raise ValueError('This page does not exist.')

        chapter_table.update_item(
            Key={'ChapterID': chapter_id},
            UpdateExpression="set ThumbNum = ThumbNum + :val",
            ExpressionAttributeValues={':val': decimal.Decimal(1)},
            ReturnValues="UPDATED_NEW")

        return redirect(url_for("full_article", article_id=article_id))

    except Exception as e:
        return str(e)
Ejemplo n.º 2
0
def new_comment(chapter_id, article_id):
    try:
        form = classes.ChapterForm(request.form)
        if not form.validate_on_submit():
            error = "request is invalidated"
            return redirect(
                url_for("full_article", article_id=article_id, error=error))

        # access to database
        dynamodb = get_dbresource()
        article_table = dynamodb.Table('articles')
        chapter_table = dynamodb.Table('chapters')
        comment_table = dynamodb.Table('comments')

        response1 = article_table.query(KeyConditionExpression=Key(
            'ArticleID').eq(escape_string(article_id)))
        response2 = chapter_table.query(KeyConditionExpression=Key(
            'ChapterID').eq(escape_string(chapter_id)))
        if response1['Count'] == 0 or response2['Count'] == 0:
            raise ValueError('This page does not exist.')

        content_body = form.content.data
        comment_id = chapter_id + '_' + str(get_microseconds())
        commenter_id = session['username']
        create_time = str(datetime.datetime.now())[:19]

        response = comment_table.query(KeyConditionExpression=Key(
            'CommentID').eq(escape_string(comment_id)))

        if response['Count'] > 0:
            flash("Server is busy, please try again.")
            return render_template("article-upload.html", title="new article")

        # upload chapter body to s3
        s3 = get_s3bucket()
        content = COMMENTS_PATH + comment_id + '.md'
        s3.put_object(Key=content, Body=content_body, ACL='public-read')

        # insert the article info into the database
        comment_table.put_item(
            Item={
                'CommentID': escape_string(comment_id),
                'Content': escape_string(content),
                'CommenterID': escape_string(commenter_id),
                'ChapterID': escape_string(chapter_id),
                'CreateTime': escape_string(create_time),
            })

        gc.collect()

        flash("new comment is created successfully")

        return redirect(url_for("full_article", article_id=article_id))

    except Exception as e:
        return str(e)  # thumbup for article
Ejemplo n.º 3
0
def login_form():
    error = ''
    try:
        form = LoginForm(request.form)
        dynamodb = get_dbresource()
        usertable = dynamodb.Table('users')

        if request.method == "POST":
            # check if form is validated
            if not form.validate_on_submit():
                error = "request is invalidated"
                return render_template("login-form.html",
                                       title='Login',
                                       form=form,
                                       error=error)

            response = usertable.query(IndexName='UIDIndex',
                                       KeyConditionExpression=Key('UserID').eq(
                                           escape_string(form.username.data)))

            if response['Count'] == 0:
                error = "Username does not exist"
                return render_template("login-form.html",
                                       title='Login',
                                       form=form,
                                       error=error)

            items = response['Items'][0]

            if sha256_crypt.verify(form.password.data, items['Password']):
                session['logged_in'] = True
                session['username'] = form.username.data
                session['nickname'] = items['Nickname']
                flash("You are now logged in")
                return redirect(url_for("article_list"))
            else:
                error = "Invalid credentials, try again."
                return render_template("login-form.html",
                                       title='Login',
                                       form=form,
                                       error=error)

        gc.collect()
        return render_template("login-form.html",
                               title='Login',
                               form=form,
                               error=error)

    except Exception as e:
        return str(e)
Ejemplo n.º 4
0
def article_list_tag(tag):
    error = ""
    try:
        # access database
        dynamodb = get_dbresource()
        articletable = dynamodb.Table('articles')
        usertable = dynamodb.Table('users')

        cover_path = "cover_pics/"

        # fetch all articles
        articles = []
        response = articletable.query(
            IndexName='TagIndex',
            KeyConditionExpression=Key('Tag').eq(tag)
        )
        for item in response['Items']:
            r = usertable.query(
                IndexName='UIDIndex',
                KeyConditionExpression=Key('UserID').eq(item['StarterID'])
            )
            if r['Count'] == 0:
                starter_name = 'Anonymous'
            else:
                starter_name = r['Items'][0]['Nickname']

            article = classes.article(
                article_id=item['ArticleID'],
                title=item['Title'],
                cover_pic=escape_string(cover_path + item['Tag'] + '.jpg'),
                tag=item['Tag'],
                starter_id=item['StarterID'],
                starter_name=starter_name,
                create_time=item['CreateTime'],
                modify_time=item['ModifyTime'],
                thumb_num=item['ThumbNum']
            )
            articles.append(article)

        articles.sort(key=operator.attrgetter('modify_time'), reverse=True)
        # cleanup
        gc.collect()

        return render_template("article-list.html", title="Gallery", articles=articles, tag=tag)

    except Exception as e:
        return str(e)  # page for showing full articles
Ejemplo n.º 5
0
def article_list():
    error = ""
    try:
        # access database
        dynamodb = get_dbresource()
        articletable = dynamodb.Table('articles')
        usertable = dynamodb.Table('users')

        cover_url = "https://s3.amazonaws.com/ece1779-ft/cover_pics/"

        # fetch all articles
        articles = []
        response = articletable.scan()
        for item in response['Items']:
            r = usertable.query(IndexName='UIDIndex',
                                KeyConditionExpression=Key('UserID').eq(
                                    item['StarterID']))
            if r['Count'] == 0:
                raise ValueError('Cannot find the author.')

            starter_name = r['Items'][0]['Nickname']

            article = classes.article(article_id=item['ArticleID'],
                                      title=item['Title'],
                                      cover_pic=escape_string(cover_url +
                                                              item['Tag']),
                                      tag=item['Tag'],
                                      starter_id=item['StarterID'],
                                      starter_name=starter_name,
                                      create_time=item['CreateTime'],
                                      modify_time=item['ModifyTime'],
                                      thumb_num=item['ThumbNum'])
            articles.append(article)

        articles.sort(key=operator.attrgetter('modify_time'), reverse=True)
        # cleanup
        gc.collect()

        return render_template("article-list.html",
                               title="Gallery",
                               articles=articles,
                               tag='all')

    except Exception as e:
        return str(e)
Ejemplo n.º 6
0
import boto3
from pymysql import escape_string
from boto3.dynamodb.conditions import Key
from app import get_dbresource, classes

import datetime
import operator

if __name__ == '__main__':
    dynamodb = get_dbresource()
    usertable = dynamodb.Table('users')
    article_table = dynamodb.Table('articles')
    chapter_table = dynamodb.Table('chapters')
    comment_table = dynamodb.Table('comments')

    response = usertable.query(
        IndexName='UIDIndex',
        KeyConditionExpression=Key('UserID').eq('tester01'))
    print(response)

    response = usertable.query(
        IndexName='UIDIndex',
        KeyConditionExpression=Key('UserID').eq('tester02'))
    print(response)

    # article_table.update_item(
    #     Key={
    #         'ArticleID': '1511229514953828'
    #     },
    #     UpdateExpression="set ModifyTime = :m",
    #     ExpressionAttributeValues={
Ejemplo n.º 7
0
def full_article(article_id):
    try:
        cover_url = "https://s3.amazonaws.com/ece1779-ft/cover_pics/"
        s3_url = "https://s3.amazonaws.com/ece1779-ft/"
        chapter_form = classes.ChapterForm(request.form)
        comment_form = classes.CommentForm(request.form)

        # access database
        dynamodb = get_dbresource()
        chaptertable = dynamodb.Table('chapters')
        usertable = dynamodb.Table('users')
        articletable = dynamodb.Table('articles')
        comment_table = dynamodb.Table('comments')

        # query for article information
        response = articletable.query(
            KeyConditionExpression=Key('ArticleID').eq(article_id))
        if response['Count'] == 0:
            raise ValueError('This page does not exist.')

        item = response['Items'][0]

        # query for starter information
        r = usertable.query(IndexName='UIDIndex',
                            KeyConditionExpression=Key('UserID').eq(
                                item['StarterID']))
        if r['Count'] == 0:
            raise ValueError('Cannot find the author.')

        starter_name = r['Items'][0]['Nickname']
        article = classes.article(article_id=item['ArticleID'],
                                  title=item['Title'],
                                  cover_pic=escape_string(cover_url +
                                                          item['Tag']),
                                  tag=item['Tag'],
                                  starter_id=item['StarterID'],
                                  starter_name=starter_name,
                                  create_time=item['CreateTime'],
                                  modify_time=item['ModifyTime'],
                                  thumb_num=item['ThumbNum'])

        # query for chapter information
        response = chaptertable.query(
            IndexName='ArticleIndex',
            KeyConditionExpression=Key('ArticleID').eq(article_id))
        # initialize the chapter list
        chapters = []
        for item in response['Items']:
            r = usertable.query(IndexName='UIDIndex',
                                KeyConditionExpression=Key('UserID').eq(
                                    item['AuthorID']))
            if r['Count'] == 0:
                raise ValueError('Cannot find the author.')

            author_name = r['Items'][0]['Nickname']
            txt = urllib.request.urlopen(
                s3_url + item['Content']).read().decode('utf-8').rstrip()
            print(txt)
            chapter = classes.chapter(chapter_id=item['ChapterID'],
                                      content=txt,
                                      article_id=item['ArticleID'],
                                      author_id=item['AuthorID'],
                                      author_name=author_name,
                                      create_time=item['CreateTime'],
                                      thumb_num=item['ThumbNum'])

            r_comment = comment_table.query(
                IndexName='ChapterIndex',
                KeyConditionExpression=Key('ChapterID').eq(chapter.chapter_id))
            if r_comment['Count'] > 0:
                chapter.comment = []
                i_comments = r_comment['Items']
                for i in i_comments:
                    r_user = usertable.query(
                        IndexName='UIDIndex',
                        KeyConditionExpression=Key('UserID').eq(
                            i['CommenterID']))
                    if r_user['Count'] > 0:
                        commenter_name = r_user['Items'][0]['Nickname']
                    else:
                        commenter_name = 'Anonymous'

                    txt = urllib.request.urlopen(
                        s3_url + i['Content']).read().decode('utf-8').rstrip()
                    comment = classes.comment(
                        comment_id=i['CommentID'],
                        chapter_id=i['ChapterID'],
                        content=txt,
                        commenter_id=i['CommenterID'],
                        commenter_name=commenter_name,
                        create_time=i['CreateTime'],
                    )
                    chapter.comment.append(comment)
                chapter.comment.sort(key=operator.attrgetter('create_time'),
                                     reverse=False)

            chapters.append(chapter)
        chapters.sort(key=operator.attrgetter('create_time'), reverse=False)

        return render_template("full-article.html",
                               article=article,
                               chapters=chapters,
                               chapterform=chapter_form,
                               commentform=comment_form)

    except Exception as e:
        return str(e)
Ejemplo n.º 8
0
def signup_form():
    error = ''
    try:
        form = SignUpForm(request.form)

        if request.method == "POST":
            # check if form is validated
            if not form.validate_on_submit():
                error = "request is invalidated"
                return render_template("signup-form.html",
                                       title='sign up',
                                       form=form,
                                       error=error)

            username = form.username.data
            nickname = form.nickname.data
            email = form.email.data
            password = sha256_crypt.encrypt((str(form.password.data)))

            dynamodb = get_dbresource()
            usertable = dynamodb.Table('users')

            # check if username is taken
            response = usertable.query(IndexName='UIDIndex',
                                       KeyConditionExpression=Key('UserID').eq(
                                           escape_string(username)))
            if response['Count'] > 0:
                error = "That username is already taken"
                return render_template('signup-form.html',
                                       title='sign up',
                                       form=form,
                                       error=error)

            # check if nickname is taken
            response = usertable.query(
                IndexName='NicknameIndex',
                KeyConditionExpression=Key('Nickname').eq(
                    escape_string(nickname)))
            if response['Count'] > 0:
                error = "That nickname is already taken"
                return render_template('signup-form.html',
                                       title='sign up',
                                       form=form,
                                       error=error)

            usertable.put_item(
                Item={
                    'UserID': escape_string(username),
                    'Nickname': escape_string(nickname),
                    'Email': escape_string(email),
                    'Password': escape_string(password)
                })
            flash("Thanks for signing up!")
            gc.collect()

            # record in session as a cookie
            session['logged_in'] = True
            session['username'] = username
            session['nickname'] = nickname

            return redirect(url_for('article_list'))

        return render_template("signup-form.html",
                               title='sign up',
                               form=form,
                               error=error)

    except Exception as e:
        return str(e)  # logout page
Ejemplo n.º 9
0
def new_article():
    error = ''
    try:
        form = classes.ArticleForm(request.form)
        if request.method == "POST":
            # check if form is validated
            if not form.validate_on_submit():
                error = "request is invalidated"
                return render_template("article-upload.html",
                                       title='new story',
                                       form=form,
                                       error=error)

            user_id = session['username']
            user_nickname = session['nickname']
            title = escape_string(form.title.data)
            content_body = form.content.data
            tag = form.tag.data

            # access to database
            dynamodb = get_dbresource()
            article_table = dynamodb.Table('articles')
            chapter_table = dynamodb.Table('chapters')

            article_id = str(get_microseconds())
            starter_id = user_id
            chapter_id = article_id + '_' + str(get_microseconds())
            author_id = user_id
            create_time = str(datetime.datetime.now())[:19]
            modify_time = create_time

            # insert the article info into the database
            response1 = article_table.query(KeyConditionExpression=Key(
                'ArticleID').eq(escape_string(article_id)))
            response2 = chapter_table.query(KeyConditionExpression=Key(
                'ChapterID').eq(escape_string(chapter_id)))

            if response1['Count'] > 0 or response2['Count'] > 0:
                flash("Server is busy, please try again.")
                return render_template("article-upload.html",
                                       title="new article",
                                       error=error)

            # upload article body to s3
            s3 = get_s3bucket()
            content = ARTICLES_PATH + article_id + '/' + chapter_id + '.md'
            s3.put_object(Key=content, Body=content_body, ACL='public-read')

            article_table.put_item(
                Item={
                    'ArticleID': escape_string(article_id),
                    'Title': escape_string(title),
                    'Tag': escape_string(tag),
                    'StarterID': escape_string(starter_id),
                    'CreateTime': escape_string(create_time),
                    'ModifyTime': escape_string(modify_time),
                    'ThumbNum': decimal.Decimal(0)
                })

            chapter_table.put_item(
                Item={
                    'ChapterID': escape_string(chapter_id),
                    'Content': escape_string(content),
                    'AuthorID': escape_string(author_id),
                    'ArticleID': escape_string(article_id),
                    'CreateTime': escape_string(create_time),
                    'ThumbNum': decimal.Decimal(0)
                })
            gc.collect()

            flash("new story is created successfully")
            return redirect(url_for("full_article", article_id=article_id))

        return render_template("article-upload.html",
                               title="new story",
                               form=form)

    except Exception as e:
        return str(e)
Ejemplo n.º 10
0
def new_chapter(article_id):
    error = ''
    try:
        form = classes.ChapterForm(request.form)
        if not form.validate_on_submit():
            error = "request is invalidated"
            return redirect(
                url_for("full_article", article_id=article_id, error=error))

        # access to database
        dynamodb = get_dbresource()
        article_table = dynamodb.Table('articles')
        chapter_table = dynamodb.Table('chapters')

        response = article_table.query(KeyConditionExpression=Key(
            'ArticleID').eq(escape_string(article_id)))
        if response['Count'] == 0:
            raise ValueError('This page does not exist.')

        content_body = form.content.data
        chapter_id = article_id + '_' + str(get_microseconds())
        author_id = session['username']
        create_time = str(datetime.datetime.now())[:19]
        modify_time = create_time

        response = chapter_table.query(KeyConditionExpression=Key(
            'ChapterID').eq(escape_string(chapter_id)))

        if response['Count'] > 0:
            flash("Server is busy, please try again.")
            return render_template("article-upload.html",
                                   title="new article",
                                   error=error)

        # upload chapter body to s3
        s3 = get_s3bucket()
        content = ARTICLES_PATH + article_id + '/' + chapter_id + '.md'
        s3.put_object(Key=content, Body=content_body, ACL='public-read')

        # insert the article info into the database
        chapter_table.put_item(
            Item={
                'ChapterID': escape_string(chapter_id),
                'Content': escape_string(content),
                'AuthorID': escape_string(author_id),
                'ArticleID': escape_string(article_id),
                'CreateTime': escape_string(create_time),
                'ThumbNum': decimal.Decimal(0)
            })

        article_table.update_item(
            Key={'ArticleID': article_id},
            UpdateExpression="set ModifyTime = :m",
            ExpressionAttributeValues={':m': modify_time},
            ReturnValues="UPDATED_NEW")

        gc.collect()

        flash("new chapter is created successfully")
        return redirect(url_for("full_article", article_id=article_id))

    except Exception as e:
        return str(e)