1 import * as Sequelize from 'sequelize'
2 import { ResultList } from '../../shared/models'
3 import { VideoCommentThread } from '../../shared/models/videos/video-comment.model'
4 import { VideoModel } from '../models/video/video'
5 import { VideoCommentModel } from '../models/video/video-comment'
6 import { getVideoCommentActivityPubUrl } from './activitypub'
8 async function createVideoComment (obj: {
10 inReplyToComment: number,
13 }, t: Sequelize.Transaction) {
14 let originCommentId: number = null
15 if (obj.inReplyToComment) {
16 const repliedComment = await VideoCommentModel.loadById(obj.inReplyToComment)
17 if (!repliedComment) throw new Error('Unknown replied comment.')
19 originCommentId = repliedComment.originCommentId || repliedComment.id
22 const comment = await VideoCommentModel.create({
25 inReplyToComment: obj.inReplyToComment,
26 videoId: obj.video.id,
28 }, { transaction: t })
30 comment.set('url', getVideoCommentActivityPubUrl(obj.video, comment))
32 return comment.save({ transaction: t })
35 function buildFormattedCommentTree (resultList: ResultList<VideoCommentModel>): VideoCommentThread {
36 // Comments are sorted by id ASC
37 const comments = resultList.data
39 const comment = comments.shift()
40 const thread: VideoCommentThread = {
41 comment: comment.toFormattedJSON(),
48 while (comments.length !== 0) {
49 const childComment = comments.shift()
51 const childCommentThread: VideoCommentThread = {
52 comment: childComment.toFormattedJSON(),
56 const parentCommentThread = idx[childComment.inReplyToCommentId]
57 if (!parentCommentThread) {
58 const msg = `Cannot format video thread tree, parent ${childComment.inReplyToCommentId} not found for child ${childComment.id}`
62 parentCommentThread.children.push(childCommentThread)
63 idx[childComment.id] = childCommentThread
69 // ---------------------------------------------------------------------------
73 buildFormattedCommentTree