1 import * as Bluebird from 'bluebird'
2 import { invert } from 'lodash'
3 import { literal, Op, WhereOptions } from 'sequelize'
18 } from 'sequelize-typescript'
19 import { isAbuseModerationCommentValid, isAbuseReasonValid, isAbuseStateValid } from '@server/helpers/custom-validators/abuses'
24 AbusePredefinedReasons,
25 abusePredefinedReasonsMap,
26 AbusePredefinedReasonsString,
31 } from '@shared/models'
32 import { ABUSE_STATES, CONSTRAINTS_FIELDS } from '../../initializers/constants'
33 import { MAbuse, MAbuseAP, MAbuseFormattable, MUserAccountId } from '../../types/models'
34 import { AccountModel, ScopeNames as AccountScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
35 import { buildBlockedAccountSQL, getSort, searchAttribute, throwIfNotValid } from '../utils'
36 import { ThumbnailModel } from '../video/thumbnail'
37 import { VideoModel } from '../video/video'
38 import { VideoBlacklistModel } from '../video/video-blacklist'
39 import { ScopeNames as VideoChannelScopeNames, SummaryOptions as ChannelSummaryOptions, VideoChannelModel } from '../video/video-channel'
40 import { VideoCommentModel } from '../video/video-comment'
41 import { VideoAbuseModel } from './video-abuse'
42 import { VideoCommentAbuseModel } from './video-comment-abuse'
44 export enum ScopeNames {
49 [ScopeNames.FOR_API]: (options: {
52 searchReporter?: string
53 searchReportee?: string
57 searchVideoChannel?: string
58 videoIs?: AbuseVideoIs
62 predefinedReasonId?: number
68 serverAccountId: number
71 const whereAnd: WhereOptions[] = []
75 [Op.notIn]: literal('(' + buildBlockedAccountSQL([ options.serverAccountId, options.userAccountId ]) + ')')
80 const escapedSearch = AbuseModel.sequelize.escape('%' + options.search + '%')
86 { '$VideoAbuse.videoId$': { [Op.not]: null } },
87 searchAttribute(options.search, '$VideoAbuse.Video.name$')
92 { '$VideoAbuse.videoId$': { [Op.not]: null } },
93 searchAttribute(options.search, '$VideoAbuse.Video.VideoChannel.name$')
98 { '$VideoAbuse.deletedVideo$': { [Op.not]: null } },
99 literal(`"VideoAbuse"."deletedVideo"->>'name' ILIKE ${escapedSearch}`)
104 { '$VideoAbuse.deletedVideo$': { [Op.not]: null } },
105 literal(`"VideoAbuse"."deletedVideo"->'channel'->>'displayName' ILIKE ${escapedSearch}`)
108 searchAttribute(options.search, '$ReporterAccount.name$'),
109 searchAttribute(options.search, '$FlaggedAccount.name$')
114 if (options.id) whereAnd.push({ id: options.id })
115 if (options.state) whereAnd.push({ state: options.state })
117 if (options.videoIs === 'deleted') {
119 '$VideoAbuse.deletedVideo$': {
125 if (options.predefinedReasonId) {
128 [Op.contains]: [ options.predefinedReasonId ]
133 if (options.filter === 'account') {
140 const onlyBlacklisted = options.videoIs === 'blacklisted'
141 const videoRequired = !!(onlyBlacklisted || options.searchVideo || options.searchVideoChannel)
147 // we don't care about this count for deleted videos, so there are not included
151 'FROM "videoAbuse" ' +
152 'WHERE "videoId" = "VideoAbuse"."videoId" AND "videoId" IS NOT NULL' +
155 'countReportsForVideo'
158 // we don't care about this count for deleted videos, so there are not included
164 'row_number() OVER (PARTITION BY "videoId" ORDER BY "createdAt") AS nth ' +
165 'FROM "videoAbuse" ' +
167 'WHERE t.id = "VideoAbuse".id AND t.id IS NOT NULL' +
175 'SELECT count("abuse"."id") ' +
177 'WHERE "abuse"."reporterAccountId" = "AbuseModel"."reporterAccountId"' +
180 'countReportsForReporter'
185 'SELECT count("abuse"."id") ' +
187 'WHERE "abuse"."flaggedAccountId" = "AbuseModel"."flaggedAccountId"' +
190 'countReportsForReportee'
196 model: AccountModel.scope(AccountScopeNames.SUMMARY),
197 as: 'ReporterAccount',
198 required: !!options.searchReporter,
199 where: searchAttribute(options.searchReporter, 'name')
202 model: AccountModel.scope({
204 AccountScopeNames.SUMMARY,
205 { actorRequired: false } as AccountSummaryOptions
208 as: 'FlaggedAccount',
209 required: !!options.searchReportee,
210 where: searchAttribute(options.searchReportee, 'name')
213 model: VideoCommentAbuseModel.unscoped(),
214 required: options.filter === 'comment',
217 model: VideoCommentModel.unscoped(),
221 model: VideoModel.unscoped(),
222 attributes: [ 'name', 'id', 'uuid' ]
229 model: VideoAbuseModel.unscoped(),
230 required: options.filter === 'video' || !!options.videoIs || videoRequired,
233 attributes: [ 'id', 'uuid', 'name', 'nsfw' ],
234 model: VideoModel.unscoped(),
235 required: videoRequired,
236 where: searchAttribute(options.searchVideo, 'name'),
239 attributes: [ 'filename', 'fileUrl' ],
240 model: ThumbnailModel
243 model: VideoChannelModel.scope({
245 VideoChannelScopeNames.SUMMARY,
246 { withAccount: false, actorRequired: false } as ChannelSummaryOptions
250 where: searchAttribute(options.searchVideoChannel, 'name'),
251 required: !!options.searchVideoChannel
254 attributes: [ 'id', 'reason', 'unfederated' ],
255 model: VideoBlacklistModel,
256 required: onlyBlacklisted
273 fields: [ 'reporterAccountId' ]
276 fields: [ 'flaggedAccountId' ]
280 export class AbuseModel extends Model<AbuseModel> {
284 @Is('AbuseReason', value => throwIfNotValid(value, isAbuseReasonValid, 'reason'))
285 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ABUSES.REASON.max))
290 @Is('AbuseState', value => throwIfNotValid(value, isAbuseStateValid, 'state'))
296 @Is('AbuseModerationComment', value => throwIfNotValid(value, isAbuseModerationCommentValid, 'moderationComment', true))
297 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ABUSES.MODERATION_COMMENT.max))
298 moderationComment: string
302 @Column(DataType.ARRAY(DataType.INTEGER))
303 predefinedReasons: AbusePredefinedReasons[]
311 @ForeignKey(() => AccountModel)
313 reporterAccountId: number
315 @BelongsTo(() => AccountModel, {
317 name: 'reporterAccountId',
320 as: 'ReporterAccount',
323 ReporterAccount: AccountModel
325 @ForeignKey(() => AccountModel)
327 flaggedAccountId: number
329 @BelongsTo(() => AccountModel, {
331 name: 'flaggedAccountId',
334 as: 'FlaggedAccount',
337 FlaggedAccount: AccountModel
339 @HasOne(() => VideoCommentAbuseModel, {
346 VideoCommentAbuse: VideoCommentAbuseModel
348 @HasOne(() => VideoAbuseModel, {
355 VideoAbuse: VideoAbuseModel
357 // FIXME: deprecated in 2.3. Remove these validators
358 static loadByIdAndVideoId (id: number, videoId?: number, uuid?: string): Bluebird<MAbuse> {
359 const videoWhere: WhereOptions = {}
361 if (videoId) videoWhere.videoId = videoId
362 if (uuid) videoWhere.deletedVideo = { uuid }
367 model: VideoAbuseModel,
376 return AbuseModel.findOne(query)
379 static loadById (id: number): Bluebird<MAbuse> {
386 return AbuseModel.findOne(query)
389 static listForApi (parameters: {
396 serverAccountId: number
397 user?: MUserAccountId
400 predefinedReason?: AbusePredefinedReasonsString
402 videoIs?: AbuseVideoIs
405 searchReporter?: string
406 searchReportee?: string
408 searchVideoChannel?: string
428 const userAccountId = user ? user.Account.id : undefined
429 const predefinedReasonId = predefinedReason ? abusePredefinedReasonsMap[predefinedReason] : undefined
434 order: getSort(sort),
435 col: 'AbuseModel.id',
456 { method: [ ScopeNames.FOR_API, filters ] }
458 .findAndCountAll(query)
459 .then(({ rows, count }) => {
460 return { total: count, data: rows }
464 toFormattedJSON (this: MAbuseFormattable): Abuse {
465 const predefinedReasons = AbuseModel.getPredefinedReasonsStrings(this.predefinedReasons)
467 const countReportsForVideo = this.get('countReportsForVideo') as number
468 const nthReportForVideo = this.get('nthReportForVideo') as number
470 const countReportsForReporter = this.get('countReportsForReporter') as number
471 const countReportsForReportee = this.get('countReportsForReportee') as number
473 let video: VideoAbuse
474 let comment: VideoCommentAbuse
476 if (this.VideoAbuse) {
477 const abuseModel = this.VideoAbuse
478 const entity = abuseModel.Video || abuseModel.deletedVideo
486 startAt: abuseModel.startAt,
487 endAt: abuseModel.endAt,
489 deleted: !abuseModel.Video,
490 blacklisted: abuseModel.Video?.isBlacklisted() || false,
491 thumbnailPath: abuseModel.Video?.getMiniatureStaticPath(),
493 channel: abuseModel.Video?.VideoChannel.toFormattedJSON() || abuseModel.deletedVideo?.channel,
495 countReports: countReportsForVideo,
496 nthReport: nthReportForVideo
500 if (this.VideoCommentAbuse) {
501 const abuseModel = this.VideoCommentAbuse
502 const entity = abuseModel.VideoComment || abuseModel.deletedComment
508 deleted: !abuseModel.VideoComment,
512 name: entity.Video.name,
513 uuid: entity.Video.uuid
523 reporterAccount: this.ReporterAccount
524 ? this.ReporterAccount.toFormattedJSON()
527 flaggedAccount: this.FlaggedAccount
528 ? this.FlaggedAccount.toFormattedJSON()
533 label: AbuseModel.getStateLabel(this.state)
536 moderationComment: this.moderationComment,
541 createdAt: this.createdAt,
542 updatedAt: this.updatedAt,
544 countReportsForReporter: (countReportsForReporter || 0),
545 countReportsForReportee: (countReportsForReportee || 0),
547 // FIXME: deprecated in 2.3, remove this
550 count: countReportsForVideo || 0,
551 nth: nthReportForVideo || 0
555 toActivityPubObject (this: MAbuseAP): AbuseObject {
556 const predefinedReasons = AbuseModel.getPredefinedReasonsStrings(this.predefinedReasons)
558 const object = this.VideoAbuse?.Video?.url || this.VideoCommentAbuse?.VideoComment?.url || this.FlaggedAccount.Actor.url
560 const startAt = this.VideoAbuse?.startAt
561 const endAt = this.VideoAbuse?.endAt
564 type: 'Flag' as 'Flag',
565 content: this.reason,
567 tag: predefinedReasons.map(r => ({
568 type: 'Hashtag' as 'Hashtag',
576 private static getStateLabel (id: number) {
577 return ABUSE_STATES[id] || 'Unknown'
580 private static getPredefinedReasonsStrings (predefinedReasons: AbusePredefinedReasons[]): AbusePredefinedReasonsString[] {
581 return (predefinedReasons || [])
582 .filter(r => r in AbusePredefinedReasons)
583 .map(r => invert(abusePredefinedReasonsMap)[r] as AbusePredefinedReasonsString)