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, 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'
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")' +
64 [ScopeNames.WITH_ACCOUNT]: {
71 [ScopeNames.WITH_IN_REPLY_TO]: {
74 model: VideoCommentModel,
75 as: 'InReplyToVideoComment'
79 [ScopeNames.WITH_VIDEO]: {
86 model: VideoChannelModel,
101 tableName: 'videoComment',
104 fields: [ 'videoId' ]
107 fields: [ 'videoId', 'originCommentId' ]
114 fields: [ 'accountId' ]
118 export class VideoCommentModel extends Model<VideoCommentModel> {
126 @Column(DataType.DATE)
130 @Is('VideoCommentUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
131 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
135 @Column(DataType.TEXT)
138 @ForeignKey(() => VideoCommentModel)
140 originCommentId: number
142 @BelongsTo(() => VideoCommentModel, {
144 name: 'originCommentId',
147 as: 'OriginVideoComment',
150 OriginVideoComment: VideoCommentModel
152 @ForeignKey(() => VideoCommentModel)
154 inReplyToCommentId: number
156 @BelongsTo(() => VideoCommentModel, {
158 name: 'inReplyToCommentId',
161 as: 'InReplyToVideoComment',
164 InReplyToVideoComment: VideoCommentModel | null
166 @ForeignKey(() => VideoModel)
170 @BelongsTo(() => VideoModel, {
178 @ForeignKey(() => AccountModel)
182 @BelongsTo(() => AccountModel, {
188 Account: AccountModel
190 static loadById (id: number, t?: Transaction): Bluebird<MComment> {
191 const query: FindOptions = {
197 if (t !== undefined) query.transaction = t
199 return VideoCommentModel.findOne(query)
202 static loadByIdAndPopulateVideoAndAccountAndReply (id: number, t?: Transaction): Bluebird<MCommentOwnerVideoReply> {
203 const query: FindOptions = {
209 if (t !== undefined) query.transaction = t
211 return VideoCommentModel
212 .scope([ ScopeNames.WITH_VIDEO, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_IN_REPLY_TO ])
216 static loadByUrlAndPopulateAccountAndVideo (url: string, t?: Transaction): Bluebird<MCommentOwnerVideo> {
217 const query: FindOptions = {
223 if (t !== undefined) query.transaction = t
225 return VideoCommentModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEO ]).findOne(query)
228 static loadByUrlAndPopulateReplyAndVideoUrlAndAccount (url: string, t?: Transaction): Bluebird<MCommentOwnerReplyVideoLight> {
229 const query: FindOptions = {
235 attributes: [ 'id', 'url' ],
236 model: VideoModel.unscoped()
241 if (t !== undefined) query.transaction = t
243 return VideoCommentModel.scope([ ScopeNames.WITH_IN_REPLY_TO, ScopeNames.WITH_ACCOUNT ]).findOne(query)
246 static async listThreadsForApi (parameters: {
251 user?: MUserAccountId
253 const { videoId, start, count, sort, user } = parameters
255 const serverActor = await getServerActor()
256 const serverAccountId = serverActor.Account.id
257 const userAccountId = user ? user.Account.id : undefined
262 order: getSort(sort),
265 inReplyToCommentId: null,
267 [Op.notIn]: Sequelize.literal(
268 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
274 const scopes: (string | ScopeOptions)[] = [
275 ScopeNames.WITH_ACCOUNT,
277 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
281 return VideoCommentModel
283 .findAndCountAll(query)
284 .then(({ rows, count }) => {
285 return { total: count, data: rows }
289 static async listThreadCommentsForApi (parameters: {
292 user?: MUserAccountId
294 const { videoId, threadId, user } = parameters
296 const serverActor = await getServerActor()
297 const serverAccountId = serverActor.Account.id
298 const userAccountId = user ? user.Account.id : undefined
301 order: [ [ 'createdAt', 'ASC' ], [ 'updatedAt', 'ASC' ] ] as Order,
306 { originCommentId: threadId }
309 [Op.notIn]: Sequelize.literal(
310 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
316 const scopes: any[] = [
317 ScopeNames.WITH_ACCOUNT,
319 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
323 return VideoCommentModel
325 .findAndCountAll(query)
326 .then(({ rows, count }) => {
327 return { total: count, data: rows }
331 static listThreadParentComments (comment: MCommentId, t: Transaction, order: 'ASC' | 'DESC' = 'ASC'): Bluebird<MCommentOwner[]> {
333 order: [ [ 'createdAt', order ] ] as Order,
336 [ Op.in ]: Sequelize.literal('(' +
337 'WITH RECURSIVE children (id, "inReplyToCommentId") AS ( ' +
338 `SELECT id, "inReplyToCommentId" FROM "videoComment" WHERE id = ${comment.id} ` +
340 'SELECT "parent"."id", "parent"."inReplyToCommentId" FROM "videoComment" "parent" ' +
341 'INNER JOIN "children" ON "children"."inReplyToCommentId" = "parent"."id"' +
343 'SELECT id FROM children' +
345 [ Op.ne ]: comment.id
351 return VideoCommentModel
352 .scope([ ScopeNames.WITH_ACCOUNT ])
356 static listAndCountByVideoId (videoId: number, start: number, count: number, t?: Transaction, order: 'ASC' | 'DESC' = 'ASC') {
358 order: [ [ 'createdAt', order ] ] as Order,
367 return VideoCommentModel.findAndCountAll<MComment>(query)
370 static listForFeed (start: number, count: number, videoId?: number): Bluebird<MCommentOwnerVideoFeed[]> {
372 order: [ [ 'createdAt', 'DESC' ] ] as Order,
378 attributes: [ 'name', 'uuid' ],
379 model: VideoModel.unscoped(),
385 if (videoId) query.where['videoId'] = videoId
387 return VideoCommentModel
388 .scope([ ScopeNames.WITH_ACCOUNT ])
392 static async getStats () {
393 const totalLocalVideoComments = await VideoCommentModel.count({
410 const totalVideoComments = await VideoCommentModel.count()
413 totalLocalVideoComments,
418 static cleanOldCommentsOf (videoId: number, beforeUpdatedAt: Date) {
422 [Op.lt]: beforeUpdatedAt
426 [Op.notIn]: buildLocalAccountIdsIn()
431 return VideoCommentModel.destroy(query)
434 getCommentStaticPath () {
435 return this.Video.getWatchStaticPath() + ';threadId=' + this.getThreadId()
438 getThreadId (): number {
439 return this.originCommentId || this.id
447 return this.Account.isOwned()
451 return null !== this.deletedAt
455 let result: string[] = []
457 const localMention = `@(${actorNameAlphabet}+)`
458 const remoteMention = `${localMention}@${WEBSERVER.HOST}`
460 const mentionRegex = this.isOwned()
461 ? '(?:(?:' + remoteMention + ')|(?:' + localMention + '))' // Include local mentions?
462 : '(?:' + remoteMention + ')'
464 const firstMentionRegex = new RegExp(`^${mentionRegex} `, 'g')
465 const endMentionRegex = new RegExp(` ${mentionRegex}$`, 'g')
466 const remoteMentionsRegex = new RegExp(' ' + remoteMention + ' ', 'g')
468 result = result.concat(
469 regexpCapture(this.text, firstMentionRegex)
470 .map(([ , username1, username2 ]) => username1 || username2),
472 regexpCapture(this.text, endMentionRegex)
473 .map(([ , username1, username2 ]) => username1 || username2),
475 regexpCapture(this.text, remoteMentionsRegex)
476 .map(([ , username ]) => username)
479 // Include local mentions
480 if (this.isOwned()) {
481 const localMentionsRegex = new RegExp(' ' + localMention + ' ', 'g')
483 result = result.concat(
484 regexpCapture(this.text, localMentionsRegex)
485 .map(([ , username ]) => username)
492 toFormattedJSON (this: MCommentFormattable) {
497 threadId: this.originCommentId || this.id,
498 inReplyToCommentId: this.inReplyToCommentId || null,
499 videoId: this.videoId,
500 createdAt: this.createdAt,
501 updatedAt: this.updatedAt,
502 deletedAt: this.deletedAt,
503 isDeleted: this.isDeleted(),
504 totalReplies: this.get('totalReplies') || 0,
505 account: this.Account ? this.Account.toFormattedJSON() : null
509 toActivityPubObject (this: MCommentAP, threadParentComments: MCommentOwner[]): VideoCommentObject | ActivityTombstoneObject {
510 if (this.isDeleted()) {
515 published: this.createdAt.toISOString(),
516 updated: this.updatedAt.toISOString(),
517 deleted: this.deletedAt.toISOString()
521 let inReplyTo: string
522 // New thread, so in AS we reply to the video
523 if (this.inReplyToCommentId === null) {
524 inReplyTo = this.Video.url
526 inReplyTo = this.InReplyToVideoComment.url
529 const tag: ActivityTagObject[] = []
530 for (const parentComment of threadParentComments) {
531 const actor = parentComment.Account.Actor
536 name: `@${actor.preferredUsername}@${actor.getHost()}`
541 type: 'Note' as 'Note',
545 updated: this.updatedAt.toISOString(),
546 published: this.createdAt.toISOString(),
548 attributedTo: this.Account.Actor.url,