1 import { FindOptions, Op, Order, QueryTypes, Sequelize, Transaction } from 'sequelize'
15 } from 'sequelize-typescript'
16 import { getServerActor } from '@server/models/application/application'
17 import { MAccount, MAccountId, MUserAccountId } from '@server/types/models'
18 import { pick, uniqify } from '@shared/core-utils'
19 import { AttributesOnly } from '@shared/typescript-utils'
20 import { ActivityTagObject, ActivityTombstoneObject } from '../../../shared/models/activitypub/objects/common-objects'
21 import { VideoCommentObject } from '../../../shared/models/activitypub/objects/video-comment-object'
22 import { VideoComment, VideoCommentAdmin } from '../../../shared/models/videos/comment/video-comment.model'
23 import { actorNameAlphabet } from '../../helpers/custom-validators/activitypub/actor'
24 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
25 import { regexpCapture } from '../../helpers/regexp'
26 import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
29 MCommentAdminFormattable,
34 MCommentOwnerReplyVideoLight,
36 MCommentOwnerVideoFeed,
37 MCommentOwnerVideoReply,
39 } from '../../types/models/video'
40 import { VideoCommentAbuseModel } from '../abuse/video-comment-abuse'
41 import { AccountModel } from '../account/account'
42 import { ActorModel } from '../actor/actor'
43 import { buildLocalAccountIdsIn, buildSQLAttributes, throwIfNotValid } from '../shared'
44 import { ListVideoCommentsOptions, VideoCommentListQueryBuilder } from './sql/comment/video-comment-list-query-builder'
45 import { VideoModel } from './video'
46 import { VideoChannelModel } from './video-channel'
48 export enum ScopeNames {
49 WITH_ACCOUNT = 'WITH_ACCOUNT',
50 WITH_IN_REPLY_TO = 'WITH_IN_REPLY_TO',
51 WITH_VIDEO = 'WITH_VIDEO'
55 [ScopeNames.WITH_ACCOUNT]: {
62 [ScopeNames.WITH_IN_REPLY_TO]: {
65 model: VideoCommentModel,
66 as: 'InReplyToVideoComment'
70 [ScopeNames.WITH_VIDEO]: {
77 model: VideoChannelModel,
92 tableName: 'videoComment',
98 fields: [ 'videoId', 'originCommentId' ]
105 fields: [ 'accountId' ]
109 { name: 'createdAt', order: 'DESC' }
114 export class VideoCommentModel extends Model<Partial<AttributesOnly<VideoCommentModel>>> {
122 @Column(DataType.DATE)
126 @Is('VideoCommentUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
127 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
131 @Column(DataType.TEXT)
134 @ForeignKey(() => VideoCommentModel)
136 originCommentId: number
138 @BelongsTo(() => VideoCommentModel, {
140 name: 'originCommentId',
143 as: 'OriginVideoComment',
146 OriginVideoComment: VideoCommentModel
148 @ForeignKey(() => VideoCommentModel)
150 inReplyToCommentId: number
152 @BelongsTo(() => VideoCommentModel, {
154 name: 'inReplyToCommentId',
157 as: 'InReplyToVideoComment',
160 InReplyToVideoComment: VideoCommentModel | null
162 @ForeignKey(() => VideoModel)
166 @BelongsTo(() => VideoModel, {
174 @ForeignKey(() => AccountModel)
178 @BelongsTo(() => AccountModel, {
184 Account: AccountModel
186 @HasMany(() => VideoCommentAbuseModel, {
188 name: 'videoCommentId',
193 CommentAbuses: VideoCommentAbuseModel[]
195 // ---------------------------------------------------------------------------
197 static getSQLAttributes (tableName: string, aliasPrefix = '') {
198 return buildSQLAttributes({
205 // ---------------------------------------------------------------------------
207 static loadById (id: number, t?: Transaction): Promise<MComment> {
208 const query: FindOptions = {
214 if (t !== undefined) query.transaction = t
216 return VideoCommentModel.findOne(query)
219 static loadByIdAndPopulateVideoAndAccountAndReply (id: number, t?: Transaction): Promise<MCommentOwnerVideoReply> {
220 const query: FindOptions = {
226 if (t !== undefined) query.transaction = t
228 return VideoCommentModel
229 .scope([ ScopeNames.WITH_VIDEO, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_IN_REPLY_TO ])
233 static loadByUrlAndPopulateAccountAndVideo (url: string, t?: Transaction): Promise<MCommentOwnerVideo> {
234 const query: FindOptions = {
240 if (t !== undefined) query.transaction = t
242 return VideoCommentModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEO ]).findOne(query)
245 static loadByUrlAndPopulateReplyAndVideoUrlAndAccount (url: string, t?: Transaction): Promise<MCommentOwnerReplyVideoLight> {
246 const query: FindOptions = {
252 attributes: [ 'id', 'url' ],
253 model: VideoModel.unscoped()
258 if (t !== undefined) query.transaction = t
260 return VideoCommentModel.scope([ ScopeNames.WITH_IN_REPLY_TO, ScopeNames.WITH_ACCOUNT ]).findOne(query)
263 static listCommentsForApi (parameters: {
268 onLocalVideo?: boolean
271 searchAccount?: string
274 const queryOptions: ListVideoCommentsOptions = {
275 ...pick(parameters, [ 'start', 'count', 'sort', 'isLocal', 'search', 'searchVideo', 'searchAccount', 'onLocalVideo' ]),
282 new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MCommentAdminFormattable>(),
283 new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).countComments()
284 ]).then(([ rows, count ]) => {
285 return { total: count, data: rows }
289 static async listThreadsForApi (parameters: {
291 isVideoOwned: boolean
295 user?: MUserAccountId
297 const { videoId, user } = parameters
299 const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ user })
301 const commonOptions: ListVideoCommentsOptions = {
307 const listOptions: ListVideoCommentsOptions = {
309 ...pick(parameters, [ 'sort', 'start', 'count' ]),
312 includeReplyCounters: true
315 const countOptions: ListVideoCommentsOptions = {
321 const notDeletedCountOptions: ListVideoCommentsOptions = {
328 new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, listOptions).listComments<MCommentAdminFormattable>(),
329 new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, countOptions).countComments(),
330 new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, notDeletedCountOptions).countComments()
331 ]).then(([ rows, count, totalNotDeletedComments ]) => {
332 return { total: count, data: rows, totalNotDeletedComments }
336 static async listThreadCommentsForApi (parameters: {
339 user?: MUserAccountId
341 const { user } = parameters
343 const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ user })
345 const queryOptions: ListVideoCommentsOptions = {
346 ...pick(parameters, [ 'videoId', 'threadId' ]),
352 includeReplyCounters: true
356 new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MCommentAdminFormattable>(),
357 new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).countComments()
358 ]).then(([ rows, count ]) => {
359 return { total: count, data: rows }
363 static listThreadParentComments (comment: MCommentId, t: Transaction, order: 'ASC' | 'DESC' = 'ASC'): Promise<MCommentOwner[]> {
365 order: [ [ 'createdAt', order ] ] as Order,
368 [Op.in]: Sequelize.literal('(' +
369 'WITH RECURSIVE children (id, "inReplyToCommentId") AS ( ' +
370 `SELECT id, "inReplyToCommentId" FROM "videoComment" WHERE id = ${comment.id} ` +
372 'SELECT "parent"."id", "parent"."inReplyToCommentId" FROM "videoComment" "parent" ' +
373 'INNER JOIN "children" ON "children"."inReplyToCommentId" = "parent"."id"' +
375 'SELECT id FROM children' +
383 return VideoCommentModel
384 .scope([ ScopeNames.WITH_ACCOUNT ])
388 static async listAndCountByVideoForAP (parameters: {
389 video: MVideoImmutable
393 const { video } = parameters
395 const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ user: null })
397 const queryOptions: ListVideoCommentsOptions = {
398 ...pick(parameters, [ 'start', 'count' ]),
400 selectType: 'comment-only',
408 new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MComment>(),
409 new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).countComments()
410 ]).then(([ rows, count ]) => {
411 return { total: count, data: rows }
415 static async listForFeed (parameters: {
420 videoChannelId?: number
422 const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ user: null })
424 const queryOptions: ListVideoCommentsOptions = {
425 ...pick(parameters, [ 'start', 'count', 'accountId', 'videoId', 'videoChannelId' ]),
436 return new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MCommentOwnerVideoFeed>()
439 static listForBulkDelete (ofAccount: MAccount, filter: { onVideosOfAccount?: MAccountId } = {}) {
440 const queryOptions: ListVideoCommentsOptions = {
441 selectType: 'comment-only',
443 accountId: ofAccount.id,
444 videoAccountOwnerId: filter.onVideosOfAccount?.id,
450 return new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MComment>()
453 static async getStats () {
454 const totalLocalVideoComments = await VideoCommentModel.count({
457 model: AccountModel.unscoped(),
461 model: ActorModel.unscoped(),
471 const totalVideoComments = await VideoCommentModel.count()
474 totalLocalVideoComments,
479 static listRemoteCommentUrlsOfLocalVideos () {
480 const query = `SELECT "videoComment".url FROM "videoComment" ` +
481 `INNER JOIN account ON account.id = "videoComment"."accountId" ` +
482 `INNER JOIN actor ON actor.id = "account"."actorId" AND actor."serverId" IS NOT NULL ` +
483 `INNER JOIN video ON video.id = "videoComment"."videoId" AND video.remote IS FALSE`
485 return VideoCommentModel.sequelize.query<{ url: string }>(query, {
486 type: QueryTypes.SELECT,
488 }).then(rows => rows.map(r => r.url))
491 static cleanOldCommentsOf (videoId: number, beforeUpdatedAt: Date) {
495 [Op.lt]: beforeUpdatedAt
499 [Op.notIn]: buildLocalAccountIdsIn()
501 // Do not delete Tombstones
506 return VideoCommentModel.destroy(query)
509 getCommentStaticPath () {
510 return this.Video.getWatchStaticPath() + ';threadId=' + this.getThreadId()
513 getThreadId (): number {
514 return this.originCommentId || this.id
518 if (!this.Account) return false
520 return this.Account.isOwned()
525 this.deletedAt = new Date()
526 this.accountId = null
530 return this.deletedAt !== null
534 let result: string[] = []
536 const localMention = `@(${actorNameAlphabet}+)`
537 const remoteMention = `${localMention}@${WEBSERVER.HOST}`
539 const mentionRegex = this.isOwned()
540 ? '(?:(?:' + remoteMention + ')|(?:' + localMention + '))' // Include local mentions?
541 : '(?:' + remoteMention + ')'
543 const firstMentionRegex = new RegExp(`^${mentionRegex} `, 'g')
544 const endMentionRegex = new RegExp(` ${mentionRegex}$`, 'g')
545 const remoteMentionsRegex = new RegExp(' ' + remoteMention + ' ', 'g')
547 result = result.concat(
548 regexpCapture(this.text, firstMentionRegex)
549 .map(([ , username1, username2 ]) => username1 || username2),
551 regexpCapture(this.text, endMentionRegex)
552 .map(([ , username1, username2 ]) => username1 || username2),
554 regexpCapture(this.text, remoteMentionsRegex)
555 .map(([ , username ]) => username)
558 // Include local mentions
559 if (this.isOwned()) {
560 const localMentionsRegex = new RegExp(' ' + localMention + ' ', 'g')
562 result = result.concat(
563 regexpCapture(this.text, localMentionsRegex)
564 .map(([ , username ]) => username)
568 return uniqify(result)
571 toFormattedJSON (this: MCommentFormattable) {
577 threadId: this.getThreadId(),
578 inReplyToCommentId: this.inReplyToCommentId || null,
579 videoId: this.videoId,
581 createdAt: this.createdAt,
582 updatedAt: this.updatedAt,
583 deletedAt: this.deletedAt,
585 isDeleted: this.isDeleted(),
587 totalRepliesFromVideoAuthor: this.get('totalRepliesFromVideoAuthor') || 0,
588 totalReplies: this.get('totalReplies') || 0,
590 account: this.Account
591 ? this.Account.toFormattedJSON()
596 toFormattedAdminJSON (this: MCommentAdminFormattable) {
602 threadId: this.getThreadId(),
603 inReplyToCommentId: this.inReplyToCommentId || null,
604 videoId: this.videoId,
606 createdAt: this.createdAt,
607 updatedAt: this.updatedAt,
611 uuid: this.Video.uuid,
612 name: this.Video.name
615 account: this.Account
616 ? this.Account.toFormattedJSON()
618 } as VideoCommentAdmin
621 toActivityPubObject (this: MCommentAP, threadParentComments: MCommentOwner[]): VideoCommentObject | ActivityTombstoneObject {
622 let inReplyTo: string
623 // New thread, so in AS we reply to the video
624 if (this.inReplyToCommentId === null) {
625 inReplyTo = this.Video.url
627 inReplyTo = this.InReplyToVideoComment.url
630 if (this.isDeleted()) {
636 published: this.createdAt.toISOString(),
637 updated: this.updatedAt.toISOString(),
638 deleted: this.deletedAt.toISOString()
642 const tag: ActivityTagObject[] = []
643 for (const parentComment of threadParentComments) {
644 if (!parentComment.Account) continue
646 const actor = parentComment.Account.Actor
651 name: `@${actor.preferredUsername}@${actor.getHost()}`
656 type: 'Note' as 'Note',
660 mediaType: 'text/markdown',
663 updated: this.updatedAt.toISOString(),
664 published: this.createdAt.toISOString(),
666 attributedTo: this.Account.Actor.url,
671 private static async buildBlockerAccountIds (options: {
673 }): Promise<number[]> {
674 const { user } = options
676 const serverActor = await getServerActor()
677 const blockerAccountIds = [ serverActor.Account.id ]
679 if (user) blockerAccountIds.push(user.Account.id)
681 return blockerAccountIds