1 import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, Is, Model, Scopes, Table, UpdatedAt } from 'sequelize-typescript'
2 import { ActivityTagObject } 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, getSort, 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'
23 MCommentOwnerReplyVideoLight,
25 MCommentOwnerVideoFeed,
26 MCommentOwnerVideoReply
27 } from '../../typings/models/video'
28 import { MUserAccountId } from '@server/typings/models'
31 WITH_ACCOUNT = 'WITH_ACCOUNT',
32 WITH_IN_REPLY_TO = 'WITH_IN_REPLY_TO',
33 WITH_VIDEO = 'WITH_VIDEO',
34 ATTRIBUTES_FOR_API = 'ATTRIBUTES_FOR_API'
38 [ScopeNames.ATTRIBUTES_FOR_API]: (serverAccountId: number, userAccountId?: number) => {
45 'WITH "blocklist" AS (' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')' +
46 'SELECT COUNT("replies"."id") - (' +
47 'SELECT COUNT("replies"."id") ' +
48 'FROM "videoComment" AS "replies" ' +
49 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
50 'AND "accountId" IN (SELECT "id" FROM "blocklist")' +
52 'FROM "videoComment" AS "replies" ' +
53 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
54 'AND "accountId" NOT IN (SELECT "id" FROM "blocklist")' +
63 [ScopeNames.WITH_ACCOUNT]: {
70 [ScopeNames.WITH_IN_REPLY_TO]: {
73 model: VideoCommentModel,
74 as: 'InReplyToVideoComment'
78 [ScopeNames.WITH_VIDEO]: {
85 model: VideoChannelModel,
100 tableName: 'videoComment',
103 fields: [ 'videoId' ]
106 fields: [ 'videoId', 'originCommentId' ]
113 fields: [ 'accountId' ]
117 export class VideoCommentModel extends Model<VideoCommentModel> {
125 @Is('VideoCommentUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
126 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
130 @Column(DataType.TEXT)
133 @ForeignKey(() => VideoCommentModel)
135 originCommentId: number
137 @BelongsTo(() => VideoCommentModel, {
139 name: 'originCommentId',
142 as: 'OriginVideoComment',
145 OriginVideoComment: VideoCommentModel
147 @ForeignKey(() => VideoCommentModel)
149 inReplyToCommentId: number
151 @BelongsTo(() => VideoCommentModel, {
153 name: 'inReplyToCommentId',
156 as: 'InReplyToVideoComment',
159 InReplyToVideoComment: VideoCommentModel | null
161 @ForeignKey(() => VideoModel)
165 @BelongsTo(() => VideoModel, {
173 @ForeignKey(() => AccountModel)
177 @BelongsTo(() => AccountModel, {
183 Account: AccountModel
185 static loadById (id: number, t?: Transaction): Bluebird<MComment> {
186 const query: FindOptions = {
192 if (t !== undefined) query.transaction = t
194 return VideoCommentModel.findOne(query)
197 static loadByIdAndPopulateVideoAndAccountAndReply (id: number, t?: Transaction): Bluebird<MCommentOwnerVideoReply> {
198 const query: FindOptions = {
204 if (t !== undefined) query.transaction = t
206 return VideoCommentModel
207 .scope([ ScopeNames.WITH_VIDEO, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_IN_REPLY_TO ])
211 static loadByUrlAndPopulateAccountAndVideo (url: string, t?: Transaction): Bluebird<MCommentOwnerVideo> {
212 const query: FindOptions = {
218 if (t !== undefined) query.transaction = t
220 return VideoCommentModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEO ]).findOne(query)
223 static loadByUrlAndPopulateReplyAndVideoUrlAndAccount (url: string, t?: Transaction): Bluebird<MCommentOwnerReplyVideoLight> {
224 const query: FindOptions = {
230 attributes: [ 'id', 'url' ],
231 model: VideoModel.unscoped()
236 if (t !== undefined) query.transaction = t
238 return VideoCommentModel.scope([ ScopeNames.WITH_IN_REPLY_TO, ScopeNames.WITH_ACCOUNT ]).findOne(query)
241 static async listThreadsForApi (parameters: {
246 user?: MUserAccountId
248 const { videoId, start, count, sort, user } = parameters
250 const serverActor = await getServerActor()
251 const serverAccountId = serverActor.Account.id
252 const userAccountId = user ? user.Account.id : undefined
257 order: getSort(sort),
260 inReplyToCommentId: null,
262 [Op.notIn]: Sequelize.literal(
263 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
269 const scopes: (string | ScopeOptions)[] = [
270 ScopeNames.WITH_ACCOUNT,
272 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
276 return VideoCommentModel
278 .findAndCountAll(query)
279 .then(({ rows, count }) => {
280 return { total: count, data: rows }
284 static async listThreadCommentsForApi (parameters: {
287 user?: MUserAccountId
289 const { videoId, threadId, user } = parameters
291 const serverActor = await getServerActor()
292 const serverAccountId = serverActor.Account.id
293 const userAccountId = user ? user.Account.id : undefined
296 order: [ [ 'createdAt', 'ASC' ], [ 'updatedAt', 'ASC' ] ] as Order,
301 { originCommentId: threadId }
304 [Op.notIn]: Sequelize.literal(
305 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
311 const scopes: any[] = [
312 ScopeNames.WITH_ACCOUNT,
314 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
318 return VideoCommentModel
320 .findAndCountAll(query)
321 .then(({ rows, count }) => {
322 return { total: count, data: rows }
326 static listThreadParentComments (comment: MCommentId, t: Transaction, order: 'ASC' | 'DESC' = 'ASC'): Bluebird<MCommentOwner[]> {
328 order: [ [ 'createdAt', order ] ] as Order,
331 [ Op.in ]: Sequelize.literal('(' +
332 'WITH RECURSIVE children (id, "inReplyToCommentId") AS ( ' +
333 `SELECT id, "inReplyToCommentId" FROM "videoComment" WHERE id = ${comment.id} ` +
335 'SELECT "parent"."id", "parent"."inReplyToCommentId" FROM "videoComment" "parent" ' +
336 'INNER JOIN "children" ON "children"."inReplyToCommentId" = "parent"."id"' +
338 'SELECT id FROM children' +
340 [ Op.ne ]: comment.id
346 return VideoCommentModel
347 .scope([ ScopeNames.WITH_ACCOUNT ])
351 static listAndCountByVideoId (videoId: number, start: number, count: number, t?: Transaction, order: 'ASC' | 'DESC' = 'ASC') {
353 order: [ [ 'createdAt', order ] ] as Order,
362 return VideoCommentModel.findAndCountAll<MComment>(query)
365 static listForFeed (start: number, count: number, videoId?: number): Bluebird<MCommentOwnerVideoFeed[]> {
367 order: [ [ 'createdAt', 'DESC' ] ] as Order,
373 attributes: [ 'name', 'uuid' ],
374 model: VideoModel.unscoped(),
380 if (videoId) query.where['videoId'] = videoId
382 return VideoCommentModel
383 .scope([ ScopeNames.WITH_ACCOUNT ])
387 static async getStats () {
388 const totalLocalVideoComments = await VideoCommentModel.count({
405 const totalVideoComments = await VideoCommentModel.count()
408 totalLocalVideoComments,
413 static cleanOldCommentsOf (videoId: number, beforeUpdatedAt: Date) {
417 [Op.lt]: beforeUpdatedAt
421 [Op.notIn]: buildLocalAccountIdsIn()
426 return VideoCommentModel.destroy(query)
429 getCommentStaticPath () {
430 return this.Video.getWatchStaticPath() + ';threadId=' + this.getThreadId()
433 getThreadId (): number {
434 return this.originCommentId || this.id
438 return this.Account.isOwned()
442 let result: string[] = []
444 const localMention = `@(${actorNameAlphabet}+)`
445 const remoteMention = `${localMention}@${WEBSERVER.HOST}`
447 const mentionRegex = this.isOwned()
448 ? '(?:(?:' + remoteMention + ')|(?:' + localMention + '))' // Include local mentions?
449 : '(?:' + remoteMention + ')'
451 const firstMentionRegex = new RegExp(`^${mentionRegex} `, 'g')
452 const endMentionRegex = new RegExp(` ${mentionRegex}$`, 'g')
453 const remoteMentionsRegex = new RegExp(' ' + remoteMention + ' ', 'g')
455 result = result.concat(
456 regexpCapture(this.text, firstMentionRegex)
457 .map(([ , username1, username2 ]) => username1 || username2),
459 regexpCapture(this.text, endMentionRegex)
460 .map(([ , username1, username2 ]) => username1 || username2),
462 regexpCapture(this.text, remoteMentionsRegex)
463 .map(([ , username ]) => username)
466 // Include local mentions
467 if (this.isOwned()) {
468 const localMentionsRegex = new RegExp(' ' + localMention + ' ', 'g')
470 result = result.concat(
471 regexpCapture(this.text, localMentionsRegex)
472 .map(([ , username ]) => username)
479 toFormattedJSON (this: MCommentFormattable) {
484 threadId: this.originCommentId || this.id,
485 inReplyToCommentId: this.inReplyToCommentId || null,
486 videoId: this.videoId,
487 createdAt: this.createdAt,
488 updatedAt: this.updatedAt,
489 totalReplies: this.get('totalReplies') || 0,
490 account: this.Account.toFormattedJSON()
494 toActivityPubObject (threadParentComments: MCommentOwner[]): VideoCommentObject {
495 let inReplyTo: string
496 // New thread, so in AS we reply to the video
497 if (this.inReplyToCommentId === null) {
498 inReplyTo = this.Video.url
500 inReplyTo = this.InReplyToVideoComment.url
503 const tag: ActivityTagObject[] = []
504 for (const parentComment of threadParentComments) {
505 const actor = parentComment.Account.Actor
510 name: `@${actor.preferredUsername}@${actor.getHost()}`
515 type: 'Note' as 'Note',
519 updated: this.updatedAt.toISOString(),
520 published: this.createdAt.toISOString(),
522 attributedTo: this.Account.Actor.url,