]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/video-comments.ts
f1edfb0ac280d461f5efff01f6811ec6fc7a2c81
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / video-comments.ts
1 import * as Bluebird from 'bluebird'
2 import { checkUrlsSameHost } from '../../helpers/activitypub'
3 import { sanitizeAndCheckVideoCommentObject } from '../../helpers/custom-validators/activitypub/video-comments'
4 import { logger } from '../../helpers/logger'
5 import { doJSONRequest } from '../../helpers/requests'
6 import { ACTIVITY_PUB, CRAWL_REQUEST_CONCURRENCY } from '../../initializers/constants'
7 import { VideoCommentModel } from '../../models/video/video-comment'
8 import { MCommentOwner, MCommentOwnerVideo, MVideoAccountLightBlacklistAllFiles } from '../../types/models/video'
9 import { getOrCreateActorAndServerAndModel } from './actor'
10 import { getOrCreateVideoAndAccountAndChannel } from './videos'
11
12 type ResolveThreadParams = {
13 url: string
14 comments?: MCommentOwner[]
15 isVideo?: boolean
16 commentCreated?: boolean
17 }
18 type ResolveThreadResult = Promise<{ video: MVideoAccountLightBlacklistAllFiles, comment: MCommentOwnerVideo, commentCreated: boolean }>
19
20 async function addVideoComments (commentUrls: string[]) {
21 return Bluebird.map(commentUrls, commentUrl => {
22 return resolveThread({ url: commentUrl, isVideo: false })
23 }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
24 }
25
26 async function resolveThread (params: ResolveThreadParams): ResolveThreadResult {
27 const { url, isVideo } = params
28 if (params.commentCreated === undefined) params.commentCreated = false
29 if (params.comments === undefined) params.comments = []
30
31 // If it is not a video, or if we don't know if it's a video
32 if (isVideo === false || isVideo === undefined) {
33 const result = await resolveCommentFromDB(params)
34 if (result) return result
35 }
36
37 try {
38 // If it is a video, or if we don't know if it's a video
39 if (isVideo === true || isVideo === undefined) {
40 // Keep await so we catch the exception
41 return await tryResolveThreadFromVideo(params)
42 }
43 } catch (err) {
44 logger.debug('Cannot resolve thread from video %s, maybe because it was not a video', url, { err })
45 }
46
47 return resolveRemoteParentComment(params)
48 }
49
50 export {
51 addVideoComments,
52 resolveThread
53 }
54
55 // ---------------------------------------------------------------------------
56
57 async function resolveCommentFromDB (params: ResolveThreadParams) {
58 const { url, comments, commentCreated } = params
59
60 const commentFromDatabase = await VideoCommentModel.loadByUrlAndPopulateReplyAndVideoUrlAndAccount(url)
61 if (commentFromDatabase) {
62 let parentComments = comments.concat([ commentFromDatabase ])
63
64 // Speed up things and resolve directly the thread
65 if (commentFromDatabase.InReplyToVideoComment) {
66 const data = await VideoCommentModel.listThreadParentComments(commentFromDatabase, undefined, 'DESC')
67
68 parentComments = parentComments.concat(data)
69 }
70
71 return resolveThread({
72 url: commentFromDatabase.Video.url,
73 comments: parentComments,
74 isVideo: true,
75 commentCreated
76 })
77 }
78
79 return undefined
80 }
81
82 async function tryResolveThreadFromVideo (params: ResolveThreadParams) {
83 const { url, comments, commentCreated } = params
84
85 // Maybe it's a reply to a video?
86 // If yes, it's done: we resolved all the thread
87 const syncParam = { likes: true, dislikes: true, shares: true, comments: false, thumbnail: true, refreshVideo: false }
88 const { video } = await getOrCreateVideoAndAccountAndChannel({ videoObject: url, syncParam })
89
90 if (video.isOwned() && !video.hasPrivacyForFederation()) {
91 throw new Error('Cannot resolve thread of video with privacy that is not compatible with federation')
92 }
93
94 let resultComment: MCommentOwnerVideo
95 if (comments.length !== 0) {
96 const firstReply = comments[comments.length - 1] as MCommentOwnerVideo
97 firstReply.inReplyToCommentId = null
98 firstReply.originCommentId = null
99 firstReply.videoId = video.id
100 firstReply.changed('updatedAt', true)
101 firstReply.Video = video
102
103 comments[comments.length - 1] = await firstReply.save()
104
105 for (let i = comments.length - 2; i >= 0; i--) {
106 const comment = comments[i] as MCommentOwnerVideo
107 comment.originCommentId = firstReply.id
108 comment.inReplyToCommentId = comments[i + 1].id
109 comment.videoId = video.id
110 comment.changed('updatedAt', true)
111 comment.Video = video
112
113 comments[i] = await comment.save()
114 }
115
116 resultComment = comments[0] as MCommentOwnerVideo
117 }
118
119 return { video, comment: resultComment, commentCreated }
120 }
121
122 async function resolveRemoteParentComment (params: ResolveThreadParams) {
123 const { url, comments } = params
124
125 if (comments.length > ACTIVITY_PUB.MAX_RECURSION_COMMENTS) {
126 throw new Error('Recursion limit reached when resolving a thread')
127 }
128
129 const { body } = await doJSONRequest<any>(url, { activityPub: true })
130
131 if (sanitizeAndCheckVideoCommentObject(body) === false) {
132 throw new Error(`Remote video comment JSON ${url} is not valid:` + JSON.stringify(body))
133 }
134
135 const actorUrl = body.attributedTo
136 if (!actorUrl && body.type !== 'Tombstone') throw new Error('Miss attributed to in comment')
137
138 if (actorUrl && checkUrlsSameHost(url, actorUrl) !== true) {
139 throw new Error(`Actor url ${actorUrl} has not the same host than the comment url ${url}`)
140 }
141
142 if (checkUrlsSameHost(body.id, url) !== true) {
143 throw new Error(`Comment url ${url} host is different from the AP object id ${body.id}`)
144 }
145
146 const actor = actorUrl
147 ? await getOrCreateActorAndServerAndModel(actorUrl, 'all')
148 : null
149
150 const comment = new VideoCommentModel({
151 url: body.id,
152 text: body.content ? body.content : '',
153 videoId: null,
154 accountId: actor ? actor.Account.id : null,
155 inReplyToCommentId: null,
156 originCommentId: null,
157 createdAt: new Date(body.published),
158 updatedAt: new Date(body.updated),
159 deletedAt: body.deleted ? new Date(body.deleted) : null
160 }) as MCommentOwner
161 comment.Account = actor ? actor.Account : null
162
163 return resolveThread({
164 url: body.inReplyTo,
165 comments: comments.concat([ comment ]),
166 commentCreated: true
167 })
168 }