PeerTube/server/core/models/video/video-comment.ts

661 lines
17 KiB
TypeScript
Raw Normal View History

2023-01-05 08:31:51 -06:00
import { FindOptions, Op, Order, QueryTypes, Sequelize, Transaction } from 'sequelize'
2020-07-07 03:57:04 -05:00
import {
AllowNull,
BelongsTo,
Column,
CreatedAt,
DataType,
ForeignKey,
HasMany,
Is,
Model,
Scopes,
Table,
UpdatedAt
} from 'sequelize-typescript'
import { pick } from '@peertube/peertube-core-utils'
import { ActivityTagObject, ActivityTombstoneObject, VideoComment, VideoCommentAdmin, VideoCommentObject } from '@peertube/peertube-models'
import { extractMentions } from '@server/helpers/mentions.js'
import { getServerActor } from '@server/models/application/application.js'
import { MAccount, MAccountId, MUserAccountId } from '@server/types/models/index.js'
import { AttributesOnly } from '@peertube/peertube-typescript-utils'
import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc.js'
import { CONSTRAINTS_FIELDS } from '../../initializers/constants.js'
2019-08-15 04:53:26 -05:00
import {
MComment,
2020-11-13 09:38:23 -06:00
MCommentAdminFormattable,
2019-08-21 07:31:57 -05:00
MCommentAP,
2019-08-20 12:05:31 -05:00
MCommentFormattable,
2019-08-15 04:53:26 -05:00
MCommentId,
MCommentOwner,
MCommentOwnerReplyVideoLight,
MCommentOwnerVideo,
MCommentOwnerVideoFeed,
MCommentOwnerVideoReply,
MVideoImmutable
} from '../../types/models/video/index.js'
import { VideoCommentAbuseModel } from '../abuse/video-comment-abuse.js'
import { AccountModel } from '../account/account.js'
import { ActorModel } from '../actor/actor.js'
import { buildLocalAccountIdsIn, buildSQLAttributes, throwIfNotValid } from '../shared/index.js'
import { ListVideoCommentsOptions, VideoCommentListQueryBuilder } from './sql/comment/video-comment-list-query-builder.js'
import { VideoChannelModel } from './video-channel.js'
import { VideoModel } from './video.js'
export enum ScopeNames {
WITH_ACCOUNT = 'WITH_ACCOUNT',
2017-12-27 09:11:53 -06:00
WITH_IN_REPLY_TO = 'WITH_IN_REPLY_TO',
2023-01-05 08:31:51 -06:00
WITH_VIDEO = 'WITH_VIDEO'
2017-12-22 03:50:07 -06:00
}
2019-04-23 02:50:57 -05:00
@Scopes(() => ({
2017-12-22 05:10:40 -06:00
[ScopeNames.WITH_ACCOUNT]: {
2017-12-22 03:50:07 -06:00
include: [
2017-12-27 09:11:53 -06:00
{
2019-08-15 04:53:26 -05:00
model: AccountModel
2017-12-27 09:11:53 -06:00
}
2019-04-23 02:50:57 -05:00
]
},
[ScopeNames.WITH_IN_REPLY_TO]: {
include: [
{
2019-04-23 02:50:57 -05:00
model: VideoCommentModel,
2017-12-28 04:16:08 -06:00
as: 'InReplyToVideoComment'
}
]
},
[ScopeNames.WITH_VIDEO]: {
include: [
{
2019-04-23 02:50:57 -05:00
model: VideoModel,
2018-01-04 04:19:16 -06:00
required: true,
include: [
{
2023-10-31 04:02:19 -05:00
model: VideoChannelModel.unscoped(),
attributes: [ 'id', 'accountId' ],
2018-01-04 04:19:16 -06:00
required: true,
include: [
{
2023-10-31 04:02:19 -05:00
attributes: [ 'id', 'url' ],
model: ActorModel.unscoped(),
2019-08-15 04:53:26 -05:00
required: true
2023-10-31 04:02:19 -05:00
},
{
attributes: [ 'id' ],
model: AccountModel.unscoped(),
required: true,
include: [
{
attributes: [ 'id', 'url' ],
model: ActorModel.unscoped(),
required: true
}
]
2018-01-04 04:19:16 -06:00
}
]
}
]
}
2019-04-23 02:50:57 -05:00
]
2017-12-22 03:50:07 -06:00
}
2019-04-23 02:50:57 -05:00
}))
@Table({
tableName: 'videoComment',
indexes: [
{
fields: [ 'videoId' ]
2017-12-22 03:50:07 -06:00
},
{
fields: [ 'videoId', 'originCommentId' ]
2018-01-26 07:14:43 -06:00
},
{
fields: [ 'url' ],
unique: true
2018-07-23 13:13:30 -05:00
},
{
fields: [ 'accountId' ]
2020-06-05 03:42:36 -05:00
},
{
fields: [
{ name: 'createdAt', order: 'DESC' }
]
}
]
})
2021-05-12 07:09:04 -05:00
export class VideoCommentModel extends Model<Partial<AttributesOnly<VideoCommentModel>>> {
@CreatedAt
createdAt: Date
@UpdatedAt
updatedAt: Date
@AllowNull(true)
@Column(DataType.DATE)
deletedAt: Date
@AllowNull(false)
@Is('VideoCommentUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
@Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
url: string
@AllowNull(false)
@Column(DataType.TEXT)
text: string
@ForeignKey(() => VideoCommentModel)
@Column
originCommentId: number
@BelongsTo(() => VideoCommentModel, {
foreignKey: {
2017-12-28 04:45:10 -06:00
name: 'originCommentId',
allowNull: true
},
2017-12-28 04:45:10 -06:00
as: 'OriginVideoComment',
onDelete: 'CASCADE'
})
OriginVideoComment: Awaited<VideoCommentModel>
@ForeignKey(() => VideoCommentModel)
@Column
inReplyToCommentId: number
@BelongsTo(() => VideoCommentModel, {
foreignKey: {
2017-12-28 04:45:10 -06:00
name: 'inReplyToCommentId',
allowNull: true
},
2017-12-28 04:16:08 -06:00
as: 'InReplyToVideoComment',
onDelete: 'CASCADE'
})
InReplyToVideoComment: Awaited<VideoCommentModel> | null
@ForeignKey(() => VideoModel)
@Column
videoId: number
@BelongsTo(() => VideoModel, {
foreignKey: {
allowNull: false
},
onDelete: 'CASCADE'
})
Video: Awaited<VideoModel>
2017-12-22 05:10:40 -06:00
@ForeignKey(() => AccountModel)
@Column
2017-12-22 05:10:40 -06:00
accountId: number
2017-12-22 05:10:40 -06:00
@BelongsTo(() => AccountModel, {
foreignKey: {
allowNull: true
},
onDelete: 'CASCADE'
})
Account: Awaited<AccountModel>
2020-07-07 03:57:04 -05:00
@HasMany(() => VideoCommentAbuseModel, {
foreignKey: {
2020-07-08 08:51:46 -05:00
name: 'videoCommentId',
2020-07-07 03:57:04 -05:00
allowNull: true
},
onDelete: 'set null'
})
CommentAbuses: Awaited<VideoCommentAbuseModel>[]
2020-07-07 03:57:04 -05:00
2023-01-09 03:29:23 -06:00
// ---------------------------------------------------------------------------
static getSQLAttributes (tableName: string, aliasPrefix = '') {
return buildSQLAttributes({
model: this,
tableName,
aliasPrefix
})
}
// ---------------------------------------------------------------------------
2020-12-08 07:30:29 -06:00
static loadById (id: number, t?: Transaction): Promise<MComment> {
2019-04-18 04:28:17 -05:00
const query: FindOptions = {
2017-12-22 03:50:07 -06:00
where: {
id
}
}
if (t !== undefined) query.transaction = t
return VideoCommentModel.findOne(query)
}
2020-12-08 07:30:29 -06:00
static loadByIdAndPopulateVideoAndAccountAndReply (id: number, t?: Transaction): Promise<MCommentOwnerVideoReply> {
2019-04-18 04:28:17 -05:00
const query: FindOptions = {
2017-12-28 04:16:08 -06:00
where: {
id
}
}
if (t !== undefined) query.transaction = t
return VideoCommentModel
.scope([ ScopeNames.WITH_VIDEO, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_IN_REPLY_TO ])
.findOne(query)
}
2020-12-08 07:30:29 -06:00
static loadByUrlAndPopulateAccountAndVideo (url: string, t?: Transaction): Promise<MCommentOwnerVideo> {
2019-04-18 04:28:17 -05:00
const query: FindOptions = {
where: {
url
}
}
if (t !== undefined) query.transaction = t
return VideoCommentModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEO ]).findOne(query)
}
2017-12-22 03:50:07 -06:00
2020-12-08 07:30:29 -06:00
static loadByUrlAndPopulateReplyAndVideoUrlAndAccount (url: string, t?: Transaction): Promise<MCommentOwnerReplyVideoLight> {
2019-04-18 04:28:17 -05:00
const query: FindOptions = {
2018-01-04 04:19:16 -06:00
where: {
url
2019-08-06 10:19:53 -05:00
},
include: [
{
attributes: [ 'id', 'url' ],
model: VideoModel.unscoped()
}
]
2018-01-04 04:19:16 -06:00
}
if (t !== undefined) query.transaction = t
2019-08-06 10:19:53 -05:00
return VideoCommentModel.scope([ ScopeNames.WITH_IN_REPLY_TO, ScopeNames.WITH_ACCOUNT ]).findOne(query)
2018-01-04 04:19:16 -06:00
}
2020-11-13 09:38:23 -06:00
static listCommentsForApi (parameters: {
start: number
count: number
sort: string
onLocalVideo?: boolean
2020-11-13 09:38:23 -06:00
isLocal?: boolean
search?: string
searchAccount?: string
searchVideo?: string
}) {
2023-01-05 08:31:51 -06:00
const queryOptions: ListVideoCommentsOptions = {
...pick(parameters, [ 'start', 'count', 'sort', 'isLocal', 'search', 'searchVideo', 'searchAccount', 'onLocalVideo' ]),
2020-11-13 09:38:23 -06:00
2023-01-05 08:31:51 -06:00
selectType: 'api',
notDeleted: true
2020-11-16 04:55:17 -06:00
}
2020-11-13 09:38:23 -06:00
return Promise.all([
2023-01-05 08:31:51 -06:00
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MCommentAdminFormattable>(),
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).countComments()
]).then(([ rows, count ]) => {
return { total: count, data: rows }
})
2020-11-13 09:38:23 -06:00
}
2019-07-18 07:28:37 -05:00
static async listThreadsForApi (parameters: {
2020-01-31 09:56:52 -06:00
videoId: number
isVideoOwned: boolean
2020-01-31 09:56:52 -06:00
start: number
count: number
sort: string
2019-08-15 04:53:26 -05:00
user?: MUserAccountId
2019-07-18 07:28:37 -05:00
}) {
2023-01-05 08:31:51 -06:00
const { videoId, user } = parameters
2019-07-18 07:28:37 -05:00
2023-01-05 08:31:51 -06:00
const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ user })
2023-01-05 08:31:51 -06:00
const commonOptions: ListVideoCommentsOptions = {
selectType: 'api',
videoId,
blockerAccountIds
}
2023-01-05 08:31:51 -06:00
const listOptions: ListVideoCommentsOptions = {
...commonOptions,
...pick(parameters, [ 'sort', 'start', 'count' ]),
isThread: true,
includeReplyCounters: true
2017-12-22 03:50:07 -06:00
}
2023-01-05 08:31:51 -06:00
const countOptions: ListVideoCommentsOptions = {
...commonOptions,
2023-01-05 08:31:51 -06:00
isThread: true
}
2023-01-05 08:31:51 -06:00
const notDeletedCountOptions: ListVideoCommentsOptions = {
...commonOptions,
notDeleted: true
}
return Promise.all([
2023-01-05 08:31:51 -06:00
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, listOptions).listComments<MCommentAdminFormattable>(),
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, countOptions).countComments(),
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, notDeletedCountOptions).countComments()
]).then(([ rows, count, totalNotDeletedComments ]) => {
return { total: count, data: rows, totalNotDeletedComments }
})
2017-12-22 03:50:07 -06:00
}
2019-07-18 07:28:37 -05:00
static async listThreadCommentsForApi (parameters: {
2020-01-31 09:56:52 -06:00
videoId: number
threadId: number
2019-08-15 04:53:26 -05:00
user?: MUserAccountId
2019-07-18 07:28:37 -05:00
}) {
2023-01-05 08:31:51 -06:00
const { user } = parameters
2019-07-18 07:28:37 -05:00
2023-01-05 08:31:51 -06:00
const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ user })
2023-01-05 08:31:51 -06:00
const queryOptions: ListVideoCommentsOptions = {
...pick(parameters, [ 'videoId', 'threadId' ]),
2017-12-22 03:50:07 -06:00
2023-01-05 08:31:51 -06:00
selectType: 'api',
sort: 'createdAt',
blockerAccountIds,
includeReplyCounters: true
}
return Promise.all([
2023-01-05 08:31:51 -06:00
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MCommentAdminFormattable>(),
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).countComments()
]).then(([ rows, count ]) => {
return { total: count, data: rows }
})
2017-12-22 03:50:07 -06:00
}
2020-12-08 07:30:29 -06:00
static listThreadParentComments (comment: MCommentId, t: Transaction, order: 'ASC' | 'DESC' = 'ASC'): Promise<MCommentOwner[]> {
2018-01-05 04:19:25 -06:00
const query = {
2019-04-18 04:28:17 -05:00
order: [ [ 'createdAt', order ] ] as Order,
2018-01-05 04:19:25 -06:00
where: {
id: {
2020-01-31 09:56:52 -06:00
[Op.in]: Sequelize.literal('(' +
2018-03-21 05:17:01 -05:00
'WITH RECURSIVE children (id, "inReplyToCommentId") AS ( ' +
`SELECT id, "inReplyToCommentId" FROM "videoComment" WHERE id = ${comment.id} ` +
'UNION ' +
'SELECT "parent"."id", "parent"."inReplyToCommentId" FROM "videoComment" "parent" ' +
'INNER JOIN "children" ON "children"."inReplyToCommentId" = "parent"."id"' +
') ' +
2018-03-21 05:17:01 -05:00
'SELECT id FROM children' +
')'),
2020-01-31 09:56:52 -06:00
[Op.ne]: comment.id
2018-01-05 04:19:25 -06:00
}
},
transaction: t
}
return VideoCommentModel
.scope([ ScopeNames.WITH_ACCOUNT ])
.findAll(query)
}
2023-01-05 08:31:51 -06:00
static async listAndCountByVideoForAP (parameters: {
video: MVideoImmutable
start: number
count: number
}) {
const { video } = parameters
const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ user: null })
const queryOptions: ListVideoCommentsOptions = {
...pick(parameters, [ 'start', 'count' ]),
selectType: 'comment-only',
videoId: video.id,
2023-01-05 08:31:51 -06:00
sort: 'createdAt',
2023-01-05 08:31:51 -06:00
blockerAccountIds
}
return Promise.all([
2023-01-05 08:31:51 -06:00
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MComment>(),
new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).countComments()
]).then(([ rows, count ]) => {
return { total: count, data: rows }
})
}
static async listForFeed (parameters: {
start: number
count: number
videoId?: number
accountId?: number
videoChannelId?: number
2023-01-05 08:31:51 -06:00
}) {
const blockerAccountIds = await VideoCommentModel.buildBlockerAccountIds({ user: null })
2023-01-05 08:31:51 -06:00
const queryOptions: ListVideoCommentsOptions = {
...pick(parameters, [ 'start', 'count', 'accountId', 'videoId', 'videoChannelId' ]),
2020-08-20 01:52:16 -05:00
2023-01-05 08:31:51 -06:00
selectType: 'feed',
2020-08-20 01:52:16 -05:00
2023-01-05 08:31:51 -06:00
sort: '-createdAt',
onPublicVideo: true,
notDeleted: true,
2020-05-06 07:12:12 -05:00
2023-01-05 08:31:51 -06:00
blockerAccountIds
2018-06-08 13:34:37 -05:00
}
2023-01-05 08:31:51 -06:00
return new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MCommentOwnerVideoFeed>()
2018-06-08 13:34:37 -05:00
}
2020-05-14 09:56:15 -05:00
static listForBulkDelete (ofAccount: MAccount, filter: { onVideosOfAccount?: MAccountId } = {}) {
2023-01-05 08:31:51 -06:00
const queryOptions: ListVideoCommentsOptions = {
selectType: 'comment-only',
2020-05-14 09:56:15 -05:00
2023-01-05 08:31:51 -06:00
accountId: ofAccount.id,
videoAccountOwnerId: filter.onVideosOfAccount?.id,
notDeleted: true,
count: 5000
2020-05-14 09:56:15 -05:00
}
2023-01-05 08:31:51 -06:00
return new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MComment>()
2020-05-14 09:56:15 -05:00
}
2018-02-28 11:04:46 -06:00
static async getStats () {
const totalLocalVideoComments = await VideoCommentModel.count({
include: [
{
2022-06-17 09:16:28 -05:00
model: AccountModel.unscoped(),
2018-02-28 11:04:46 -06:00
required: true,
include: [
{
2022-06-17 09:16:28 -05:00
model: ActorModel.unscoped(),
2018-02-28 11:04:46 -06:00
required: true,
where: {
serverId: null
}
}
]
}
]
})
const totalVideoComments = await VideoCommentModel.count()
return {
totalLocalVideoComments,
totalVideoComments
}
}
static listRemoteCommentUrlsOfLocalVideos () {
const query = `SELECT "videoComment".url FROM "videoComment" ` +
`INNER JOIN account ON account.id = "videoComment"."accountId" ` +
`INNER JOIN actor ON actor.id = "account"."actorId" AND actor."serverId" IS NOT NULL ` +
`INNER JOIN video ON video.id = "videoComment"."videoId" AND video.remote IS FALSE`
return VideoCommentModel.sequelize.query<{ url: string }>(query, {
type: QueryTypes.SELECT,
raw: true
}).then(rows => rows.map(r => r.url))
}
2019-03-19 10:23:02 -05:00
static cleanOldCommentsOf (videoId: number, beforeUpdatedAt: Date) {
const query = {
where: {
updatedAt: {
2019-04-18 04:28:17 -05:00
[Op.lt]: beforeUpdatedAt
2019-03-19 10:23:02 -05:00
},
2019-08-06 10:19:53 -05:00
videoId,
accountId: {
[Op.notIn]: buildLocalAccountIdsIn()
2020-05-14 09:56:15 -05:00
},
// Do not delete Tombstones
deletedAt: null
2019-08-06 10:19:53 -05:00
}
2019-03-19 10:23:02 -05:00
}
return VideoCommentModel.destroy(query)
}
2018-12-26 03:36:24 -06:00
getCommentStaticPath () {
return this.Video.getWatchStaticPath() + ';threadId=' + this.getThreadId()
}
2018-01-05 04:19:25 -06:00
getThreadId (): number {
return this.originCommentId || this.id
}
2018-01-04 04:19:16 -06:00
isOwned () {
2023-01-05 08:31:51 -06:00
if (!this.Account) return false
2018-01-04 04:19:16 -06:00
return this.Account.isOwned()
}
2021-06-15 02:17:19 -05:00
markAsDeleted () {
this.text = ''
this.deletedAt = new Date()
this.accountId = null
}
isDeleted () {
2020-01-31 09:56:52 -06:00
return this.deletedAt !== null
}
extractMentions () {
return extractMentions(this.text, this.isOwned())
}
2019-08-20 12:05:31 -05:00
toFormattedJSON (this: MCommentFormattable) {
2017-12-22 03:50:07 -06:00
return {
id: this.id,
url: this.url,
text: this.text,
2020-11-13 09:38:23 -06:00
threadId: this.getThreadId(),
2017-12-27 13:03:37 -06:00
inReplyToCommentId: this.inReplyToCommentId || null,
2017-12-22 03:50:07 -06:00
videoId: this.videoId,
2020-11-13 09:38:23 -06:00
2017-12-22 03:50:07 -06:00
createdAt: this.createdAt,
2017-12-22 05:10:40 -06:00
updatedAt: this.updatedAt,
deletedAt: this.deletedAt,
2020-11-13 09:38:23 -06:00
isDeleted: this.isDeleted(),
2020-11-13 09:38:23 -06:00
totalRepliesFromVideoAuthor: this.get('totalRepliesFromVideoAuthor') || 0,
2017-12-27 09:11:53 -06:00
totalReplies: this.get('totalReplies') || 0,
2020-11-13 09:38:23 -06:00
account: this.Account
? this.Account.toFormattedJSON()
: null
2017-12-22 03:50:07 -06:00
} as VideoComment
}
2020-11-13 09:38:23 -06:00
toFormattedAdminJSON (this: MCommentAdminFormattable) {
return {
id: this.id,
url: this.url,
text: this.text,
threadId: this.getThreadId(),
inReplyToCommentId: this.inReplyToCommentId || null,
videoId: this.videoId,
createdAt: this.createdAt,
updatedAt: this.updatedAt,
video: {
id: this.Video.id,
uuid: this.Video.uuid,
name: this.Video.name
},
account: this.Account
? this.Account.toFormattedJSON()
: null
} as VideoCommentAdmin
}
toActivityPubObject (this: MCommentAP, threadParentComments: MCommentOwner[]): VideoCommentObject | ActivityTombstoneObject {
let inReplyTo: string
// New thread, so in AS we reply to the video
if (this.inReplyToCommentId === null) {
inReplyTo = this.Video.url
} else {
inReplyTo = this.InReplyToVideoComment.url
}
if (this.isDeleted()) {
return {
id: this.url,
type: 'Tombstone',
formerType: 'Note',
inReplyTo,
published: this.createdAt.toISOString(),
updated: this.updatedAt.toISOString(),
deleted: this.deletedAt.toISOString()
}
}
2018-01-05 04:19:25 -06:00
const tag: ActivityTagObject[] = []
for (const parentComment of threadParentComments) {
if (!parentComment.Account) continue
2018-01-05 04:19:25 -06:00
const actor = parentComment.Account.Actor
tag.push({
type: 'Mention',
href: actor.url,
name: `@${actor.preferredUsername}@${actor.getHost()}`
})
}
return {
type: 'Note' as 'Note',
id: this.url,
content: this.text,
mediaType: 'text/markdown',
inReplyTo,
2017-12-28 04:16:08 -06:00
updated: this.updatedAt.toISOString(),
published: this.createdAt.toISOString(),
2017-12-28 04:16:08 -06:00
url: this.url,
2018-01-05 04:19:25 -06:00
attributedTo: this.Account.Actor.url,
tag
}
}
private static async buildBlockerAccountIds (options: {
2023-01-05 08:31:51 -06:00
user: MUserAccountId
}): Promise<number[]> {
const { user } = options
const serverActor = await getServerActor()
const blockerAccountIds = [ serverActor.Account.id ]
if (user) blockerAccountIds.push(user.Account.id)
return blockerAccountIds
}
}