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