PeerTube/server/lib/video-comment.ts

77 lines
2.2 KiB
TypeScript
Raw Normal View History

2017-12-22 03:50:07 -06:00
import * as Sequelize from 'sequelize'
import { ResultList } from '../../shared/models'
2017-12-22 05:10:40 -06:00
import { VideoCommentThreadTree } from '../../shared/models/videos/video-comment.model'
2017-12-22 03:50:07 -06:00
import { VideoModel } from '../models/video/video'
import { VideoCommentModel } from '../models/video/video-comment'
import { getVideoCommentActivityPubUrl } from './activitypub'
async function createVideoComment (obj: {
text: string,
2017-12-22 05:10:40 -06:00
inReplyToCommentId: number,
2017-12-22 03:50:07 -06:00
video: VideoModel
2017-12-22 05:10:40 -06:00
accountId: number
2017-12-22 03:50:07 -06:00
}, t: Sequelize.Transaction) {
let originCommentId: number = null
2017-12-22 05:10:40 -06:00
if (obj.inReplyToCommentId) {
const repliedComment = await VideoCommentModel.loadById(obj.inReplyToCommentId)
2017-12-22 03:50:07 -06:00
if (!repliedComment) throw new Error('Unknown replied comment.')
originCommentId = repliedComment.originCommentId || repliedComment.id
}
const comment = await VideoCommentModel.create({
text: obj.text,
originCommentId,
2017-12-22 05:10:40 -06:00
inReplyToCommentId: obj.inReplyToCommentId,
2017-12-22 03:50:07 -06:00
videoId: obj.video.id,
2017-12-22 05:10:40 -06:00
accountId: obj.accountId,
url: 'fake url'
}, { transaction: t, validate: false })
2017-12-22 03:50:07 -06:00
comment.set('url', getVideoCommentActivityPubUrl(obj.video, comment))
return comment.save({ transaction: t })
}
2017-12-22 05:10:40 -06:00
function buildFormattedCommentTree (resultList: ResultList<VideoCommentModel>): VideoCommentThreadTree {
2017-12-22 03:50:07 -06:00
// Comments are sorted by id ASC
const comments = resultList.data
const comment = comments.shift()
2017-12-22 05:10:40 -06:00
const thread: VideoCommentThreadTree = {
2017-12-22 03:50:07 -06:00
comment: comment.toFormattedJSON(),
children: []
}
const idx = {
[comment.id]: thread
}
while (comments.length !== 0) {
const childComment = comments.shift()
2017-12-22 05:10:40 -06:00
const childCommentThread: VideoCommentThreadTree = {
2017-12-22 03:50:07 -06:00
comment: childComment.toFormattedJSON(),
children: []
}
const parentCommentThread = idx[childComment.inReplyToCommentId]
if (!parentCommentThread) {
const msg = `Cannot format video thread tree, parent ${childComment.inReplyToCommentId} not found for child ${childComment.id}`
throw new Error(msg)
}
parentCommentThread.children.push(childCommentThread)
idx[childComment.id] = childCommentThread
}
return thread
}
// ---------------------------------------------------------------------------
export {
createVideoComment,
buildFormattedCommentTree
}