1 import { uniq } from 'lodash'
2 import { FindAndCountOptions, FindOptions, Op, Order, QueryTypes, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
16 } from 'sequelize-typescript'
17 import { getServerActor } from '@server/models/application/application'
18 import { MAccount, MAccountId, MUserAccountId } from '@server/types/models'
19 import { AttributesOnly } from '@shared/core-utils'
20 import { VideoPrivacy } from '@shared/models'
21 import { ActivityTagObject, ActivityTombstoneObject } from '../../../shared/models/activitypub/objects/common-objects'
22 import { VideoCommentObject } from '../../../shared/models/activitypub/objects/video-comment-object'
23 import { VideoComment, VideoCommentAdmin } from '../../../shared/models/videos/comment/video-comment.model'
24 import { actorNameAlphabet } from '../../helpers/custom-validators/activitypub/actor'
25 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
26 import { regexpCapture } from '../../helpers/regexp'
27 import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
30 MCommentAdminFormattable,
35 MCommentOwnerReplyVideoLight,
37 MCommentOwnerVideoFeed,
38 MCommentOwnerVideoReply,
40 } from '../../types/models/video'
41 import { VideoCommentAbuseModel } from '../abuse/video-comment-abuse'
42 import { AccountModel } from '../account/account'
43 import { ActorModel, unusedActorAttributesForAPI } from '../actor/actor'
45 buildBlockedAccountSQL,
46 buildBlockedAccountSQLOptimized,
47 buildLocalAccountIdsIn,
52 import { VideoModel } from './video'
53 import { VideoChannelModel } from './video-channel'
55 export enum ScopeNames {
56 WITH_ACCOUNT = 'WITH_ACCOUNT',
57 WITH_ACCOUNT_FOR_API = 'WITH_ACCOUNT_FOR_API',
58 WITH_IN_REPLY_TO = 'WITH_IN_REPLY_TO',
59 WITH_VIDEO = 'WITH_VIDEO',
60 ATTRIBUTES_FOR_API = 'ATTRIBUTES_FOR_API'
64 [ScopeNames.ATTRIBUTES_FOR_API]: (blockerAccountIds: number[]) => {
71 'WITH "blocklist" AS (' + buildBlockedAccountSQL(blockerAccountIds) + ')' +
72 'SELECT COUNT("replies"."id") ' +
73 'FROM "videoComment" AS "replies" ' +
74 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
75 'AND "deletedAt" IS NULL ' +
76 'AND "accountId" NOT IN (SELECT "id" FROM "blocklist")' +
84 'SELECT COUNT("replies"."id") ' +
85 'FROM "videoComment" AS "replies" ' +
86 'INNER JOIN "video" ON "video"."id" = "replies"."videoId" ' +
87 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
88 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
89 'AND "replies"."accountId" = "videoChannel"."accountId"' +
92 'totalRepliesFromVideoAuthor'
98 [ScopeNames.WITH_ACCOUNT]: {
105 [ScopeNames.WITH_ACCOUNT_FOR_API]: {
108 model: AccountModel.unscoped(),
112 exclude: unusedActorAttributesForAPI
114 model: ActorModel, // Default scope includes avatar and server
121 [ScopeNames.WITH_IN_REPLY_TO]: {
124 model: VideoCommentModel,
125 as: 'InReplyToVideoComment'
129 [ScopeNames.WITH_VIDEO]: {
136 model: VideoChannelModel,
151 tableName: 'videoComment',
154 fields: [ 'videoId' ]
157 fields: [ 'videoId', 'originCommentId' ]
164 fields: [ 'accountId' ]
168 { name: 'createdAt', order: 'DESC' }
173 export class VideoCommentModel extends Model<Partial<AttributesOnly<VideoCommentModel>>> {
181 @Column(DataType.DATE)
185 @Is('VideoCommentUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
186 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
190 @Column(DataType.TEXT)
193 @ForeignKey(() => VideoCommentModel)
195 originCommentId: number
197 @BelongsTo(() => VideoCommentModel, {
199 name: 'originCommentId',
202 as: 'OriginVideoComment',
205 OriginVideoComment: VideoCommentModel
207 @ForeignKey(() => VideoCommentModel)
209 inReplyToCommentId: number
211 @BelongsTo(() => VideoCommentModel, {
213 name: 'inReplyToCommentId',
216 as: 'InReplyToVideoComment',
219 InReplyToVideoComment: VideoCommentModel | null
221 @ForeignKey(() => VideoModel)
225 @BelongsTo(() => VideoModel, {
233 @ForeignKey(() => AccountModel)
237 @BelongsTo(() => AccountModel, {
243 Account: AccountModel
245 @HasMany(() => VideoCommentAbuseModel, {
247 name: 'videoCommentId',
252 CommentAbuses: VideoCommentAbuseModel[]
254 static loadById (id: number, t?: Transaction): Promise<MComment> {
255 const query: FindOptions = {
261 if (t !== undefined) query.transaction = t
263 return VideoCommentModel.findOne(query)
266 static loadByIdAndPopulateVideoAndAccountAndReply (id: number, t?: Transaction): Promise<MCommentOwnerVideoReply> {
267 const query: FindOptions = {
273 if (t !== undefined) query.transaction = t
275 return VideoCommentModel
276 .scope([ ScopeNames.WITH_VIDEO, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_IN_REPLY_TO ])
280 static loadByUrlAndPopulateAccountAndVideo (url: string, t?: Transaction): Promise<MCommentOwnerVideo> {
281 const query: FindOptions = {
287 if (t !== undefined) query.transaction = t
289 return VideoCommentModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEO ]).findOne(query)
292 static loadByUrlAndPopulateReplyAndVideoUrlAndAccount (url: string, t?: Transaction): Promise<MCommentOwnerReplyVideoLight> {
293 const query: FindOptions = {
299 attributes: [ 'id', 'url' ],
300 model: VideoModel.unscoped()
305 if (t !== undefined) query.transaction = t
307 return VideoCommentModel.scope([ ScopeNames.WITH_IN_REPLY_TO, ScopeNames.WITH_ACCOUNT ]).findOne(query)
310 static listCommentsForApi (parameters: {
317 searchAccount?: string
320 const { start, count, sort, isLocal, search, searchAccount, searchVideo } = parameters
322 const where: WhereOptions = {
326 const whereAccount: WhereOptions = {}
327 const whereActor: WhereOptions = {}
328 const whereVideo: WhereOptions = {}
330 if (isLocal === true) {
331 Object.assign(whereActor, {
334 } else if (isLocal === false) {
335 Object.assign(whereActor, {
343 Object.assign(where, {
345 searchAttribute(search, 'text'),
346 searchAttribute(search, '$Account.Actor.preferredUsername$'),
347 searchAttribute(search, '$Account.name$'),
348 searchAttribute(search, '$Video.name$')
354 Object.assign(whereActor, {
356 searchAttribute(searchAccount, '$Account.Actor.preferredUsername$'),
357 searchAttribute(searchAccount, '$Account.name$')
363 Object.assign(whereVideo, searchAttribute(searchVideo, 'name'))
366 const query: FindAndCountOptions = {
369 order: getCommentSort(sort),
373 model: AccountModel.unscoped(),
379 exclude: unusedActorAttributesForAPI
381 model: ActorModel, // Default scope includes avatar and server
388 model: VideoModel.unscoped(),
395 return VideoCommentModel
396 .findAndCountAll(query)
397 .then(({ rows, count }) => {
398 return { total: count, data: rows }
402 static async listThreadsForApi (parameters: {
404 isVideoOwned: boolean
408 user?: MUserAccountId
410 const { videoId, isVideoOwned, start, count, sort, user } = parameters
412 const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ videoId, user, isVideoOwned })
414 const accountBlockedWhere = {
416 [Op.notIn]: Sequelize.literal(
417 '(' + buildBlockedAccountSQL(blockerAccountIds) + ')'
425 order: getCommentSort(sort),
432 inReplyToCommentId: null
446 const scopesList: (string | ScopeOptions)[] = [
447 ScopeNames.WITH_ACCOUNT_FOR_API,
449 method: [ ScopeNames.ATTRIBUTES_FOR_API, blockerAccountIds ]
457 ...accountBlockedWhere
462 VideoCommentModel.scope(scopesList).findAndCountAll(queryList),
463 VideoCommentModel.count(queryCount)
464 ]).then(([ { rows, count }, totalNotDeletedComments ]) => {
465 return { total: count, data: rows, totalNotDeletedComments }
469 static async listThreadCommentsForApi (parameters: {
471 isVideoOwned: boolean
473 user?: MUserAccountId
475 const { videoId, threadId, user, isVideoOwned } = parameters
477 const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ videoId, user, isVideoOwned })
480 order: [ [ 'createdAt', 'ASC' ], [ 'updatedAt', 'ASC' ] ] as Order,
487 { originCommentId: threadId }
494 [Op.notIn]: Sequelize.literal(
495 '(' + buildBlockedAccountSQL(blockerAccountIds) + ')'
508 const scopes: any[] = [
509 ScopeNames.WITH_ACCOUNT_FOR_API,
511 method: [ ScopeNames.ATTRIBUTES_FOR_API, blockerAccountIds ]
515 return VideoCommentModel.scope(scopes)
516 .findAndCountAll(query)
517 .then(({ rows, count }) => {
518 return { total: count, data: rows }
522 static listThreadParentComments (comment: MCommentId, t: Transaction, order: 'ASC' | 'DESC' = 'ASC'): Promise<MCommentOwner[]> {
524 order: [ [ 'createdAt', order ] ] as Order,
527 [Op.in]: Sequelize.literal('(' +
528 'WITH RECURSIVE children (id, "inReplyToCommentId") AS ( ' +
529 `SELECT id, "inReplyToCommentId" FROM "videoComment" WHERE id = ${comment.id} ` +
531 'SELECT "parent"."id", "parent"."inReplyToCommentId" FROM "videoComment" "parent" ' +
532 'INNER JOIN "children" ON "children"."inReplyToCommentId" = "parent"."id"' +
534 'SELECT id FROM children' +
542 return VideoCommentModel
543 .scope([ ScopeNames.WITH_ACCOUNT ])
547 static async listAndCountByVideoForAP (video: MVideoImmutable, start: number, count: number, t?: Transaction) {
548 const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({
550 isVideoOwned: video.isOwned()
554 order: [ [ 'createdAt', 'ASC' ] ] as Order,
560 [Op.notIn]: Sequelize.literal(
561 '(' + buildBlockedAccountSQL(blockerAccountIds) + ')'
568 return VideoCommentModel.findAndCountAll<MComment>(query)
571 static async listForFeed (parameters: {
576 videoChannelId?: number
577 }): Promise<MCommentOwnerVideoFeed[]> {
578 const serverActor = await getServerActor()
579 const { start, count, videoId, accountId, videoChannelId } = parameters
581 const whereAnd: WhereOptions[] = buildBlockedAccountSQLOptimized(
582 '"VideoCommentModel"."accountId"',
583 [ serverActor.Account.id, '"Video->VideoChannel"."accountId"' ]
592 const accountWhere = {
596 const videoChannelWhere = videoChannelId ? { id: videoChannelId } : undefined
599 order: [ [ 'createdAt', 'DESC' ] ] as Order,
604 accountId: accountWhere
608 attributes: [ 'name', 'uuid' ],
609 model: VideoModel.unscoped(),
612 privacy: VideoPrivacy.PUBLIC
616 attributes: [ 'accountId' ],
617 model: VideoChannelModel.unscoped(),
619 where: videoChannelWhere
626 if (videoId) query.where['videoId'] = videoId
628 return VideoCommentModel
629 .scope([ ScopeNames.WITH_ACCOUNT ])
633 static listForBulkDelete (ofAccount: MAccount, filter: { onVideosOfAccount?: MAccountId } = {}) {
634 const accountWhere = filter.onVideosOfAccount
635 ? { id: filter.onVideosOfAccount.id }
642 accountId: ofAccount.id
650 model: VideoChannelModel,
665 return VideoCommentModel
666 .scope([ ScopeNames.WITH_ACCOUNT ])
670 static async getStats () {
671 const totalLocalVideoComments = await VideoCommentModel.count({
688 const totalVideoComments = await VideoCommentModel.count()
691 totalLocalVideoComments,
696 static listRemoteCommentUrlsOfLocalVideos () {
697 const query = `SELECT "videoComment".url FROM "videoComment" ` +
698 `INNER JOIN account ON account.id = "videoComment"."accountId" ` +
699 `INNER JOIN actor ON actor.id = "account"."actorId" AND actor."serverId" IS NOT NULL ` +
700 `INNER JOIN video ON video.id = "videoComment"."videoId" AND video.remote IS FALSE`
702 return VideoCommentModel.sequelize.query<{ url: string }>(query, {
703 type: QueryTypes.SELECT,
705 }).then(rows => rows.map(r => r.url))
708 static cleanOldCommentsOf (videoId: number, beforeUpdatedAt: Date) {
712 [Op.lt]: beforeUpdatedAt
716 [Op.notIn]: buildLocalAccountIdsIn()
718 // Do not delete Tombstones
723 return VideoCommentModel.destroy(query)
726 getCommentStaticPath () {
727 return this.Video.getWatchStaticPath() + ';threadId=' + this.getThreadId()
730 getThreadId (): number {
731 return this.originCommentId || this.id
739 return this.Account.isOwned()
744 this.deletedAt = new Date()
745 this.accountId = null
749 return this.deletedAt !== null
753 let result: string[] = []
755 const localMention = `@(${actorNameAlphabet}+)`
756 const remoteMention = `${localMention}@${WEBSERVER.HOST}`
758 const mentionRegex = this.isOwned()
759 ? '(?:(?:' + remoteMention + ')|(?:' + localMention + '))' // Include local mentions?
760 : '(?:' + remoteMention + ')'
762 const firstMentionRegex = new RegExp(`^${mentionRegex} `, 'g')
763 const endMentionRegex = new RegExp(` ${mentionRegex}$`, 'g')
764 const remoteMentionsRegex = new RegExp(' ' + remoteMention + ' ', 'g')
766 result = result.concat(
767 regexpCapture(this.text, firstMentionRegex)
768 .map(([ , username1, username2 ]) => username1 || username2),
770 regexpCapture(this.text, endMentionRegex)
771 .map(([ , username1, username2 ]) => username1 || username2),
773 regexpCapture(this.text, remoteMentionsRegex)
774 .map(([ , username ]) => username)
777 // Include local mentions
778 if (this.isOwned()) {
779 const localMentionsRegex = new RegExp(' ' + localMention + ' ', 'g')
781 result = result.concat(
782 regexpCapture(this.text, localMentionsRegex)
783 .map(([ , username ]) => username)
790 toFormattedJSON (this: MCommentFormattable) {
796 threadId: this.getThreadId(),
797 inReplyToCommentId: this.inReplyToCommentId || null,
798 videoId: this.videoId,
800 createdAt: this.createdAt,
801 updatedAt: this.updatedAt,
802 deletedAt: this.deletedAt,
804 isDeleted: this.isDeleted(),
806 totalRepliesFromVideoAuthor: this.get('totalRepliesFromVideoAuthor') || 0,
807 totalReplies: this.get('totalReplies') || 0,
809 account: this.Account
810 ? this.Account.toFormattedJSON()
815 toFormattedAdminJSON (this: MCommentAdminFormattable) {
821 threadId: this.getThreadId(),
822 inReplyToCommentId: this.inReplyToCommentId || null,
823 videoId: this.videoId,
825 createdAt: this.createdAt,
826 updatedAt: this.updatedAt,
830 uuid: this.Video.uuid,
831 name: this.Video.name
834 account: this.Account
835 ? this.Account.toFormattedJSON()
837 } as VideoCommentAdmin
840 toActivityPubObject (this: MCommentAP, threadParentComments: MCommentOwner[]): VideoCommentObject | ActivityTombstoneObject {
841 let inReplyTo: string
842 // New thread, so in AS we reply to the video
843 if (this.inReplyToCommentId === null) {
844 inReplyTo = this.Video.url
846 inReplyTo = this.InReplyToVideoComment.url
849 if (this.isDeleted()) {
855 published: this.createdAt.toISOString(),
856 updated: this.updatedAt.toISOString(),
857 deleted: this.deletedAt.toISOString()
861 const tag: ActivityTagObject[] = []
862 for (const parentComment of threadParentComments) {
863 if (!parentComment.Account) continue
865 const actor = parentComment.Account.Actor
870 name: `@${actor.preferredUsername}@${actor.getHost()}`
875 type: 'Note' as 'Note',
879 updated: this.updatedAt.toISOString(),
880 published: this.createdAt.toISOString(),
882 attributedTo: this.Account.Actor.url,
887 private static async buildBlockerAccountIds (options: {
889 isVideoOwned: boolean
890 user?: MUserAccountId
892 const { videoId, user, isVideoOwned } = options
894 const serverActor = await getServerActor()
895 const blockerAccountIds = [ serverActor.Account.id ]
897 if (user) blockerAccountIds.push(user.Account.id)
900 const videoOwnerAccount = await AccountModel.loadAccountIdFromVideo(videoId)
901 blockerAccountIds.push(videoOwnerAccount.id)
904 return blockerAccountIds