]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/abuse/abuse.ts
Add migrations
[github/Chocobozzz/PeerTube.git] / server / models / abuse / abuse.ts
CommitLineData
feb34f6b 1import * as Bluebird from 'bluebird'
d95d1559
C
2import { invert } from 'lodash'
3import { literal, Op, WhereOptions } from 'sequelize'
86521a67 4import {
feb34f6b
C
5 AllowNull,
6 BelongsTo,
7 Column,
8 CreatedAt,
9 DataType,
10 Default,
11 ForeignKey,
d95d1559 12 HasOne,
feb34f6b
C
13 Is,
14 Model,
15 Scopes,
16 Table,
17 UpdatedAt
86521a67 18} from 'sequelize-typescript'
d95d1559 19import { isAbuseModerationCommentValid, isAbuseReasonValid, isAbuseStateValid } from '@server/helpers/custom-validators/abuses'
268eebed 20import {
d95d1559 21 Abuse,
57f6896f 22 AbuseFilter,
d95d1559
C
23 AbuseObject,
24 AbusePredefinedReasons,
25 abusePredefinedReasonsMap,
26 AbusePredefinedReasonsString,
27 AbuseState,
28 AbuseVideoIs,
57f6896f
C
29 VideoAbuse,
30 VideoCommentAbuse
d95d1559 31} from '@shared/models'
57f6896f 32import { ABUSE_STATES, CONSTRAINTS_FIELDS } from '../../initializers/constants'
d95d1559 33import { MAbuse, MAbuseAP, MAbuseFormattable, MUserAccountId } from '../../types/models'
4f32032f 34import { AccountModel, ScopeNames as AccountScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
feb34f6b 35import { buildBlockedAccountSQL, getSort, searchAttribute, throwIfNotValid } from '../utils'
d95d1559
C
36import { ThumbnailModel } from '../video/thumbnail'
37import { VideoModel } from '../video/video'
38import { VideoBlacklistModel } from '../video/video-blacklist'
4f32032f
C
39import { ScopeNames as VideoChannelScopeNames, SummaryOptions as ChannelSummaryOptions, VideoChannelModel } from '../video/video-channel'
40import { VideoCommentModel } from '../video/video-comment'
d95d1559
C
41import { VideoAbuseModel } from './video-abuse'
42import { VideoCommentAbuseModel } from './video-comment-abuse'
3fd3ab2d 43
844db39e
RK
44export enum ScopeNames {
45 FOR_API = 'FOR_API'
46}
47
48@Scopes(() => ({
49 [ScopeNames.FOR_API]: (options: {
0d3a2982 50 // search
844db39e
RK
51 search?: string
52 searchReporter?: string
0d3a2982 53 searchReportee?: string
d95d1559
C
54
55 // video releated
844db39e
RK
56 searchVideo?: string
57 searchVideoChannel?: string
d95d1559 58 videoIs?: AbuseVideoIs
fc8aabd0 59
0d3a2982
RK
60 // filters
61 id?: number
1ebddadd 62 predefinedReasonId?: number
d95d1559 63 filter?: AbuseFilter
feb34f6b 64
d95d1559 65 state?: AbuseState
fc8aabd0 66
0d3a2982 67 // accountIds
844db39e 68 serverAccountId: number
0251197e 69 userAccountId: number
844db39e 70 }) => {
57f6896f 71 const whereAnd: WhereOptions[] = []
d95d1559 72
57f6896f 73 whereAnd.push({
844db39e 74 reporterAccountId: {
696d83fd 75 [Op.notIn]: literal('(' + buildBlockedAccountSQL([ options.serverAccountId, options.userAccountId ]) + ')')
844db39e 76 }
57f6896f 77 })
844db39e
RK
78
79 if (options.search) {
d95d1559
C
80 const escapedSearch = AbuseModel.sequelize.escape('%' + options.search + '%')
81
57f6896f 82 whereAnd.push({
844db39e
RK
83 [Op.or]: [
84 {
85 [Op.and]: [
d95d1559
C
86 { '$VideoAbuse.videoId$': { [Op.not]: null } },
87 searchAttribute(options.search, '$VideoAbuse.Video.name$')
844db39e
RK
88 ]
89 },
90 {
91 [Op.and]: [
d95d1559
C
92 { '$VideoAbuse.videoId$': { [Op.not]: null } },
93 searchAttribute(options.search, '$VideoAbuse.Video.VideoChannel.name$')
844db39e
RK
94 ]
95 },
96 {
97 [Op.and]: [
d95d1559
C
98 { '$VideoAbuse.deletedVideo$': { [Op.not]: null } },
99 literal(`"VideoAbuse"."deletedVideo"->>'name' ILIKE ${escapedSearch}`)
844db39e
RK
100 ]
101 },
102 {
103 [Op.and]: [
d95d1559
C
104 { '$VideoAbuse.deletedVideo$': { [Op.not]: null } },
105 literal(`"VideoAbuse"."deletedVideo"->'channel'->>'displayName' ILIKE ${escapedSearch}`)
844db39e
RK
106 ]
107 },
d95d1559
C
108 searchAttribute(options.search, '$ReporterAccount.name$'),
109 searchAttribute(options.search, '$FlaggedAccount.name$')
844db39e
RK
110 ]
111 })
112 }
113
57f6896f
C
114 if (options.id) whereAnd.push({ id: options.id })
115 if (options.state) whereAnd.push({ state: options.state })
0d3a2982 116
feb34f6b 117 if (options.videoIs === 'deleted') {
57f6896f 118 whereAnd.push({
d95d1559 119 '$VideoAbuse.deletedVideo$': {
feb34f6b
C
120 [Op.not]: null
121 }
0d3a2982
RK
122 })
123 }
124
1ebddadd 125 if (options.predefinedReasonId) {
57f6896f 126 whereAnd.push({
1ebddadd
RK
127 predefinedReasons: {
128 [Op.contains]: [ options.predefinedReasonId ]
129 }
130 })
131 }
132
57f6896f
C
133 if (options.filter === 'account') {
134 whereAnd.push({
135 videoId: null,
136 commentId: null
137 })
138 }
139
140 const onlyBlacklisted = options.videoIs === 'blacklisted'
141 const videoRequired = !!(onlyBlacklisted || options.searchVideo || options.searchVideoChannel)
142
844db39e 143 return {
5fd4ca00
RK
144 attributes: {
145 include: [
146 [
efa012ed 147 // we don't care about this count for deleted videos, so there are not included
5fd4ca00
RK
148 literal(
149 '(' +
0251197e
RK
150 'SELECT count(*) ' +
151 'FROM "videoAbuse" ' +
4f32032f 152 'WHERE "videoId" = "VideoAbuse"."videoId" AND "videoId" IS NOT NULL' +
5fd4ca00
RK
153 ')'
154 ),
155 'countReportsForVideo'
156 ],
157 [
efa012ed 158 // we don't care about this count for deleted videos, so there are not included
5fd4ca00
RK
159 literal(
160 '(' +
161 'SELECT t.nth ' +
162 'FROM ( ' +
163 'SELECT id, ' +
164 'row_number() OVER (PARTITION BY "videoId" ORDER BY "createdAt") AS nth ' +
165 'FROM "videoAbuse" ' +
166 ') t ' +
4f32032f 167 'WHERE t.id = "VideoAbuse".id AND t.id IS NOT NULL' +
5fd4ca00
RK
168 ')'
169 ),
170 'nthReportForVideo'
171 ],
172 [
173 literal(
174 '(' +
4f32032f
C
175 'SELECT count("abuse"."id") ' +
176 'FROM "abuse" ' +
177 'WHERE "abuse"."reporterAccountId" = "AbuseModel"."reporterAccountId"' +
efa012ed
RK
178 ')'
179 ),
4f32032f 180 'countReportsForReporter'
efa012ed
RK
181 ],
182 [
183 literal(
184 '(' +
4f32032f
C
185 'SELECT count("abuse"."id") ' +
186 'FROM "abuse" ' +
187 'WHERE "abuse"."flaggedAccountId" = "AbuseModel"."flaggedAccountId"' +
5fd4ca00
RK
188 ')'
189 ),
4f32032f 190 'countReportsForReportee'
5fd4ca00
RK
191 ]
192 ]
193 },
86521a67
RK
194 include: [
195 {
d95d1559
C
196 model: AccountModel.scope(AccountScopeNames.SUMMARY),
197 as: 'ReporterAccount',
4f32032f 198 required: !!options.searchReporter,
0251197e 199 where: searchAttribute(options.searchReporter, 'name')
86521a67
RK
200 },
201 {
4f32032f
C
202 model: AccountModel.scope({
203 method: [
204 AccountScopeNames.SUMMARY,
205 { actorRequired: false } as AccountSummaryOptions
206 ]
207 }),
d95d1559 208 as: 'FlaggedAccount',
4f32032f 209 required: !!options.searchReportee,
d95d1559
C
210 where: searchAttribute(options.searchReportee, 'name')
211 },
57f6896f
C
212 {
213 model: VideoCommentAbuseModel.unscoped(),
214 required: options.filter === 'comment',
215 include: [
216 {
217 model: VideoCommentModel.unscoped(),
218 required: false,
219 include: [
220 {
221 model: VideoModel.unscoped(),
4f32032f 222 attributes: [ 'name', 'id', 'uuid' ]
57f6896f
C
223 }
224 ]
225 }
226 ]
227 },
d95d1559 228 {
4f32032f 229 model: VideoAbuseModel.unscoped(),
d95d1559 230 required: options.filter === 'video' || !!options.videoIs || videoRequired,
86521a67
RK
231 include: [
232 {
4f32032f
C
233 attributes: [ 'id', 'uuid', 'name', 'nsfw' ],
234 model: VideoModel.unscoped(),
d95d1559
C
235 required: videoRequired,
236 where: searchAttribute(options.searchVideo, 'name'),
0d3a2982
RK
237 include: [
238 {
4f32032f 239 attributes: [ 'filename', 'fileUrl' ],
d95d1559
C
240 model: ThumbnailModel
241 },
242 {
4f32032f
C
243 model: VideoChannelModel.scope({
244 method: [
245 VideoChannelScopeNames.SUMMARY,
246 { withAccount: false, actorRequired: false } as ChannelSummaryOptions
247 ]
248 }),
249
d95d1559 250 where: searchAttribute(options.searchVideoChannel, 'name'),
4f32032f 251 required: !!options.searchVideoChannel
d95d1559
C
252 },
253 {
254 attributes: [ 'id', 'reason', 'unfederated' ],
255 model: VideoBlacklistModel,
256 required: onlyBlacklisted
0d3a2982
RK
257 }
258 ]
86521a67
RK
259 }
260 ]
86521a67 261 }
844db39e 262 ],
57f6896f
C
263 where: {
264 [Op.and]: whereAnd
265 }
86521a67 266 }
844db39e 267 }
86521a67 268}))
3fd3ab2d 269@Table({
d95d1559 270 tableName: 'abuse',
3fd3ab2d 271 indexes: [
55fa55a9 272 {
d95d1559 273 fields: [ 'reporterAccountId' ]
55fa55a9
C
274 },
275 {
d95d1559 276 fields: [ 'flaggedAccountId' ]
55fa55a9 277 }
e02643f3 278 ]
3fd3ab2d 279})
d95d1559 280export class AbuseModel extends Model<AbuseModel> {
e02643f3 281
3fd3ab2d 282 @AllowNull(false)
1506307f 283 @Default(null)
4f32032f 284 @Is('AbuseReason', value => throwIfNotValid(value, isAbuseReasonValid, 'reason'))
d95d1559 285 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ABUSES.REASON.max))
3fd3ab2d 286 reason: string
21e0727a 287
268eebed
C
288 @AllowNull(false)
289 @Default(null)
4f32032f 290 @Is('AbuseState', value => throwIfNotValid(value, isAbuseStateValid, 'state'))
268eebed 291 @Column
d95d1559 292 state: AbuseState
268eebed
C
293
294 @AllowNull(true)
295 @Default(null)
4f32032f 296 @Is('AbuseModerationComment', value => throwIfNotValid(value, isAbuseModerationCommentValid, 'moderationComment', true))
d95d1559 297 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ABUSES.MODERATION_COMMENT.max))
268eebed
C
298 moderationComment: string
299
1ebddadd
RK
300 @AllowNull(true)
301 @Default(null)
302 @Column(DataType.ARRAY(DataType.INTEGER))
d95d1559 303 predefinedReasons: AbusePredefinedReasons[]
1ebddadd 304
3fd3ab2d
C
305 @CreatedAt
306 createdAt: Date
21e0727a 307
3fd3ab2d
C
308 @UpdatedAt
309 updatedAt: Date
e02643f3 310
3fd3ab2d
C
311 @ForeignKey(() => AccountModel)
312 @Column
313 reporterAccountId: number
55fa55a9 314
3fd3ab2d 315 @BelongsTo(() => AccountModel, {
55fa55a9 316 foreignKey: {
d95d1559 317 name: 'reporterAccountId',
68d19a0a 318 allowNull: true
55fa55a9 319 },
d95d1559 320 as: 'ReporterAccount',
68d19a0a 321 onDelete: 'set null'
55fa55a9 322 })
d95d1559 323 ReporterAccount: AccountModel
3fd3ab2d 324
d95d1559 325 @ForeignKey(() => AccountModel)
3fd3ab2d 326 @Column
d95d1559 327 flaggedAccountId: number
55fa55a9 328
d95d1559 329 @BelongsTo(() => AccountModel, {
55fa55a9 330 foreignKey: {
d95d1559 331 name: 'flaggedAccountId',
68d19a0a 332 allowNull: true
55fa55a9 333 },
d95d1559 334 as: 'FlaggedAccount',
68d19a0a 335 onDelete: 'set null'
55fa55a9 336 })
d95d1559
C
337 FlaggedAccount: AccountModel
338
339 @HasOne(() => VideoCommentAbuseModel, {
340 foreignKey: {
341 name: 'abuseId',
342 allowNull: false
343 },
344 onDelete: 'cascade'
345 })
346 VideoCommentAbuse: VideoCommentAbuseModel
3fd3ab2d 347
d95d1559
C
348 @HasOne(() => VideoAbuseModel, {
349 foreignKey: {
350 name: 'abuseId',
351 allowNull: false
352 },
353 onDelete: 'cascade'
354 })
355 VideoAbuse: VideoAbuseModel
356
57f6896f 357 // FIXME: deprecated in 2.3. Remove these validators
d95d1559
C
358 static loadByIdAndVideoId (id: number, videoId?: number, uuid?: string): Bluebird<MAbuse> {
359 const videoWhere: WhereOptions = {}
360
361 if (videoId) videoWhere.videoId = videoId
362 if (uuid) videoWhere.deletedVideo = { uuid }
68d19a0a 363
268eebed 364 const query = {
d95d1559
C
365 include: [
366 {
367 model: VideoAbuseModel,
368 required: true,
369 where: videoWhere
370 }
371 ],
268eebed 372 where: {
d95d1559 373 id
268eebed
C
374 }
375 }
d95d1559 376 return AbuseModel.findOne(query)
268eebed
C
377 }
378
57f6896f
C
379 static loadById (id: number): Bluebird<MAbuse> {
380 const query = {
381 where: {
382 id
383 }
384 }
385
386 return AbuseModel.findOne(query)
387 }
388
f0a47bc9 389 static listForApi (parameters: {
a1587156
C
390 start: number
391 count: number
392 sort: string
feb34f6b 393
d95d1559
C
394 filter?: AbuseFilter
395
f0a47bc9
C
396 serverAccountId: number
397 user?: MUserAccountId
feb34f6b
C
398
399 id?: number
d95d1559
C
400 predefinedReason?: AbusePredefinedReasonsString
401 state?: AbuseState
402 videoIs?: AbuseVideoIs
feb34f6b
C
403
404 search?: string
405 searchReporter?: string
406 searchReportee?: string
407 searchVideo?: string
408 searchVideoChannel?: string
f0a47bc9 409 }) {
feb34f6b
C
410 const {
411 start,
412 count,
413 sort,
414 search,
415 user,
416 serverAccountId,
417 state,
418 videoIs,
1ebddadd 419 predefinedReason,
feb34f6b
C
420 searchReportee,
421 searchVideo,
d95d1559 422 filter,
feb34f6b
C
423 searchVideoChannel,
424 searchReporter,
425 id
426 } = parameters
427
f0a47bc9 428 const userAccountId = user ? user.Account.id : undefined
d95d1559 429 const predefinedReasonId = predefinedReason ? abusePredefinedReasonsMap[predefinedReason] : undefined
f0a47bc9 430
3fd3ab2d
C
431 const query = {
432 offset: start,
433 limit: count,
3bb6c526 434 order: getSort(sort),
d95d1559 435 col: 'AbuseModel.id',
86521a67 436 distinct: true
3fd3ab2d 437 }
55fa55a9 438
844db39e 439 const filters = {
feb34f6b 440 id,
d95d1559 441 filter,
1ebddadd 442 predefinedReasonId,
feb34f6b
C
443 search,
444 state,
445 videoIs,
446 searchReportee,
447 searchVideo,
448 searchVideoChannel,
449 searchReporter,
844db39e
RK
450 serverAccountId,
451 userAccountId
452 }
453
d95d1559 454 return AbuseModel
1ebddadd
RK
455 .scope([
456 { method: [ ScopeNames.FOR_API, filters ] }
457 ])
844db39e 458 .findAndCountAll(query)
3fd3ab2d
C
459 .then(({ rows, count }) => {
460 return { total: count, data: rows }
461 })
55fa55a9
C
462 }
463
d95d1559
C
464 toFormattedJSON (this: MAbuseFormattable): Abuse {
465 const predefinedReasons = AbuseModel.getPredefinedReasonsStrings(this.predefinedReasons)
4f32032f 466
5fd4ca00
RK
467 const countReportsForVideo = this.get('countReportsForVideo') as number
468 const nthReportForVideo = this.get('nthReportForVideo') as number
4f32032f
C
469
470 const countReportsForReporter = this.get('countReportsForReporter') as number
471 const countReportsForReportee = this.get('countReportsForReportee') as number
5fd4ca00 472
d95d1559 473 let video: VideoAbuse
57f6896f 474 let comment: VideoCommentAbuse
d95d1559
C
475
476 if (this.VideoAbuse) {
477 const abuseModel = this.VideoAbuse
478 const entity = abuseModel.Video || abuseModel.deletedVideo
479
480 video = {
481 id: entity.id,
482 uuid: entity.uuid,
483 name: entity.name,
484 nsfw: entity.nsfw,
485
486 startAt: abuseModel.startAt,
487 endAt: abuseModel.endAt,
488
489 deleted: !abuseModel.Video,
490 blacklisted: abuseModel.Video?.isBlacklisted() || false,
491 thumbnailPath: abuseModel.Video?.getMiniatureStaticPath(),
4f32032f
C
492
493 channel: abuseModel.Video?.VideoChannel.toFormattedJSON() || abuseModel.deletedVideo?.channel,
494
495 countReports: countReportsForVideo,
496 nthReport: nthReportForVideo
d95d1559
C
497 }
498 }
68d19a0a 499
57f6896f
C
500 if (this.VideoCommentAbuse) {
501 const abuseModel = this.VideoCommentAbuse
502 const entity = abuseModel.VideoComment || abuseModel.deletedComment
503
504 comment = {
505 id: entity.id,
506 text: entity.text,
507
508 deleted: !abuseModel.VideoComment,
509
510 video: {
511 id: entity.Video.id,
512 name: entity.Video.name,
513 uuid: entity.Video.uuid
514 }
515 }
516 }
517
3fd3ab2d
C
518 return {
519 id: this.id,
520 reason: this.reason,
1ebddadd 521 predefinedReasons,
d95d1559 522
4f32032f
C
523 reporterAccount: this.ReporterAccount
524 ? this.ReporterAccount.toFormattedJSON()
525 : null,
526
527 flaggedAccount: this.FlaggedAccount
528 ? this.FlaggedAccount.toFormattedJSON()
529 : null,
d95d1559 530
268eebed
C
531 state: {
532 id: this.state,
d95d1559 533 label: AbuseModel.getStateLabel(this.state)
268eebed 534 },
d95d1559 535
268eebed 536 moderationComment: this.moderationComment,
d95d1559
C
537
538 video,
57f6896f 539 comment,
d95d1559 540
5fd4ca00
RK
541 createdAt: this.createdAt,
542 updatedAt: this.updatedAt,
4f32032f
C
543
544 countReportsForReporter: (countReportsForReporter || 0),
545 countReportsForReportee: (countReportsForReportee || 0),
d95d1559
C
546
547 // FIXME: deprecated in 2.3, remove this
548 startAt: null,
4f32032f
C
549 endAt: null,
550 count: countReportsForVideo || 0,
551 nth: nthReportForVideo || 0
3fd3ab2d
C
552 }
553 }
554
d95d1559
C
555 toActivityPubObject (this: MAbuseAP): AbuseObject {
556 const predefinedReasons = AbuseModel.getPredefinedReasonsStrings(this.predefinedReasons)
557
558 const object = this.VideoAbuse?.Video?.url || this.VideoCommentAbuse?.VideoComment?.url || this.FlaggedAccount.Actor.url
1ebddadd 559
d95d1559
C
560 const startAt = this.VideoAbuse?.startAt
561 const endAt = this.VideoAbuse?.endAt
1ebddadd 562
3fd3ab2d
C
563 return {
564 type: 'Flag' as 'Flag',
565 content: this.reason,
d95d1559 566 object,
1ebddadd
RK
567 tag: predefinedReasons.map(r => ({
568 type: 'Hashtag' as 'Hashtag',
569 name: r
570 })),
571 startAt,
572 endAt
3fd3ab2d
C
573 }
574 }
268eebed
C
575
576 private static getStateLabel (id: number) {
d95d1559 577 return ABUSE_STATES[id] || 'Unknown'
268eebed 578 }
1ebddadd 579
d95d1559 580 private static getPredefinedReasonsStrings (predefinedReasons: AbusePredefinedReasons[]): AbusePredefinedReasonsString[] {
1ebddadd 581 return (predefinedReasons || [])
d95d1559
C
582 .filter(r => r in AbusePredefinedReasons)
583 .map(r => invert(abusePredefinedReasonsMap)[r] as AbusePredefinedReasonsString)
1ebddadd 584 }
55fa55a9 585}