Esempio n. 1
0
    def put(self, id):
        # get the current user's id
        user_id = current_identity.id
        post = PostModel.find_by_id(id)
        print('here')
        if post is None:
            return {
                'success': False,
                'message': 'Post was not found'
                }, 404

        # check if the current user is the owner of the post
        if post.user != user_id:
            return {
                'success': False,
                'message': 'Not Authorized to Edit this post'
                }, 401

        data = Post.parser.parse_args()
        post.title = data['title']
        post.body = data['body']
        post.category_id = data['category_id']

        # try to delete the post or 500
        try:
            post.save_to_db()
        except:
            return {'message': 'Something went wrong'}, 500
        return {
            'success': True,
            'message': 'Post was edited successfully.'
            }, 200
Esempio n. 2
0
    def post(self):
        data = Comment.parser.parse_args()

        if len(data['name']) > Configuration.MAX_COMMENT_NAME_SIZE:
            return {
                'message':
                'A comment\'s name length is more than {}'.format(
                    Configuration.MAX_COMMENT_NAME_SIZE)
            }

        if len(data['email']) > Configuration.MAX_EMAIL_ADDRESS_SIZE:
            return {
                'message':
                'email\'s length is more than {}'.format(
                    Configuration.MAX_EMAIL_ADDRESS_SIZE)
            }

        if not PM.find_by_id(data['post_id']):
            return {
                'message':
                'There is no such post: \'{}\''.format(data['post_id'])
            }

        post_id = data['post_id']
        del data['post_id']
        comment = CM(**data)

        comment.post_id = post_id
        try:
            comment.save_to_db()
        except SQLAlchemyError as e:
            err = str(e.__class__.__name__)
            return {'message': '{}'.format(err)}, 500
        return comment.get_json(), 201
Esempio n. 3
0
    def delete(cls, post_id):
        post = PostModel.find_by_id(post_id)

        if post.user_id != current_user.id:
            return {'message': 'This Action is Unauthorized Bro'}, 401
        post.delete_from_db()
        return {'message': 'Post Deleted'}
Esempio n. 4
0
 def increment_post_saved(postid):
     target_post = PostModel.find_by_id(postid)
     if target_post is None:
         return "Target post not found"
     target_post.saved += 1
     target_post.save_to_db()
     return ""
Esempio n. 5
0
    def put(cls, post_id):
        post_data = post_schema.load(request.get_json())

        post = PostModel.find_by_id(id=post_id)
        if not post:
            return {'message': POST_NOT_FOUND}, 404

        user_id = get_jwt_identity()
        if not post.verify_post_author(user_id):
            abort(403)

        post.title = post_data.title
        post.content = post_data.content
        # if image is updated must delete the prev one
        if post.image != post_data.image and post_data.image:
            folder = 'user_{}'.format(user_id)
            new_filename = post_data.image.split(f'user_{user_id}/')[-1]
            if post.image:
                existing_filename = post.image.split(f'user_{user_id}/')[-1]
                try:
                    os.remove(get_path(filename=existing_filename, folder=folder))
                    post.image = post_data.image
                except FileNotFoundError:
                    return {'message': IMAGE_NOT_FOUND.format(existing_filename)}, 404
            else:
                post.image = post_data.image
                

        post.save_to_db()
        return (
            '',
            204,
            {'Location': url_for('resources.posts.post', post_id=post.id)}
        )
Esempio n. 6
0
    def put(self, _id):
        data = Post.parser.parse_args()

        if len(data['title']) > Configuration.MAX_POST_TITLE_SIZE:
            return {
                'message':
                'A title\'s length is more than {}'.format(
                    Configuration.MAX_POST_TITLE_SIZE)
            }
        category = data['category_id']
        if category:
            if not CM.query.filter(CM.id == category).first():
                return {
                    'message':
                    'There is no such category: \'{}\''.format(category)
                }

        tag_names = data['tags']
        if tag_names:
            tags = get_tags(tag_names)
        else:
            tags = []

        comments_id = data['comments']
        if comments_id:
            comments = get_comments(comments_id)
        else:
            comments = []

        del data['tags']
        del data['category_id']
        del data['comments']

        post = PostModel.find_by_id(_id)
        if not post:
            post = PostModel(**data)
            if tags:
                post = get_item_tags(tags, post)
            if comments:
                post = get_item_comments(comments, post)
        else:
            post.title = data['title']
            post.body = data['body']
            post.user_id = data['user_id']
            post.is_published = data['is_published']
            post.category_id = category
            post.tags = []
            post.comments = []
            if tags:
                post = get_item_tags(tags, post)
            if comments:
                post = get_item_comments(comments, post)

        try:
            post.save_to_db()
        except SQLAlchemyError as e:
            err = str(e.__class__.__name__)
            return {'message': '{}'.format(err)}, 500
        return post.get_json(), 201
