1 import * as Bluebird from 'bluebird'
2 import { uniq } from 'lodash'
3 import { FindOptions, Op, Order, ScopeOptions, Sequelize, Transaction } from 'sequelize'
4 import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Is, Model, Scopes, Table, UpdatedAt } from 'sequelize-typescript'
5 import { getServerActor } from '@server/models/application/application'
6 import { MAccount, MAccountId, MUserAccountId } from '@server/typings/models'
7 import { VideoPrivacy } from '@shared/models'
8 import { ActivityTagObject, ActivityTombstoneObject } from '../../../shared/models/activitypub/objects/common-objects'
9 import { VideoCommentObject } from '../../../shared/models/activitypub/objects/video-comment-object'
10 import { VideoComment } from '../../../shared/models/videos/video-comment.model'
11 import { actorNameAlphabet } from '../../helpers/custom-validators/activitypub/actor'
12 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
13 import { regexpCapture } from '../../helpers/regexp'
14 import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
21 MCommentOwnerReplyVideoLight,
23 MCommentOwnerVideoFeed,
24 MCommentOwnerVideoReply,
26 } from '../../typings/models/video'
27 import { AccountModel } from '../account/account'
28 import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor'
29 import { buildBlockedAccountSQL, buildLocalAccountIdsIn, getCommentSort, throwIfNotValid } from '../utils'
30 import { VideoModel } from './video'
31 import { VideoChannelModel } from './video-channel'
34 WITH_ACCOUNT = 'WITH_ACCOUNT',
35 WITH_ACCOUNT_FOR_API = 'WITH_ACCOUNT_FOR_API',
36 WITH_IN_REPLY_TO = 'WITH_IN_REPLY_TO',
37 WITH_VIDEO = 'WITH_VIDEO',
38 ATTRIBUTES_FOR_API = 'ATTRIBUTES_FOR_API'
42 [ScopeNames.ATTRIBUTES_FOR_API]: (blockerAccountIds: number[]) => {
49 'WITH "blocklist" AS (' + buildBlockedAccountSQL(blockerAccountIds) + ')' +
50 'SELECT COUNT("replies"."id") - (' +
51 'SELECT COUNT("replies"."id") ' +
52 'FROM "videoComment" AS "replies" ' +
53 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
54 'AND "accountId" IN (SELECT "id" FROM "blocklist")' +
56 'FROM "videoComment" AS "replies" ' +
57 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
58 'AND "accountId" NOT IN (SELECT "id" FROM "blocklist")' +
66 'SELECT COUNT("replies"."id") ' +
67 'FROM "videoComment" AS "replies" ' +
68 'INNER JOIN "video" ON "video"."id" = "replies"."videoId" ' +
69 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
70 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
71 'AND "replies"."accountId" = "videoChannel"."accountId"' +
74 'totalRepliesFromVideoAuthor'
80 [ScopeNames.WITH_ACCOUNT]: {
87 [ScopeNames.WITH_ACCOUNT_FOR_API]: {
90 model: AccountModel.unscoped(),
94 exclude: unusedActorAttributesForAPI
96 model: ActorModel, // Default scope includes avatar and server
103 [ScopeNames.WITH_IN_REPLY_TO]: {
106 model: VideoCommentModel,
107 as: 'InReplyToVideoComment'
111 [ScopeNames.WITH_VIDEO]: {
118 model: VideoChannelModel,
133 tableName: 'videoComment',
136 fields: [ 'videoId' ]
139 fields: [ 'videoId', 'originCommentId' ]
146 fields: [ 'accountId' ]
150 export class VideoCommentModel extends Model<VideoCommentModel> {
158 @Column(DataType.DATE)
162 @Is('VideoCommentUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
163 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
167 @Column(DataType.TEXT)
170 @ForeignKey(() => VideoCommentModel)
172 originCommentId: number
174 @BelongsTo(() => VideoCommentModel, {
176 name: 'originCommentId',
179 as: 'OriginVideoComment',
182 OriginVideoComment: VideoCommentModel
184 @ForeignKey(() => VideoCommentModel)
186 inReplyToCommentId: number
188 @BelongsTo(() => VideoCommentModel, {
190 name: 'inReplyToCommentId',
193 as: 'InReplyToVideoComment',
196 InReplyToVideoComment: VideoCommentModel | null
198 @ForeignKey(() => VideoModel)
202 @BelongsTo(() => VideoModel, {
210 @ForeignKey(() => AccountModel)
214 @BelongsTo(() => AccountModel, {
220 Account: AccountModel
222 static loadById (id: number, t?: Transaction): Bluebird<MComment> {
223 const query: FindOptions = {
229 if (t !== undefined) query.transaction = t
231 return VideoCommentModel.findOne(query)
234 static loadByIdAndPopulateVideoAndAccountAndReply (id: number, t?: Transaction): Bluebird<MCommentOwnerVideoReply> {
235 const query: FindOptions = {
241 if (t !== undefined) query.transaction = t
243 return VideoCommentModel
244 .scope([ ScopeNames.WITH_VIDEO, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_IN_REPLY_TO ])
248 static loadByUrlAndPopulateAccountAndVideo (url: string, t?: Transaction): Bluebird<MCommentOwnerVideo> {
249 const query: FindOptions = {
255 if (t !== undefined) query.transaction = t
257 return VideoCommentModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEO ]).findOne(query)
260 static loadByUrlAndPopulateReplyAndVideoUrlAndAccount (url: string, t?: Transaction): Bluebird<MCommentOwnerReplyVideoLight> {
261 const query: FindOptions = {
267 attributes: [ 'id', 'url' ],
268 model: VideoModel.unscoped()
273 if (t !== undefined) query.transaction = t
275 return VideoCommentModel.scope([ ScopeNames.WITH_IN_REPLY_TO, ScopeNames.WITH_ACCOUNT ]).findOne(query)
278 static async listThreadsForApi (parameters: {
280 isVideoOwned: boolean
284 user?: MUserAccountId
286 const { videoId, isVideoOwned, start, count, sort, user } = parameters
288 const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ videoId, user, isVideoOwned })
293 order: getCommentSort(sort),
300 inReplyToCommentId: null
306 [Op.notIn]: Sequelize.literal(
307 '(' + buildBlockedAccountSQL(blockerAccountIds) + ')'
320 const scopes: (string | ScopeOptions)[] = [
321 ScopeNames.WITH_ACCOUNT_FOR_API,
323 method: [ ScopeNames.ATTRIBUTES_FOR_API, blockerAccountIds ]
327 return VideoCommentModel
329 .findAndCountAll(query)
330 .then(({ rows, count }) => {
331 return { total: count, data: rows }
335 static async listThreadCommentsForApi (parameters: {
337 isVideoOwned: boolean
339 user?: MUserAccountId
341 const { videoId, threadId, user, isVideoOwned } = parameters
343 const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ videoId, user, isVideoOwned })
346 order: [ [ 'createdAt', 'ASC' ], [ 'updatedAt', 'ASC' ] ] as Order,
351 { originCommentId: threadId }
354 [Op.notIn]: Sequelize.literal(
355 '(' + buildBlockedAccountSQL(blockerAccountIds) + ')'
361 const scopes: any[] = [
362 ScopeNames.WITH_ACCOUNT_FOR_API,
364 method: [ ScopeNames.ATTRIBUTES_FOR_API, blockerAccountIds ]
368 return VideoCommentModel
370 .findAndCountAll(query)
371 .then(({ rows, count }) => {
372 return { total: count, data: rows }
376 static listThreadParentComments (comment: MCommentId, t: Transaction, order: 'ASC' | 'DESC' = 'ASC'): Bluebird<MCommentOwner[]> {
378 order: [ [ 'createdAt', order ] ] as Order,
381 [Op.in]: Sequelize.literal('(' +
382 'WITH RECURSIVE children (id, "inReplyToCommentId") AS ( ' +
383 `SELECT id, "inReplyToCommentId" FROM "videoComment" WHERE id = ${comment.id} ` +
385 'SELECT "parent"."id", "parent"."inReplyToCommentId" FROM "videoComment" "parent" ' +
386 'INNER JOIN "children" ON "children"."inReplyToCommentId" = "parent"."id"' +
388 'SELECT id FROM children' +
396 return VideoCommentModel
397 .scope([ ScopeNames.WITH_ACCOUNT ])
401 static async listAndCountByVideoForAP (video: MVideoImmutable, start: number, count: number, t?: Transaction) {
402 const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({
404 isVideoOwned: video.isOwned()
408 order: [ [ 'createdAt', 'ASC' ] ] as Order,
414 [Op.notIn]: Sequelize.literal(
415 '(' + buildBlockedAccountSQL(blockerAccountIds) + ')'
422 return VideoCommentModel.findAndCountAll<MComment>(query)
425 static async listForFeed (start: number, count: number, videoId?: number): Promise<MCommentOwnerVideoFeed[]> {
426 const serverActor = await getServerActor()
429 order: [ [ 'createdAt', 'DESC' ] ] as Order,
435 [Op.notIn]: Sequelize.literal(
436 '(' + buildBlockedAccountSQL([ serverActor.Account.id, '"Video->VideoChannel"."accountId"' ]) + ')'
442 attributes: [ 'name', 'uuid' ],
443 model: VideoModel.unscoped(),
446 privacy: VideoPrivacy.PUBLIC
450 attributes: [ 'accountId' ],
451 model: VideoChannelModel.unscoped(),
459 if (videoId) query.where['videoId'] = videoId
461 return VideoCommentModel
462 .scope([ ScopeNames.WITH_ACCOUNT ])
466 static listForBulkDelete (ofAccount: MAccount, filter: { onVideosOfAccount?: MAccountId } = {}) {
467 const accountWhere = filter.onVideosOfAccount
468 ? { id: filter.onVideosOfAccount.id }
475 accountId: ofAccount.id
483 model: VideoChannelModel,
498 return VideoCommentModel
499 .scope([ ScopeNames.WITH_ACCOUNT ])
503 static async getStats () {
504 const totalLocalVideoComments = await VideoCommentModel.count({
521 const totalVideoComments = await VideoCommentModel.count()
524 totalLocalVideoComments,
529 static cleanOldCommentsOf (videoId: number, beforeUpdatedAt: Date) {
533 [Op.lt]: beforeUpdatedAt
537 [Op.notIn]: buildLocalAccountIdsIn()
539 // Do not delete Tombstones
544 return VideoCommentModel.destroy(query)
547 getCommentStaticPath () {
548 return this.Video.getWatchStaticPath() + ';threadId=' + this.getThreadId()
551 getThreadId (): number {
552 return this.originCommentId || this.id
560 return this.Account.isOwned()
564 return this.deletedAt !== null
568 let result: string[] = []
570 const localMention = `@(${actorNameAlphabet}+)`
571 const remoteMention = `${localMention}@${WEBSERVER.HOST}`
573 const mentionRegex = this.isOwned()
574 ? '(?:(?:' + remoteMention + ')|(?:' + localMention + '))' // Include local mentions?
575 : '(?:' + remoteMention + ')'
577 const firstMentionRegex = new RegExp(`^${mentionRegex} `, 'g')
578 const endMentionRegex = new RegExp(` ${mentionRegex}$`, 'g')
579 const remoteMentionsRegex = new RegExp(' ' + remoteMention + ' ', 'g')
581 result = result.concat(
582 regexpCapture(this.text, firstMentionRegex)
583 .map(([ , username1, username2 ]) => username1 || username2),
585 regexpCapture(this.text, endMentionRegex)
586 .map(([ , username1, username2 ]) => username1 || username2),
588 regexpCapture(this.text, remoteMentionsRegex)
589 .map(([ , username ]) => username)
592 // Include local mentions
593 if (this.isOwned()) {
594 const localMentionsRegex = new RegExp(' ' + localMention + ' ', 'g')
596 result = result.concat(
597 regexpCapture(this.text, localMentionsRegex)
598 .map(([ , username ]) => username)
605 toFormattedJSON (this: MCommentFormattable) {
610 threadId: this.originCommentId || this.id,
611 inReplyToCommentId: this.inReplyToCommentId || null,
612 videoId: this.videoId,
613 createdAt: this.createdAt,
614 updatedAt: this.updatedAt,
615 deletedAt: this.deletedAt,
616 isDeleted: this.isDeleted(),
617 totalRepliesFromVideoAuthor: this.get('totalRepliesFromVideoAuthor') || 0,
618 totalReplies: this.get('totalReplies') || 0,
619 account: this.Account ? this.Account.toFormattedJSON() : null
623 toActivityPubObject (this: MCommentAP, threadParentComments: MCommentOwner[]): VideoCommentObject | ActivityTombstoneObject {
624 let inReplyTo: string
625 // New thread, so in AS we reply to the video
626 if (this.inReplyToCommentId === null) {
627 inReplyTo = this.Video.url
629 inReplyTo = this.InReplyToVideoComment.url
632 if (this.isDeleted()) {
638 published: this.createdAt.toISOString(),
639 updated: this.updatedAt.toISOString(),
640 deleted: this.deletedAt.toISOString()
644 const tag: ActivityTagObject[] = []
645 for (const parentComment of threadParentComments) {
646 if (!parentComment.Account) continue
648 const actor = parentComment.Account.Actor
653 name: `@${actor.preferredUsername}@${actor.getHost()}`
658 type: 'Note' as 'Note',
662 updated: this.updatedAt.toISOString(),
663 published: this.createdAt.toISOString(),
665 attributedTo: this.Account.Actor.url,
670 private static async buildBlockerAccountIds (options: {
672 isVideoOwned: boolean
673 user?: MUserAccountId
675 const { videoId, user, isVideoOwned } = options
677 const serverActor = await getServerActor()
678 const blockerAccountIds = [ serverActor.Account.id ]
680 if (user) blockerAccountIds.push(user.Account.id)
683 const videoOwnerAccount = await AccountModel.loadAccountIdFromVideo(videoId)
684 blockerAccountIds.push(videoOwnerAccount.id)
687 return blockerAccountIds