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