1 import * as Bluebird from 'bluebird'
2 import { invert } from 'lodash'
3 import { literal, Op, QueryTypes, 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 { getSort, 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 { buildAbuseListQuery, BuildAbusesQueryOptions } from './abuse-query-builder'
42 import { VideoAbuseModel } from './video-abuse'
43 import { VideoCommentAbuseModel } from './video-comment-abuse'
45 export enum ScopeNames {
50 [ScopeNames.FOR_API]: () => {
55 // we don't care about this count for deleted videos, so there are not included
59 'FROM "videoAbuse" ' +
60 'WHERE "videoId" = "VideoAbuse"."videoId" AND "videoId" IS NOT NULL' +
63 'countReportsForVideo'
66 // we don't care about this count for deleted videos, so there are not included
72 'row_number() OVER (PARTITION BY "videoId" ORDER BY "createdAt") AS nth ' +
73 'FROM "videoAbuse" ' +
75 'WHERE t.id = "VideoAbuse".id AND t.id IS NOT NULL' +
83 'SELECT count("abuse"."id") ' +
85 'WHERE "abuse"."reporterAccountId" = "AbuseModel"."reporterAccountId"' +
88 'countReportsForReporter'
93 'SELECT count("abuse"."id") ' +
95 'WHERE "abuse"."flaggedAccountId" = "AbuseModel"."flaggedAccountId"' +
98 'countReportsForReportee'
104 model: AccountModel.scope({
106 AccountScopeNames.SUMMARY,
107 { actorRequired: false } as AccountSummaryOptions
110 as: 'ReporterAccount'
113 model: AccountModel.scope({
115 AccountScopeNames.SUMMARY,
116 { actorRequired: false } as AccountSummaryOptions
122 model: VideoCommentAbuseModel.unscoped(),
125 model: VideoCommentModel.unscoped(),
128 model: VideoModel.unscoped(),
129 attributes: [ 'name', 'id', 'uuid' ]
136 model: VideoAbuseModel.unscoped(),
139 attributes: [ 'id', 'uuid', 'name', 'nsfw' ],
140 model: VideoModel.unscoped(),
143 attributes: [ 'filename', 'fileUrl' ],
144 model: ThumbnailModel
147 model: VideoChannelModel.scope({
149 VideoChannelScopeNames.SUMMARY,
150 { withAccount: false, actorRequired: false } as ChannelSummaryOptions
156 attributes: [ 'id', 'reason', 'unfederated' ],
158 model: VideoBlacklistModel
172 fields: [ 'reporterAccountId' ]
175 fields: [ 'flaggedAccountId' ]
179 export class AbuseModel extends Model<AbuseModel> {
183 @Is('AbuseReason', value => throwIfNotValid(value, isAbuseReasonValid, 'reason'))
184 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ABUSES.REASON.max))
189 @Is('AbuseState', value => throwIfNotValid(value, isAbuseStateValid, 'state'))
195 @Is('AbuseModerationComment', value => throwIfNotValid(value, isAbuseModerationCommentValid, 'moderationComment', true))
196 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ABUSES.MODERATION_COMMENT.max))
197 moderationComment: string
201 @Column(DataType.ARRAY(DataType.INTEGER))
202 predefinedReasons: AbusePredefinedReasons[]
210 @ForeignKey(() => AccountModel)
212 reporterAccountId: number
214 @BelongsTo(() => AccountModel, {
216 name: 'reporterAccountId',
219 as: 'ReporterAccount',
222 ReporterAccount: AccountModel
224 @ForeignKey(() => AccountModel)
226 flaggedAccountId: number
228 @BelongsTo(() => AccountModel, {
230 name: 'flaggedAccountId',
233 as: 'FlaggedAccount',
236 FlaggedAccount: AccountModel
238 @HasOne(() => VideoCommentAbuseModel, {
245 VideoCommentAbuse: VideoCommentAbuseModel
247 @HasOne(() => VideoAbuseModel, {
254 VideoAbuse: VideoAbuseModel
256 // FIXME: deprecated in 2.3. Remove these validators
257 static loadByIdAndVideoId (id: number, videoId?: number, uuid?: string): Bluebird<MAbuse> {
258 const videoWhere: WhereOptions = {}
260 if (videoId) videoWhere.videoId = videoId
261 if (uuid) videoWhere.deletedVideo = { uuid }
266 model: VideoAbuseModel,
275 return AbuseModel.findOne(query)
278 static loadById (id: number): Bluebird<MAbuse> {
285 return AbuseModel.findOne(query)
288 static async listForApi (parameters: {
295 serverAccountId: number
296 user?: MUserAccountId
299 predefinedReason?: AbusePredefinedReasonsString
301 videoIs?: AbuseVideoIs
304 searchReporter?: string
305 searchReportee?: string
307 searchVideoChannel?: string
327 const userAccountId = user ? user.Account.id : undefined
328 const predefinedReasonId = predefinedReason ? abusePredefinedReasonsMap[predefinedReason] : undefined
330 const queryOptions: BuildAbusesQueryOptions = {
348 const [ total, data ] = await Promise.all([
349 AbuseModel.internalCountForApi(queryOptions),
350 AbuseModel.internalListForApi(queryOptions)
353 return { total, data }
356 toFormattedJSON (this: MAbuseFormattable): Abuse {
357 const predefinedReasons = AbuseModel.getPredefinedReasonsStrings(this.predefinedReasons)
359 const countReportsForVideo = this.get('countReportsForVideo') as number
360 const nthReportForVideo = this.get('nthReportForVideo') as number
362 const countReportsForReporter = this.get('countReportsForReporter') as number
363 const countReportsForReportee = this.get('countReportsForReportee') as number
365 let video: VideoAbuse
366 let comment: VideoCommentAbuse
368 if (this.VideoAbuse) {
369 const abuseModel = this.VideoAbuse
370 const entity = abuseModel.Video || abuseModel.deletedVideo
378 startAt: abuseModel.startAt,
379 endAt: abuseModel.endAt,
381 deleted: !abuseModel.Video,
382 blacklisted: abuseModel.Video?.isBlacklisted() || false,
383 thumbnailPath: abuseModel.Video?.getMiniatureStaticPath(),
385 channel: abuseModel.Video?.VideoChannel.toFormattedJSON() || abuseModel.deletedVideo?.channel,
387 countReports: countReportsForVideo,
388 nthReport: nthReportForVideo
392 if (this.VideoCommentAbuse) {
393 const abuseModel = this.VideoCommentAbuse
394 const entity = abuseModel.VideoComment || abuseModel.deletedComment
400 deleted: !abuseModel.VideoComment,
404 name: entity.Video.name,
405 uuid: entity.Video.uuid
415 reporterAccount: this.ReporterAccount
416 ? this.ReporterAccount.toFormattedJSON()
419 flaggedAccount: this.FlaggedAccount
420 ? this.FlaggedAccount.toFormattedJSON()
425 label: AbuseModel.getStateLabel(this.state)
428 moderationComment: this.moderationComment,
433 createdAt: this.createdAt,
434 updatedAt: this.updatedAt,
436 countReportsForReporter: (countReportsForReporter || 0),
437 countReportsForReportee: (countReportsForReportee || 0),
439 // FIXME: deprecated in 2.3, remove this
442 count: countReportsForVideo || 0,
443 nth: nthReportForVideo || 0
447 toActivityPubObject (this: MAbuseAP): AbuseObject {
448 const predefinedReasons = AbuseModel.getPredefinedReasonsStrings(this.predefinedReasons)
450 const object = this.VideoAbuse?.Video?.url || this.VideoCommentAbuse?.VideoComment?.url || this.FlaggedAccount.Actor.url
452 const startAt = this.VideoAbuse?.startAt
453 const endAt = this.VideoAbuse?.endAt
456 type: 'Flag' as 'Flag',
457 content: this.reason,
459 tag: predefinedReasons.map(r => ({
460 type: 'Hashtag' as 'Hashtag',
468 private static async internalCountForApi (parameters: BuildAbusesQueryOptions) {
469 const { query, replacements } = buildAbuseListQuery(parameters, 'count')
471 type: QueryTypes.SELECT as QueryTypes.SELECT,
475 const [ { total } ] = await AbuseModel.sequelize.query<{ total: string }>(query, options)
476 if (total === null) return 0
478 return parseInt(total, 10)
481 private static async internalListForApi (parameters: BuildAbusesQueryOptions) {
482 const { query, replacements } = buildAbuseListQuery(parameters, 'id')
484 type: QueryTypes.SELECT as QueryTypes.SELECT,
488 const rows = await AbuseModel.sequelize.query<{ id: string }>(query, options)
489 const ids = rows.map(r => r.id)
491 if (ids.length === 0) return []
493 return AbuseModel.scope(ScopeNames.FOR_API)
495 order: getSort(parameters.sort),
504 private static getStateLabel (id: number) {
505 return ABUSE_STATES[id] || 'Unknown'
508 private static getPredefinedReasonsStrings (predefinedReasons: AbusePredefinedReasons[]): AbusePredefinedReasonsString[] {
509 return (predefinedReasons || [])
510 .filter(r => r in AbusePredefinedReasons)
511 .map(r => invert(abusePredefinedReasonsMap)[r] as AbusePredefinedReasonsString)