Exemple #1
0
def submit():
    form = get_post_form()
    if request.method == 'GET':
        return render_template('posts/form.html', submit_post_form=form)
    else:
        if form.validate_on_submit():
            content = form.content.data
            # If the post is a link (is 1), we cast this because it's coming from
            # a hidden field
            post_type_id = int(form.post_type_id.data)
            if post_type_id == 1:
                content = form.url.data
                if not check_url(content):
                    return abort(404)
            else:
                # Clean the content
                content = bleach_input(content)
            if not content:
                return abort(400)

            post = Post(user_id=current_user.id,
                        category_id=form.category_id.data,
                        post_type_id=post_type_id,
                        title=form.title.data,
                        slug=slugify(form.title.data),
                        content=content)
            db.session.add(post)
            db.session.commit()
            post.uuid = encode_id(post.id)
            db.session.commit()
            post_rating = PostRating(post_id=post.id, positive=0, negative=0)
            db.session.add(post_rating)
            post.update_hot()
            if form.picture.data or form.picture_remote.data:
                if form.picture.data:
                    # If the user uploads an image from the form
                    _, filepath = tempfile.mkstemp()
                    form.picture.data.save(filepath)
                else:
                    # If the url is retrieved via embedly
                    _, filepath = tempfile.mkstemp()
                    with open(filepath, 'wb') as handle:
                        response = requests.get(form.picture_remote.data,
                                                stream=True)
                        for block in response.iter_content(1024):
                            if not block:
                                break
                            handle.write(block)

                # In both cases we get the image now saved in temp and upload it
                # to Imgur
                if imgur_client:
                    image = imgur_client.upload_from_path(filepath,
                                                          config=None,
                                                          anon=True)
                else:
                    image = dict(link=None, deletehash=None)

                if app.config['USE_UPLOADS_LOCAL_STORAGE']:
                    # Use the post UUID as a name for the local image.
                    # If Imgur is not available save it in the database with a _ to
                    # imply that the file is available only locally.
                    if not image['link']:
                        image['link'] = '_' + post.uuid
                    image_name = post.uuid + '.jpg'
                    # The root of the local storage path
                    local_storage_path = app.config[
                        'UPLOADS_LOCAL_STORAGE_PATH']
                    # Get the first 2 chars of the image name to make a subfolder
                    storage_folder = os.path.join(local_storage_path,
                                                  image_name[:2])
                    # Check if the subfolder exists
                    if not os.path.exists(storage_folder):
                        # Make it if it does not
                        os.mkdir(storage_folder)
                    # Build the full path to store the image
                    storage_filepath = os.path.join(storage_folder, image_name)
                    # Copy from temp to the storage path
                    im = Image.open(filepath)
                    im.save(storage_filepath, "JPEG")
                    # Make all the thumbnails
                    generate_local_thumbnails(storage_filepath)
                post.picture = image['link']
                post.picture_deletehash = image['deletehash']
                os.remove(filepath)
            db.session.commit()

            # Subscribe owner to updates for this post (mainly comments)
            notification_subscribe(current_user.id, 1, post.id)

            # Clear all the caches
            delete_redis_cache_keys('post_list')
            delete_redis_cache_keys('post_list', post.category.url)

            return jsonify(post_url=url_for('posts.view',
                                            category=post.category.url,
                                            uuid=post.uuid,
                                            slug=post.slug))
        else:
            return abort(400, '{"message" : "form validation error"}')
Exemple #2
0
def submit():
    form = PostForm()
    form.category_id.choices = [(c.id, c.name) for c in Category.query.all()]
    if form.validate_on_submit():
        content = form.content.data
        # If the post is a link (is 1), we cast this because it's coming from
        # a hidden field
        post_type_id = int(form.post_type_id.data)
        if post_type_id == 1:
            content = form.url.data
            if not check_url(content):
                return abort(404)
        else:
            # Clean the content
            content = bleach_input(content)
        if not content:
            return abort(400)

        post = Post(
            user_id=current_user.id,
            category_id=form.category_id.data,
            post_type_id=post_type_id,
            title=form.title.data,
            slug=slugify(form.title.data),
            content=content,
        )
        db.session.add(post)
        db.session.commit()
        post.uuid = encode_id(post.id)
        db.session.commit()
        post_rating = PostRating(post_id=post.id, positive=0, negative=0)
        db.session.add(post_rating)
        post.update_hot()
        if form.picture.data or form.picture_remote.data:
            if form.picture.data:
                # If the user uploads an image from the form
                filename = secure_filename(form.picture.data.filename)
                filepath = "/tmp/" + filename
                form.picture.data.save(filepath)
            else:
                # If the url is retrieved via embedly
                filename = secure_filename(form.picture_remote.data)
                filepath = "/tmp/" + filename
                with open(filepath, "wb") as handle:
                    response = requests.get(form.picture_remote.data, stream=True)
                    for block in response.iter_content(1024):
                        if not block:
                            break
                        handle.write(block)

            # In both cases we get the image now saved in temp and upload it
            # to Imgur
            if imgur_client:
                image = imgur_client.upload_from_path(filepath, config=None, anon=True)
            else:
                image = dict(link=None, deletehash=None)

            if app.config["USE_UPLOADS_LOCAL_STORAGE"]:
                # Use the post UUID as a name for the local image.
                # If Imgur is not available save it in the database with a _ to
                # imply that the file is available only locally.
                if not image["link"]:
                    image["link"] = "_" + post.uuid
                image_name = post.uuid + ".jpg"
                # The root of the local storage path
                local_storage_path = app.config["UPLOADS_LOCAL_STORAGE_PATH"]
                # Get the first 2 chars of the image name to make a subfolder
                storage_folder = os.path.join(local_storage_path, image_name[:2])
                # Check if the subfolder exists
                if not os.path.exists(storage_folder):
                    # Make it if it does not
                    os.mkdir(storage_folder)
                # Build the full path to store the image
                storage_filepath = os.path.join(storage_folder, image_name)
                # Copy from temp to the storage path
                im = Image.open(filepath)
                im.save(storage_filepath, "JPEG")
                # Make all the thumbnails
                generate_local_thumbnails(storage_filepath)
            post.picture = image["link"]
            post.picture_deletehash = image["deletehash"]
            os.remove(filepath)
        db.session.commit()

        # Subscribe owner to updates for this post (mainly comments)
        notification_subscribe(current_user.id, 1, post.id)

        # Clear all the caches
        delete_redis_cache_keys("post_list")
        delete_redis_cache_keys("post_list", post.category.url)

        return jsonify(post_url=url_for("posts.view", category=post.category.url, uuid=post.uuid, slug=post.slug))
    else:
        return abort(400, '{"message" : "form validation error"}')