Esempio n. 7
0
 def put(cls, post_id):
     data = post_parser.parse_args()
     post = PostModel.find_by_id(post_id)
     if post.user_id != current_user.id:
         return {'message': 'This Action is Unauthorized Bro'}, 401
     post.content = data['content']
     post.save_to_db()
     return post.json()
Esempio n. 8
0
def get_posts(posts_id):
    posts = []
    for _id in posts_id:
        post = PM.find_by_id(_id)
        if post:
            posts.append(post)
        else:
            return {'message': 'There is no such post: \'{}\''.format(_id)}
    return posts
Esempio n. 9
0
 def delete(self, id_post):
     post = PostModel.find_by_id(id_post)
     if not post:
         return {"message": "Post does not exist"}, 400
     liked = LikeModel.find_by_id_post_and_user(id_post, current_identity.id)
     if liked:
         LikeModel.query.filter_by(id_post=id_post, id_user=current_identity.id).delete()
         db.session.commit()
         return {"message": "Post unliked"}, 201
     return {"message": "Post not liked yet"}, 400
Esempio n. 10
0
 def decrement_post_saved(postid):
     target_post = PostModel.find_by_id(postid)
     if target_post is None:
         return "Target post not found"
     if target_post.saved > 0:
         target_post.saved -= 1
     else:
         return "Post already had saved count of 0"
     target_post.save_to_db()
     return ""
Esempio n. 11
0
def get_post(id, check_author=True):
    post = PostModel.find_by_id(id)

    if post is None:
        abort(404, "Post id {0} doesn't exist.".format(id))

    if check_author and post.user_id != g.user.id:
        abort(403)

    return post
Esempio n. 12
0
    def put(self, post_id):
        data = Post.parser.parse_args()

        post = PostModel.find_by_id(post_id)

        if post is None:
            post = PostModel(post_id, data['title'])
        else:
            post.title = data['title']

        post.save_to_db()
        return post.json()
    def post(cls, post_id):
        post = PostModel.find_by_id(post_id)
        if not post:
            return {'message': POST_NOT_FOUND}, 404
        comment = comment_schema.load(request.get_json())
        user_id = get_jwt_identity()
        comment.author_id = user_id
        comment.post_id = post.id
        comment.save_to_db()

        return ('', 201, {
            'Location': url_for('resources.posts.post', post_id=post.id)
        })
Esempio n. 14
0
 def put(self, id_post):
     post = PostModel.find_by_id(id_post)
     if not post:
         return {"message": "Post does not exist"}, 400
     liked = LikeModel.find_by_id_post_and_user(id_post, current_identity.id)
     if not liked:
         like = LikeModel(id_post)
         like.save_to_db()
         return {"message": "Post liked"}, 201
     else:
         liked.date_created = datetime.datetime.now()
         return {"message": "Post liked again"}, 200
     return {"message": "Error"}, 400
Esempio n. 15
0
 def filter_by_id(wanted):
     if not wanted:
         return "Wanted post list is empty", None
     # check if wanted list is only comprised of numbers and spaces
     wanted_nospace = wanted.replace(" ", "")
     if not wanted_nospace.isdigit():
         return "Post ids should only consist of integers", None
     wanted_list = wanted.split(' ')
     result = []
     for each in wanted_list:
         result.append(PostModel.find_by_id(each))
     if len(wanted_list) != len(result):
         return "Inconsistent loading of posts", None
     return "", result
Esempio n. 16
0
    def post(self, post_id):
        if PostModel.find_by_id(post_id):
            return {
                'message':
                "An item with id: '{}' already exist".format(post_id)
            }, 400

        data = Post.parser.parse_args()
        post = PostModel(post_id, data['title'])

        try:
            post.save_to_db()
        except:
            return {'message': 'An error inserting post'}, 500

        return post.json(), 201
Esempio n. 17
0
 def delete_saved(postid, userid):
     target_user = UserModel.find_by_id(userid)
     #check if post id is valid
     target_post = PostModel.find_by_id(postid)
     if target_post is None:
         return "Post with the given id doesn't exist"
     #check that saved is not empty
     if target_user.saved:
         saved_list = target_user.saved.split(' ')
         #ensure postid exists inside user's saved list
         for each in saved_list:
             if postid == each:
                 saved_list.remove(postid)
                 target_user.saved_count = len(saved_list)
                 target_user.saved = ' '.join(saved_list)
                 target_user.save_to_db()
                 return ""
         return "target post not found for this user's saved list"
     else:
         return "saved list for this user is already empty"
