Init commit

This commit is contained in:
ShreejitPanchal
2026-05-19 19:56:02 +08:00
commit 6601501eff
4047 changed files with 2185372 additions and 0 deletions

View File

@@ -0,0 +1,749 @@
import { ActorFollow, type FollowState } from '@peertube/peertube-models'
import { isActivityPubUrlValid } from '@server/helpers/custom-validators/activitypub/misc.js'
import { afterCommitIfTransaction } from '@server/helpers/database-utils.js'
import { getServerActor } from '@server/models/application/application.js'
import {
MActor,
MActorFollowActors,
MActorFollowActorsDefault,
MActorFollowActorsDefaultSubscription,
MActorFollowFollowingHost,
MActorFollowFormattable,
MActorFollowSubscriptions
} from '@server/types/models/index.js'
import difference from 'lodash-es/difference.js'
import { Attributes, FindOptions, IncludeOptions, Includeable, Op, QueryTypes, Transaction, WhereAttributeHash } from 'sequelize'
import {
AfterCreate,
AfterDestroy,
AfterUpdate,
AllowNull,
BelongsTo,
Column,
CreatedAt,
DataType,
Default,
ForeignKey,
Is,
IsInt,
Max,
Table,
UpdatedAt
} from 'sequelize-typescript'
import { logger } from '../../helpers/logger.js'
import {
ACTOR_FOLLOW_SCORE,
CONSTRAINTS_FIELDS,
FOLLOW_STATES,
SERVER_ACTOR_NAME,
SORTABLE_COLUMNS,
USER_EXPORT_MAX_ITEMS
} from '../../initializers/constants.js'
import { AccountModel } from '../account/account.js'
import { ServerModel } from '../server/server.js'
import { SequelizeModel, buildSQLAttributes, createSafeIn, getSubscriptionSort, searchAttribute, throwIfNotValid } from '../shared/index.js'
import { doesExist } from '../shared/query.js'
import { VideoChannelModel } from '../video/video-channel.js'
import { ActorModel, unusedActorAttributesForAPI } from './actor.js'
import { InstanceListFollowersQueryBuilder, ListFollowersOptions } from './sql/instance-list-followers-query-builder.js'
import { InstanceListFollowingQueryBuilder, ListFollowingOptions } from './sql/instance-list-following-query-builder.js'
@Table({
tableName: 'actorFollow',
indexes: [
{
fields: [ 'actorId' ]
},
{
fields: [ 'targetActorId' ]
},
{
fields: [ 'actorId', 'targetActorId' ],
unique: true
},
{
fields: [ 'score' ]
},
{
fields: [ 'url' ],
unique: true
}
]
})
export class ActorFollowModel extends SequelizeModel<ActorFollowModel> {
@AllowNull(false)
@Column(DataType.ENUM(...Object.values(FOLLOW_STATES)))
declare state: FollowState
@AllowNull(false)
@Default(ACTOR_FOLLOW_SCORE.BASE)
@IsInt
@Max(ACTOR_FOLLOW_SCORE.MAX)
@Column
declare score: number
// Allow null because we added this column in PeerTube v3, and don't want to generate fake URLs of remote follows
@AllowNull(true)
@Is('ActorFollowUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
@Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
declare url: string
@CreatedAt
declare createdAt: Date
@UpdatedAt
declare updatedAt: Date
@ForeignKey(() => ActorModel)
@Column
declare actorId: number
@BelongsTo(() => ActorModel, {
foreignKey: {
name: 'actorId',
allowNull: false
},
as: 'ActorFollower',
onDelete: 'CASCADE'
})
declare ActorFollower: Awaited<ActorModel>
@ForeignKey(() => ActorModel)
@Column
declare targetActorId: number
@BelongsTo(() => ActorModel, {
foreignKey: {
name: 'targetActorId',
allowNull: false
},
as: 'ActorFollowing',
onDelete: 'CASCADE'
})
declare ActorFollowing: Awaited<ActorModel>
@AfterCreate
static incrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
let by = 0
if (instance.state === 'accepted') by = 1
return afterCommitIfTransaction(options.transaction, () => {
return Promise.all([
ActorModel.recalculateFollowsCount({ ofId: instance.actorId, type: 'following', by }),
ActorModel.recalculateFollowsCount({ ofId: instance.targetActorId, type: 'followers', by })
])
})
}
@AfterUpdate
static incrementOrDecrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
let by = 0
if (instance.previous('state') !== 'accepted' && instance.state === 'accepted') by = 1
else if (instance.previous('state') === 'accepted' && instance.state !== 'accepted') by = -1
return afterCommitIfTransaction(options.transaction, () => {
return Promise.all([
ActorModel.recalculateFollowsCount({ ofId: instance.actorId, type: 'following', by }),
ActorModel.recalculateFollowsCount({ ofId: instance.targetActorId, type: 'followers', by })
])
})
}
@AfterDestroy
static decrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
let by = 0
if (instance.state === 'accepted') by = -1
return afterCommitIfTransaction(options.transaction, () => {
return Promise.all([
ActorModel.recalculateFollowsCount({ ofId: instance.actorId, type: 'following', by }),
ActorModel.recalculateFollowsCount({ ofId: instance.targetActorId, type: 'followers', by })
])
})
}
// ---------------------------------------------------------------------------
static getSQLAttributes (tableName: string, aliasPrefix = '') {
return buildSQLAttributes({
model: this,
tableName,
aliasPrefix
})
}
// ---------------------------------------------------------------------------
/*
* @deprecated Use `findOrCreateCustom` instead
*/
static findOrCreate (): any {
throw new Error('Must not be called')
}
// findOrCreate has issues with actor follow hooks
static async findOrCreateCustom (options: {
byActor: MActor
targetActor: MActor
activityId: string
state: FollowState
transaction: Transaction
}): Promise<[MActorFollowActors, boolean]> {
const { byActor, targetActor, activityId, state, transaction } = options
let created = false
let actorFollow: MActorFollowActors = await ActorFollowModel.loadByActorAndTarget(byActor.id, targetActor.id, transaction)
if (!actorFollow) {
created = true
actorFollow = await ActorFollowModel.create({
actorId: byActor.id,
targetActorId: targetActor.id,
url: activityId,
state
}, { transaction })
actorFollow.ActorFollowing = targetActor
actorFollow.ActorFollower = byActor
}
return [ actorFollow, created ]
}
// Remove actor follows with a score of 0 (too many requests where they were unreachable)
static async removeBadActorFollows () {
const actorFollows = await ActorFollowModel.listBadActorFollows()
const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
await Promise.all(actorFollowsRemovePromises)
const numberOfActorFollowsRemoved = actorFollows.length
if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
}
static isFollowedBy (actorId: number, followerActorId: number) {
const query = `SELECT 1 FROM "actorFollow" ` +
`WHERE "actorId" = $followerActorId AND "targetActorId" = $actorId AND "state" = 'accepted' ` +
`LIMIT 1`
return doesExist({ sequelize: this.sequelize, query, bind: { actorId, followerActorId } })
}
static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Promise<MActorFollowActorsDefault> {
const query = {
where: {
actorId,
targetActorId
},
include: [
{
model: ActorModel,
required: true,
as: 'ActorFollower'
},
{
model: ActorModel,
required: true,
as: 'ActorFollowing'
}
],
transaction: t
}
return ActorFollowModel.findOne(query)
}
static loadByActorAndTargetNameAndHostForAPI (options: {
actorId: number
targetName: string
targetHost: string
state?: FollowState
transaction?: Transaction
}): Promise<MActorFollowActorsDefaultSubscription> {
const { actorId, targetHost, targetName, state, transaction } = options
const actorFollowingPartInclude: IncludeOptions = {
model: ActorModel,
required: true,
as: 'ActorFollowing',
where: ActorModel.wherePreferredUsername(targetName),
include: [
{
model: VideoChannelModel.unscoped(),
required: false
}
]
}
if (targetHost === null) {
actorFollowingPartInclude.where['serverId'] = null
} else {
actorFollowingPartInclude.include.push({
model: ServerModel,
required: true,
where: {
host: targetHost
}
})
}
const where: WhereAttributeHash<Attributes<ActorFollowModel>> = { actorId }
if (state) where.state = state
const query: FindOptions<Attributes<ActorFollowModel>> = {
where,
include: [
actorFollowingPartInclude,
{
model: ActorModel,
required: true,
as: 'ActorFollower'
}
],
transaction
}
return ActorFollowModel.findOne(query)
}
static listSubscriptionsOf (actorId: number, targets: { name: string, host?: string }[]): Promise<MActorFollowFollowingHost[]> {
const whereTab = targets
.map(t => {
if (t.host) {
return {
[Op.and]: [
ActorModel.wherePreferredUsername(t.name),
{ $host$: t.host }
]
}
}
return {
[Op.and]: [
ActorModel.wherePreferredUsername(t.name),
{ $serverId$: null }
]
}
})
const query = {
attributes: [ 'id' ],
where: {
[Op.and]: [
{
[Op.or]: whereTab
},
{
state: 'accepted',
actorId
}
]
},
include: [
{
attributes: [ 'preferredUsername' ],
model: ActorModel.unscoped(),
required: true,
as: 'ActorFollowing',
include: [
{
attributes: [ 'host' ],
model: ServerModel.unscoped(),
required: false
}
]
}
]
}
return ActorFollowModel.findAll(query)
}
static listInstanceFollowingForApi (options: ListFollowingOptions) {
return Promise.all([
new InstanceListFollowingQueryBuilder(this.sequelize, options).count(),
new InstanceListFollowingQueryBuilder(this.sequelize, options).list<MActorFollowFormattable>()
]).then(([ total, data ]) => ({ total, data }))
}
static listFollowersForApi (options: ListFollowersOptions) {
return Promise.all([
new InstanceListFollowersQueryBuilder(this.sequelize, options).count(),
new InstanceListFollowersQueryBuilder(this.sequelize, options).list<MActorFollowFormattable>()
]).then(([ total, data ]) => ({ total, data }))
}
static listSubscriptionsForApi (options: {
actorId: number
start: number
count: number
sort: string
search?: string
}) {
const { actorId, start, count, sort } = options
const where = {
state: 'accepted',
actorId
}
if (options.search) {
Object.assign(where, {
[Op.or]: [
searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
searchAttribute(options.search, '$ActorFollowing.VideoChannel.name$')
]
})
}
const getQuery = (forCount: boolean) => {
let channelInclude: Includeable[] = []
if (forCount !== true) {
channelInclude = [
{
attributes: {
exclude: unusedActorAttributesForAPI
},
model: ActorModel,
required: true
},
{
model: AccountModel.unscoped(),
required: true,
include: [
{
attributes: {
exclude: unusedActorAttributesForAPI
},
model: ActorModel,
required: true
}
]
}
]
}
return {
attributes: forCount === true
? []
: SORTABLE_COLUMNS.USER_SUBSCRIPTIONS.filter(s => s !== 'channelUpdatedAt'),
distinct: true,
offset: start,
limit: count,
order: getSubscriptionSort(sort),
where,
include: [
{
attributes: [ 'id' ],
model: ActorModel.unscoped(),
as: 'ActorFollowing',
required: true,
include: [
{
model: VideoChannelModel.unscoped(),
required: true,
include: channelInclude
}
]
}
]
}
}
return Promise.all([
ActorFollowModel.count(getQuery(true)),
ActorFollowModel.findAll<MActorFollowSubscriptions>(getQuery(false))
]).then(([ total, rows ]) => ({
total,
data: rows.map(r => r.ActorFollowing.VideoChannel)
}))
}
static async keepUnfollowedInstance (hosts: string[]) {
const followerId = (await getServerActor()).id
const query = {
attributes: [ 'id' ],
where: {
actorId: followerId
},
include: [
{
attributes: [ 'id' ],
model: ActorModel.unscoped(),
required: true,
as: 'ActorFollowing',
where: {
preferredUsername: SERVER_ACTOR_NAME
},
include: [
{
attributes: [ 'host' ],
model: ServerModel.unscoped(),
required: true,
where: {
host: {
[Op.in]: hosts
}
}
}
]
}
]
}
const res = await ActorFollowModel.findAll(query)
const followedHosts = res.map(row => row.ActorFollowing.Server.host)
return difference(hosts, followedHosts)
}
// ---------------------------------------------------------------------------
static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
return ActorFollowModel.createListAcceptedFollowForApiQuery({ type: 'followers', actorIds, t, start, count })
.then(({ data, total }) => ({ total, data: data.map(d => d.selectionUrl) }))
}
static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
return ActorFollowModel.createListAcceptedFollowForApiQuery({
type: 'followers',
actorIds,
t,
columnUrl: 'sharedInboxUrl',
distinct: true
}).then(({ data, total }) => ({ total, data: data.map(d => d.selectionUrl) }))
}
static async listAcceptedFollowersForExport (targetActorId: number) {
const data = await ActorFollowModel.findAll({
where: {
state: 'accepted',
targetActorId
},
include: [
{
attributes: [ 'preferredUsername', 'url' ],
model: ActorModel.unscoped(),
required: true,
as: 'ActorFollower',
include: [
{
attributes: [ 'host' ],
model: ServerModel.unscoped(),
required: false
}
]
}
],
limit: USER_EXPORT_MAX_ITEMS
})
return data.map(f => ({
createdAt: f.createdAt,
followerHandle: f.ActorFollower.getFullIdentifier(),
followerUrl: f.ActorFollower.url
}))
}
// ---------------------------------------------------------------------------
static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
return ActorFollowModel.createListAcceptedFollowForApiQuery({ type: 'following', actorIds, t, start, count })
.then(({ data, total }) => ({ total, data: data.map(d => d.selectionUrl) }))
}
static async listAcceptedFollowingForExport (actorId: number) {
const data = await ActorFollowModel.findAll({
where: {
state: 'accepted',
actorId
},
include: [
{
attributes: [ 'preferredUsername', 'url' ],
model: ActorModel.unscoped(),
required: true,
as: 'ActorFollowing',
include: [
{
attributes: [ 'host' ],
model: ServerModel.unscoped(),
required: false
}
]
}
],
limit: USER_EXPORT_MAX_ITEMS
})
return data.map(f => ({
createdAt: f.createdAt,
followingHandle: f.ActorFollowing.getFullIdentifier(),
followingUrl: f.ActorFollowing.url
}))
}
// ---------------------------------------------------------------------------
static async getStats () {
const serverActor = await getServerActor()
const totalInstanceFollowing = await ActorFollowModel.count({
where: {
actorId: serverActor.id,
state: 'accepted'
}
})
const totalInstanceFollowers = await ActorFollowModel.count({
where: {
targetActorId: serverActor.id,
state: 'accepted'
}
})
return {
totalInstanceFollowing,
totalInstanceFollowers
}
}
static updateScore (inboxUrl: string, value: number, t?: Transaction) {
const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
'WHERE id IN (' +
'SELECT "actorFollow"."id" FROM "actorFollow" ' +
'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
`WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
')'
const options = {
type: QueryTypes.BULKUPDATE,
transaction: t
}
return ActorFollowModel.sequelize.query(query, options)
}
static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
if (serverIds.length === 0) return
const me = await getServerActor()
const serverIdsString = createSafeIn(ActorFollowModel.sequelize, serverIds)
const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
'WHERE id IN (' +
'SELECT "actorFollow"."id" FROM "actorFollow" ' +
'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
`WHERE "actorFollow"."actorId" = ${me.Account.Actor.id} ` + // I'm the follower
`AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
')'
const options = {
type: QueryTypes.BULKUPDATE,
transaction: t
}
return ActorFollowModel.sequelize.query(query, options)
}
private static async createListAcceptedFollowForApiQuery (options: {
type: 'followers' | 'following'
actorIds: number[]
t: Transaction
start?: number
count?: number
columnUrl?: string // Default 'url'
distinct?: boolean // Default false
selectTotal?: boolean // Default true
}) {
const { type, actorIds, t, start, count, columnUrl = 'url', distinct = false, selectTotal = true } = options
let firstJoin: string
let secondJoin: string
if (type === 'followers') {
firstJoin = 'targetActorId'
secondJoin = 'actorId'
} else {
firstJoin = 'actorId'
secondJoin = 'targetActorId'
}
const selections: string[] = []
selections.push(
distinct === true
? `DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`
: `"Follows"."${columnUrl}" AS "selectionUrl"`
)
if (selectTotal) selections.push('COUNT(*) AS "total"')
const tasks: Promise<any>[] = []
for (const selection of selections) {
let query = 'SELECT ' + selection + ' FROM "actor" ' +
'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
`WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
if (count !== undefined) query += 'LIMIT ' + count
if (start !== undefined) query += ' OFFSET ' + start
const options = {
bind: { actorIds },
type: QueryTypes.SELECT,
transaction: t
}
tasks.push(ActorFollowModel.sequelize.query(query, options))
}
const [ followers, resDataTotal ] = await Promise.all(tasks)
return {
data: followers.map(f => ({ selectionUrl: f.selectionUrl, createdAt: f.createdAt })) as { selectionUrl: string, createdAt: string }[],
total: selectTotal
? parseInt(resDataTotal?.[0]?.total || 0, 10)
: undefined
}
}
private static listBadActorFollows () {
const query = {
where: {
score: {
[Op.lte]: 0
}
},
logging: false
}
return ActorFollowModel.findAll(query)
}
toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
const follower = this.ActorFollower.toFormattedJSON()
const following = this.ActorFollowing.toFormattedJSON()
return {
id: this.id,
follower,
following,
score: this.score,
state: this.state,
createdAt: this.createdAt,
updatedAt: this.updatedAt
}
}
}

View File

@@ -0,0 +1,201 @@
import { ActivityIconObject, ActorImage, ActorImageType, type ActorImageType_Type } from '@peertube/peertube-models'
import { getLowercaseExtension } from '@peertube/peertube-node-utils'
import { MActorId, MActorImage, MActorImageFormattable, MActorImagePath } from '@server/types/models/index.js'
import { remove } from 'fs-extra/esm'
import { join } from 'path'
import { Op, Transaction } from 'sequelize'
import { AfterDestroy, AllowNull, BelongsTo, Column, CreatedAt, Default, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'
import { logger } from '../../helpers/logger.js'
import { CONFIG } from '../../initializers/config.js'
import { LAZY_STATIC_PATHS, MIMETYPES, WEBSERVER } from '../../initializers/constants.js'
import { SequelizeModel, buildSQLAttributes } from '../shared/index.js'
import { ActorModel } from './actor.js'
@Table({
tableName: 'actorImage',
indexes: [
{
fields: [ 'filename' ],
unique: true
},
{
fields: [ 'actorId', 'type', 'width' ],
unique: true
}
]
})
export class ActorImageModel extends SequelizeModel<ActorImageModel> {
@AllowNull(false)
@Column
declare filename: string
@AllowNull(true)
@Default(null)
@Column
declare height: number
@AllowNull(true)
@Default(null)
@Column
declare width: number
@AllowNull(true)
@Column
declare fileUrl: string
@AllowNull(false)
@Column
declare onDisk: boolean
@AllowNull(false)
@Column
declare type: ActorImageType_Type
@CreatedAt
declare createdAt: Date
@UpdatedAt
declare updatedAt: Date
@ForeignKey(() => ActorModel)
@Column
declare actorId: number
@BelongsTo(() => ActorModel, {
foreignKey: {
allowNull: false
},
onDelete: 'CASCADE'
})
declare Actor: Awaited<ActorModel> // TODO: Remove awaited: https://github.com/sequelize/sequelize-typescript/issues/825
@AfterDestroy
static removeFile (instance: ActorImageModel) {
logger.info('Removing actor image file %s.', instance.filename)
// Don't block the transaction
instance.removeImage()
.catch(err => logger.error('Cannot remove actor image file %s.', instance.filename, { err }))
}
// ---------------------------------------------------------------------------
static getSQLAttributes (tableName: string, aliasPrefix = '') {
return buildSQLAttributes({
model: this,
tableName,
aliasPrefix
})
}
// ---------------------------------------------------------------------------
static loadByFilename (filename: string) {
const query = {
where: {
filename
}
}
return ActorImageModel.findOne(query)
}
static listByActor (actor: MActorId, type: ActorImageType_Type, transaction?: Transaction) {
const query = {
where: {
actorId: actor.id,
type
},
transaction
}
return ActorImageModel.findAll(query)
}
static async listActorImages (actor: MActorId, transaction?: Transaction) {
const promises = [ ActorImageType.AVATAR, ActorImageType.BANNER ].map(type => ActorImageModel.listByActor(actor, type, transaction))
const [ avatars, banners ] = await Promise.all(promises)
return { avatars, banners }
}
static listRemoteOnDisk () {
return this.findAll<MActorImage>({
where: {
onDisk: true
},
include: [
{
attributes: [ 'id' ],
model: ActorModel.unscoped(),
required: true,
where: {
serverId: {
[Op.ne]: null
}
}
}
]
})
}
static getImageUrl (image: MActorImagePath) {
if (!image) return undefined
return WEBSERVER.URL + image.getStaticPath()
}
// ---------------------------------------------------------------------------
toFormattedJSON (this: MActorImageFormattable): ActorImage {
return {
height: this.height,
width: this.width,
path: this.getStaticPath(),
fileUrl: ActorImageModel.getImageUrl(this),
createdAt: this.createdAt,
updatedAt: this.updatedAt
}
}
toActivityPubObject (): ActivityIconObject {
return {
type: 'Image',
mediaType: this.getMimeType(),
height: this.height,
width: this.width,
url: ActorImageModel.getImageUrl(this)
}
}
getStaticPath (this: MActorImagePath) {
switch (this.type) {
case ActorImageType.AVATAR:
return join(LAZY_STATIC_PATHS.AVATARS, this.filename)
case ActorImageType.BANNER:
return join(LAZY_STATIC_PATHS.BANNERS, this.filename)
default:
throw new Error('Unknown actor image type: ' + this.type)
}
}
getPath () {
return join(CONFIG.STORAGE.ACTOR_IMAGES_DIR, this.filename)
}
removeImage () {
const imagePath = join(CONFIG.STORAGE.ACTOR_IMAGES_DIR, this.filename)
return remove(imagePath)
}
isLocal () {
return !this.fileUrl
}
getMimeType () {
return MIMETYPES.IMAGE.EXT_MIMETYPE[getLowercaseExtension(this.filename)]
}
}

View File

@@ -0,0 +1,67 @@
import { CONSTRAINTS_FIELDS } from '@server/initializers/constants.js'
import { col, fn, Transaction, where } from 'sequelize'
import { AllowNull, Column, DataType, Table, UpdatedAt } from 'sequelize-typescript'
import { SequelizeModel } from '../shared/index.js'
// ---------------------------------------------------------------------------
// For example deleted actors
// Usernames we want to reserve to prevent reuse that would break federation
// ---------------------------------------------------------------------------
@Table({
tableName: 'actorReserved',
indexes: [
{
fields: [ fn('lower', col('preferredUsername')) ],
name: 'actor_reserved_preferred_username_lower',
unique: true
}
]
})
export class ActorReservedModel extends SequelizeModel<ActorReservedModel> {
@AllowNull(false)
@Column
declare preferredUsername: string
@AllowNull(false)
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PUBLIC_KEY.max))
declare publicKey: string
@AllowNull(false)
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PRIVATE_KEY.max))
declare privateKey: string
@AllowNull(false)
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
declare url: string
@AllowNull(false)
@Column
actorId: number
@AllowNull(true)
@Column
accountId: number
@AllowNull(true)
@Column
videoChannelId: number
@UpdatedAt
declare updatedAt: Date
static loadByActorId (actorId: number) {
return this.findOne({
where: { actorId }
})
}
static loadByName (preferredUsername: string, transaction?: Transaction) {
return this.findOne({
where: [
where(fn('lower', col('preferredUsername')), preferredUsername.toLowerCase())
],
transaction
})
}
}

View File

@@ -0,0 +1,824 @@
import { findAppropriateImage, forceNumber, maxBy } from '@peertube/peertube-core-utils'
import { ActivityIconObject, ActorImageType, ActorImageType_Type, type ActivityPubActorType } from '@peertube/peertube-models'
import { AttributesOnly } from '@peertube/peertube-typescript-utils'
import { activityPubContextify } from '@server/helpers/activity-pub-utils.js'
import { getContextFilter } from '@server/lib/activitypub/context.js'
import { ModelCache } from '@server/models/shared/model-cache.js'
import { Op, QueryTypes, Transaction, col, fn, literal, where } from 'sequelize'
import {
AllowNull,
BeforeDestroy,
BelongsTo,
Column,
CreatedAt,
DataType,
DefaultScope,
ForeignKey,
HasMany,
Is,
Scopes,
Table,
UpdatedAt
} from 'sequelize-typescript'
import { Where } from 'sequelize/types/utils'
import {
isActorFollowersCountValid,
isActorFollowingCountValid,
isActorPreferredUsernameValid,
isActorPrivateKeyValid,
isActorPublicKeyValid
} from '../../helpers/custom-validators/activitypub/actor.js'
import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc.js'
import { ACTIVITY_PUB, ACTIVITY_PUB_ACTOR_TYPES, CONSTRAINTS_FIELDS, SERVER_ACTOR_NAME, WEBSERVER } from '../../initializers/constants.js'
import {
MActor,
MActorAPAccount,
MActorAPChannel,
MActorAccountChannelId,
MActorFollowersUrl,
MActorFormattable,
MActorFull,
MActorHost,
MActorHostOnly,
MActorId,
MActorSummaryFormattable,
MActorUrl,
MActorWithInboxes
} from '../../types/models/index.js'
import { AccountModel } from '../account/account.js'
import { getServerActor } from '../application/application.js'
import { UploadImageModel } from '../application/upload-image.js'
import { ServerModel } from '../server/server.js'
import { SequelizeModel, buildSQLAttributes, isOutdated, throwIfNotValid } from '../shared/index.js'
import { VideoChannelModel } from '../video/video-channel.js'
import { VideoModel } from '../video/video.js'
import { ActorFollowModel } from './actor-follow.js'
import { ActorImageModel } from './actor-image.js'
import { ActorReservedModel } from './actor-reserved.js'
export const actorSummaryAttributes = [
'id',
'preferredUsername',
'url',
'serverId',
'accountId',
'videoChannelId'
] as const satisfies (keyof AttributesOnly<ActorModel>)[]
enum ScopeNames {
FULL = 'FULL'
}
export const unusedActorAttributesForAPI: (keyof AttributesOnly<ActorModel>)[] = [
'publicKey',
'privateKey',
'inboxUrl',
'outboxUrl',
'sharedInboxUrl',
'followersUrl',
'followingUrl'
]
@DefaultScope(() => ({
include: [
{
model: ServerModel,
required: false
},
{
model: ActorImageModel,
as: 'Avatars',
required: false
}
]
}))
@Scopes(() => ({
[ScopeNames.FULL]: {
include: [
{
model: AccountModel.unscoped(),
required: false
},
{
model: VideoChannelModel.unscoped(),
required: false,
include: [
{
model: AccountModel,
required: true
}
]
},
{
model: ServerModel,
required: false
},
{
model: ActorImageModel,
as: 'Avatars',
required: false
},
{
model: ActorImageModel,
as: 'Banners',
required: false
}
]
}
}))
@Table({
tableName: 'actor',
indexes: [
{
fields: [ 'url' ],
unique: true
},
{
fields: [ fn('lower', col('preferredUsername')), 'serverId' ],
name: 'actor_preferred_username_lower_server_id',
unique: true,
where: {
serverId: {
[Op.ne]: null
}
}
},
{
fields: [ fn('lower', col('preferredUsername')) ],
name: 'actor_preferred_username_lower',
unique: true,
where: {
serverId: null
}
},
{
fields: [ 'inboxUrl', 'sharedInboxUrl' ]
},
{
fields: [ 'sharedInboxUrl' ]
},
{
fields: [ 'serverId' ]
},
{
fields: [ 'followersUrl' ]
},
{
fields: [ 'accountId' ],
unique: true
},
{
fields: [ 'videoChannelId' ],
unique: true
}
]
})
export class ActorModel extends SequelizeModel<ActorModel> {
@AllowNull(false)
@Column(DataType.ENUM(...Object.values(ACTIVITY_PUB_ACTOR_TYPES)))
declare type: ActivityPubActorType
@AllowNull(false)
@Is('ActorPreferredUsername', value => throwIfNotValid(value, isActorPreferredUsernameValid, 'actor preferred username'))
@Column
declare preferredUsername: string
@AllowNull(false)
@Is('ActorUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
declare url: string
@AllowNull(true)
@Is('ActorPublicKey', value => throwIfNotValid(value, isActorPublicKeyValid, 'public key', true))
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PUBLIC_KEY.max))
declare publicKey: string
@AllowNull(true)
@Is('ActorPublicKey', value => throwIfNotValid(value, isActorPrivateKeyValid, 'private key', true))
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PRIVATE_KEY.max))
declare privateKey: string
@AllowNull(false)
@Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowersCountValid, 'followers count'))
@Column
declare followersCount: number
@AllowNull(false)
@Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowingCountValid, 'following count'))
@Column
declare followingCount: number
@AllowNull(false)
@Is('ActorInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'inbox url'))
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
declare inboxUrl: string
@AllowNull(true)
@Is('ActorOutboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'outbox url', true))
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
declare outboxUrl: string
@AllowNull(true)
@Is('ActorSharedInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'shared inbox url', true))
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
declare sharedInboxUrl: string
@AllowNull(true)
@Is('ActorFollowersUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'followers url', true))
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
declare followersUrl: string
@AllowNull(true)
@Is('ActorFollowingUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'following url', true))
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
declare followingUrl: string
@AllowNull(true)
@Column
declare remoteCreatedAt: Date
@CreatedAt
declare createdAt: Date
@UpdatedAt
declare updatedAt: Date
@HasMany(() => ActorImageModel, {
as: 'Avatars',
onDelete: 'cascade',
hooks: true,
foreignKey: {
allowNull: false
},
scope: {
type: ActorImageType.AVATAR
}
})
declare Avatars: Awaited<ActorImageModel>[]
@HasMany(() => ActorImageModel, {
as: 'Banners',
onDelete: 'cascade',
hooks: true,
foreignKey: {
allowNull: false
},
scope: {
type: ActorImageType.BANNER
}
})
declare Banners: Awaited<ActorImageModel>[]
@HasMany(() => UploadImageModel, {
as: 'UploadImages',
onDelete: 'cascade',
hooks: true,
foreignKey: {
allowNull: false
}
})
declare UploadImages: Awaited<UploadImageModel>[]
@HasMany(() => ActorFollowModel, {
foreignKey: {
name: 'actorId',
allowNull: false
},
as: 'ActorFollowings',
onDelete: 'cascade'
})
declare ActorFollowing: Awaited<ActorFollowModel>[]
@HasMany(() => ActorFollowModel, {
foreignKey: {
name: 'targetActorId',
allowNull: false
},
as: 'ActorFollowers',
onDelete: 'cascade'
})
declare ActorFollowers: Awaited<ActorFollowModel>[]
@ForeignKey(() => ServerModel)
@Column
declare serverId: number
@BelongsTo(() => ServerModel, {
foreignKey: {
allowNull: true
},
onDelete: 'cascade'
})
declare Server: Awaited<ServerModel>
@ForeignKey(() => VideoChannelModel)
@Column
declare videoChannelId: number
@BelongsTo(() => VideoChannelModel, {
foreignKey: {
allowNull: true
},
onDelete: 'cascade'
})
declare VideoChannel: Awaited<VideoChannelModel>
@ForeignKey(() => AccountModel)
@Column
declare accountId: number
@BelongsTo(() => AccountModel, {
foreignKey: {
allowNull: true
},
onDelete: 'cascade'
})
declare Account: Awaited<AccountModel>
// ---------------------------------------------------------------------------
@BeforeDestroy
static async reserveActor (instance: ActorModel, options) {
if (instance.isLocal()) {
await ActorReservedModel.create({
preferredUsername: instance.preferredUsername,
url: instance.url,
publicKey: instance.publicKey,
privateKey: instance.privateKey,
actorId: instance.id,
accountId: instance.accountId,
videoChannelId: instance.videoChannelId
}, { transaction: options.transaction })
}
return undefined
}
// ---------------------------------------------------------------------------
static getSQLAttributes (tableName: string, aliasPrefix = '') {
return buildSQLAttributes({
model: this,
tableName,
aliasPrefix
})
}
static getSQLAPIAttributes (tableName: string, aliasPrefix = '') {
return buildSQLAttributes({
model: this,
tableName,
aliasPrefix,
excludeAttributes: unusedActorAttributesForAPI
})
}
static getSQLSummaryAttributes (tableName: string, aliasPrefix = '') {
return buildSQLAttributes({
model: ActorModel,
tableName,
aliasPrefix,
includeAttributes: actorSummaryAttributes
})
}
// ---------------------------------------------------------------------------
// FIXME: have to specify the result type to not break peertube typings generation
static wherePreferredUsername (preferredUsername: string, colName = 'preferredUsername'): Where {
return where(fn('lower', col(colName)), preferredUsername.toLowerCase())
}
// ---------------------------------------------------------------------------
static async load (id: number, transaction?: Transaction): Promise<MActor> {
const actorServer = await getServerActor()
if (id === actorServer.id) return actorServer
return ActorModel.unscoped().findByPk(id, { transaction })
}
static loadFull (id: number, transaction?: Transaction): Promise<MActorFull> {
return ActorModel.scope(ScopeNames.FULL).findByPk(id, { transaction })
}
static loadAccountActorFollowerUrlByVideoId (videoId: number, transaction: Transaction) {
const query = `SELECT "actor"."id" AS "id", "actor"."followersUrl" AS "followersUrl" ` +
`FROM "actor" ` +
`INNER JOIN "account" ON "actor"."accountId" = "account"."id" ` +
`INNER JOIN "videoChannel" ON "videoChannel"."accountId" = "account"."id" ` +
`INNER JOIN "video" ON "video"."channelId" = "videoChannel"."id" AND "video"."id" = :videoId`
const options = {
type: QueryTypes.SELECT as QueryTypes.SELECT,
replacements: { videoId },
plain: true,
transaction
}
return ActorModel.sequelize.query<MActorId & MActorFollowersUrl>(query, options)
.then(res => {
if (res && res.length !== 0) return res[0]
return undefined
})
}
static listByFollowersUrls (followersUrls: string[], transaction?: Transaction): Promise<MActorFull[]> {
const query = {
where: {
followersUrl: {
[Op.in]: followersUrls
}
},
transaction
}
return ActorModel.scope(ScopeNames.FULL).findAll(query)
}
static loadLocalByName (preferredUsername: string, transaction?: Transaction): Promise<MActorFull> {
const fun = () => {
const query = {
where: {
[Op.and]: [
this.wherePreferredUsername(preferredUsername, '"ActorModel"."preferredUsername"'),
{
serverId: null
}
]
},
transaction
}
return ActorModel.scope(ScopeNames.FULL).findOne(query)
}
return ModelCache.Instance.doCache({
cacheType: 'local-actor-name',
key: preferredUsername,
// The server actor never change, so we can easily cache it
whitelist: () => preferredUsername === SERVER_ACTOR_NAME,
fun
})
}
static loadLocalUrlByName (preferredUsername: string, transaction?: Transaction): Promise<MActorUrl> {
const fun = () => {
const query = {
attributes: [ 'url' ],
where: {
[Op.and]: [
this.wherePreferredUsername(preferredUsername),
{
serverId: null
}
]
},
transaction
}
return ActorModel.unscoped().findOne(query)
}
return ModelCache.Instance.doCache({
cacheType: 'local-actor-url',
key: preferredUsername,
// The server actor never change, so we can easily cache it
whitelist: () => preferredUsername === SERVER_ACTOR_NAME,
fun
})
}
static loadByNameAndHost (preferredUsername: string, host: string): Promise<MActorFull> {
const query = {
where: this.wherePreferredUsername(preferredUsername, '"ActorModel"."preferredUsername"'),
include: [
{
model: ServerModel,
required: true,
where: {
host
}
}
]
}
return ActorModel.scope(ScopeNames.FULL).findOne(query)
}
static loadByUrl (url: string, transaction?: Transaction): Promise<MActorAccountChannelId> {
const query = {
where: {
url
},
transaction,
include: [
{
attributes: [ 'id' ],
model: AccountModel.unscoped(),
required: false
},
{
attributes: [ 'id' ],
model: VideoChannelModel.unscoped(),
required: false
}
]
}
return ActorModel.unscoped().findOne(query)
}
static loadByUrlAndPopulateAccountAndChannel (url: string, transaction?: Transaction): Promise<MActorFull> {
const query = {
where: {
url
},
transaction
}
return ActorModel.scope(ScopeNames.FULL).findOne(query)
}
static loadByUniqueKeys (options: {
preferredUsername: string
serverId: number
url: string
transaction: Transaction
}) {
const { preferredUsername, serverId, url, transaction } = options
return ActorModel.findOne({
where: {
[Op.or]: [
{
url
},
{
serverId,
preferredUsername
}
]
},
transaction
})
}
// ---------------------------------------------------------------------------
static async recalculateFollowsCount (options: {
ofId: number
type: 'followers' | 'following'
by: number
transaction?: Transaction
}) {
const { transaction, ofId, type, by } = options
const sanitizedOfId = forceNumber(ofId)
const where = { id: sanitizedOfId }
let columnToUpdate: 'followersCount' | 'followingCount'
let columnOfCount: string
if (type === 'followers') {
columnToUpdate = 'followersCount'
columnOfCount = 'targetActorId'
} else {
columnToUpdate = 'followingCount'
columnOfCount = 'actorId'
}
const actor = await this.load(ofId, transaction)
// Remote actor where we don't store all the actor follows
// So we just increment the counter
if (actor.serverId) {
if (!by) return
return ActorModel.increment(columnToUpdate, {
by,
where,
transaction
})
}
return ActorModel.update({
[columnToUpdate]: literal(`(SELECT COUNT(*) FROM "actorFollow" WHERE "${columnOfCount}" = ${sanitizedOfId} AND "state" = 'accepted')`)
}, { where, transaction })
}
// ---------------------------------------------------------------------------
static loadAccountActorByVideoId (videoId: number, transaction: Transaction): Promise<MActor> {
const query = {
include: [
{
attributes: [ 'id' ],
model: AccountModel.unscoped(),
required: true,
include: [
{
attributes: [ 'id', 'accountId' ],
model: VideoChannelModel.unscoped(),
required: true,
include: [
{
attributes: [ 'id', 'channelId' ],
model: VideoModel.unscoped(),
where: {
id: videoId
}
}
]
}
]
}
],
transaction
}
return ActorModel.unscoped().findOne(query)
}
// ---------------------------------------------------------------------------
static getPublicKeyUrl (url: string) {
return url + '#main-key'
}
// ---------------------------------------------------------------------------
getSharedInbox (this: MActorWithInboxes) {
return this.sharedInboxUrl || this.inboxUrl
}
toFormattedSummaryJSON (this: MActorSummaryFormattable) {
return {
url: this.url,
name: this.preferredUsername,
host: this.getHost(),
avatars: (this.Avatars || []).map(a => a.toFormattedJSON())
}
}
toFormattedJSON (this: MActorFormattable, includeBanner = true) {
return {
...this.toFormattedSummaryJSON(),
id: this.id,
hostRedundancyAllowed: this.getRedundancyAllowed(),
followingCount: this.followingCount,
followersCount: this.followersCount,
createdAt: this.getCreatedAt(),
banners: includeBanner
? (this.Banners || []).map(b => b.toFormattedJSON())
: undefined
}
}
toActivityPubObject (this: MActorAPChannel | MActorAPAccount, name: string) {
let icon: ActivityIconObject[] // Avatars
let image: ActivityIconObject[] // Banners
if (this.hasImage(ActorImageType.AVATAR)) {
let avatars = this.Avatars
// Use 120px avatar as first position if possible, so that remote servers use it in priority (instead of using 48x48px)
const avatar120Px = avatars.find(a => a.width === 120)
if (avatar120Px) avatars = [ avatar120Px, ...avatars.filter(a => a.width !== 120) ]
icon = avatars.map(a => a.toActivityPubObject())
}
if (this.hasImage(ActorImageType.BANNER)) {
image = (this as MActorAPChannel).Banners.map(b => b.toActivityPubObject())
}
const json = {
type: this.type,
id: this.url,
following: this.getFollowingUrl(),
followers: this.getFollowersUrl(),
playlists: this.getPlaylistsUrl(),
inbox: this.inboxUrl,
outbox: this.outboxUrl,
preferredUsername: this.preferredUsername,
name,
endpoints: {
sharedInbox: this.sharedInboxUrl
},
publicKey: {
id: ActorModel.getPublicKeyUrl(this.url),
owner: this.url,
publicKeyPem: this.publicKey
},
published: this.getCreatedAt().toISOString(),
icon,
image
}
return activityPubContextify(json, 'Actor', getContextFilter())
}
getFollowerSharedInboxUrls (t: Transaction) {
const query = {
attributes: [ 'sharedInboxUrl' ],
include: [
{
attribute: [],
model: ActorFollowModel.unscoped(),
required: true,
as: 'ActorFollowing',
where: {
state: 'accepted',
targetActorId: this.id
}
}
],
transaction: t
}
return ActorModel.findAll(query)
.then(accounts => accounts.map(a => a.sharedInboxUrl))
}
getFollowingUrl () {
return this.url + '/following'
}
getFollowersUrl () {
return this.url + '/followers'
}
getPlaylistsUrl () {
return this.url + '/playlists'
}
isLocal () {
return this.serverId === null
}
getWebfingerUrl (this: MActorHost) {
return 'acct:' + this.preferredUsername + '@' + this.getHost()
}
getIdentifier (this: MActorHost) {
return this.Server ? `${this.preferredUsername}@${this.Server.host}` : this.preferredUsername
}
getFullIdentifier (this: MActorHost) {
return `${this.preferredUsername}@${this.getHost()}`
}
getHost (this: MActorHostOnly) {
if (this.serverId && !this.Server) throw new Error('Server is not loaded in the object')
return this.Server ? this.Server.host : WEBSERVER.HOST
}
getRedundancyAllowed () {
return this.Server ? this.Server.redundancyAllowed : false
}
hasImage (type: ActorImageType_Type) {
const images = type === ActorImageType.AVATAR
? this.Avatars
: this.Banners
return Array.isArray(images) && images.length !== 0
}
getMaxQualityImage (type: ActorImageType_Type) {
if (!this.hasImage(type)) return undefined
const images = type === ActorImageType.AVATAR
? this.Avatars
: this.Banners
return maxBy(images, 'height')
}
getAppropriateQualityImage (type: ActorImageType_Type, width: number) {
if (!this.hasImage(type)) return undefined
const images = type === ActorImageType.AVATAR
? this.Avatars
: this.Banners
return findAppropriateImage(images, width)
}
isOutdated () {
if (this.isLocal()) return false
return isOutdated(this, ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL)
}
getCreatedAt (this: MActorAPChannel | MActorAPAccount | MActorFormattable) {
return this.remoteCreatedAt || this.createdAt
}
}

View File

@@ -0,0 +1,46 @@
import { ActivityPubActorType, FollowState } from '@peertube/peertube-models'
import { AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'
import { Sequelize } from 'sequelize'
import { InstanceListFollowsQueryBuilder } from './shared/instance-list-follows-query-builder.js'
export interface ListFollowersOptions extends AbstractListQueryOptions {
actorIds: number[]
state?: FollowState
actorType?: ActivityPubActorType
search?: string
}
export class InstanceListFollowersQueryBuilder extends InstanceListFollowsQueryBuilder<ListFollowersOptions> {
constructor (
protected readonly sequelize: Sequelize,
protected readonly options: ListFollowersOptions
) {
super(sequelize, options)
}
protected buildSubQueryWhere () {
this.buildActorFollowingJoin()
this.subQueryWhere = 'WHERE "ActorFollowing"."id" IN (:actorIds) '
this.replacements.actorIds = this.options.actorIds
if (this.options.state) {
this.subQueryWhere += 'AND "ActorFollowModel"."state" = :state '
this.replacements.state = this.options.state
}
if (this.options.search) {
const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')
this.subQueryWhere += `AND (` +
`"ActorFollower->Server"."host" ILIKE ${escapedLikeSearch} ` +
`OR "ActorFollower"."preferredUsername" ILIKE ${escapedLikeSearch} ` +
`)`
}
if (this.options.actorType) {
this.subQueryWhere += `AND "ActorFollower"."type" = :actorType `
this.replacements.actorType = this.options.actorType
}
}
}

View File

@@ -0,0 +1,46 @@
import { ActivityPubActorType, FollowState } from '@peertube/peertube-models'
import { AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'
import { Sequelize } from 'sequelize'
import { InstanceListFollowsQueryBuilder } from './shared/instance-list-follows-query-builder.js'
export interface ListFollowingOptions extends AbstractListQueryOptions {
followerId: number
state?: FollowState
actorType?: ActivityPubActorType
search?: string
}
export class InstanceListFollowingQueryBuilder extends InstanceListFollowsQueryBuilder<ListFollowingOptions> {
constructor (
protected readonly sequelize: Sequelize,
protected readonly options: ListFollowingOptions
) {
super(sequelize, options)
}
protected buildSubQueryWhere () {
this.buildActorFollowingJoin()
this.subQueryWhere = 'WHERE "ActorFollowModel"."actorId" = :followerId '
this.replacements.followerId = this.options.followerId
if (this.options.state) {
this.subQueryWhere += 'AND "ActorFollowModel"."state" = :state '
this.replacements.state = this.options.state
}
if (this.options.search) {
const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')
this.subQueryWhere += `AND (` +
`"ActorFollowing->Server"."host" ILIKE ${escapedLikeSearch} ` +
`OR "ActorFollowing"."preferredUsername" ILIKE ${escapedLikeSearch} ` +
`)`
}
if (this.options.actorType) {
this.subQueryWhere += `AND "ActorFollowing"."type" = :actorType `
this.replacements.actorType = this.options.actorType
}
}
}

View File

@@ -0,0 +1,27 @@
import { Memoize } from '@server/helpers/memoize.js'
import { ServerModel } from '@server/models/server/server.js'
import { ActorModel } from '../../actor.js'
import { ActorFollowModel } from '../../actor-follow.js'
import { ActorImageModel } from '../../actor-image.js'
export class ActorFollowTableAttributes {
@Memoize()
getFollowAttributes () {
return ActorFollowModel.getSQLAttributes('ActorFollowModel').join(', ')
}
@Memoize()
getActorAttributes (actorTableName: string) {
return ActorModel.getSQLAPIAttributes(actorTableName, `${actorTableName}.`).join(', ')
}
@Memoize()
getServerAttributes (actorTableName: string) {
return ServerModel.getSQLAttributes(`${actorTableName}->Server`, `${actorTableName}.Server.`).join(', ')
}
@Memoize()
getAvatarAttributes (actorTableName: string) {
return ActorImageModel.getSQLAttributes(`${actorTableName}->Avatars`, `${actorTableName}.Avatars.`).join(', ')
}
}

View File

@@ -0,0 +1,75 @@
import { ActorImageType } from '@peertube/peertube-models'
import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'
import { Sequelize } from 'sequelize'
import { getInstanceFollowsSort } from '../../../shared/index.js'
import { ActorFollowTableAttributes } from './actor-follow-table-attributes.js'
export abstract class InstanceListFollowsQueryBuilder<T extends AbstractListQueryOptions> extends AbstractListQuery {
protected readonly tableAttributes = new ActorFollowTableAttributes()
private builtActorFollowingJoin = false
constructor (
protected readonly sequelize: Sequelize,
protected readonly options: T
) {
super(sequelize, { modelName: 'ActorFollowModel', tableName: 'actorFollow' }, options)
}
protected buildQueryJoin () {
this.join += this.getAvatarsJoin('ActorFollower')
this.join += this.getAvatarsJoin('ActorFollowing')
}
protected buildQueryAttributes () {
this.attributes = [
...this.attributes,
this.tableAttributes.getAvatarAttributes('ActorFollower'),
this.tableAttributes.getAvatarAttributes('ActorFollowing')
]
}
protected buildSubQueryJoin () {
this.buildActorFollowingJoin()
}
protected buildSubQueryAttributes () {
this.subQueryAttributes = [
...this.subQueryAttributes,
this.tableAttributes.getFollowAttributes(),
this.tableAttributes.getActorAttributes('ActorFollower'),
this.tableAttributes.getActorAttributes('ActorFollowing'),
this.tableAttributes.getServerAttributes('ActorFollower'),
this.tableAttributes.getServerAttributes('ActorFollowing')
]
}
protected getSort (sort: string) {
return getInstanceFollowsSort(sort)
}
protected buildActorFollowingJoin () {
if (this.builtActorFollowingJoin) return
this.subQueryJoin += 'INNER JOIN "actor" "ActorFollower" ON "ActorFollower"."id" = "ActorFollowModel"."actorId" ' +
'INNER JOIN "actor" "ActorFollowing" ON "ActorFollowing"."id" = "ActorFollowModel"."targetActorId" '
this.subQueryJoin += this.getServerJoin('ActorFollowing')
this.subQueryJoin += this.getServerJoin('ActorFollower')
this.builtActorFollowingJoin = true
}
// ---------------------------------------------------------------------------
private getServerJoin (actorName: string) {
return `LEFT JOIN "server" "${actorName}->Server" ON "${actorName}"."serverId" = "${actorName}->Server"."id" `
}
private getAvatarsJoin (actorName: string) {
return `LEFT JOIN "actorImage" "${actorName}->Avatars" ON "${actorName}.id" = "${actorName}->Avatars"."actorId" ` +
`AND "${actorName}->Avatars"."type" = ${ActorImageType.AVATAR} `
}
}