Merge branch 'release/v1.0.0' into develop
[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'
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
13 async function videoCommentActivityObjectToDBAttributes (video: VideoModel, actor: ActorModel, comment: VideoCommentObject) {
14   let originCommentId: number = null
15   let inReplyToCommentId: number = null
16
17   // If this is not a reply to the video (thread), create or get the parent comment
18   if (video.url !== comment.inReplyTo) {
19     const { comment: parent } = await addVideoComment(video, comment.inReplyTo)
20     if (!parent) {
21       logger.warn('Cannot fetch or get parent comment %s of comment %s.', comment.inReplyTo, comment.id)
22       return undefined
23     }
24
25     originCommentId = parent.originCommentId || parent.id
26     inReplyToCommentId = parent.id
27   }
28
29   return {
30     url: comment.id,
31     text: comment.content,
32     videoId: video.id,
33     accountId: actor.Account.id,
34     inReplyToCommentId,
35     originCommentId,
36     createdAt: new Date(comment.published),
37     updatedAt: new Date(comment.updated)
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   const actor = await getOrCreateActorAndServerAndModel(actorUrl)
65   const entry = await videoCommentActivityObjectToDBAttributes(videoInstance, actor, body)
66   if (!entry) return { created: false }
67
68   const [ comment, created ] = await VideoCommentModel.findOrCreate({
69     where: {
70       url: body.id
71     },
72     defaults: entry
73   })
74
75   return { comment, created }
76 }
77
78 async function resolveThread (url: string, comments: VideoCommentModel[] = []) {
79    // Already have this comment?
80   const commentFromDatabase = await VideoCommentModel.loadByUrlAndPopulateReplyAndVideo(url)
81   if (commentFromDatabase) {
82     let parentComments = comments.concat([ commentFromDatabase ])
83
84     // Speed up things and resolve directly the thread
85     if (commentFromDatabase.InReplyToVideoComment) {
86       const data = await VideoCommentModel.listThreadParentComments(commentFromDatabase, undefined, 'DESC')
87
88       parentComments = parentComments.concat(data)
89     }
90
91     return resolveThread(commentFromDatabase.Video.url, parentComments)
92   }
93
94   try {
95     // Maybe it's a reply to a video?
96     // If yes, it's done: we resolved all the thread
97     const { video } = await getOrCreateVideoAndAccountAndChannel({ videoObject: url })
98
99     if (comments.length !== 0) {
100       const firstReply = comments[ comments.length - 1 ]
101       firstReply.inReplyToCommentId = null
102       firstReply.originCommentId = null
103       firstReply.videoId = video.id
104       comments[comments.length - 1] = await firstReply.save()
105
106       for (let i = comments.length - 2; i >= 0; i--) {
107         const comment = comments[ i ]
108         comment.originCommentId = firstReply.id
109         comment.inReplyToCommentId = comments[ i + 1 ].id
110         comment.videoId = video.id
111
112         comments[i] = await comment.save()
113       }
114     }
115
116     return { video, parents: comments }
117   } catch (err) {
118     logger.debug('Cannot get or create account and video and channel for reply %s, fetch comment', url, { err })
119
120     if (comments.length > ACTIVITY_PUB.MAX_RECURSION_COMMENTS) {
121       throw new Error('Recursion limit reached when resolving a thread')
122     }
123
124     const { body } = await doRequest({
125       uri: url,
126       json: true,
127       activityPub: true
128     })
129
130     if (sanitizeAndCheckVideoCommentObject(body) === false) {
131       throw new Error('Remote video comment JSON is not valid :' + JSON.stringify(body))
132     }
133
134     const actorUrl = body.attributedTo
135     if (!actorUrl) throw new Error('Miss attributed to in comment')
136
137     const actor = await getOrCreateActorAndServerAndModel(actorUrl)
138     const comment = new VideoCommentModel({
139       url: body.id,
140       text: body.content,
141       videoId: null,
142       accountId: actor.Account.id,
143       inReplyToCommentId: null,
144       originCommentId: null,
145       createdAt: new Date(body.published),
146       updatedAt: new Date(body.updated)
147     })
148
149     return resolveThread(body.inReplyTo, comments.concat([ comment ]))
150   }
151
152 }
153
154 export {
155   videoCommentActivityObjectToDBAttributes,
156   addVideoComments,
157   addVideoComment,
158   resolveThread
159 }