Upgrade sequelize
[oweals/peertube.git] / server / lib / activitypub / video-comments.ts
1 import { VideoCommentObject } from '../../../shared/models/activitypub/objects/video-comment-object'
2 import { sanitizeAndCheckVideoCommentObject } from '../../helpers/custom-validators/activitypub/video-comments'
3 import { logger } from '../../helpers/logger'
4 import { doRequest } from '../../helpers/requests'
5 import { ACTIVITY_PUB, CRAWL_REQUEST_CONCURRENCY } from '../../initializers/constants'
6 import { ActorModel } from '../../models/activitypub/actor'
7 import { VideoModel } from '../../models/video/video'
8 import { VideoCommentModel } from '../../models/video/video-comment'
9 import { getOrCreateActorAndServerAndModel } from './actor'
10 import { getOrCreateVideoAndAccountAndChannel } from './videos'
11 import * as Bluebird from 'bluebird'
12 import { checkUrlsSameHost } from '../../helpers/activitypub'
13
14 async function videoCommentActivityObjectToDBAttributes (video: VideoModel, actor: ActorModel, comment: VideoCommentObject) {
15   let originCommentId: number = null
16   let inReplyToCommentId: number = null
17
18   // If this is not a reply to the video (thread), create or get the parent comment
19   if (video.url !== comment.inReplyTo) {
20     const { comment: parent } = await addVideoComment(video, comment.inReplyTo)
21     if (!parent) {
22       logger.warn('Cannot fetch or get parent comment %s of comment %s.', comment.inReplyTo, comment.id)
23       return undefined
24     }
25
26     originCommentId = parent.originCommentId || parent.id
27     inReplyToCommentId = parent.id
28   }
29
30   return {
31     url: comment.id,
32     text: comment.content,
33     videoId: video.id,
34     accountId: actor.Account.id,
35     inReplyToCommentId,
36     originCommentId,
37     createdAt: new Date(comment.published)
38   }
39 }
40
41 async function addVideoComments (commentUrls: string[], instance: VideoModel) {
42   return Bluebird.map(commentUrls, commentUrl => {
43     return addVideoComment(instance, commentUrl)
44   }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
45 }
46
47 async function addVideoComment (videoInstance: VideoModel, commentUrl: string) {
48   logger.info('Fetching remote video comment %s.', commentUrl)
49
50   const { body } = await doRequest({
51     uri: commentUrl,
52     json: true,
53     activityPub: true
54   })
55
56   if (sanitizeAndCheckVideoCommentObject(body) === false) {
57     logger.debug('Remote video comment JSON is not valid.', { body })
58     return { created: false }
59   }
60
61   const actorUrl = body.attributedTo
62   if (!actorUrl) return { created: false }
63
64   if (checkUrlsSameHost(commentUrl, actorUrl) !== true) {
65     throw new Error(`Actor url ${actorUrl} has not the same host than the comment url ${commentUrl}`)
66   }
67
68   if (checkUrlsSameHost(body.id, commentUrl) !== true) {
69     throw new Error(`Comment url ${commentUrl} host is different from the AP object id ${body.id}`)
70   }
71
72   const actor = await getOrCreateActorAndServerAndModel(actorUrl, 'all')
73   const entry = await videoCommentActivityObjectToDBAttributes(videoInstance, actor, body)
74   if (!entry) return { created: false }
75
76   const [ comment, created ] = await VideoCommentModel.upsert<VideoCommentModel>(entry, { returning: true })
77   comment.Account = actor.Account
78   comment.Video = videoInstance
79
80   return { comment, created }
81 }
82
83 async function resolveThread (url: string, comments: VideoCommentModel[] = []) {
84    // Already have this comment?
85   const commentFromDatabase = await VideoCommentModel.loadByUrlAndPopulateReplyAndVideo(url)
86   if (commentFromDatabase) {
87     let parentComments = comments.concat([ commentFromDatabase ])
88
89     // Speed up things and resolve directly the thread
90     if (commentFromDatabase.InReplyToVideoComment) {
91       const data = await VideoCommentModel.listThreadParentComments(commentFromDatabase, undefined, 'DESC')
92
93       parentComments = parentComments.concat(data)
94     }
95
96     return resolveThread(commentFromDatabase.Video.url, parentComments)
97   }
98
99   try {
100     // Maybe it's a reply to a video?
101     // If yes, it's done: we resolved all the thread
102     const { video } = await getOrCreateVideoAndAccountAndChannel({ videoObject: url })
103
104     if (comments.length !== 0) {
105       const firstReply = comments[ comments.length - 1 ]
106       firstReply.inReplyToCommentId = null
107       firstReply.originCommentId = null
108       firstReply.videoId = video.id
109       comments[comments.length - 1] = await firstReply.save()
110
111       for (let i = comments.length - 2; i >= 0; i--) {
112         const comment = comments[ i ]
113         comment.originCommentId = firstReply.id
114         comment.inReplyToCommentId = comments[ i + 1 ].id
115         comment.videoId = video.id
116
117         comments[i] = await comment.save()
118       }
119     }
120
121     return { video, parents: comments }
122   } catch (err) {
123     logger.debug('Cannot get or create account and video and channel for reply %s, fetch comment', url, { err })
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({
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) throw new Error('Miss attributed to in comment')
141
142     if (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 = await getOrCreateActorAndServerAndModel(actorUrl)
151     const comment = new VideoCommentModel({
152       url: body.id,
153       text: body.content,
154       videoId: null,
155       accountId: actor.Account.id,
156       inReplyToCommentId: null,
157       originCommentId: null,
158       createdAt: new Date(body.published),
159       updatedAt: new Date(body.updated)
160     })
161
162     return resolveThread(body.inReplyTo, comments.concat([ comment ]))
163   }
164
165 }
166
167 export {
168   videoCommentActivityObjectToDBAttributes,
169   addVideoComments,
170   addVideoComment,
171   resolveThread
172 }