def get(self, number): # Gets all comments for the ticket comments = CommentModel.find_by_number(number) if comments: return {"comments": comments} return {"message": "Ticket not found."}
def delete_storie(storie_id, storie_user_id): db = MongoController.get_mongodb_instance(MONGODB_USER, MONGODB_PASSWD) storie = db.stories.find_one({ '_id': storie_id, 'user_id': storie_user_id }) if storie == None: raise NoStorieFoundException CommentModel.remove_comment_by_storie_id(storie_id) ReactionModel.remove_reaction_by_storie_id(storie_id) db.stories.remove({'_id': storie_id}) storie = StorieModel.format_storie_dates(storie) return storie
def get(self, post_id): return { 'comments': [ comment_schema.dump(x) for x in CommentModel.find_by_post_id(post_id) ] }
def get(self, storie_id): try: comments = CommentModel.get_storie_comments(storie_id) return comments except NoStorieFoundException as e: return ErrorHandler.create_error_response(str(e), 404) except DBConnectionError as e: return ErrorHandler.create_error_response(str(e), 500)
def patch(self, number): # Adds comment to ticket data = CommentAdder.parser.parse_args() ticket = TicketModel.find_by_number(number) if ticket: timestamp = int(time.time()) comment = CommentModel(number, timestamp, **data) try: comment.add_to_db() except IntegrityError: return { "message": "An error occurred inserting the item." }, 500 return comment.json(), 202 return {"message": "Ticket not found."}, 400
def delete(cls, comment_id: int): user_id = get_jwt_identity() comment = CommentModel.find_by_comment_id(comment_id) if comment: if comment.user_id == user_id: comment.delete_comment() return {"Message": gettext("comment_delete_successful")}, 201 return {"Message": gettext("comment_not_authorized_to_change_others_comment")}, 401 return {"Message": gettext("comment_not_exist")}, 401
def get_comments(comments_id): comments = [] for comment_id in comments_id: comment = CommentModel.find_by_name(comment_id) if comment: comments.append(comment) else: return {'message': 'There is no such comment: \'{}\''.format(_id)} return comments
def get(self, post_id): login = get_jwt_identity() user = UserModel.find_by_username(login) if user: last_comment = CommentModel.get_last_comment(post_id) return comment_schema.dump(last_comment) else: return {"message": "User not found"}, 404
def get(self, id_tourist_spot): # GET /tourist-spot/<id>/picture return { "commentary_list": list( map( lambda x: x.json(), CommentModel.find_comment_by_id_tourist_spot( id_tourist_spot))) }
def delete(self, _id): comment = CM.find_by_id(_id) if comment: try: comment.delete_from_db() except SQLAlchemyError as e: err = str(e.__class__.__name__) return {'message': '{}'.format(err)}, 500 return {'message': 'Comment was deleted'} return { 'message': 'Comment with name: \'{}\' was not found'.format(name) }
def delete(cls, comment_id): """Update a comment with provided ID, check that user owns the comment""" comment = CommentModel.find_by_id(comment_id) if not comment: return {'message': COMMENT_NOT_FOUND}, 404 user_id = get_jwt_identity() if not comment.verify_comment_author(user_id): abort(403) comment.delete_from_db() return ('', 204, {'Location': url_for('resources.posts.posts')})
def delete(self, course_id, comment_id): comment = CommentModel.find_by_id(comment_id) if comment is None: return {"message": "Comment not found."}, 404 try: comment.delete() except: return { "message": "An error occurred while deleting Comment." }, 500 return {"message": "Comment deleted."}, 200
def delete(self, comment_id): try: self._validate_author(comment_id) comment = CommentModel.remove_comment(comment_id) UserActivityModel.log_comment_activity(comment["user_id"], comment["storie_id"], "DELETE") return self._get_comments_response(comment) except NoCommentFoundException as e: return ErrorHandler.create_error_response(str(e), 404) except UserMismatchException as e: return ErrorHandler.create_error_response(str(e), 409) except DBConnectionError as e: return ErrorHandler.create_error_response(str(e), 500)
def get_storie_resume(storie): storie_resume = { "storie_id": storie["_id"], "past": DateController.get_past_days(storie["created_time"]), "num_comments": CommentModel.count_storie_comments(storie["_id"]), "num_reactions": (storie["reactions"]["LIKE"]["count"] + storie["reactions"]["NOTLIKE"]["count"] + storie["reactions"]["GETBORED"]["count"] + storie["reactions"]["ENJOY"]["count"]) } return storie_resume
def test_create_comment(self, mock_db): mock_db_instance = mock.MagicMock() mock_db.return_value.get_mongodb_instance.return_value = mock_db_instance storie_id = '5ae66a31d4ef925dac59a95b' user_id = '10' result = CommentModel.create_comment({ 'storie_id': storie_id, 'user_id': user_id, 'message': 'test' }) self._comment_id = result['_id'] self.assertEqual(user_id, result['user_id']) self.assertEqual(storie_id, result['storie_id']) self.assertEqual('test', result['message'])
def put(cls, comment_id: int): user_id = get_jwt_identity() comment = CommentModel.find_by_comment_id(comment_id) comment_json = request.get_json() try: comment_data = comment_schema.load(comment_json, partial=("user_id", "post_id")) except ValidationError as err: return err.messages, 401 if comment: if comment.user_id == user_id: comment.comment = comment_data.comment comment.insert_comment() return {"Message": gettext("comment_update_successful")}, 201 return {"Message": gettext("comment_not_authorized_to_change_others_comment")}, 401 return {"Message": gettext("comment_not_exist")}, 401
def delete(self, comment_id): login = get_jwt_identity() user = UserModel.find_by_username(login) if user: comment_to_be_deleted = CommentModel.find_by_comment_id(comment_id) if comment_to_be_deleted: if comment_to_be_deleted.login == user.login: comment_to_be_deleted.delete_from_db() return {'message': 'Comment deleted'}, 200 else: return { 'message': 'It is not a comment of user logged in.' }, 404 else: return {"message": "User not found"}, 404
def delete(self, post_id): post_delete = PostModel.find_by_post_id(post_id) if post_delete.login == get_jwt_identity(): comments_delete = CommentModel.find_by_post_id(post_delete.post_id) hashtags_delete = HashtagModel.get_hashtags_for_post(post_delete.post_id) if comments_delete: for comment in comments_delete: comment.delete_from_db() if hashtags_delete: for hashtag in hashtags_delete: hashtag.delete_from_db() post_delete.delete_from_db() return {'message': 'Post deleted'}, 200 else: return {'message': 'It is not a post of user logged in.'}, 404
def put(cls, comment_id): """Update a comment with provided ID, check that user owns the comment""" comment_data = comment_schema.load(request.get_json()) comment = CommentModel.find_by_id(comment_id) if not comment: return {'message': COMMENT_NOT_FOUND}, 404 user_id = get_jwt_identity() if not comment.verify_comment_author(user_id): abort(403) comment.body = comment_data.body comment.save_to_db() return ('', 204, { 'Location': url_for('resources.comments.comment', comment_id=comment.id) })
def put(self, comment_id): try: self.parser.add_argument('_id', required=True, help="Field id is mandatory") self.parser.add_argument('_rev', required=True, help="Field rev is mandatory") self.parser.add_argument('storie_id', required=True, help="Field storie_id is mandatory") self.parser.add_argument('user_id', required=True, help="Field user_id is mandatory") self.parser.add_argument('message', required=True, help="Field message is mandatory") self._validate_author(comment_id) args = self.parser.parse_args() body = json.loads(request.data.decode('utf-8')) comment = CommentModel.update_comment(comment_id, body) UserActivityModel.log_comment_activity(comment["user_id"], comment["storie_id"], "EDIT") return ResponseBuilder.build_response(comment, 200) except BadRequest as ex: return ErrorHandler.create_error_response( "Fields id, rev, storie_id, user_id and message are mandatory", 400) except NoUserDataFoundException as e: return ErrorHandler.create_error_response(str(e), 400) except NoCommentFoundException as e: return ErrorHandler.create_error_response(str(e), 404) except DataVersionException as e: return ErrorHandler.create_error_response(str(e), 409) except UserMismatchException as e: return ErrorHandler.create_error_response(str(e), 409) except DBConnectionError as e: return ErrorHandler.create_error_response(str(e), 500)
def post(cls, comment_id): comment = CommentModel.find_by_id(comment_id) if not comment: return {'message': COMMENT_NOT_FOUND}, 404 user_id = get_jwt_identity() # see if the Like already exists existing_like = LikeModel.find(user_id, comment_id) if not existing_like: # create new_like = LikeModel(user_id=user_id, comment_id=comment_id) new_like.save_to_db() status_code = 201 else: # delete existing_like.delete_from_db() status_code = 204 return ('', status_code, { 'Location': url_for('resources.comments.comment', comment_id=comment.id) })
def put(self, comment_id): login = get_jwt_identity() user = UserModel.find_by_username(login) if user: existing_comment = CommentModel.find_by_comment_id(comment_id) if existing_comment: if existing_comment.login == user.login: try: comment_to_update = comment_update_schema.load( request.get_json(), partial=True, instance=existing_comment) except ValidationError as err: return err.messages, 400 possible_hashtags = HashtagModel.find_hashtags_in_text( existing_comment.comment) if possible_hashtags: for hashtag in possible_hashtags: existing_hashtag = HashtagModel.find_only_for_comment( hashtag, existing_comment.post_id, existing_comment.comment_id) if not existing_hashtag: hashtag_data = { "post_id": existing_comment.post_id, "hashtag": hashtag, "comment_id": existing_comment.comment_id } new_hashtag = hashtag_schema.load(hashtag_data) new_hashtag.save_to_db() comment_to_update.save_to_db() return {"message": "Comment updated successfully."}, 200 else: return { 'message': 'It is not a comment of user logged in.' }, 404 else: return {"message": "User not found"}, 404
def post(self): data = Comment.parser.parse_args() body = data['body'] post_id = data['post_id'] user_id = get_jwt_identity() comment = CommentModel(body,user_id,post_id) if comment.find_same_comment(user_id,post_id,body): return {"message": "You already commented that already."}, 500 try: comment.save_to_db() except: return {"message": "An error occurred posting this comment."}, 500 return comment.json(), 201
def put(self, course_id, comment_id): data = parser.parse_args() data['course_id'] = course_id comment = CommentModel.find_by_id(comment_id) if comment is None: new_comment = CommentModel(**data) try: new_comment.save() return new_comment.json(), 201 except: return { "message": "An error occurred while inserting Comment." }, 500 try: comment.update(**data) except: return { "message": "An error occurred while updating Comment." }, 500 return comment.json(), 200
def post(self, book_id): comment_text = Book.parser.parse_args()["comment_text"] print(Book.parser.parse_args()) new_comment = CommentModel(comment_text=comment_text, book_id=book_id) new_comment.save_to_db() return BookModel.find_by_id(book_id).json()
def get(self, course_id): comments = CommentModel.find_by_course(course_id) return [comment.json() for comment in comments], 200
def test_db(): from models.user import UserModel, RoleModel student = RoleModel('student') instructor = RoleModel('instructor') db.session.add_all([student, instructor]) db.session.commit() bart = UserModel('bart', 'bart', 'bart', 'student', firstname=None, lastname=None, picture=None) lisa = UserModel('lisa', 'lisa', 'lisa', 'student', firstname=None, lastname=None, picture=None) millhouse = UserModel('millhouse', 'millhouse', 'millhouse', 'student', firstname=None, lastname=None, picture=None) edna = UserModel('edna', 'edna', 'edna', 'instructor', firstname=None, lastname=None, picture=None) simour = UserModel('simour', 'simour', 'simour', 'instructor', firstname=None, lastname=None, picture=None) db.session.add_all([bart, lisa, millhouse, edna, simour]) db.session.commit() print('::: test roles and users ::: ok') ################### print('students') for student in student.users: print('>>> {}'.format(student.username)) print('instructors') for instructor in instructor.users: print('>>> {}'.format(instructor.username)) ################### from models.course import CourseModel from models.category import CategoryModel maths = CategoryModel('maths', fr_label=None, en_label=None, picture=None) english = CategoryModel('english', fr_label=None, en_label=None, picture=None) db.session.add_all([maths, english]) db.session.commit() math_course = CourseModel('mathematics', 'basic operations', simour.id, maths.id, picture=None) english_course = CourseModel('english', 'grammar', edna.id, english.id, picture=None) db.session.add_all([math_course, english_course]) db.session.commit() math_course.register_student(bart.id) math_course.register_student(lisa.id) english_course.register_student(lisa.id) english_course.register_student(millhouse.id) db.session.commit() print('::: test categories and courses ::: ok') ################### print('students enrolled in math') for student in math_course.students: print('>>> {}'.format(student.username)) print('author of math_course') print('>>> {}'.format(math_course.author.username)) print('edna published courses') for course in edna.published_courses: print('>>> {} - {}'.format(course.title, course.category.name)) ################### from models.chapter import ChapterModel from models.quiz import QuizModel from models.question import QuestionModel from models.answer import AnswerModel chapter1 = ChapterModel('adds', '2 + 2 = 4', 1, math_course.id) chapter2 = ChapterModel('subs', '2 - 2 = 0', 2, math_course.id) db.session.add_all([chapter1, chapter2]) db.session.commit() quiz1 = QuizModel('first grade', 1, math_course.id) quiz2 = QuizModel('second grade', 2, math_course.id) db.session.add(quiz1) db.session.add(quiz2) db.session.commit() question1 = QuestionModel('1 + 1?', 1, 2, quiz1.id) db.session.add(question1) db.session.commit() answer1 = AnswerModel('0', 1, question1.id) db.session.add(answer1) answer2 = AnswerModel('2', 2, question1.id) db.session.add(answer2) question2 = QuestionModel('3 - 1?', 2, 1, quiz1.id) db.session.add(question2) answer3 = AnswerModel('2', 1, question2.id) db.session.add(answer3) answer4 = AnswerModel('4', 2, question2.id) db.session.add(answer4) db.session.commit() print('::: test chapters and quizzes and questions and answers ::: ok') ################### print('chapters in math_course') for chapter in math_course.chapters: print('>>> {}'.format(chapter.title)) print('quizzes in math_course') for quiz in math_course.quizzes: print('>>> {}'.format(quiz.title)) print('questions in quiz1') for question in quiz1.questions: print('>>> {}'.format(question.question)) print('answers in question1') for answer in question1.answers: print('>>> {}'.format(answer.answer)) print('for question1 the good answer is number {}'.format( question1.good_answer)) current_question = question1.question good_answer = AnswerModel.query.filter_by( number=question1.good_answer).first() print('question: {} | response: {}'.format(current_question, good_answer.answer)) ################### from models.comment import CommentModel from models.rating import RatingModel comment1 = CommentModel('hay caramba', 'hay caramba', math_course.id, bart.id) comment2 = CommentModel('retention', 'retention', math_course.id, simour.id) comment3 = CommentModel('eat my short', 'eat my short', math_course.id, bart.id) db.session.add_all([comment1, comment2, comment3]) db.session.commit() rate1 = RatingModel(5, english_course.id, lisa.id) rate2 = RatingModel(3, english_course.id, millhouse.id) db.session.add_all([rate1, rate2]) db.session.commit() print('::: test comments and ratings ::: ok') ################### print('comments in math_course') for comment in math_course.comments: print('>>> {} by {}'.format(comment.title, comment.author.username)) print('ratings in english_course') for rate in english_course.ratings: print('>>> {}/5 by {}'.format(rate.rate, rate.author.username)) ################### from models.badge import BadgeModel from models.score import ScoreModel score = ScoreModel(2, 2, lisa.id, quiz1.id) db.session.add(score) db.session.commit() badge = BadgeModel('honor', math_course.id, lisa.id) db.session.add(badge) db.session.commit() print('::: test scores and badges ::: ok') ################### print('badges earned by lisa') for badge in lisa.badges: print('>>> {}'.format(badge.name)) print('scores in quiz1') for score in quiz1.scores: print('>>> {} by {}'.format(score.score, score.student.username))
def model(): return CommentModel()
def _validate_author(self, comment_id): comment = CommentModel.get_comment_with_id(comment_id) author_id = comment.get('user_id') validate_sender(author_id)
def _get_num_user_messages_today(self): return CommentModel.count_today_comments()