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
25 } from '../../typings/models/video'
26 import { AccountModel } from '../account/account'
27 import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor'
28 import { buildBlockedAccountSQL, buildLocalAccountIdsIn, getCommentSort, throwIfNotValid } from '../utils'
29 import { VideoModel } from './video'
30 import { VideoChannelModel } from './video-channel'
33 WITH_ACCOUNT = 'WITH_ACCOUNT',
34 WITH_ACCOUNT_FOR_API = 'WITH_ACCOUNT_FOR_API',
35 WITH_IN_REPLY_TO = 'WITH_IN_REPLY_TO',
36 WITH_VIDEO = 'WITH_VIDEO',
37 ATTRIBUTES_FOR_API = 'ATTRIBUTES_FOR_API'
41 [ScopeNames.ATTRIBUTES_FOR_API]: (serverAccountId: number, userAccountId?: number) => {
48 'WITH "blocklist" AS (' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')' +
49 'SELECT COUNT("replies"."id") - (' +
50 'SELECT COUNT("replies"."id") ' +
51 'FROM "videoComment" AS "replies" ' +
52 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
53 'AND "accountId" IN (SELECT "id" FROM "blocklist")' +
55 'FROM "videoComment" AS "replies" ' +
56 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
57 'AND "accountId" NOT IN (SELECT "id" FROM "blocklist")' +
65 'SELECT COUNT("replies"."id") ' +
66 'FROM "videoComment" AS "replies" ' +
67 'INNER JOIN "video" ON "video"."id" = "replies"."videoId" ' +
68 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
69 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
70 'AND "replies"."accountId" = "videoChannel"."accountId"' +
73 'totalRepliesFromVideoAuthor'
79 [ScopeNames.WITH_ACCOUNT]: {
86 [ScopeNames.WITH_ACCOUNT_FOR_API]: {
89 model: AccountModel.unscoped(),
93 exclude: unusedActorAttributesForAPI
95 model: ActorModel, // Default scope includes avatar and server
102 [ScopeNames.WITH_IN_REPLY_TO]: {
105 model: VideoCommentModel,
106 as: 'InReplyToVideoComment'
110 [ScopeNames.WITH_VIDEO]: {
117 model: VideoChannelModel,
132 tableName: 'videoComment',
135 fields: [ 'videoId' ]
138 fields: [ 'videoId', 'originCommentId' ]
145 fields: [ 'accountId' ]
149 export class VideoCommentModel extends Model<VideoCommentModel> {
157 @Column(DataType.DATE)
161 @Is('VideoCommentUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
162 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
166 @Column(DataType.TEXT)
169 @ForeignKey(() => VideoCommentModel)
171 originCommentId: number
173 @BelongsTo(() => VideoCommentModel, {
175 name: 'originCommentId',
178 as: 'OriginVideoComment',
181 OriginVideoComment: VideoCommentModel
183 @ForeignKey(() => VideoCommentModel)
185 inReplyToCommentId: number
187 @BelongsTo(() => VideoCommentModel, {
189 name: 'inReplyToCommentId',
192 as: 'InReplyToVideoComment',
195 InReplyToVideoComment: VideoCommentModel | null
197 @ForeignKey(() => VideoModel)
201 @BelongsTo(() => VideoModel, {
209 @ForeignKey(() => AccountModel)
213 @BelongsTo(() => AccountModel, {
219 Account: AccountModel
221 static loadById (id: number, t?: Transaction): Bluebird<MComment> {
222 const query: FindOptions = {
228 if (t !== undefined) query.transaction = t
230 return VideoCommentModel.findOne(query)
233 static loadByIdAndPopulateVideoAndAccountAndReply (id: number, t?: Transaction): Bluebird<MCommentOwnerVideoReply> {
234 const query: FindOptions = {
240 if (t !== undefined) query.transaction = t
242 return VideoCommentModel
243 .scope([ ScopeNames.WITH_VIDEO, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_IN_REPLY_TO ])
247 static loadByUrlAndPopulateAccountAndVideo (url: string, t?: Transaction): Bluebird<MCommentOwnerVideo> {
248 const query: FindOptions = {
254 if (t !== undefined) query.transaction = t
256 return VideoCommentModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEO ]).findOne(query)
259 static loadByUrlAndPopulateReplyAndVideoUrlAndAccount (url: string, t?: Transaction): Bluebird<MCommentOwnerReplyVideoLight> {
260 const query: FindOptions = {
266 attributes: [ 'id', 'url' ],
267 model: VideoModel.unscoped()
272 if (t !== undefined) query.transaction = t
274 return VideoCommentModel.scope([ ScopeNames.WITH_IN_REPLY_TO, ScopeNames.WITH_ACCOUNT ]).findOne(query)
277 static async listThreadsForApi (parameters: {
282 user?: MUserAccountId
284 const { videoId, start, count, sort, user } = parameters
286 const serverActor = await getServerActor()
287 const serverAccountId = serverActor.Account.id
288 const userAccountId = user ? user.Account.id : undefined
293 order: getCommentSort(sort),
300 inReplyToCommentId: null
306 [Op.notIn]: Sequelize.literal(
307 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
320 const scopes: (string | ScopeOptions)[] = [
321 ScopeNames.WITH_ACCOUNT_FOR_API,
323 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
327 return VideoCommentModel
329 .findAndCountAll(query)
330 .then(({ rows, count }) => {
331 return { total: count, data: rows }
335 static async listThreadCommentsForApi (parameters: {
338 user?: MUserAccountId
340 const { videoId, threadId, user } = parameters
342 const serverActor = await getServerActor()
343 const serverAccountId = serverActor.Account.id
344 const userAccountId = user ? user.Account.id : undefined
347 order: [ [ 'createdAt', 'ASC' ], [ 'updatedAt', 'ASC' ] ] as Order,
352 { originCommentId: threadId }
355 [Op.notIn]: Sequelize.literal(
356 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
362 const scopes: any[] = [
363 ScopeNames.WITH_ACCOUNT_FOR_API,
365 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
369 return VideoCommentModel
371 .findAndCountAll(query)
372 .then(({ rows, count }) => {
373 return { total: count, data: rows }
377 static listThreadParentComments (comment: MCommentId, t: Transaction, order: 'ASC' | 'DESC' = 'ASC'): Bluebird<MCommentOwner[]> {
379 order: [ [ 'createdAt', order ] ] as Order,
382 [Op.in]: Sequelize.literal('(' +
383 'WITH RECURSIVE children (id, "inReplyToCommentId") AS ( ' +
384 `SELECT id, "inReplyToCommentId" FROM "videoComment" WHERE id = ${comment.id} ` +
386 'SELECT "parent"."id", "parent"."inReplyToCommentId" FROM "videoComment" "parent" ' +
387 'INNER JOIN "children" ON "children"."inReplyToCommentId" = "parent"."id"' +
389 'SELECT id FROM children' +
397 return VideoCommentModel
398 .scope([ ScopeNames.WITH_ACCOUNT ])
402 static listAndCountByVideoId (videoId: number, start: number, count: number, t?: Transaction, order: 'ASC' | 'DESC' = 'ASC') {
404 order: [ [ 'createdAt', order ] ] as Order,
413 return VideoCommentModel.findAndCountAll<MComment>(query)
416 static async listForFeed (start: number, count: number, videoId?: number): Promise<MCommentOwnerVideoFeed[]> {
417 const serverActor = await getServerActor()
420 order: [ [ 'createdAt', 'DESC' ] ] as Order,
426 [Op.notIn]: Sequelize.literal(
427 '(' + buildBlockedAccountSQL(serverActor.Account.id) + ')'
433 attributes: [ 'name', 'uuid' ],
434 model: VideoModel.unscoped(),
437 privacy: VideoPrivacy.PUBLIC
443 if (videoId) query.where['videoId'] = videoId
445 return VideoCommentModel
446 .scope([ ScopeNames.WITH_ACCOUNT ])
450 static listForBulkDelete (ofAccount: MAccount, filter: { onVideosOfAccount?: MAccountId } = {}) {
451 const accountWhere = filter.onVideosOfAccount
452 ? { id: filter.onVideosOfAccount.id }
459 accountId: ofAccount.id
467 model: VideoChannelModel,
482 return VideoCommentModel
483 .scope([ ScopeNames.WITH_ACCOUNT ])
487 static async getStats () {
488 const totalLocalVideoComments = await VideoCommentModel.count({
505 const totalVideoComments = await VideoCommentModel.count()
508 totalLocalVideoComments,
513 static cleanOldCommentsOf (videoId: number, beforeUpdatedAt: Date) {
517 [Op.lt]: beforeUpdatedAt
521 [Op.notIn]: buildLocalAccountIdsIn()
523 // Do not delete Tombstones
528 return VideoCommentModel.destroy(query)
531 getCommentStaticPath () {
532 return this.Video.getWatchStaticPath() + ';threadId=' + this.getThreadId()
535 getThreadId (): number {
536 return this.originCommentId || this.id
544 return this.Account.isOwned()
548 return this.deletedAt !== null
552 let result: string[] = []
554 const localMention = `@(${actorNameAlphabet}+)`
555 const remoteMention = `${localMention}@${WEBSERVER.HOST}`
557 const mentionRegex = this.isOwned()
558 ? '(?:(?:' + remoteMention + ')|(?:' + localMention + '))' // Include local mentions?
559 : '(?:' + remoteMention + ')'
561 const firstMentionRegex = new RegExp(`^${mentionRegex} `, 'g')
562 const endMentionRegex = new RegExp(` ${mentionRegex}$`, 'g')
563 const remoteMentionsRegex = new RegExp(' ' + remoteMention + ' ', 'g')
565 result = result.concat(
566 regexpCapture(this.text, firstMentionRegex)
567 .map(([ , username1, username2 ]) => username1 || username2),
569 regexpCapture(this.text, endMentionRegex)
570 .map(([ , username1, username2 ]) => username1 || username2),
572 regexpCapture(this.text, remoteMentionsRegex)
573 .map(([ , username ]) => username)
576 // Include local mentions
577 if (this.isOwned()) {
578 const localMentionsRegex = new RegExp(' ' + localMention + ' ', 'g')
580 result = result.concat(
581 regexpCapture(this.text, localMentionsRegex)
582 .map(([ , username ]) => username)
589 toFormattedJSON (this: MCommentFormattable) {
594 threadId: this.originCommentId || this.id,
595 inReplyToCommentId: this.inReplyToCommentId || null,
596 videoId: this.videoId,
597 createdAt: this.createdAt,
598 updatedAt: this.updatedAt,
599 deletedAt: this.deletedAt,
600 isDeleted: this.isDeleted(),
601 totalRepliesFromVideoAuthor: this.get('totalRepliesFromVideoAuthor') || 0,
602 totalReplies: this.get('totalReplies') || 0,
603 account: this.Account ? this.Account.toFormattedJSON() : null
607 toActivityPubObject (this: MCommentAP, threadParentComments: MCommentOwner[]): VideoCommentObject | ActivityTombstoneObject {
608 let inReplyTo: string
609 // New thread, so in AS we reply to the video
610 if (this.inReplyToCommentId === null) {
611 inReplyTo = this.Video.url
613 inReplyTo = this.InReplyToVideoComment.url
616 if (this.isDeleted()) {
622 published: this.createdAt.toISOString(),
623 updated: this.updatedAt.toISOString(),
624 deleted: this.deletedAt.toISOString()
628 const tag: ActivityTagObject[] = []
629 for (const parentComment of threadParentComments) {
630 if (!parentComment.Account) continue
632 const actor = parentComment.Account.Actor
637 name: `@${actor.preferredUsername}@${actor.getHost()}`
642 type: 'Note' as 'Note',
646 updated: this.updatedAt.toISOString(),
647 published: this.createdAt.toISOString(),
649 attributedTo: this.Account.Actor.url,