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'
30 import { VideoPrivacy } from '@shared/models'
33 WITH_ACCOUNT = 'WITH_ACCOUNT',
34 WITH_IN_REPLY_TO = 'WITH_IN_REPLY_TO',
35 WITH_VIDEO = 'WITH_VIDEO',
36 ATTRIBUTES_FOR_API = 'ATTRIBUTES_FOR_API'
40 [ScopeNames.ATTRIBUTES_FOR_API]: (serverAccountId: number, userAccountId?: number) => {
47 'WITH "blocklist" AS (' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')' +
48 'SELECT COUNT("replies"."id") - (' +
49 'SELECT COUNT("replies"."id") ' +
50 'FROM "videoComment" AS "replies" ' +
51 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
52 'AND "accountId" IN (SELECT "id" FROM "blocklist")' +
54 'FROM "videoComment" AS "replies" ' +
55 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
56 'AND "accountId" NOT IN (SELECT "id" FROM "blocklist")' +
64 'SELECT COUNT("replies"."id") ' +
65 'FROM "videoComment" AS "replies" ' +
66 'INNER JOIN "video" ON "video"."id" = "replies"."videoId" ' +
67 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
68 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
69 'AND "replies"."accountId" = "videoChannel"."accountId"' +
72 'totalRepliesFromVideoAuthor'
78 [ScopeNames.WITH_ACCOUNT]: {
85 [ScopeNames.WITH_IN_REPLY_TO]: {
88 model: VideoCommentModel,
89 as: 'InReplyToVideoComment'
93 [ScopeNames.WITH_VIDEO]: {
100 model: VideoChannelModel,
115 tableName: 'videoComment',
118 fields: [ 'videoId' ]
121 fields: [ 'videoId', 'originCommentId' ]
128 fields: [ 'accountId' ]
132 export class VideoCommentModel extends Model<VideoCommentModel> {
140 @Column(DataType.DATE)
144 @Is('VideoCommentUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
145 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
149 @Column(DataType.TEXT)
152 @ForeignKey(() => VideoCommentModel)
154 originCommentId: number
156 @BelongsTo(() => VideoCommentModel, {
158 name: 'originCommentId',
161 as: 'OriginVideoComment',
164 OriginVideoComment: VideoCommentModel
166 @ForeignKey(() => VideoCommentModel)
168 inReplyToCommentId: number
170 @BelongsTo(() => VideoCommentModel, {
172 name: 'inReplyToCommentId',
175 as: 'InReplyToVideoComment',
178 InReplyToVideoComment: VideoCommentModel | null
180 @ForeignKey(() => VideoModel)
184 @BelongsTo(() => VideoModel, {
192 @ForeignKey(() => AccountModel)
196 @BelongsTo(() => AccountModel, {
202 Account: AccountModel
204 static loadById (id: number, t?: Transaction): Bluebird<MComment> {
205 const query: FindOptions = {
211 if (t !== undefined) query.transaction = t
213 return VideoCommentModel.findOne(query)
216 static loadByIdAndPopulateVideoAndAccountAndReply (id: number, t?: Transaction): Bluebird<MCommentOwnerVideoReply> {
217 const query: FindOptions = {
223 if (t !== undefined) query.transaction = t
225 return VideoCommentModel
226 .scope([ ScopeNames.WITH_VIDEO, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_IN_REPLY_TO ])
230 static loadByUrlAndPopulateAccountAndVideo (url: string, t?: Transaction): Bluebird<MCommentOwnerVideo> {
231 const query: FindOptions = {
237 if (t !== undefined) query.transaction = t
239 return VideoCommentModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEO ]).findOne(query)
242 static loadByUrlAndPopulateReplyAndVideoUrlAndAccount (url: string, t?: Transaction): Bluebird<MCommentOwnerReplyVideoLight> {
243 const query: FindOptions = {
249 attributes: [ 'id', 'url' ],
250 model: VideoModel.unscoped()
255 if (t !== undefined) query.transaction = t
257 return VideoCommentModel.scope([ ScopeNames.WITH_IN_REPLY_TO, ScopeNames.WITH_ACCOUNT ]).findOne(query)
260 static async listThreadsForApi (parameters: {
265 user?: MUserAccountId
267 const { videoId, start, count, sort, user } = parameters
269 const serverActor = await getServerActor()
270 const serverAccountId = serverActor.Account.id
271 const userAccountId = user ? user.Account.id : undefined
276 order: getCommentSort(sort),
279 inReplyToCommentId: null,
281 [Op.notIn]: Sequelize.literal(
282 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
288 const scopes: (string | ScopeOptions)[] = [
289 ScopeNames.WITH_ACCOUNT,
291 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
295 return VideoCommentModel
297 .findAndCountAll(query)
298 .then(({ rows, count }) => {
299 return { total: count, data: rows }
303 static async listThreadCommentsForApi (parameters: {
306 user?: MUserAccountId
308 const { videoId, threadId, user } = parameters
310 const serverActor = await getServerActor()
311 const serverAccountId = serverActor.Account.id
312 const userAccountId = user ? user.Account.id : undefined
315 order: [ [ 'createdAt', 'ASC' ], [ 'updatedAt', 'ASC' ] ] as Order,
320 { originCommentId: threadId }
323 [Op.notIn]: Sequelize.literal(
324 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
330 const scopes: any[] = [
331 ScopeNames.WITH_ACCOUNT,
333 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
337 return VideoCommentModel
339 .findAndCountAll(query)
340 .then(({ rows, count }) => {
341 return { total: count, data: rows }
345 static listThreadParentComments (comment: MCommentId, t: Transaction, order: 'ASC' | 'DESC' = 'ASC'): Bluebird<MCommentOwner[]> {
347 order: [ [ 'createdAt', order ] ] as Order,
350 [Op.in]: Sequelize.literal('(' +
351 'WITH RECURSIVE children (id, "inReplyToCommentId") AS ( ' +
352 `SELECT id, "inReplyToCommentId" FROM "videoComment" WHERE id = ${comment.id} ` +
354 'SELECT "parent"."id", "parent"."inReplyToCommentId" FROM "videoComment" "parent" ' +
355 'INNER JOIN "children" ON "children"."inReplyToCommentId" = "parent"."id"' +
357 'SELECT id FROM children' +
365 return VideoCommentModel
366 .scope([ ScopeNames.WITH_ACCOUNT ])
370 static listAndCountByVideoId (videoId: number, start: number, count: number, t?: Transaction, order: 'ASC' | 'DESC' = 'ASC') {
372 order: [ [ 'createdAt', order ] ] as Order,
381 return VideoCommentModel.findAndCountAll<MComment>(query)
384 static listForFeed (start: number, count: number, videoId?: number): Bluebird<MCommentOwnerVideoFeed[]> {
386 order: [ [ 'createdAt', 'DESC' ] ] as Order,
394 attributes: [ 'name', 'uuid' ],
395 model: VideoModel.unscoped(),
398 privacy: VideoPrivacy.PUBLIC
404 if (videoId) query.where['videoId'] = videoId
406 return VideoCommentModel
407 .scope([ ScopeNames.WITH_ACCOUNT ])
411 static async getStats () {
412 const totalLocalVideoComments = await VideoCommentModel.count({
429 const totalVideoComments = await VideoCommentModel.count()
432 totalLocalVideoComments,
437 static cleanOldCommentsOf (videoId: number, beforeUpdatedAt: Date) {
441 [Op.lt]: beforeUpdatedAt
445 [Op.notIn]: buildLocalAccountIdsIn()
450 return VideoCommentModel.destroy(query)
453 getCommentStaticPath () {
454 return this.Video.getWatchStaticPath() + ';threadId=' + this.getThreadId()
457 getThreadId (): number {
458 return this.originCommentId || this.id
466 return this.Account.isOwned()
470 return this.deletedAt !== null
474 let result: string[] = []
476 const localMention = `@(${actorNameAlphabet}+)`
477 const remoteMention = `${localMention}@${WEBSERVER.HOST}`
479 const mentionRegex = this.isOwned()
480 ? '(?:(?:' + remoteMention + ')|(?:' + localMention + '))' // Include local mentions?
481 : '(?:' + remoteMention + ')'
483 const firstMentionRegex = new RegExp(`^${mentionRegex} `, 'g')
484 const endMentionRegex = new RegExp(` ${mentionRegex}$`, 'g')
485 const remoteMentionsRegex = new RegExp(' ' + remoteMention + ' ', 'g')
487 result = result.concat(
488 regexpCapture(this.text, firstMentionRegex)
489 .map(([ , username1, username2 ]) => username1 || username2),
491 regexpCapture(this.text, endMentionRegex)
492 .map(([ , username1, username2 ]) => username1 || username2),
494 regexpCapture(this.text, remoteMentionsRegex)
495 .map(([ , username ]) => username)
498 // Include local mentions
499 if (this.isOwned()) {
500 const localMentionsRegex = new RegExp(' ' + localMention + ' ', 'g')
502 result = result.concat(
503 regexpCapture(this.text, localMentionsRegex)
504 .map(([ , username ]) => username)
511 toFormattedJSON (this: MCommentFormattable) {
516 threadId: this.originCommentId || this.id,
517 inReplyToCommentId: this.inReplyToCommentId || null,
518 videoId: this.videoId,
519 createdAt: this.createdAt,
520 updatedAt: this.updatedAt,
521 deletedAt: this.deletedAt,
522 isDeleted: this.isDeleted(),
523 totalRepliesFromVideoAuthor: this.get('totalRepliesFromVideoAuthor') || 0,
524 totalReplies: this.get('totalReplies') || 0,
525 account: this.Account ? this.Account.toFormattedJSON() : null
529 toActivityPubObject (this: MCommentAP, threadParentComments: MCommentOwner[]): VideoCommentObject | ActivityTombstoneObject {
530 let inReplyTo: string
531 // New thread, so in AS we reply to the video
532 if (this.inReplyToCommentId === null) {
533 inReplyTo = this.Video.url
535 inReplyTo = this.InReplyToVideoComment.url
538 if (this.isDeleted()) {
544 published: this.createdAt.toISOString(),
545 updated: this.updatedAt.toISOString(),
546 deleted: this.deletedAt.toISOString()
550 const tag: ActivityTagObject[] = []
551 for (const parentComment of threadParentComments) {
552 if (!parentComment.Account) continue
554 const actor = parentComment.Account.Actor
559 name: `@${actor.preferredUsername}@${actor.getHost()}`
564 type: 'Note' as 'Note',
568 updated: this.updatedAt.toISOString(),
569 published: this.createdAt.toISOString(),
571 attributedTo: this.Account.Actor.url,