Exemple #3
0
def submit(post_id):
    form = CommentForm()
    post = Post.query.get_or_404(post_id)
    if form.validate_on_submit():
        parent_id = form.parent_id.data
        if not parent_id:
            parent_id = None
        else:
            parent_id = int(form.parent_id.data)
        comment = Comment(
            user_id=current_user.id,
            post_id=post.id,
            parent_id=parent_id,
            content = bleach_input(form.content.data))
        db.session.add(comment)
        db.session.commit()
        comment.uuid = encode_id(comment.id)
        comment_rating = CommentRating(
            comment_id=comment.id,
            positive=0,
            negative=0
            )
        db.session.add(comment_rating)
        db.session.commit()

        # Subscribe user to post (skips if already subscribed)
        notification_subscribe(current_user.id, 1, post.id)

        if parent_id:
            # If the comment is a reply notify the subscribed users
            notification_object_add(current_user.id, 'replied', 2, comment.id,
                2, parent_id)
            # Subscribe to comments to parent comment
            notification_subscribe(current_user.id, 2, parent_id)
        else:
            # Push notification to users subscribed to the post
            notification_object_add(current_user.id, 'commented', 2, comment.id,
                1, post.id)
            # Subscribe to comments to own comment
            notification_subscribe(current_user.id, 2, comment.id)

        # Clear cache for current user
        delete_redis_cache_post(post.uuid)
        # Clear cache for all subscribed users
        for subscription in notification_get_subscriptions(
            1, post.id, current_user.id):
            delete_redis_cache_post(post.uuid, subscription.user_id)

        # This is to prevent encoding error when jsonify prints out
        # a non ASCII name
        if comment.user.first_name and comment.user.last_name:
            display_name = u"{0} {1}".format(
                comment.user.first_name,
                comment.user.last_name)
        else:
            display_name = comment.user.username

        return jsonify(comment=dict(
            user_name=display_name,
            gravatar=comment.user.gravatar(),
            content=comment.content,
            comment_id=comment.id,
            parent_id=comment.parent_id,
            post_uuid=post.uuid,
            creation_date=comment.pretty_creation_date,
            post_url=url_for('posts.view',
                category=post.category.url,
                uuid=post.uuid,
                slug=post.slug)
            ))
    else:
        return abort(400)
Exemple #4
0
def submit(post_id):
    form = CommentForm()
    post = Post.query.get_or_404(post_id)
    if form.validate_on_submit():
        parent_id = form.parent_id.data
        if not parent_id:
            parent_id = None
        else:
            parent_id = int(form.parent_id.data)
        comment = Comment(user_id=current_user.id,
                          post_id=post.id,
                          parent_id=parent_id,
                          content=bleach_input(form.content.data))
        db.session.add(comment)
        db.session.commit()
        comment.uuid = encode_id(comment.id)
        comment_rating = CommentRating(comment_id=comment.id,
                                       positive=0,
                                       negative=0)
        db.session.add(comment_rating)
        db.session.commit()

        # Subscribe user to post (skips if already subscribed)
        notification_subscribe(current_user.id, 1, post.id)

        if parent_id:
            # If the comment is a reply notify the subscribed users
            notification_object_add(current_user.id, 'replied', 2, comment.id,
                                    2, parent_id)
            # Subscribe to comments to parent comment
            notification_subscribe(current_user.id, 2, parent_id)
        else:
            # Push notification to users subscribed to the post
            notification_object_add(current_user.id, 'commented', 2,
                                    comment.id, 1, post.id)
            # Subscribe to comments to own comment
            notification_subscribe(current_user.id, 2, comment.id)

        # Clear cache for current user
        delete_redis_cache_post(post.uuid)
        # Clear cache for all subscribed users
        for subscription in notification_get_subscriptions(
                1, post.id, current_user.id):
            delete_redis_cache_post(post.uuid, subscription.user_id)

        # This is to prevent encoding error when jsonify prints out
        # a non ASCII name
        if comment.user.first_name and comment.user.last_name:
            display_name = u"{0} {1}".format(comment.user.first_name,
                                             comment.user.last_name)
        else:
            display_name = comment.user.username

        return jsonify(
            comment=dict(user_name=display_name,
                         gravatar=comment.user.gravatar(),
                         content=comment.content,
                         comment_id=comment.id,
                         parent_id=comment.parent_id,
                         post_uuid=post.uuid,
                         creation_date=comment.pretty_creation_date,
                         post_url=url_for('posts.view',
                                          category=post.category.url,
                                          uuid=post.uuid,
                                          slug=post.slug)))
    else:
        return abort(400)