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