]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/models/video/video-comment.ts
Remove comment federation by video owner
[github/Chocobozzz/PeerTube.git] / server / models / video / video-comment.ts
... / ...
CommitLineData
1import {
2 AllowNull,
3 BeforeDestroy,
4 BelongsTo,
5 Column,
6 CreatedAt,
7 DataType,
8 ForeignKey,
9 Is,
10 Model,
11 Scopes,
12 Table,
13 UpdatedAt
14} from 'sequelize-typescript'
15import { ActivityTagObject } from '../../../shared/models/activitypub/objects/common-objects'
16import { VideoCommentObject } from '../../../shared/models/activitypub/objects/video-comment-object'
17import { VideoComment } from '../../../shared/models/videos/video-comment.model'
18import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
19import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
20import { sendDeleteVideoComment } from '../../lib/activitypub/send'
21import { AccountModel } from '../account/account'
22import { ActorModel } from '../activitypub/actor'
23import { AvatarModel } from '../avatar/avatar'
24import { ServerModel } from '../server/server'
25import { buildBlockedAccountSQL, buildLocalAccountIdsIn, getSort, throwIfNotValid } from '../utils'
26import { VideoModel } from './video'
27import { VideoChannelModel } from './video-channel'
28import { getServerActor } from '../../helpers/utils'
29import { UserModel } from '../account/user'
30import { actorNameAlphabet } from '../../helpers/custom-validators/activitypub/actor'
31import { regexpCapture } from '../../helpers/regexp'
32import { uniq } from 'lodash'
33import { FindOptions, literal, Op, Order, ScopeOptions, Sequelize, Transaction } from 'sequelize'
34
35enum ScopeNames {
36 WITH_ACCOUNT = 'WITH_ACCOUNT',
37 WITH_IN_REPLY_TO = 'WITH_IN_REPLY_TO',
38 WITH_VIDEO = 'WITH_VIDEO',
39 ATTRIBUTES_FOR_API = 'ATTRIBUTES_FOR_API'
40}
41
42@Scopes(() => ({
43 [ScopeNames.ATTRIBUTES_FOR_API]: (serverAccountId: number, userAccountId?: number) => {
44 return {
45 attributes: {
46 include: [
47 [
48 Sequelize.literal(
49 '(' +
50 'WITH "blocklist" AS (' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')' +
51 'SELECT COUNT("replies"."id") - (' +
52 'SELECT COUNT("replies"."id") ' +
53 'FROM "videoComment" AS "replies" ' +
54 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
55 'AND "accountId" IN (SELECT "id" FROM "blocklist")' +
56 ')' +
57 'FROM "videoComment" AS "replies" ' +
58 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
59 'AND "accountId" NOT IN (SELECT "id" FROM "blocklist")' +
60 ')'
61 ),
62 'totalReplies'
63 ]
64 ]
65 }
66 } as FindOptions
67 },
68 [ScopeNames.WITH_ACCOUNT]: {
69 include: [
70 {
71 model: AccountModel,
72 include: [
73 {
74 model: ActorModel,
75 include: [
76 {
77 model: ServerModel,
78 required: false
79 },
80 {
81 model: AvatarModel,
82 required: false
83 }
84 ]
85 }
86 ]
87 }
88 ]
89 },
90 [ScopeNames.WITH_IN_REPLY_TO]: {
91 include: [
92 {
93 model: VideoCommentModel,
94 as: 'InReplyToVideoComment'
95 }
96 ]
97 },
98 [ScopeNames.WITH_VIDEO]: {
99 include: [
100 {
101 model: VideoModel,
102 required: true,
103 include: [
104 {
105 model: VideoChannelModel.unscoped(),
106 required: true,
107 include: [
108 {
109 model: ActorModel,
110 required: true
111 },
112 {
113 model: AccountModel,
114 required: true,
115 include: [
116 {
117 model: ActorModel,
118 required: true
119 }
120 ]
121 }
122 ]
123 }
124 ]
125 }
126 ]
127 }
128}))
129@Table({
130 tableName: 'videoComment',
131 indexes: [
132 {
133 fields: [ 'videoId' ]
134 },
135 {
136 fields: [ 'videoId', 'originCommentId' ]
137 },
138 {
139 fields: [ 'url' ],
140 unique: true
141 },
142 {
143 fields: [ 'accountId' ]
144 }
145 ]
146})
147export class VideoCommentModel extends Model<VideoCommentModel> {
148 @CreatedAt
149 createdAt: Date
150
151 @UpdatedAt
152 updatedAt: Date
153
154 @AllowNull(false)
155 @Is('VideoCommentUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
156 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
157 url: string
158
159 @AllowNull(false)
160 @Column(DataType.TEXT)
161 text: string
162
163 @ForeignKey(() => VideoCommentModel)
164 @Column
165 originCommentId: number
166
167 @BelongsTo(() => VideoCommentModel, {
168 foreignKey: {
169 name: 'originCommentId',
170 allowNull: true
171 },
172 as: 'OriginVideoComment',
173 onDelete: 'CASCADE'
174 })
175 OriginVideoComment: VideoCommentModel
176
177 @ForeignKey(() => VideoCommentModel)
178 @Column
179 inReplyToCommentId: number
180
181 @BelongsTo(() => VideoCommentModel, {
182 foreignKey: {
183 name: 'inReplyToCommentId',
184 allowNull: true
185 },
186 as: 'InReplyToVideoComment',
187 onDelete: 'CASCADE'
188 })
189 InReplyToVideoComment: VideoCommentModel | null
190
191 @ForeignKey(() => VideoModel)
192 @Column
193 videoId: number
194
195 @BelongsTo(() => VideoModel, {
196 foreignKey: {
197 allowNull: false
198 },
199 onDelete: 'CASCADE'
200 })
201 Video: VideoModel
202
203 @ForeignKey(() => AccountModel)
204 @Column
205 accountId: number
206
207 @BelongsTo(() => AccountModel, {
208 foreignKey: {
209 allowNull: false
210 },
211 onDelete: 'CASCADE'
212 })
213 Account: AccountModel
214
215 static loadById (id: number, t?: Transaction) {
216 const query: FindOptions = {
217 where: {
218 id
219 }
220 }
221
222 if (t !== undefined) query.transaction = t
223
224 return VideoCommentModel.findOne(query)
225 }
226
227 static loadByIdAndPopulateVideoAndAccountAndReply (id: number, t?: Transaction) {
228 const query: FindOptions = {
229 where: {
230 id
231 }
232 }
233
234 if (t !== undefined) query.transaction = t
235
236 return VideoCommentModel
237 .scope([ ScopeNames.WITH_VIDEO, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_IN_REPLY_TO ])
238 .findOne(query)
239 }
240
241 static loadByUrlAndPopulateAccountAndVideo (url: string, t?: Transaction) {
242 const query: FindOptions = {
243 where: {
244 url
245 }
246 }
247
248 if (t !== undefined) query.transaction = t
249
250 return VideoCommentModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEO ]).findOne(query)
251 }
252
253 static loadByUrlAndPopulateReplyAndVideoUrlAndAccount (url: string, t?: Transaction) {
254 const query: FindOptions = {
255 where: {
256 url
257 },
258 include: [
259 {
260 attributes: [ 'id', 'url' ],
261 model: VideoModel.unscoped()
262 }
263 ]
264 }
265
266 if (t !== undefined) query.transaction = t
267
268 return VideoCommentModel.scope([ ScopeNames.WITH_IN_REPLY_TO, ScopeNames.WITH_ACCOUNT ]).findOne(query)
269 }
270
271 static async listThreadsForApi (parameters: {
272 videoId: number,
273 start: number,
274 count: number,
275 sort: string,
276 user?: UserModel
277 }) {
278 const { videoId, start, count, sort, user } = parameters
279
280 const serverActor = await getServerActor()
281 const serverAccountId = serverActor.Account.id
282 const userAccountId = user ? user.Account.id : undefined
283
284 const query = {
285 offset: start,
286 limit: count,
287 order: getSort(sort),
288 where: {
289 videoId,
290 inReplyToCommentId: null,
291 accountId: {
292 [Op.notIn]: Sequelize.literal(
293 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
294 )
295 }
296 }
297 }
298
299 const scopes: (string | ScopeOptions)[] = [
300 ScopeNames.WITH_ACCOUNT,
301 {
302 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
303 }
304 ]
305
306 return VideoCommentModel
307 .scope(scopes)
308 .findAndCountAll(query)
309 .then(({ rows, count }) => {
310 return { total: count, data: rows }
311 })
312 }
313
314 static async listThreadCommentsForApi (parameters: {
315 videoId: number,
316 threadId: number,
317 user?: UserModel
318 }) {
319 const { videoId, threadId, user } = parameters
320
321 const serverActor = await getServerActor()
322 const serverAccountId = serverActor.Account.id
323 const userAccountId = user ? user.Account.id : undefined
324
325 const query = {
326 order: [ [ 'createdAt', 'ASC' ], [ 'updatedAt', 'ASC' ] ] as Order,
327 where: {
328 videoId,
329 [ Op.or ]: [
330 { id: threadId },
331 { originCommentId: threadId }
332 ],
333 accountId: {
334 [Op.notIn]: Sequelize.literal(
335 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
336 )
337 }
338 }
339 }
340
341 const scopes: any[] = [
342 ScopeNames.WITH_ACCOUNT,
343 {
344 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
345 }
346 ]
347
348 return VideoCommentModel
349 .scope(scopes)
350 .findAndCountAll(query)
351 .then(({ rows, count }) => {
352 return { total: count, data: rows }
353 })
354 }
355
356 static listThreadParentComments (comment: VideoCommentModel, t: Transaction, order: 'ASC' | 'DESC' = 'ASC') {
357 const query = {
358 order: [ [ 'createdAt', order ] ] as Order,
359 where: {
360 id: {
361 [ Op.in ]: Sequelize.literal('(' +
362 'WITH RECURSIVE children (id, "inReplyToCommentId") AS ( ' +
363 `SELECT id, "inReplyToCommentId" FROM "videoComment" WHERE id = ${comment.id} ` +
364 'UNION ' +
365 'SELECT "parent"."id", "parent"."inReplyToCommentId" FROM "videoComment" "parent" ' +
366 'INNER JOIN "children" ON "children"."inReplyToCommentId" = "parent"."id"' +
367 ') ' +
368 'SELECT id FROM children' +
369 ')'),
370 [ Op.ne ]: comment.id
371 }
372 },
373 transaction: t
374 }
375
376 return VideoCommentModel
377 .scope([ ScopeNames.WITH_ACCOUNT ])
378 .findAll(query)
379 }
380
381 static listAndCountByVideoId (videoId: number, start: number, count: number, t?: Transaction, order: 'ASC' | 'DESC' = 'ASC') {
382 const query = {
383 order: [ [ 'createdAt', order ] ] as Order,
384 offset: start,
385 limit: count,
386 where: {
387 videoId
388 },
389 transaction: t
390 }
391
392 return VideoCommentModel.findAndCountAll(query)
393 }
394
395 static listForFeed (start: number, count: number, videoId?: number) {
396 const query = {
397 order: [ [ 'createdAt', 'DESC' ] ] as Order,
398 offset: start,
399 limit: count,
400 where: {},
401 include: [
402 {
403 attributes: [ 'name', 'uuid' ],
404 model: VideoModel.unscoped(),
405 required: true
406 }
407 ]
408 }
409
410 if (videoId) query.where['videoId'] = videoId
411
412 return VideoCommentModel
413 .scope([ ScopeNames.WITH_ACCOUNT ])
414 .findAll(query)
415 }
416
417 static async getStats () {
418 const totalLocalVideoComments = await VideoCommentModel.count({
419 include: [
420 {
421 model: AccountModel,
422 required: true,
423 include: [
424 {
425 model: ActorModel,
426 required: true,
427 where: {
428 serverId: null
429 }
430 }
431 ]
432 }
433 ]
434 })
435 const totalVideoComments = await VideoCommentModel.count()
436
437 return {
438 totalLocalVideoComments,
439 totalVideoComments
440 }
441 }
442
443 static cleanOldCommentsOf (videoId: number, beforeUpdatedAt: Date) {
444 const query = {
445 where: {
446 updatedAt: {
447 [Op.lt]: beforeUpdatedAt
448 },
449 videoId,
450 accountId: {
451 [Op.notIn]: buildLocalAccountIdsIn()
452 }
453 }
454 }
455
456 return VideoCommentModel.destroy(query)
457 }
458
459 getCommentStaticPath () {
460 return this.Video.getWatchStaticPath() + ';threadId=' + this.getThreadId()
461 }
462
463 getThreadId (): number {
464 return this.originCommentId || this.id
465 }
466
467 isOwned () {
468 return this.Account.isOwned()
469 }
470
471 extractMentions () {
472 let result: string[] = []
473
474 const localMention = `@(${actorNameAlphabet}+)`
475 const remoteMention = `${localMention}@${WEBSERVER.HOST}`
476
477 const mentionRegex = this.isOwned()
478 ? '(?:(?:' + remoteMention + ')|(?:' + localMention + '))' // Include local mentions?
479 : '(?:' + remoteMention + ')'
480
481 const firstMentionRegex = new RegExp(`^${mentionRegex} `, 'g')
482 const endMentionRegex = new RegExp(` ${mentionRegex}$`, 'g')
483 const remoteMentionsRegex = new RegExp(' ' + remoteMention + ' ', 'g')
484
485 result = result.concat(
486 regexpCapture(this.text, firstMentionRegex)
487 .map(([ , username1, username2 ]) => username1 || username2),
488
489 regexpCapture(this.text, endMentionRegex)
490 .map(([ , username1, username2 ]) => username1 || username2),
491
492 regexpCapture(this.text, remoteMentionsRegex)
493 .map(([ , username ]) => username)
494 )
495
496 // Include local mentions
497 if (this.isOwned()) {
498 const localMentionsRegex = new RegExp(' ' + localMention + ' ', 'g')
499
500 result = result.concat(
501 regexpCapture(this.text, localMentionsRegex)
502 .map(([ , username ]) => username)
503 )
504 }
505
506 return uniq(result)
507 }
508
509 toFormattedJSON () {
510 return {
511 id: this.id,
512 url: this.url,
513 text: this.text,
514 threadId: this.originCommentId || this.id,
515 inReplyToCommentId: this.inReplyToCommentId || null,
516 videoId: this.videoId,
517 createdAt: this.createdAt,
518 updatedAt: this.updatedAt,
519 totalReplies: this.get('totalReplies') || 0,
520 account: this.Account.toFormattedJSON()
521 } as VideoComment
522 }
523
524 toActivityPubObject (threadParentComments: VideoCommentModel[]): VideoCommentObject {
525 let inReplyTo: string
526 // New thread, so in AS we reply to the video
527 if (this.inReplyToCommentId === null) {
528 inReplyTo = this.Video.url
529 } else {
530 inReplyTo = this.InReplyToVideoComment.url
531 }
532
533 const tag: ActivityTagObject[] = []
534 for (const parentComment of threadParentComments) {
535 const actor = parentComment.Account.Actor
536
537 tag.push({
538 type: 'Mention',
539 href: actor.url,
540 name: `@${actor.preferredUsername}@${actor.getHost()}`
541 })
542 }
543
544 return {
545 type: 'Note' as 'Note',
546 id: this.url,
547 content: this.text,
548 inReplyTo,
549 updated: this.updatedAt.toISOString(),
550 published: this.createdAt.toISOString(),
551 url: this.url,
552 attributedTo: this.Account.Actor.url,
553 tag
554 }
555 }
556}