Esempio n. 18
0
    def append_saved(postid, userid):
        saved_list = []
        target_user = UserModel.find_by_id(userid)
        #check if post id is valid
        target_post = PostModel.find_by_id(postid)
        if target_post is None:
            return "Post with the given id doesn't exist"
        #check that saved is not empty and no same posts are being added
        if target_user.saved:
            saved_list = target_user.saved.split(' ')
            for each in saved_list:
                if postid == each:
                    return "Already saved that post."
        #check that saved count is within limit
        if target_user.saved_count > 29:
            return "Reached maximum capacity for saving posts"

        saved_list.append(postid)
        target_user.saved_count = len(saved_list)
        target_user.saved = ' '.join(saved_list)
        target_user.save_to_db()
        return ""
Esempio n. 19
0
 def delete(self):
     data = PostList.parser.parse_args()
     deleted_posts = []
     messages = []
     for post_id in data['deleted_posts']:
         if str(post_id).isdigit():
             post = PostModel.find_by_id(post_id)
             if post:
                 try:
                     post.delete_from_db()
                 except SQLAlchemyError as e:
                     err = str(e.__class__.__name__)
                     return {'message': '{}'.format(err)}, 500
                 deleted_posts.append(post_id)
             else:
                 messages.append({
                     post_id:
                     'Post with id={} was not found'.format(post_id)
                 })
         else:
             messages.append({post_id: 'id must be a number'})
     if not messages:
         messages.append({'status': "done"})
     return {'deleted_posts': deleted_posts, 'messages': messages}
Esempio n. 20
0
    def delete(cls, post_id):
        post = PostModel.find_by_id(id=post_id)
        if not post:
            return {'message': POST_NOT_FOUND}, 404

        user_id = get_jwt_identity()
        if not post.verify_post_author(user_id):
            abort(403)
        
        if post.image:
            folder = 'user_{}'.format(user_id)
            filename = post.image.split(f'user_{user_id}/')[-1]
            try:
                os.remove(get_path(filename=filename, folder=folder))
            except FileNotFoundError:
                pass
        
        post.delete_from_db()

        return (
            '',
            204,
            {"Location": url_for('resources.posts.posts')}
        )
Esempio n. 21
0
    def delete(self, id):
        # get the current user's id
        user_id = current_identity.id
        post = PostModel.find_by_id(id)

        if post is None:
            return {'success': False, 'message': 'Post was not found'}, 404

        # check if the current user is the owner of the post
        if post.user != user_id:
            return {
                'success': False,
                'message': 'Not Authorized to delete this post'
                }, 401

        # try to delete the post or 500
        try:
            post.delete_from_db()
        except:
            return {'message': 'Something went wrong'}, 500
        return {
            'success': True,
            'message': 'Post was deleted successfully.'
            }, 200
Esempio n. 22
0
    def get(cls, post_id):
        post = PostModel.find_by_id(post_id)
        if not post:
            return {'message': POST_NOT_FOUND}, 404

        return {'post': post_schema.dump(post)}, 200
Esempio n. 23
0
    def get(self, post_id):
        post = PostModel.find_by_id(post_id)
        if post:
            return post.json()

        return {'message': 'post not found'}, 404
Esempio n. 24
0
 def get(cls, post_id: int):
     post = PostModel.find_by_id(post_id)
     if not post:
         return {"message": "Post not found."}
     return post_schema.dump(post), 200
Esempio n. 25
0
 def get(cls, post_id):
     post = PostModel.find_by_id(post_id)
     if not post:
         return {'message': 'Post Not Found'}, 404
     return post.json()
Esempio n. 26
0
 def get(self, _id):
     post = PostModel.find_by_id(_id)
     if post:
         return {"text": post.text, "likes": LikeModel.count_post_likes(_id), "id_user": post.id_user,
                 "date_created": post.date_created.strftime('%Y-%m-%d %H:%M')}, 200
     return {"message": "Wrong post id"}, 400
Esempio n. 27
0
 def delete(cls, post_id: int):
     post = PostModel.find_by_id(post_id)
     if post:
         post.delete_from_db()
         return {"message": "Deleted Successfully."}
     return {"message": "Post not found."}
Esempio n. 28
0
 def delete(self, post_id):
     post = PostModel.find_by_id(post_id)
     if post:
         post.delete_from_db()
         return {'message': f'post with id {post_id} has been deleted'}
     return {'message': 'no post where found to delete'}
Esempio n. 29
0
	def get(self, post_id):
		post = PostModel.find_by_id(post_id)
		return {"posts" : post.json()},200
Esempio n. 30
0
	def delete(self, post_id):
		post = PostModel.find_by_id(post_id)
		post.delete_to_db()
		return {"msg" : "Post deleted"}, 200