1 import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Is, Model, Scopes, Table, UpdatedAt } from 'sequelize-typescript'
2 import { ActivityTagObject, ActivityTombstoneObject } from '../../../shared/models/activitypub/objects/common-objects'
3 import { VideoCommentObject } from '../../../shared/models/activitypub/objects/video-comment-object'
4 import { VideoComment } from '../../../shared/models/videos/video-comment.model'
5 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
6 import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
7 import { AccountModel } from '../account/account'
8 import { ActorModel } from '../activitypub/actor'
9 import { buildBlockedAccountSQL, buildLocalAccountIdsIn, getCommentSort, throwIfNotValid } from '../utils'
10 import { VideoModel } from './video'
11 import { VideoChannelModel } from './video-channel'
12 import { getServerActor } from '../../helpers/utils'
13 import { actorNameAlphabet } from '../../helpers/custom-validators/activitypub/actor'
14 import { regexpCapture } from '../../helpers/regexp'
15 import { uniq } from 'lodash'
16 import { FindOptions, Op, Order, ScopeOptions, Sequelize, Transaction } from 'sequelize'
17 import * as Bluebird from 'bluebird'
24 MCommentOwnerReplyVideoLight,
26 MCommentOwnerVideoFeed,
27 MCommentOwnerVideoReply
28 } from '../../typings/models/video'
29 import { MUserAccountId } from '@server/typings/models'
32 WITH_ACCOUNT = 'WITH_ACCOUNT',
33 WITH_IN_REPLY_TO = 'WITH_IN_REPLY_TO',
34 WITH_VIDEO = 'WITH_VIDEO',
35 ATTRIBUTES_FOR_API = 'ATTRIBUTES_FOR_API'
39 [ScopeNames.ATTRIBUTES_FOR_API]: (serverAccountId: number, userAccountId?: number) => {
46 'WITH "blocklist" AS (' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')' +
47 'SELECT COUNT("replies"."id") - (' +
48 'SELECT COUNT("replies"."id") ' +
49 'FROM "videoComment" AS "replies" ' +
50 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
51 'AND "accountId" IN (SELECT "id" FROM "blocklist")' +
53 'FROM "videoComment" AS "replies" ' +
54 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
55 'AND "accountId" NOT IN (SELECT "id" FROM "blocklist")' +
63 'SELECT COUNT("replies"."id") ' +
64 'FROM "videoComment" AS "replies" ' +
65 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
66 'AND "accountId" = ' + userAccountId +
69 'totalRepliesFromVideoAuthor'
75 [ScopeNames.WITH_ACCOUNT]: {
82 [ScopeNames.WITH_IN_REPLY_TO]: {
85 model: VideoCommentModel,
86 as: 'InReplyToVideoComment'
90 [ScopeNames.WITH_VIDEO]: {
97 model: VideoChannelModel,
112 tableName: 'videoComment',
115 fields: [ 'videoId' ]
118 fields: [ 'videoId', 'originCommentId' ]
125 fields: [ 'accountId' ]
129 export class VideoCommentModel extends Model<VideoCommentModel> {
137 @Column(DataType.DATE)
141 @Is('VideoCommentUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
142 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
146 @Column(DataType.TEXT)
149 @ForeignKey(() => VideoCommentModel)
151 originCommentId: number
153 @BelongsTo(() => VideoCommentModel, {
155 name: 'originCommentId',
158 as: 'OriginVideoComment',
161 OriginVideoComment: VideoCommentModel
163 @ForeignKey(() => VideoCommentModel)
165 inReplyToCommentId: number
167 @BelongsTo(() => VideoCommentModel, {
169 name: 'inReplyToCommentId',
172 as: 'InReplyToVideoComment',
175 InReplyToVideoComment: VideoCommentModel | null
177 @ForeignKey(() => VideoModel)
181 @BelongsTo(() => VideoModel, {
189 @ForeignKey(() => AccountModel)
193 @BelongsTo(() => AccountModel, {
199 Account: AccountModel
201 static loadById (id: number, t?: Transaction): Bluebird<MComment> {
202 const query: FindOptions = {
208 if (t !== undefined) query.transaction = t
210 return VideoCommentModel.findOne(query)
213 static loadByIdAndPopulateVideoAndAccountAndReply (id: number, t?: Transaction): Bluebird<MCommentOwnerVideoReply> {
214 const query: FindOptions = {
220 if (t !== undefined) query.transaction = t
222 return VideoCommentModel
223 .scope([ ScopeNames.WITH_VIDEO, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_IN_REPLY_TO ])
227 static loadByUrlAndPopulateAccountAndVideo (url: string, t?: Transaction): Bluebird<MCommentOwnerVideo> {
228 const query: FindOptions = {
234 if (t !== undefined) query.transaction = t
236 return VideoCommentModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEO ]).findOne(query)
239 static loadByUrlAndPopulateReplyAndVideoUrlAndAccount (url: string, t?: Transaction): Bluebird<MCommentOwnerReplyVideoLight> {
240 const query: FindOptions = {
246 attributes: [ 'id', 'url' ],
247 model: VideoModel.unscoped()
252 if (t !== undefined) query.transaction = t
254 return VideoCommentModel.scope([ ScopeNames.WITH_IN_REPLY_TO, ScopeNames.WITH_ACCOUNT ]).findOne(query)
257 static async listThreadsForApi (parameters: {
262 user?: MUserAccountId
264 const { videoId, start, count, sort, user } = parameters
266 const serverActor = await getServerActor()
267 const serverAccountId = serverActor.Account.id
268 const userAccountId = user ? user.Account.id : undefined
273 order: getCommentSort(sort),
276 inReplyToCommentId: null,
278 [Op.notIn]: Sequelize.literal(
279 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
285 const scopes: (string | ScopeOptions)[] = [
286 ScopeNames.WITH_ACCOUNT,
288 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
292 return VideoCommentModel
294 .findAndCountAll(query)
295 .then(({ rows, count }) => {
296 return { total: count, data: rows }
300 static async listThreadCommentsForApi (parameters: {
303 user?: MUserAccountId
305 const { videoId, threadId, user } = parameters
307 const serverActor = await getServerActor()
308 const serverAccountId = serverActor.Account.id
309 const userAccountId = user ? user.Account.id : undefined
312 order: [ [ 'createdAt', 'ASC' ], [ 'updatedAt', 'ASC' ] ] as Order,
317 { originCommentId: threadId }
320 [Op.notIn]: Sequelize.literal(
321 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
327 const scopes: any[] = [
328 ScopeNames.WITH_ACCOUNT,
330 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
334 return VideoCommentModel
336 .findAndCountAll(query)
337 .then(({ rows, count }) => {
338 return { total: count, data: rows }
342 static listThreadParentComments (comment: MCommentId, t: Transaction, order: 'ASC' | 'DESC' = 'ASC'): Bluebird<MCommentOwner[]> {
344 order: [ [ 'createdAt', order ] ] as Order,
347 [ Op.in ]: Sequelize.literal('(' +
348 'WITH RECURSIVE children (id, "inReplyToCommentId") AS ( ' +
349 `SELECT id, "inReplyToCommentId" FROM "videoComment" WHERE id = ${comment.id} ` +
351 'SELECT "parent"."id", "parent"."inReplyToCommentId" FROM "videoComment" "parent" ' +
352 'INNER JOIN "children" ON "children"."inReplyToCommentId" = "parent"."id"' +
354 'SELECT id FROM children' +
356 [ Op.ne ]: comment.id
362 return VideoCommentModel
363 .scope([ ScopeNames.WITH_ACCOUNT ])
367 static listAndCountByVideoId (videoId: number, start: number, count: number, t?: Transaction, order: 'ASC' | 'DESC' = 'ASC') {
369 order: [ [ 'createdAt', order ] ] as Order,
378 return VideoCommentModel.findAndCountAll<MComment>(query)
381 static listForFeed (start: number, count: number, videoId?: number): Bluebird<MCommentOwnerVideoFeed[]> {
383 order: [ [ 'createdAt', 'DESC' ] ] as Order,
389 attributes: [ 'name', 'uuid' ],
390 model: VideoModel.unscoped(),
396 if (videoId) query.where['videoId'] = videoId
398 return VideoCommentModel
399 .scope([ ScopeNames.WITH_ACCOUNT ])
403 static async getStats () {
404 const totalLocalVideoComments = await VideoCommentModel.count({
421 const totalVideoComments = await VideoCommentModel.count()
424 totalLocalVideoComments,
429 static cleanOldCommentsOf (videoId: number, beforeUpdatedAt: Date) {
433 [Op.lt]: beforeUpdatedAt
437 [Op.notIn]: buildLocalAccountIdsIn()
442 return VideoCommentModel.destroy(query)
445 getCommentStaticPath () {
446 return this.Video.getWatchStaticPath() + ';threadId=' + this.getThreadId()
449 getThreadId (): number {
450 return this.originCommentId || this.id
458 return this.Account.isOwned()
462 return null !== this.deletedAt
466 let result: string[] = []
468 const localMention = `@(${actorNameAlphabet}+)`
469 const remoteMention = `${localMention}@${WEBSERVER.HOST}`
471 const mentionRegex = this.isOwned()
472 ? '(?:(?:' + remoteMention + ')|(?:' + localMention + '))' // Include local mentions?
473 : '(?:' + remoteMention + ')'
475 const firstMentionRegex = new RegExp(`^${mentionRegex} `, 'g')
476 const endMentionRegex = new RegExp(` ${mentionRegex}$`, 'g')
477 const remoteMentionsRegex = new RegExp(' ' + remoteMention + ' ', 'g')
479 result = result.concat(
480 regexpCapture(this.text, firstMentionRegex)
481 .map(([ , username1, username2 ]) => username1 || username2),
483 regexpCapture(this.text, endMentionRegex)
484 .map(([ , username1, username2 ]) => username1 || username2),
486 regexpCapture(this.text, remoteMentionsRegex)
487 .map(([ , username ]) => username)
490 // Include local mentions
491 if (this.isOwned()) {
492 const localMentionsRegex = new RegExp(' ' + localMention + ' ', 'g')
494 result = result.concat(
495 regexpCapture(this.text, localMentionsRegex)
496 .map(([ , username ]) => username)
503 toFormattedJSON (this: MCommentFormattable) {
508 threadId: this.originCommentId || this.id,
509 inReplyToCommentId: this.inReplyToCommentId || null,
510 videoId: this.videoId,
511 createdAt: this.createdAt,
512 updatedAt: this.updatedAt,
513 deletedAt: this.deletedAt,
514 isDeleted: this.isDeleted(),
515 totalRepliesFromVideoAuthor: this.get('totalRepliesFromVideoAuthor') || 0,
516 totalReplies: this.get('totalReplies') || 0,
517 account: this.Account ? this.Account.toFormattedJSON() : null
521 toActivityPubObject (this: MCommentAP, threadParentComments: MCommentOwner[]): VideoCommentObject | ActivityTombstoneObject {
522 let inReplyTo: string
523 // New thread, so in AS we reply to the video
524 if (this.inReplyToCommentId === null) {
525 inReplyTo = this.Video.url
527 inReplyTo = this.InReplyToVideoComment.url
530 if (this.isDeleted()) {
536 published: this.createdAt.toISOString(),
537 updated: this.updatedAt.toISOString(),
538 deleted: this.deletedAt.toISOString()
542 const tag: ActivityTagObject[] = []
543 for (const parentComment of threadParentComments) {
544 if (!parentComment.Account) continue
546 const actor = parentComment.Account.Actor
551 name: `@${actor.preferredUsername}@${actor.getHost()}`
556 type: 'Note' as 'Note',
560 updated: this.updatedAt.toISOString(),
561 published: this.createdAt.toISOString(),
563 attributedTo: this.Account.Actor.url,