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