]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/video-comments.ts
Merge remote-tracking branch 'weblate/develop' into develop
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / video-comments.ts
1 import { sanitizeAndCheckVideoCommentObject } from '../../helpers/custom-validators/activitypub/video-comments'
2 import { logger } from '../../helpers/logger'
3 import { doRequest } from '../../helpers/requests'
4 import { ACTIVITY_PUB, CRAWL_REQUEST_CONCURRENCY } from '../../initializers/constants'
5 import { VideoCommentModel } from '../../models/video/video-comment'
6 import { getOrCreateActorAndServerAndModel } from './actor'
7 import { getOrCreateVideoAndAccountAndChannel } from './videos'
8 import * as Bluebird from 'bluebird'
9 import { checkUrlsSameHost } from '../../helpers/activitypub'
10 import { MCommentOwner, MCommentOwnerVideo, MVideoAccountLightBlacklistAllFiles } from '../../types/models/video'
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 get or create account and video and channel for reply %s, fetch comment', url, { err })
45 }
46
47 return resolveParentComment(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 resolveParentComment (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 doRequest<any>({
130 uri: url,
131 json: true,
132 activityPub: true
133 })
134
135 if (sanitizeAndCheckVideoCommentObject(body) === false) {
136 throw new Error('Remote video comment JSON is not valid:' + JSON.stringify(body))
137 }
138
139 const actorUrl = body.attributedTo
140 if (!actorUrl && body.type !== 'Tombstone') throw new Error('Miss attributed to in comment')
141
142 if (actorUrl && checkUrlsSameHost(url, actorUrl) !== true) {
143 throw new Error(`Actor url ${actorUrl} has not the same host than the comment url ${url}`)
144 }
145
146 if (checkUrlsSameHost(body.id, url) !== true) {
147 throw new Error(`Comment url ${url} host is different from the AP object id ${body.id}`)
148 }
149
150 const actor = actorUrl
151 ? await getOrCreateActorAndServerAndModel(actorUrl, 'all')
152 : null
153
154 const comment = new VideoCommentModel({
155 url: body.id,
156 text: body.content ? body.content : '',
157 videoId: null,
158 accountId: actor ? actor.Account.id : null,
159 inReplyToCommentId: null,
160 originCommentId: null,
161 createdAt: new Date(body.published),
162 updatedAt: new Date(body.updated),
163 deletedAt: body.deleted ? new Date(body.deleted) : null
164 }) as MCommentOwner
165 comment.Account = actor ? actor.Account : null
166
167 return resolveThread({
168 url: body.inReplyTo,
169 comments: comments.concat([ comment ]),
170 commentCreated: true
171 })
172 }