14 } from 'sequelize-typescript'
15 import { ActivityTagObject } from '../../../shared/models/activitypub/objects/common-objects'
16 import { VideoCommentObject } from '../../../shared/models/activitypub/objects/video-comment-object'
17 import { VideoComment } from '../../../shared/models/videos/video-comment.model'
18 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
19 import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
20 import { sendDeleteVideoComment } from '../../lib/activitypub/send'
21 import { AccountModel } from '../account/account'
22 import { ActorModel } from '../activitypub/actor'
23 import { AvatarModel } from '../avatar/avatar'
24 import { ServerModel } from '../server/server'
25 import { buildBlockedAccountSQL, buildLocalAccountIdsIn, getSort, throwIfNotValid } from '../utils'
26 import { VideoModel } from './video'
27 import { VideoChannelModel } from './video-channel'
28 import { getServerActor } from '../../helpers/utils'
29 import { UserModel } from '../account/user'
30 import { actorNameAlphabet } from '../../helpers/custom-validators/activitypub/actor'
31 import { regexpCapture } from '../../helpers/regexp'
32 import { uniq } from 'lodash'
33 import { FindOptions, literal, Op, Order, ScopeOptions, Sequelize, Transaction } from 'sequelize'
36 WITH_ACCOUNT = 'WITH_ACCOUNT',
37 WITH_IN_REPLY_TO = 'WITH_IN_REPLY_TO',
38 WITH_VIDEO = 'WITH_VIDEO',
39 ATTRIBUTES_FOR_API = 'ATTRIBUTES_FOR_API'
43 [ScopeNames.ATTRIBUTES_FOR_API]: (serverAccountId: number, userAccountId?: number) => {
50 'WITH "blocklist" AS (' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')' +
51 'SELECT COUNT("replies"."id") - (' +
52 'SELECT COUNT("replies"."id") ' +
53 'FROM "videoComment" AS "replies" ' +
54 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
55 'AND "accountId" IN (SELECT "id" FROM "blocklist")' +
57 'FROM "videoComment" AS "replies" ' +
58 'WHERE "replies"."originCommentId" = "VideoCommentModel"."id" ' +
59 'AND "accountId" NOT IN (SELECT "id" FROM "blocklist")' +
68 [ScopeNames.WITH_ACCOUNT]: {
90 [ScopeNames.WITH_IN_REPLY_TO]: {
93 model: VideoCommentModel,
94 as: 'InReplyToVideoComment'
98 [ScopeNames.WITH_VIDEO]: {
105 model: VideoChannelModel.unscoped(),
130 tableName: 'videoComment',
133 fields: [ 'videoId' ]
136 fields: [ 'videoId', 'originCommentId' ]
143 fields: [ 'accountId' ]
147 export class VideoCommentModel extends Model<VideoCommentModel> {
155 @Is('VideoCommentUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
156 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
160 @Column(DataType.TEXT)
163 @ForeignKey(() => VideoCommentModel)
165 originCommentId: number
167 @BelongsTo(() => VideoCommentModel, {
169 name: 'originCommentId',
172 as: 'OriginVideoComment',
175 OriginVideoComment: VideoCommentModel
177 @ForeignKey(() => VideoCommentModel)
179 inReplyToCommentId: number
181 @BelongsTo(() => VideoCommentModel, {
183 name: 'inReplyToCommentId',
186 as: 'InReplyToVideoComment',
189 InReplyToVideoComment: VideoCommentModel | null
191 @ForeignKey(() => VideoModel)
195 @BelongsTo(() => VideoModel, {
203 @ForeignKey(() => AccountModel)
207 @BelongsTo(() => AccountModel, {
213 Account: AccountModel
215 static loadById (id: number, t?: Transaction) {
216 const query: FindOptions = {
222 if (t !== undefined) query.transaction = t
224 return VideoCommentModel.findOne(query)
227 static loadByIdAndPopulateVideoAndAccountAndReply (id: number, t?: Transaction) {
228 const query: FindOptions = {
234 if (t !== undefined) query.transaction = t
236 return VideoCommentModel
237 .scope([ ScopeNames.WITH_VIDEO, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_IN_REPLY_TO ])
241 static loadByUrlAndPopulateAccountAndVideo (url: string, t?: Transaction) {
242 const query: FindOptions = {
248 if (t !== undefined) query.transaction = t
250 return VideoCommentModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEO ]).findOne(query)
253 static loadByUrlAndPopulateReplyAndVideoUrlAndAccount (url: string, t?: Transaction) {
254 const query: FindOptions = {
260 attributes: [ 'id', 'url' ],
261 model: VideoModel.unscoped()
266 if (t !== undefined) query.transaction = t
268 return VideoCommentModel.scope([ ScopeNames.WITH_IN_REPLY_TO, ScopeNames.WITH_ACCOUNT ]).findOne(query)
271 static async listThreadsForApi (parameters: {
278 const { videoId, start, count, sort, user } = parameters
280 const serverActor = await getServerActor()
281 const serverAccountId = serverActor.Account.id
282 const userAccountId = user ? user.Account.id : undefined
287 order: getSort(sort),
290 inReplyToCommentId: null,
292 [Op.notIn]: Sequelize.literal(
293 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
299 const scopes: (string | ScopeOptions)[] = [
300 ScopeNames.WITH_ACCOUNT,
302 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
306 return VideoCommentModel
308 .findAndCountAll(query)
309 .then(({ rows, count }) => {
310 return { total: count, data: rows }
314 static async listThreadCommentsForApi (parameters: {
319 const { videoId, threadId, user } = parameters
321 const serverActor = await getServerActor()
322 const serverAccountId = serverActor.Account.id
323 const userAccountId = user ? user.Account.id : undefined
326 order: [ [ 'createdAt', 'ASC' ], [ 'updatedAt', 'ASC' ] ] as Order,
331 { originCommentId: threadId }
334 [Op.notIn]: Sequelize.literal(
335 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
341 const scopes: any[] = [
342 ScopeNames.WITH_ACCOUNT,
344 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
348 return VideoCommentModel
350 .findAndCountAll(query)
351 .then(({ rows, count }) => {
352 return { total: count, data: rows }
356 static listThreadParentComments (comment: VideoCommentModel, t: Transaction, order: 'ASC' | 'DESC' = 'ASC') {
358 order: [ [ 'createdAt', order ] ] as Order,
361 [ Op.in ]: Sequelize.literal('(' +
362 'WITH RECURSIVE children (id, "inReplyToCommentId") AS ( ' +
363 `SELECT id, "inReplyToCommentId" FROM "videoComment" WHERE id = ${comment.id} ` +
365 'SELECT "parent"."id", "parent"."inReplyToCommentId" FROM "videoComment" "parent" ' +
366 'INNER JOIN "children" ON "children"."inReplyToCommentId" = "parent"."id"' +
368 'SELECT id FROM children' +
370 [ Op.ne ]: comment.id
376 return VideoCommentModel
377 .scope([ ScopeNames.WITH_ACCOUNT ])
381 static listAndCountByVideoId (videoId: number, start: number, count: number, t?: Transaction, order: 'ASC' | 'DESC' = 'ASC') {
383 order: [ [ 'createdAt', order ] ] as Order,
392 return VideoCommentModel.findAndCountAll(query)
395 static listForFeed (start: number, count: number, videoId?: number) {
397 order: [ [ 'createdAt', 'DESC' ] ] as Order,
403 attributes: [ 'name', 'uuid' ],
404 model: VideoModel.unscoped(),
410 if (videoId) query.where['videoId'] = videoId
412 return VideoCommentModel
413 .scope([ ScopeNames.WITH_ACCOUNT ])
417 static async getStats () {
418 const totalLocalVideoComments = await VideoCommentModel.count({
435 const totalVideoComments = await VideoCommentModel.count()
438 totalLocalVideoComments,
443 static cleanOldCommentsOf (videoId: number, beforeUpdatedAt: Date) {
447 [Op.lt]: beforeUpdatedAt
451 [Op.notIn]: buildLocalAccountIdsIn()
456 return VideoCommentModel.destroy(query)
459 getCommentStaticPath () {
460 return this.Video.getWatchStaticPath() + ';threadId=' + this.getThreadId()
463 getThreadId (): number {
464 return this.originCommentId || this.id
468 return this.Account.isOwned()
472 let result: string[] = []
474 const localMention = `@(${actorNameAlphabet}+)`
475 const remoteMention = `${localMention}@${WEBSERVER.HOST}`
477 const mentionRegex = this.isOwned()
478 ? '(?:(?:' + remoteMention + ')|(?:' + localMention + '))' // Include local mentions?
479 : '(?:' + remoteMention + ')'
481 const firstMentionRegex = new RegExp(`^${mentionRegex} `, 'g')
482 const endMentionRegex = new RegExp(` ${mentionRegex}$`, 'g')
483 const remoteMentionsRegex = new RegExp(' ' + remoteMention + ' ', 'g')
485 result = result.concat(
486 regexpCapture(this.text, firstMentionRegex)
487 .map(([ , username1, username2 ]) => username1 || username2),
489 regexpCapture(this.text, endMentionRegex)
490 .map(([ , username1, username2 ]) => username1 || username2),
492 regexpCapture(this.text, remoteMentionsRegex)
493 .map(([ , username ]) => username)
496 // Include local mentions
497 if (this.isOwned()) {
498 const localMentionsRegex = new RegExp(' ' + localMention + ' ', 'g')
500 result = result.concat(
501 regexpCapture(this.text, localMentionsRegex)
502 .map(([ , username ]) => username)
514 threadId: this.originCommentId || this.id,
515 inReplyToCommentId: this.inReplyToCommentId || null,
516 videoId: this.videoId,
517 createdAt: this.createdAt,
518 updatedAt: this.updatedAt,
519 totalReplies: this.get('totalReplies') || 0,
520 account: this.Account.toFormattedJSON()
524 toActivityPubObject (threadParentComments: VideoCommentModel[]): VideoCommentObject {
525 let inReplyTo: string
526 // New thread, so in AS we reply to the video
527 if (this.inReplyToCommentId === null) {
528 inReplyTo = this.Video.url
530 inReplyTo = this.InReplyToVideoComment.url
533 const tag: ActivityTagObject[] = []
534 for (const parentComment of threadParentComments) {
535 const actor = parentComment.Account.Actor
540 name: `@${actor.preferredUsername}@${actor.getHost()}`
545 type: 'Note' as 'Note',
549 updated: this.updatedAt.toISOString(),
550 published: this.createdAt.toISOString(),
552 attributedTo: this.Account.Actor.url,