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'
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 @Is('VideoCommentUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
127 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
131 @Column(DataType.TEXT)
134 @ForeignKey(() => VideoCommentModel)
136 originCommentId: number
138 @BelongsTo(() => VideoCommentModel, {
140 name: 'originCommentId',
143 as: 'OriginVideoComment',
146 OriginVideoComment: VideoCommentModel
148 @ForeignKey(() => VideoCommentModel)
150 inReplyToCommentId: number
152 @BelongsTo(() => VideoCommentModel, {
154 name: 'inReplyToCommentId',
157 as: 'InReplyToVideoComment',
160 InReplyToVideoComment: VideoCommentModel | null
162 @ForeignKey(() => VideoModel)
166 @BelongsTo(() => VideoModel, {
174 @ForeignKey(() => AccountModel)
178 @BelongsTo(() => AccountModel, {
184 Account: AccountModel
186 static loadById (id: number, t?: Transaction): Bluebird<MComment> {
187 const query: FindOptions = {
193 if (t !== undefined) query.transaction = t
195 return VideoCommentModel.findOne(query)
198 static loadByIdAndPopulateVideoAndAccountAndReply (id: number, t?: Transaction): Bluebird<MCommentOwnerVideoReply> {
199 const query: FindOptions = {
205 if (t !== undefined) query.transaction = t
207 return VideoCommentModel
208 .scope([ ScopeNames.WITH_VIDEO, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_IN_REPLY_TO ])
212 static loadByUrlAndPopulateAccountAndVideo (url: string, t?: Transaction): Bluebird<MCommentOwnerVideo> {
213 const query: FindOptions = {
219 if (t !== undefined) query.transaction = t
221 return VideoCommentModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEO ]).findOne(query)
224 static loadByUrlAndPopulateReplyAndVideoUrlAndAccount (url: string, t?: Transaction): Bluebird<MCommentOwnerReplyVideoLight> {
225 const query: FindOptions = {
231 attributes: [ 'id', 'url' ],
232 model: VideoModel.unscoped()
237 if (t !== undefined) query.transaction = t
239 return VideoCommentModel.scope([ ScopeNames.WITH_IN_REPLY_TO, ScopeNames.WITH_ACCOUNT ]).findOne(query)
242 static async listThreadsForApi (parameters: {
247 user?: MUserAccountId
249 const { videoId, start, count, sort, user } = parameters
251 const serverActor = await getServerActor()
252 const serverAccountId = serverActor.Account.id
253 const userAccountId = user ? user.Account.id : undefined
258 order: getSort(sort),
261 inReplyToCommentId: null,
263 [Op.notIn]: Sequelize.literal(
264 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
270 const scopes: (string | ScopeOptions)[] = [
271 ScopeNames.WITH_ACCOUNT,
273 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
277 return VideoCommentModel
279 .findAndCountAll(query)
280 .then(({ rows, count }) => {
281 return { total: count, data: rows }
285 static async listThreadCommentsForApi (parameters: {
288 user?: MUserAccountId
290 const { videoId, threadId, user } = parameters
292 const serverActor = await getServerActor()
293 const serverAccountId = serverActor.Account.id
294 const userAccountId = user ? user.Account.id : undefined
297 order: [ [ 'createdAt', 'ASC' ], [ 'updatedAt', 'ASC' ] ] as Order,
302 { originCommentId: threadId }
305 [Op.notIn]: Sequelize.literal(
306 '(' + buildBlockedAccountSQL(serverAccountId, userAccountId) + ')'
312 const scopes: any[] = [
313 ScopeNames.WITH_ACCOUNT,
315 method: [ ScopeNames.ATTRIBUTES_FOR_API, serverAccountId, userAccountId ]
319 return VideoCommentModel
321 .findAndCountAll(query)
322 .then(({ rows, count }) => {
323 return { total: count, data: rows }
327 static listThreadParentComments (comment: MCommentId, t: Transaction, order: 'ASC' | 'DESC' = 'ASC'): Bluebird<MCommentOwner[]> {
329 order: [ [ 'createdAt', order ] ] as Order,
332 [ Op.in ]: Sequelize.literal('(' +
333 'WITH RECURSIVE children (id, "inReplyToCommentId") AS ( ' +
334 `SELECT id, "inReplyToCommentId" FROM "videoComment" WHERE id = ${comment.id} ` +
336 'SELECT "parent"."id", "parent"."inReplyToCommentId" FROM "videoComment" "parent" ' +
337 'INNER JOIN "children" ON "children"."inReplyToCommentId" = "parent"."id"' +
339 'SELECT id FROM children' +
341 [ Op.ne ]: comment.id
347 return VideoCommentModel
348 .scope([ ScopeNames.WITH_ACCOUNT ])
352 static listAndCountByVideoId (videoId: number, start: number, count: number, t?: Transaction, order: 'ASC' | 'DESC' = 'ASC') {
354 order: [ [ 'createdAt', order ] ] as Order,
363 return VideoCommentModel.findAndCountAll<MComment>(query)
366 static listForFeed (start: number, count: number, videoId?: number): Bluebird<MCommentOwnerVideoFeed[]> {
368 order: [ [ 'createdAt', 'DESC' ] ] as Order,
374 attributes: [ 'name', 'uuid' ],
375 model: VideoModel.unscoped(),
381 if (videoId) query.where['videoId'] = videoId
383 return VideoCommentModel
384 .scope([ ScopeNames.WITH_ACCOUNT ])
388 static async getStats () {
389 const totalLocalVideoComments = await VideoCommentModel.count({
406 const totalVideoComments = await VideoCommentModel.count()
409 totalLocalVideoComments,
414 static cleanOldCommentsOf (videoId: number, beforeUpdatedAt: Date) {
418 [Op.lt]: beforeUpdatedAt
422 [Op.notIn]: buildLocalAccountIdsIn()
427 return VideoCommentModel.destroy(query)
430 getCommentStaticPath () {
431 return this.Video.getWatchStaticPath() + ';threadId=' + this.getThreadId()
434 getThreadId (): number {
435 return this.originCommentId || this.id
439 return this.Account.isOwned()
443 let result: string[] = []
445 const localMention = `@(${actorNameAlphabet}+)`
446 const remoteMention = `${localMention}@${WEBSERVER.HOST}`
448 const mentionRegex = this.isOwned()
449 ? '(?:(?:' + remoteMention + ')|(?:' + localMention + '))' // Include local mentions?
450 : '(?:' + remoteMention + ')'
452 const firstMentionRegex = new RegExp(`^${mentionRegex} `, 'g')
453 const endMentionRegex = new RegExp(` ${mentionRegex}$`, 'g')
454 const remoteMentionsRegex = new RegExp(' ' + remoteMention + ' ', 'g')
456 result = result.concat(
457 regexpCapture(this.text, firstMentionRegex)
458 .map(([ , username1, username2 ]) => username1 || username2),
460 regexpCapture(this.text, endMentionRegex)
461 .map(([ , username1, username2 ]) => username1 || username2),
463 regexpCapture(this.text, remoteMentionsRegex)
464 .map(([ , username ]) => username)
467 // Include local mentions
468 if (this.isOwned()) {
469 const localMentionsRegex = new RegExp(' ' + localMention + ' ', 'g')
471 result = result.concat(
472 regexpCapture(this.text, localMentionsRegex)
473 .map(([ , username ]) => username)
480 toFormattedJSON (this: MCommentFormattable) {
485 threadId: this.originCommentId || this.id,
486 inReplyToCommentId: this.inReplyToCommentId || null,
487 videoId: this.videoId,
488 createdAt: this.createdAt,
489 updatedAt: this.updatedAt,
490 totalReplies: this.get('totalReplies') || 0,
491 account: this.Account.toFormattedJSON()
495 toActivityPubObject (this: MCommentAP, threadParentComments: MCommentOwner[]): VideoCommentObject {
496 let inReplyTo: string
497 // New thread, so in AS we reply to the video
498 if (this.inReplyToCommentId === null) {
499 inReplyTo = this.Video.url
501 inReplyTo = this.InReplyToVideoComment.url
504 const tag: ActivityTagObject[] = []
505 for (const parentComment of threadParentComments) {
506 const actor = parentComment.Account.Actor
511 name: `@${actor.preferredUsername}@${actor.getHost()}`
516 type: 'Note' as 'Note',
520 updated: this.updatedAt.toISOString(),
521 published: this.createdAt.toISOString(),
523 attributedTo: this.Account.Actor.url,