PageRenderTime 28ms CodeModel.GetById 0ms RepoModel.GetById 1ms app.codeStats 0ms

/api/routes/Comments.py

https://gitlab.com/fdemian/Shelob
Python | 203 lines | 179 code | 22 blank | 2 comment | 5 complexity | c62508f2395e2b37788ceaa95e685902 MD5 | raw file
  1. import json
  2. from api.model.sessionHelper import get_session
  3. from api.model.models import Story, Comment, Notification, User
  4. from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
  5. from api.authentication.AuthenticatedHandler import AuthenticatedHandler
  6. from tornado.gen import coroutine
  7. import datetime
  8. class CommentsHandler(AuthenticatedHandler):
  9. def data_received(self, chunk):
  10. pass
  11. @coroutine
  12. def get(self):
  13. response = {"message": "This is not a valid method for this resource."}
  14. self.set_status(405, 'Error')
  15. self.set_header("Access-Control-Allow-Origin", "*")
  16. self.write(response)
  17. return
  18. # POST /stories/id/comments
  19. def post(self, story_id):
  20. request = self.request.body.decode("utf-8")
  21. json_request = json.loads(json.loads(request))
  22. author_name = json_request["name"]
  23. content = json.dumps(json_request["content"])
  24. avatar = json_request["avatar"]
  25. author_url = json_request["url"]
  26. is_anonymous = json_request['anonymous']
  27. author = None
  28. current_date = datetime.datetime.now()
  29. print(is_anonymous)
  30. try:
  31. session = self.settings['db']
  32. story = session.query(Story).filter(Story.id == story_id).one()
  33. comment = Comment()
  34. if is_anonymous:
  35. comment.author = author_name
  36. else:
  37. # TODO: validate user login.
  38. author = session.query(User).filter(User.username == author_name).one()
  39. story_author = session.query(User).filter(User.username == author.username).one()
  40. comment.author = author.username
  41. comment.content = content
  42. comment.avatar = ''
  43. comment.url = author_url
  44. comment.story_id = story.id
  45. comment.date = current_date
  46. session.add(comment)
  47. session.commit()
  48. json_comment = {
  49. 'id': comment.id,
  50. 'author': comment.author,
  51. 'content': comment.content,
  52. 'avatar': comment.avatar,
  53. 'url': comment.url,
  54. 'story': story.title,
  55. 'date': str(comment.date),
  56. 'storyId': story.id
  57. }
  58. # TODO: remove "author is not None". Its just there to temporarily fix notifications logic.
  59. if self.settings['notifications_enabled'] and author is not None:
  60. text = comment.author + " commented on " + story.title
  61. link = "/stories/" + str(story.id) + "/" + story.title
  62. notification_id = self.save_notification(session, author, "comment", text, link)
  63. self.notify_new_comment(text, link, notification_id, story_author.id)
  64. response = json_comment
  65. status = 200
  66. status_str = 'Ok'
  67. except NoResultFound:
  68. # User or story not found in database
  69. status = 500
  70. status_str = "Error"
  71. response = {'message': 'User or story does not exist.'}
  72. except MultipleResultsFound:
  73. status = 500
  74. status_str = "Error"
  75. response = {'message': 'Multiple results found.'}
  76. self.set_header("Content-Type", "application/jsonp;charset=UTF-8")
  77. self.set_header("Access-Control-Allow-Origin", "*")
  78. self.set_status(status, status_str)
  79. self.write(response)
  80. return
  81. @coroutine
  82. def put(self):
  83. response = {"message": "This is not a valid method for this resource."}
  84. self.set_status(405, 'Error')
  85. self.set_header("Access-Control-Allow-Origin", "*")
  86. self.write(response)
  87. return
  88. @coroutine
  89. def delete(self):
  90. response = {"message": "This is not a valid method for this resource."}
  91. self.set_status(405, 'Error')
  92. self.set_header("Access-Control-Allow-Origin", "*")
  93. self.write(response)
  94. return
  95. @coroutine
  96. def trace(self):
  97. response = {"message": "This is not a valid method for this resource."}
  98. self.set_status(405, 'Error')
  99. self.set_header("Access-Control-Allow-Origin", "*")
  100. self.write(json.dumps(response))
  101. return
  102. @coroutine
  103. def connect(self):
  104. response = {"message": "This is not a valid method for this resource."}
  105. self.set_status(405, 'Error')
  106. self.set_header("Access-Control-Allow-Origin", "*")
  107. self.write(response)
  108. return
  109. @coroutine
  110. def options(self, id):
  111. response = {}
  112. self.set_header("Content-Type", "test/plain;charset=UTF-8")
  113. self.set_header("Access-Control-Allow-Origin", "*")
  114. self.set_header("Access-Control-Allow-Headers", "Authorization")
  115. self.set_status(200, "Ok")
  116. self.write(response)
  117. return
  118. @coroutine
  119. def patch(self):
  120. response = {"message": "This is not a valid method for this resource."}
  121. self.set_status(405, 'Error')
  122. self.set_header("Access-Control-Allow-Origin", "*")
  123. self.write(response)
  124. return
  125. @coroutine
  126. def head(self):
  127. response = {"message": "This is not a valid method for this resource."}
  128. self.set_status(405, 'Error')
  129. self.set_header("Access-Control-Allow-Origin", "*")
  130. self.write(response)
  131. return
  132. def notify_new_comment(self, text, link, id, author_id):
  133. notifications_handler = self.settings['notification_handlers'][str(author_id)]
  134. # The story author is not online. There's no need to send a notification.
  135. if notifications_handler is None:
  136. return
  137. message = {
  138. 'id': id,
  139. 'type': "comment",
  140. 'text': text,
  141. 'link': link,
  142. 'read': False
  143. }
  144. notifications_handler.write_message(json.dumps(message))
  145. return
  146. @staticmethod
  147. def save_notification(session, user, notification_type, text, link):
  148. notification_to_save = Notification()
  149. notification_to_save.user_id = user.id
  150. notification_to_save.type = notification_type
  151. notification_to_save.text = text
  152. notification_to_save.link = link
  153. notification_to_save.read = False
  154. session.add(notification_to_save)
  155. session.commit()
  156. return notification_to_save.id