video-comment.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import * as Sequelize from 'sequelize'
  2. import { ResultList } from '../../shared/models'
  3. import { VideoCommentThreadTree } from '../../shared/models/videos/video-comment.model'
  4. import { AccountModel } from '../models/account/account'
  5. import { VideoModel } from '../models/video/video'
  6. import { VideoCommentModel } from '../models/video/video-comment'
  7. import { getVideoCommentActivityPubUrl } from './activitypub'
  8. import { sendCreateVideoComment } from './activitypub/send'
  9. async function createVideoComment (obj: {
  10. text: string,
  11. inReplyToComment: VideoCommentModel | null,
  12. video: VideoModel
  13. account: AccountModel
  14. }, t: Sequelize.Transaction) {
  15. let originCommentId: number | null = null
  16. let inReplyToCommentId: number | null = null
  17. if (obj.inReplyToComment && obj.inReplyToComment !== null) {
  18. originCommentId = obj.inReplyToComment.originCommentId || obj.inReplyToComment.id
  19. inReplyToCommentId = obj.inReplyToComment.id
  20. }
  21. const comment = await VideoCommentModel.create({
  22. text: obj.text,
  23. originCommentId,
  24. inReplyToCommentId,
  25. videoId: obj.video.id,
  26. accountId: obj.account.id,
  27. url: 'fake url'
  28. }, { transaction: t, validate: false } as any) // FIXME: sequelize typings
  29. comment.set('url', getVideoCommentActivityPubUrl(obj.video, comment))
  30. const savedComment = await comment.save({ transaction: t })
  31. savedComment.InReplyToVideoComment = obj.inReplyToComment
  32. savedComment.Video = obj.video
  33. savedComment.Account = obj.account
  34. await sendCreateVideoComment(savedComment, t)
  35. return savedComment
  36. }
  37. function buildFormattedCommentTree (resultList: ResultList<VideoCommentModel>): VideoCommentThreadTree {
  38. // Comments are sorted by id ASC
  39. const comments = resultList.data
  40. const comment = comments.shift()
  41. const thread: VideoCommentThreadTree = {
  42. comment: comment.toFormattedJSON(),
  43. children: []
  44. }
  45. const idx = {
  46. [comment.id]: thread
  47. }
  48. while (comments.length !== 0) {
  49. const childComment = comments.shift()
  50. const childCommentThread: VideoCommentThreadTree = {
  51. comment: childComment.toFormattedJSON(),
  52. children: []
  53. }
  54. const parentCommentThread = idx[childComment.inReplyToCommentId]
  55. // Maybe the parent comment was blocked by the admin/user
  56. if (!parentCommentThread) continue
  57. parentCommentThread.children.push(childCommentThread)
  58. idx[childComment.id] = childCommentThread
  59. }
  60. return thread
  61. }
  62. // ---------------------------------------------------------------------------
  63. export {
  64. createVideoComment,
  65. buildFormattedCommentTree
  66. }