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