1
0
Fork 0
peertube/server/core/models/abuse/abuse.ts

664 lines
17 KiB
TypeScript
Raw Normal View History

import { abusePredefinedReasonsMap, forceNumber } from '@peertube/peertube-core-utils'
import {
AbuseFilter,
AbuseObject,
AbusePredefinedReasonsString,
AbusePredefinedReasonsType,
AbuseVideoIs,
AdminAbuse,
AdminVideoAbuse,
AdminVideoCommentAbuse,
UserAbuse,
UserVideoAbuse,
type AbuseStateType,
AbuseState
} from '@peertube/peertube-models'
import { isAbuseModerationCommentValid, isAbuseReasonValid, isAbuseStateValid } from '@server/helpers/custom-validators/abuses.js'
import invert from 'lodash-es/invert.js'
import { Op, QueryTypes, literal } from 'sequelize'
import {
2020-05-06 11:39:07 -04:00
AllowNull,
BelongsTo,
Column,
CreatedAt,
DataType,
Default,
ForeignKey,
2020-07-01 10:05:30 -04:00
HasOne,
2024-02-22 04:12:04 -05:00
Is, Scopes,
2020-05-06 11:39:07 -04:00
Table,
UpdatedAt
} from 'sequelize-typescript'
import { ABUSE_STATES, CONSTRAINTS_FIELDS } from '../../initializers/constants.js'
import {
MAbuseAP,
MAbuseAdminFormattable,
MAbuseFull,
MAbuseReporter,
MAbuseUserFormattable,
MUserAccountId
} from '../../types/models/index.js'
import { AccountModel, ScopeNames as AccountScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account.js'
2024-02-22 04:12:04 -05:00
import { SequelizeModel, getSort, parseAggregateResult, throwIfNotValid } from '../shared/index.js'
import { ThumbnailModel } from '../video/thumbnail.js'
import { VideoBlacklistModel } from '../video/video-blacklist.js'
import { SummaryOptions as ChannelSummaryOptions, VideoChannelModel, ScopeNames as VideoChannelScopeNames } from '../video/video-channel.js'
import { ScopeNames as CommentScopeNames, VideoCommentModel } from '../video/video-comment.js'
import { VideoModel, ScopeNames as VideoScopeNames } from '../video/video.js'
import { BuildAbusesQueryOptions, buildAbuseListQuery } from './sql/abuse-query-builder.js'
import { VideoAbuseModel } from './video-abuse.js'
import { VideoCommentAbuseModel } from './video-comment-abuse.js'
2017-12-12 11:53:50 -05:00
export enum ScopeNames {
FOR_API = 'FOR_API'
}
@Scopes(() => ({
2020-07-07 11:18:26 -04:00
[ScopeNames.FOR_API]: () => {
return {
attributes: {
include: [
2020-07-24 09:05:51 -04:00
[
literal(
'(' +
'SELECT count(*) ' +
'FROM "abuseMessage" ' +
'WHERE "abuseId" = "AbuseModel"."id"' +
')'
),
'countMessages'
],
[
2020-04-20 09:15:10 -04:00
// we don't care about this count for deleted videos, so there are not included
literal(
'(' +
'SELECT count(*) ' +
'FROM "videoAbuse" ' +
2020-07-07 08:34:16 -04:00
'WHERE "videoId" = "VideoAbuse"."videoId" AND "videoId" IS NOT NULL' +
')'
),
'countReportsForVideo'
],
[
2020-04-20 09:15:10 -04:00
// we don't care about this count for deleted videos, so there are not included
literal(
'(' +
'SELECT t.nth ' +
'FROM ( ' +
'SELECT id, ' +
'row_number() OVER (PARTITION BY "videoId" ORDER BY "createdAt") AS nth ' +
'FROM "videoAbuse" ' +
') t ' +
2020-07-07 08:34:16 -04:00
'WHERE t.id = "VideoAbuse".id AND t.id IS NOT NULL' +
')'
),
'nthReportForVideo'
],
[
literal(
'(' +
2020-07-07 08:34:16 -04:00
'SELECT count("abuse"."id") ' +
'FROM "abuse" ' +
'WHERE "abuse"."reporterAccountId" = "AbuseModel"."reporterAccountId"' +
2020-04-20 09:15:10 -04:00
')'
),
2020-07-07 08:34:16 -04:00
'countReportsForReporter'
2020-04-20 09:15:10 -04:00
],
[
literal(
'(' +
2020-07-07 08:34:16 -04:00
'SELECT count("abuse"."id") ' +
'FROM "abuse" ' +
'WHERE "abuse"."flaggedAccountId" = "AbuseModel"."flaggedAccountId"' +
')'
),
2020-07-07 08:34:16 -04:00
'countReportsForReportee'
]
]
},
include: [
{
2020-07-07 11:18:26 -04:00
model: AccountModel.scope({
method: [
AccountScopeNames.SUMMARY,
{ actorRequired: false } as AccountSummaryOptions
]
}),
as: 'ReporterAccount'
},
{
2020-07-07 08:34:16 -04:00
model: AccountModel.scope({
method: [
AccountScopeNames.SUMMARY,
{ actorRequired: false } as AccountSummaryOptions
]
}),
2020-07-07 11:18:26 -04:00
as: 'FlaggedAccount'
2020-07-01 10:05:30 -04:00
},
2020-07-07 04:57:04 -04:00
{
model: VideoCommentAbuseModel.unscoped(),
include: [
{
model: VideoCommentModel.unscoped(),
include: [
{
model: VideoModel.unscoped(),
2020-07-07 08:34:16 -04:00
attributes: [ 'name', 'id', 'uuid' ]
2020-07-07 04:57:04 -04:00
}
]
}
]
},
2020-07-01 10:05:30 -04:00
{
2020-07-07 08:34:16 -04:00
model: VideoAbuseModel.unscoped(),
include: [
{
2020-07-07 08:34:16 -04:00
attributes: [ 'id', 'uuid', 'name', 'nsfw' ],
model: VideoModel.unscoped(),
include: [
{
attributes: [ 'filename', 'fileUrl', 'type' ],
2020-07-01 10:05:30 -04:00
model: ThumbnailModel
},
{
2020-07-07 08:34:16 -04:00
model: VideoChannelModel.scope({
method: [
VideoChannelScopeNames.SUMMARY,
{ withAccount: false, actorRequired: false } as ChannelSummaryOptions
]
}),
2020-07-07 11:18:26 -04:00
required: false
2020-07-01 10:05:30 -04:00
},
{
attributes: [ 'id', 'reason', 'unfederated' ],
2020-07-07 11:18:26 -04:00
required: false,
model: VideoBlacklistModel
}
]
}
]
}
2020-07-07 11:18:26 -04:00
]
}
}
}))
2017-12-12 11:53:50 -05:00
@Table({
2020-07-01 10:05:30 -04:00
tableName: 'abuse',
2017-12-12 11:53:50 -05:00
indexes: [
2017-01-04 14:59:23 -05:00
{
2020-07-01 10:05:30 -04:00
fields: [ 'reporterAccountId' ]
2017-01-04 14:59:23 -05:00
},
{
2020-07-01 10:05:30 -04:00
fields: [ 'flaggedAccountId' ]
2017-01-04 14:59:23 -05:00
}
2017-05-22 14:58:25 -04:00
]
2017-12-12 11:53:50 -05:00
})
2024-02-22 04:12:04 -05:00
export class AbuseModel extends SequelizeModel<AbuseModel> {
2017-05-22 14:58:25 -04:00
2017-12-12 11:53:50 -05:00
@AllowNull(false)
@Default(null)
2020-07-07 08:34:16 -04:00
@Is('AbuseReason', value => throwIfNotValid(value, isAbuseReasonValid, 'reason'))
2020-07-01 10:05:30 -04:00
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ABUSES.REASON.max))
2017-12-12 11:53:50 -05:00
reason: string
2017-11-16 11:04:19 -05:00
@AllowNull(false)
@Default(null)
2020-07-07 08:34:16 -04:00
@Is('AbuseState', value => throwIfNotValid(value, isAbuseStateValid, 'state'))
@Column
state: AbuseStateType
@AllowNull(true)
@Default(null)
2020-07-07 08:34:16 -04:00
@Is('AbuseModerationComment', value => throwIfNotValid(value, isAbuseModerationCommentValid, 'moderationComment', true))
2020-07-01 10:05:30 -04:00
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ABUSES.MODERATION_COMMENT.max))
moderationComment: string
@AllowNull(true)
@Default(null)
@Column(DataType.ARRAY(DataType.INTEGER))
predefinedReasons: AbusePredefinedReasonsType[]
@AllowNull(true)
@Column
processedAt: Date
2017-12-12 11:53:50 -05:00
@CreatedAt
createdAt: Date
2017-11-16 11:04:19 -05:00
2017-12-12 11:53:50 -05:00
@UpdatedAt
updatedAt: Date
2017-05-22 14:58:25 -04:00
2017-12-12 11:53:50 -05:00
@ForeignKey(() => AccountModel)
@Column
reporterAccountId: number
2017-01-04 14:59:23 -05:00
2017-12-12 11:53:50 -05:00
@BelongsTo(() => AccountModel, {
2017-01-04 14:59:23 -05:00
foreignKey: {
2020-07-01 10:05:30 -04:00
name: 'reporterAccountId',
allowNull: true
2017-01-04 14:59:23 -05:00
},
2020-07-01 10:05:30 -04:00
as: 'ReporterAccount',
onDelete: 'set null'
2017-01-04 14:59:23 -05:00
})
ReporterAccount: Awaited<AccountModel>
2017-12-12 11:53:50 -05:00
2020-07-01 10:05:30 -04:00
@ForeignKey(() => AccountModel)
2017-12-12 11:53:50 -05:00
@Column
2020-07-01 10:05:30 -04:00
flaggedAccountId: number
2017-01-04 14:59:23 -05:00
2020-07-01 10:05:30 -04:00
@BelongsTo(() => AccountModel, {
2017-01-04 14:59:23 -05:00
foreignKey: {
2020-07-01 10:05:30 -04:00
name: 'flaggedAccountId',
allowNull: true
2017-01-04 14:59:23 -05:00
},
2020-07-01 10:05:30 -04:00
as: 'FlaggedAccount',
onDelete: 'set null'
2017-01-04 14:59:23 -05:00
})
FlaggedAccount: Awaited<AccountModel>
2020-07-01 10:05:30 -04:00
@HasOne(() => VideoCommentAbuseModel, {
foreignKey: {
name: 'abuseId',
allowNull: false
},
onDelete: 'cascade'
})
VideoCommentAbuse: Awaited<VideoCommentAbuseModel>
2017-12-12 11:53:50 -05:00
2020-07-01 10:05:30 -04:00
@HasOne(() => VideoAbuseModel, {
foreignKey: {
name: 'abuseId',
allowNull: false
},
onDelete: 'cascade'
})
VideoAbuse: Awaited<VideoAbuseModel>
2020-07-01 10:05:30 -04:00
2020-12-08 08:30:29 -05:00
static loadByIdWithReporter (id: number): Promise<MAbuseReporter> {
2020-07-07 04:57:04 -04:00
const query = {
where: {
id
},
include: [
{
model: AccountModel,
as: 'ReporterAccount'
}
]
2020-07-07 04:57:04 -04:00
}
return AbuseModel.findOne(query)
}
2020-12-08 08:30:29 -05:00
static loadFull (id: number): Promise<MAbuseFull> {
const query = {
where: {
id
},
include: [
{
model: AccountModel.scope(AccountScopeNames.SUMMARY),
required: false,
as: 'ReporterAccount'
},
{
model: AccountModel.scope(AccountScopeNames.SUMMARY),
as: 'FlaggedAccount'
},
{
model: VideoAbuseModel,
required: false,
include: [
{
model: VideoModel.scope([ VideoScopeNames.WITH_ACCOUNT_DETAILS ])
}
]
},
{
model: VideoCommentAbuseModel,
required: false,
include: [
{
model: VideoCommentModel.scope([
CommentScopeNames.WITH_ACCOUNT
]),
include: [
{
model: VideoModel
}
]
}
]
}
]
}
return AbuseModel.findOne(query)
}
2020-07-24 09:05:51 -04:00
static async listForAdminApi (parameters: {
2020-01-31 10:56:52 -05:00
start: number
count: number
sort: string
2020-05-06 11:39:07 -04:00
2020-07-01 10:05:30 -04:00
filter?: AbuseFilter
2019-08-29 08:31:04 -04:00
serverAccountId: number
user?: MUserAccountId
2020-05-06 11:39:07 -04:00
id?: number
2020-07-01 10:05:30 -04:00
predefinedReason?: AbusePredefinedReasonsString
state?: AbuseStateType
2020-07-01 10:05:30 -04:00
videoIs?: AbuseVideoIs
2020-05-06 11:39:07 -04:00
search?: string
searchReporter?: string
searchReportee?: string
searchVideo?: string
searchVideoChannel?: string
2019-08-29 08:31:04 -04:00
}) {
2020-05-06 11:39:07 -04:00
const {
start,
count,
sort,
search,
user,
serverAccountId,
state,
videoIs,
predefinedReason,
2020-05-06 11:39:07 -04:00
searchReportee,
searchVideo,
2020-07-01 10:05:30 -04:00
filter,
2020-05-06 11:39:07 -04:00
searchVideoChannel,
searchReporter,
id
} = parameters
2019-08-29 08:31:04 -04:00
const userAccountId = user ? user.Account.id : undefined
2020-07-01 10:05:30 -04:00
const predefinedReasonId = predefinedReason ? abusePredefinedReasonsMap[predefinedReason] : undefined
2019-08-29 08:31:04 -04:00
2020-07-07 11:18:26 -04:00
const queryOptions: BuildAbusesQueryOptions = {
start,
count,
sort,
2020-05-06 11:39:07 -04:00
id,
2020-07-01 10:05:30 -04:00
filter,
predefinedReasonId,
2020-05-06 11:39:07 -04:00
search,
state,
videoIs,
searchReportee,
searchVideo,
searchVideoChannel,
searchReporter,
serverAccountId,
userAccountId
}
2020-07-07 11:18:26 -04:00
const [ total, data ] = await Promise.all([
AbuseModel.internalCountForApi(queryOptions),
AbuseModel.internalListForApi(queryOptions)
])
return { total, data }
2017-01-04 14:59:23 -05:00
}
2020-07-24 09:05:51 -04:00
static async listForUserApi (parameters: {
user: MUserAccountId
2020-07-07 08:34:16 -04:00
2020-07-24 09:05:51 -04:00
start: number
count: number
sort: string
2020-07-07 08:34:16 -04:00
2020-07-24 09:05:51 -04:00
id?: number
search?: string
state?: AbuseStateType
2020-07-24 09:05:51 -04:00
}) {
const {
start,
count,
sort,
search,
user,
state,
id
} = parameters
2020-07-24 09:05:51 -04:00
const queryOptions: BuildAbusesQueryOptions = {
start,
count,
sort,
id,
search,
state,
reporterAccountId: user.Account.id
}
const [ total, data ] = await Promise.all([
AbuseModel.internalCountForApi(queryOptions),
AbuseModel.internalListForApi(queryOptions)
])
return { total, data }
}
2020-07-01 10:05:30 -04:00
// ---------------------------------------------------------------------------
static getStats () {
const query = `SELECT ` +
`AVG(EXTRACT(EPOCH FROM ("processedAt" - "createdAt") * 1000)) ` +
`FILTER (WHERE "processedAt" IS NOT NULL AND "createdAt" > CURRENT_DATE - INTERVAL '3 months')` +
`AS "avgResponseTime", ` +
// "processedAt" has been introduced in PeerTube 6.1 so also check the abuse state to check processed abuses
`COUNT(*) FILTER (WHERE "processedAt" IS NOT NULL OR "state" != ${AbuseState.PENDING}) AS "processedAbuses", ` +
`COUNT(*) AS "totalAbuses" ` +
`FROM "abuse"`
return AbuseModel.sequelize.query<any>(query, {
type: QueryTypes.SELECT,
raw: true
}).then(([ row ]) => {
return {
totalAbuses: parseAggregateResult(row.totalAbuses),
totalAbusesProcessed: parseAggregateResult(row.processedAbuses),
averageAbuseResponseTimeMs: row?.avgResponseTime
? forceNumber(row.avgResponseTime)
: null
}
})
}
// ---------------------------------------------------------------------------
2020-07-24 09:05:51 -04:00
buildBaseVideoCommentAbuse (this: MAbuseUserFormattable) {
2021-02-26 03:28:50 -05:00
// Associated video comment could have been destroyed if the video has been deleted
2022-11-15 09:00:19 -05:00
if (!this.VideoCommentAbuse?.VideoComment) return null
2020-07-01 10:05:30 -04:00
2021-02-26 03:28:50 -05:00
const entity = this.VideoCommentAbuse.VideoComment
2020-07-01 10:05:30 -04:00
2020-07-24 09:05:51 -04:00
return {
id: entity.id,
threadId: entity.getThreadId(),
2020-07-01 10:05:30 -04:00
2020-07-24 09:05:51 -04:00
text: entity.text ?? '',
2020-07-07 08:34:16 -04:00
2020-07-24 09:05:51 -04:00
deleted: entity.isDeleted(),
2020-07-07 08:34:16 -04:00
2020-07-24 09:05:51 -04:00
video: {
id: entity.Video.id,
name: entity.Video.name,
uuid: entity.Video.uuid
2020-07-01 10:05:30 -04:00
}
}
2020-07-24 09:05:51 -04:00
}
2020-07-24 09:05:51 -04:00
buildBaseVideoAbuse (this: MAbuseUserFormattable): UserVideoAbuse {
if (!this.VideoAbuse) return null
2020-07-07 04:57:04 -04:00
2020-07-24 09:05:51 -04:00
const abuseModel = this.VideoAbuse
const entity = abuseModel.Video || abuseModel.deletedVideo
2020-07-24 09:05:51 -04:00
return {
id: entity.id,
uuid: entity.uuid,
name: entity.name,
nsfw: entity.nsfw,
2020-07-07 04:57:04 -04:00
2020-07-24 09:05:51 -04:00
startAt: abuseModel.startAt,
endAt: abuseModel.endAt,
2020-07-07 04:57:04 -04:00
2020-07-24 09:05:51 -04:00
deleted: !abuseModel.Video,
blacklisted: abuseModel.Video?.isBlacklisted() || false,
thumbnailPath: abuseModel.Video?.getMiniatureStaticPath(),
channel: abuseModel.Video?.VideoChannel.toFormattedJSON() || abuseModel.deletedVideo?.channel
2020-07-07 04:57:04 -04:00
}
2020-07-24 09:05:51 -04:00
}
buildBaseAbuse (this: MAbuseUserFormattable, countMessages: number): UserAbuse {
const predefinedReasons = AbuseModel.getPredefinedReasonsStrings(this.predefinedReasons)
2020-07-07 04:57:04 -04:00
2017-12-12 11:53:50 -05:00
return {
id: this.id,
reason: this.reason,
predefinedReasons,
2020-07-01 10:05:30 -04:00
2020-07-07 08:34:16 -04:00
flaggedAccount: this.FlaggedAccount
? this.FlaggedAccount.toFormattedJSON()
: null,
2020-07-01 10:05:30 -04:00
state: {
id: this.state,
2020-07-01 10:05:30 -04:00
label: AbuseModel.getStateLabel(this.state)
},
2020-07-01 10:05:30 -04:00
2020-07-24 09:05:51 -04:00
countMessages,
createdAt: this.createdAt,
updatedAt: this.updatedAt
}
}
toFormattedAdminJSON (this: MAbuseAdminFormattable): AdminAbuse {
const countReportsForVideo = this.get('countReportsForVideo') as number
const nthReportForVideo = this.get('nthReportForVideo') as number
const countReportsForReporter = this.get('countReportsForReporter') as number
const countReportsForReportee = this.get('countReportsForReportee') as number
const countMessages = this.get('countMessages') as number
const baseVideo = this.buildBaseVideoAbuse()
const video: AdminVideoAbuse = baseVideo
? Object.assign(baseVideo, {
countReports: countReportsForVideo,
nthReport: nthReportForVideo
})
: null
const comment: AdminVideoCommentAbuse = this.buildBaseVideoCommentAbuse()
const abuse = this.buildBaseAbuse(countMessages || 0)
return Object.assign(abuse, {
2020-07-01 10:05:30 -04:00
video,
2020-07-07 04:57:04 -04:00
comment,
2020-07-01 10:05:30 -04:00
moderationComment: this.moderationComment,
2020-07-24 09:05:51 -04:00
reporterAccount: this.ReporterAccount
? this.ReporterAccount.toFormattedJSON()
: null,
2020-07-07 08:34:16 -04:00
countReportsForReporter: (countReportsForReporter || 0),
2020-11-10 08:41:20 -05:00
countReportsForReportee: (countReportsForReportee || 0)
2020-07-24 09:05:51 -04:00
})
}
toFormattedUserJSON (this: MAbuseUserFormattable): UserAbuse {
const countMessages = this.get('countMessages') as number
const video = this.buildBaseVideoAbuse()
const comment = this.buildBaseVideoCommentAbuse()
2020-07-24 09:05:51 -04:00
const abuse = this.buildBaseAbuse(countMessages || 0)
return Object.assign(abuse, {
video,
comment
})
2017-12-12 11:53:50 -05:00
}
2020-07-01 10:05:30 -04:00
toActivityPubObject (this: MAbuseAP): AbuseObject {
const predefinedReasons = AbuseModel.getPredefinedReasonsStrings(this.predefinedReasons)
const object = this.VideoAbuse?.Video?.url || this.VideoCommentAbuse?.VideoComment?.url || this.FlaggedAccount.Actor.url
2020-07-01 10:05:30 -04:00
const startAt = this.VideoAbuse?.startAt
const endAt = this.VideoAbuse?.endAt
2017-12-12 11:53:50 -05:00
return {
type: 'Flag' as 'Flag',
content: this.reason,
mediaType: 'text/markdown',
2020-07-01 10:05:30 -04:00
object,
tag: predefinedReasons.map(r => ({
type: 'Hashtag' as 'Hashtag',
name: r
})),
startAt,
endAt
2017-12-12 11:53:50 -05:00
}
}
2020-07-07 11:18:26 -04:00
private static async internalCountForApi (parameters: BuildAbusesQueryOptions) {
const { query, replacements } = buildAbuseListQuery(parameters, 'count')
const options = {
type: QueryTypes.SELECT as QueryTypes.SELECT,
replacements
}
const [ { total } ] = await AbuseModel.sequelize.query<{ total: string }>(query, options)
if (total === null) return 0
return parseInt(total, 10)
}
private static async internalListForApi (parameters: BuildAbusesQueryOptions) {
const { query, replacements } = buildAbuseListQuery(parameters, 'id')
const options = {
type: QueryTypes.SELECT as QueryTypes.SELECT,
replacements
}
const rows = await AbuseModel.sequelize.query<{ id: string }>(query, options)
const ids = rows.map(r => r.id)
if (ids.length === 0) return []
return AbuseModel.scope(ScopeNames.FOR_API)
.findAll({
order: getSort(parameters.sort),
where: {
id: {
[Op.in]: ids
}
}
})
}
private static getStateLabel (id: number) {
2020-07-01 10:05:30 -04:00
return ABUSE_STATES[id] || 'Unknown'
}
private static getPredefinedReasonsStrings (predefinedReasons: AbusePredefinedReasonsType[]): AbusePredefinedReasonsString[] {
2020-08-06 08:58:01 -04:00
const invertedPredefinedReasons = invert(abusePredefinedReasonsMap)
return (predefinedReasons || [])
2020-08-06 08:58:01 -04:00
.map(r => invertedPredefinedReasons[r] as AbusePredefinedReasonsString)
.filter(v => !!v)
}
2017-01-04 14:59:23 -05:00
}