1 import { map } from 'bluebird'
2 import { sanitizeAndCheckVideoCommentObject } from '../../helpers/custom-validators/activitypub/video-comments'
3 import { logger } from '../../helpers/logger'
4 import { doJSONRequest } from '../../helpers/requests'
5 import { ACTIVITY_PUB, CRAWL_REQUEST_CONCURRENCY } from '../../initializers/constants'
6 import { VideoCommentModel } from '../../models/video/video-comment'
7 import { MComment, MCommentOwner, MCommentOwnerVideo, MVideoAccountLightBlacklistAllFiles } from '../../types/models/video'
8 import { isRemoteVideoCommentAccepted } from '../moderation'
9 import { Hooks } from '../plugins/hooks'
10 import { getOrCreateAPActor } from './actors'
11 import { checkUrlsSameHost } from './url'
12 import { getOrCreateAPVideo } from './videos'
14 type ResolveThreadParams = {
16 comments?: MCommentOwner[]
18 commentCreated?: boolean
20 type ResolveThreadResult = Promise<{ video: MVideoAccountLightBlacklistAllFiles, comment: MCommentOwnerVideo, commentCreated: boolean }>
22 async function addVideoComments (commentUrls: string[]) {
23 return map(commentUrls, async commentUrl => {
25 await resolveThread({ url: commentUrl, isVideo: false })
27 logger.warn('Cannot resolve thread %s.', commentUrl, { err })
29 }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
32 async function resolveThread (params: ResolveThreadParams): ResolveThreadResult {
33 const { url, isVideo } = params
35 if (params.commentCreated === undefined) params.commentCreated = false
36 if (params.comments === undefined) params.comments = []
38 // If it is not a video, or if we don't know if it's a video, try to get the thread from DB
39 if (isVideo === false || isVideo === undefined) {
40 const result = await resolveCommentFromDB(params)
41 if (result) return result
45 // If it is a video, or if we don't know if it's a video
46 if (isVideo === true || isVideo === undefined) {
47 // Keep await so we catch the exception
48 return await tryToResolveThreadFromVideo(params)
51 logger.debug('Cannot resolve thread from video %s, maybe because it was not a video', url, { err })
54 return resolveRemoteParentComment(params)
62 // ---------------------------------------------------------------------------
64 async function resolveCommentFromDB (params: ResolveThreadParams) {
65 const { url, comments, commentCreated } = params
67 const commentFromDatabase = await VideoCommentModel.loadByUrlAndPopulateReplyAndVideoUrlAndAccount(url)
68 if (!commentFromDatabase) return undefined
70 let parentComments = comments.concat([ commentFromDatabase ])
72 // Speed up things and resolve directly the thread
73 if (commentFromDatabase.InReplyToVideoComment) {
74 const data = await VideoCommentModel.listThreadParentComments(commentFromDatabase, undefined, 'DESC')
76 parentComments = parentComments.concat(data)
79 return resolveThread({
80 url: commentFromDatabase.Video.url,
81 comments: parentComments,
87 async function tryToResolveThreadFromVideo (params: ResolveThreadParams) {
88 const { url, comments, commentCreated } = params
90 // Maybe it's a reply to a video?
91 // If yes, it's done: we resolved all the thread
92 const syncParam = { rates: true, shares: true, comments: false, thumbnail: true, refreshVideo: false }
93 const { video } = await getOrCreateAPVideo({ videoObject: url, syncParam })
95 if (video.isOwned() && !video.hasPrivacyForFederation()) {
96 throw new Error('Cannot resolve thread of video with privacy that is not compatible with federation')
99 let resultComment: MCommentOwnerVideo
100 if (comments.length !== 0) {
101 const firstReply = comments[comments.length - 1] as MCommentOwnerVideo
102 firstReply.inReplyToCommentId = null
103 firstReply.originCommentId = null
104 firstReply.videoId = video.id
105 firstReply.changed('updatedAt', true)
106 firstReply.Video = video
108 if (await isRemoteCommentAccepted(firstReply) !== true) {
112 comments[comments.length - 1] = await firstReply.save()
114 for (let i = comments.length - 2; i >= 0; i--) {
115 const comment = comments[i] as MCommentOwnerVideo
116 comment.originCommentId = firstReply.id
117 comment.inReplyToCommentId = comments[i + 1].id
118 comment.videoId = video.id
119 comment.changed('updatedAt', true)
120 comment.Video = video
122 if (await isRemoteCommentAccepted(comment) !== true) {
126 comments[i] = await comment.save()
129 resultComment = comments[0] as MCommentOwnerVideo
132 return { video, comment: resultComment, commentCreated }
135 async function resolveRemoteParentComment (params: ResolveThreadParams) {
136 const { url, comments } = params
138 if (comments.length > ACTIVITY_PUB.MAX_RECURSION_COMMENTS) {
139 throw new Error('Recursion limit reached when resolving a thread')
142 const { body } = await doJSONRequest<any>(url, { activityPub: true })
144 if (sanitizeAndCheckVideoCommentObject(body) === false) {
145 throw new Error(`Remote video comment JSON ${url} is not valid:` + JSON.stringify(body))
148 const actorUrl = body.attributedTo
149 if (!actorUrl && body.type !== 'Tombstone') throw new Error('Miss attributed to in comment')
151 if (actorUrl && checkUrlsSameHost(url, actorUrl) !== true) {
152 throw new Error(`Actor url ${actorUrl} has not the same host than the comment url ${url}`)
155 if (checkUrlsSameHost(body.id, url) !== true) {
156 throw new Error(`Comment url ${url} host is different from the AP object id ${body.id}`)
159 const actor = actorUrl
160 ? await getOrCreateAPActor(actorUrl, 'all')
163 const comment = new VideoCommentModel({
165 text: body.content ? body.content : '',
167 accountId: actor ? actor.Account.id : null,
168 inReplyToCommentId: null,
169 originCommentId: null,
170 createdAt: new Date(body.published),
171 updatedAt: new Date(body.updated),
172 deletedAt: body.deleted ? new Date(body.deleted) : null
174 comment.Account = actor ? actor.Account : null
176 return resolveThread({
178 comments: comments.concat([ comment ]),
183 async function isRemoteCommentAccepted (comment: MComment) {
185 if (comment.id) return true
187 const acceptParameters = {
191 const acceptedResult = await Hooks.wrapFun(
192 isRemoteVideoCommentAccepted,
194 'filter:activity-pub.remote-video-comment.create.accept.result'
197 if (!acceptedResult || acceptedResult.accepted !== true) {
198 logger.info('Refused to create a remote comment.', { acceptedResult, acceptParameters })