はじまりの大地
このコミットが含まれているのは:
@@ -0,0 +1,745 @@
|
||||
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, getSort, 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)))
|
||||
state: FollowState
|
||||
|
||||
@AllowNull(false)
|
||||
@Default(ACTOR_FOLLOW_SCORE.BASE)
|
||||
@IsInt
|
||||
@Max(ACTOR_FOLLOW_SCORE.MAX)
|
||||
@Column
|
||||
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))
|
||||
url: string
|
||||
|
||||
@CreatedAt
|
||||
createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
updatedAt: Date
|
||||
|
||||
@ForeignKey(() => ActorModel)
|
||||
@Column
|
||||
actorId: number
|
||||
|
||||
@BelongsTo(() => ActorModel, {
|
||||
foreignKey: {
|
||||
name: 'actorId',
|
||||
allowNull: false
|
||||
},
|
||||
as: 'ActorFollower',
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
ActorFollower: Awaited<ActorModel>
|
||||
|
||||
@ForeignKey(() => ActorModel)
|
||||
@Column
|
||||
targetActorId: number
|
||||
|
||||
@BelongsTo(() => ActorModel, {
|
||||
foreignKey: {
|
||||
name: 'targetActorId',
|
||||
allowNull: false
|
||||
},
|
||||
as: 'ActorFollowing',
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
ActorFollowing: Awaited<ActorModel>
|
||||
|
||||
@AfterCreate
|
||||
@AfterUpdate
|
||||
static incrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
|
||||
return afterCommitIfTransaction(options.transaction, () => {
|
||||
return Promise.all([
|
||||
ActorModel.rebuildFollowsCount(instance.actorId, 'following'),
|
||||
ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers')
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
@AfterDestroy
|
||||
static decrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
|
||||
return afterCommitIfTransaction(options.transaction, () => {
|
||||
return Promise.all([
|
||||
ActorModel.rebuildFollowsCount(instance.actorId, 'following'),
|
||||
ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers')
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
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 ]
|
||||
}
|
||||
|
||||
static removeFollowsOf (actorId: number, t?: Transaction) {
|
||||
const query = {
|
||||
where: {
|
||||
[Op.or]: [
|
||||
{
|
||||
actorId
|
||||
},
|
||||
{
|
||||
targetActorId: actorId
|
||||
}
|
||||
]
|
||||
},
|
||||
transaction: t
|
||||
}
|
||||
|
||||
return ActorFollowModel.destroy(query)
|
||||
}
|
||||
|
||||
// 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).countFollowing(),
|
||||
new InstanceListFollowingQueryBuilder(this.sequelize, options).listFollowing()
|
||||
]).then(([ total, data ]) => ({ total, data }))
|
||||
}
|
||||
|
||||
static listFollowersForApi (options: ListFollowersOptions) {
|
||||
return Promise.all([
|
||||
new InstanceListFollowersQueryBuilder(this.sequelize, options).countFollowers(),
|
||||
new InstanceListFollowersQueryBuilder(this.sequelize, options).listFollowers()
|
||||
]).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,
|
||||
distinct: true,
|
||||
offset: start,
|
||||
limit: count,
|
||||
order: getSort(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.actorId} ` + // 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { ActivityIconObject, ActorImage, ActorImageType, type ActorImageType_Type } from '@peertube/peertube-models'
|
||||
import { getLowercaseExtension } from '@peertube/peertube-node-utils'
|
||||
import { MActorId, MActorImage, MActorImageFormattable } from '@server/types/models/index.js'
|
||||
import { remove } from 'fs-extra/esm'
|
||||
import { join } from 'path'
|
||||
import { Op } 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
|
||||
filename: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Default(null)
|
||||
@Column
|
||||
height: number
|
||||
|
||||
@AllowNull(true)
|
||||
@Default(null)
|
||||
@Column
|
||||
width: number
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
fileUrl: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
onDisk: boolean
|
||||
|
||||
@AllowNull(false)
|
||||
@Column
|
||||
type: ActorImageType_Type
|
||||
|
||||
@CreatedAt
|
||||
createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
updatedAt: Date
|
||||
|
||||
@ForeignKey(() => ActorModel)
|
||||
@Column
|
||||
actorId: number
|
||||
|
||||
@BelongsTo(() => ActorModel, {
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
onDelete: 'CASCADE'
|
||||
})
|
||||
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) {
|
||||
const query = {
|
||||
where: {
|
||||
actorId: actor.id,
|
||||
type
|
||||
}
|
||||
}
|
||||
|
||||
return ActorImageModel.findAll(query)
|
||||
}
|
||||
|
||||
static async listActorImages (actor: MActorId) {
|
||||
const promises = [ ActorImageType.AVATAR, ActorImageType.BANNER ].map(type => ActorImageModel.listByActor(actor, type))
|
||||
|
||||
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: MActorImage) {
|
||||
if (!image) return undefined
|
||||
|
||||
return WEBSERVER.URL + image.getStaticPath()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
toFormattedJSON (this: MActorImageFormattable): ActorImage {
|
||||
return {
|
||||
width: this.width,
|
||||
path: this.getStaticPath(),
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt
|
||||
}
|
||||
}
|
||||
|
||||
toActivityPubObject (): ActivityIconObject {
|
||||
const extension = getLowercaseExtension(this.filename)
|
||||
|
||||
return {
|
||||
type: 'Image',
|
||||
mediaType: MIMETYPES.IMAGE.EXT_MIMETYPE[extension],
|
||||
height: this.height,
|
||||
width: this.width,
|
||||
url: ActorImageModel.getImageUrl(this)
|
||||
}
|
||||
}
|
||||
|
||||
getStaticPath () {
|
||||
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)
|
||||
}
|
||||
|
||||
isOwned () {
|
||||
return !this.fileUrl
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,696 @@
|
||||
import { 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,
|
||||
BelongsTo,
|
||||
Column,
|
||||
CreatedAt,
|
||||
DataType,
|
||||
DefaultScope,
|
||||
ForeignKey,
|
||||
HasMany,
|
||||
HasOne,
|
||||
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 { 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'
|
||||
|
||||
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' ]
|
||||
}
|
||||
]
|
||||
})
|
||||
export class ActorModel extends SequelizeModel<ActorModel> {
|
||||
|
||||
@AllowNull(false)
|
||||
@Column(DataType.ENUM(...Object.values(ACTIVITY_PUB_ACTOR_TYPES)))
|
||||
type: ActivityPubActorType
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('ActorPreferredUsername', value => throwIfNotValid(value, isActorPreferredUsernameValid, 'actor preferred username'))
|
||||
@Column
|
||||
preferredUsername: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('ActorUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
|
||||
url: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Is('ActorPublicKey', value => throwIfNotValid(value, isActorPublicKeyValid, 'public key', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PUBLIC_KEY.max))
|
||||
publicKey: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Is('ActorPublicKey', value => throwIfNotValid(value, isActorPrivateKeyValid, 'private key', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PRIVATE_KEY.max))
|
||||
privateKey: string
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowersCountValid, 'followers count'))
|
||||
@Column
|
||||
followersCount: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowingCountValid, 'following count'))
|
||||
@Column
|
||||
followingCount: number
|
||||
|
||||
@AllowNull(false)
|
||||
@Is('ActorInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'inbox url'))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
|
||||
inboxUrl: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Is('ActorOutboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'outbox url', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
|
||||
outboxUrl: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Is('ActorSharedInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'shared inbox url', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
|
||||
sharedInboxUrl: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Is('ActorFollowersUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'followers url', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
|
||||
followersUrl: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Is('ActorFollowingUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'following url', true))
|
||||
@Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
|
||||
followingUrl: string
|
||||
|
||||
@AllowNull(true)
|
||||
@Column
|
||||
remoteCreatedAt: Date
|
||||
|
||||
@CreatedAt
|
||||
createdAt: Date
|
||||
|
||||
@UpdatedAt
|
||||
updatedAt: Date
|
||||
|
||||
@HasMany(() => ActorImageModel, {
|
||||
as: 'Avatars',
|
||||
onDelete: 'cascade',
|
||||
hooks: true,
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
scope: {
|
||||
type: ActorImageType.AVATAR
|
||||
}
|
||||
})
|
||||
Avatars: Awaited<ActorImageModel>[]
|
||||
|
||||
@HasMany(() => ActorImageModel, {
|
||||
as: 'Banners',
|
||||
onDelete: 'cascade',
|
||||
hooks: true,
|
||||
foreignKey: {
|
||||
allowNull: false
|
||||
},
|
||||
scope: {
|
||||
type: ActorImageType.BANNER
|
||||
}
|
||||
})
|
||||
Banners: Awaited<ActorImageModel>[]
|
||||
|
||||
@HasMany(() => ActorFollowModel, {
|
||||
foreignKey: {
|
||||
name: 'actorId',
|
||||
allowNull: false
|
||||
},
|
||||
as: 'ActorFollowings',
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
ActorFollowing: Awaited<ActorFollowModel>[]
|
||||
|
||||
@HasMany(() => ActorFollowModel, {
|
||||
foreignKey: {
|
||||
name: 'targetActorId',
|
||||
allowNull: false
|
||||
},
|
||||
as: 'ActorFollowers',
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
ActorFollowers: Awaited<ActorFollowModel>[]
|
||||
|
||||
@ForeignKey(() => ServerModel)
|
||||
@Column
|
||||
serverId: number
|
||||
|
||||
@BelongsTo(() => ServerModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'cascade'
|
||||
})
|
||||
Server: Awaited<ServerModel>
|
||||
|
||||
@HasOne(() => AccountModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'cascade',
|
||||
hooks: true
|
||||
})
|
||||
Account: Awaited<AccountModel>
|
||||
|
||||
@HasOne(() => VideoChannelModel, {
|
||||
foreignKey: {
|
||||
allowNull: true
|
||||
},
|
||||
onDelete: 'cascade',
|
||||
hooks: true
|
||||
})
|
||||
VideoChannel: Awaited<VideoChannelModel>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static getSQLAttributes (tableName: string, aliasPrefix = '') {
|
||||
return buildSQLAttributes({
|
||||
model: this,
|
||||
tableName,
|
||||
aliasPrefix
|
||||
})
|
||||
}
|
||||
|
||||
static getSQLAPIAttributes (tableName: string, aliasPrefix = '') {
|
||||
return buildSQLAttributes({
|
||||
model: this,
|
||||
tableName,
|
||||
aliasPrefix,
|
||||
excludeAttributes: unusedActorAttributesForAPI
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// 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): Promise<MActor> {
|
||||
const actorServer = await getServerActor()
|
||||
if (id === actorServer.id) return actorServer
|
||||
|
||||
return ActorModel.unscoped().findByPk(id)
|
||||
}
|
||||
|
||||
static loadFull (id: number): Promise<MActorFull> {
|
||||
return ActorModel.scope(ScopeNames.FULL).findByPk(id)
|
||||
}
|
||||
|
||||
static loadAccountActorFollowerUrlByVideoId (videoId: number, transaction: Transaction) {
|
||||
const query = `SELECT "actor"."id" AS "id", "actor"."followersUrl" AS "followersUrl" ` +
|
||||
`FROM "actor" ` +
|
||||
`INNER JOIN "account" ON "actor"."id" = "account"."actorId" ` +
|
||||
`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 rebuildFollowsCount (ofId: number, type: 'followers' | 'following', transaction?: Transaction) {
|
||||
const sanitizedOfId = forceNumber(ofId)
|
||||
const where = { id: sanitizedOfId }
|
||||
|
||||
let columnToUpdate: string
|
||||
let columnOfCount: string
|
||||
|
||||
if (type === 'followers') {
|
||||
columnToUpdate = 'followersCount'
|
||||
columnOfCount = 'targetActorId'
|
||||
} else {
|
||||
columnToUpdate = 'followingCount'
|
||||
columnOfCount = 'actorId'
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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)) {
|
||||
icon = this.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,
|
||||
url: this.url,
|
||||
name,
|
||||
endpoints: {
|
||||
sharedInbox: this.sharedInboxUrl
|
||||
},
|
||||
publicKey: {
|
||||
id: this.getPublicKeyUrl(),
|
||||
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'
|
||||
}
|
||||
|
||||
getPublicKeyUrl () {
|
||||
return this.url + '#main-key'
|
||||
}
|
||||
|
||||
isOwned () {
|
||||
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) {
|
||||
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')
|
||||
}
|
||||
|
||||
isOutdated () {
|
||||
if (this.isOwned()) return false
|
||||
|
||||
return isOutdated(this, ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL)
|
||||
}
|
||||
|
||||
getCreatedAt (this: MActorAPChannel | MActorAPAccount | MActorFormattable) {
|
||||
return this.remoteCreatedAt || this.createdAt
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { Sequelize } from 'sequelize'
|
||||
import { ModelBuilder } from '@server/models/shared/index.js'
|
||||
import { MActorFollowActorsDefault } from '@server/types/models/index.js'
|
||||
import { ActivityPubActorType, FollowState } from '@peertube/peertube-models'
|
||||
import { parseRowCountResult } from '../../shared/index.js'
|
||||
import { InstanceListFollowsQueryBuilder } from './shared/instance-list-follows-query-builder.js'
|
||||
|
||||
export interface ListFollowersOptions {
|
||||
actorIds: number[]
|
||||
start: number
|
||||
count: number
|
||||
sort: string
|
||||
state?: FollowState
|
||||
actorType?: ActivityPubActorType
|
||||
search?: string
|
||||
}
|
||||
|
||||
export class InstanceListFollowersQueryBuilder extends InstanceListFollowsQueryBuilder <ListFollowersOptions> {
|
||||
|
||||
constructor (
|
||||
protected readonly sequelize: Sequelize,
|
||||
protected readonly options: ListFollowersOptions
|
||||
) {
|
||||
super(sequelize, options)
|
||||
}
|
||||
|
||||
async listFollowers () {
|
||||
this.buildListQuery()
|
||||
|
||||
const results = await this.runQuery({ nest: true })
|
||||
const modelBuilder = new ModelBuilder<MActorFollowActorsDefault>(this.sequelize)
|
||||
|
||||
return modelBuilder.createModels(results, 'ActorFollow')
|
||||
}
|
||||
|
||||
async countFollowers () {
|
||||
this.buildCountQuery()
|
||||
|
||||
const result = await this.runQuery()
|
||||
|
||||
return parseRowCountResult(result)
|
||||
}
|
||||
|
||||
protected getWhere () {
|
||||
let where = 'WHERE "ActorFollowing"."id" IN (:actorIds) '
|
||||
this.replacements.actorIds = this.options.actorIds
|
||||
|
||||
if (this.options.state) {
|
||||
where += 'AND "ActorFollowModel"."state" = :state '
|
||||
this.replacements.state = this.options.state
|
||||
}
|
||||
|
||||
if (this.options.search) {
|
||||
const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')
|
||||
|
||||
where += `AND (` +
|
||||
`"ActorFollower->Server"."host" ILIKE ${escapedLikeSearch} ` +
|
||||
`OR "ActorFollower"."preferredUsername" ILIKE ${escapedLikeSearch} ` +
|
||||
`)`
|
||||
}
|
||||
|
||||
if (this.options.actorType) {
|
||||
where += `AND "ActorFollower"."type" = :actorType `
|
||||
this.replacements.actorType = this.options.actorType
|
||||
}
|
||||
|
||||
return where
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { Sequelize } from 'sequelize'
|
||||
import { ModelBuilder } from '@server/models/shared/index.js'
|
||||
import { MActorFollowActorsDefault } from '@server/types/models/index.js'
|
||||
import { ActivityPubActorType, FollowState } from '@peertube/peertube-models'
|
||||
import { parseRowCountResult } from '../../shared/index.js'
|
||||
import { InstanceListFollowsQueryBuilder } from './shared/instance-list-follows-query-builder.js'
|
||||
|
||||
export interface ListFollowingOptions {
|
||||
followerId: number
|
||||
start: number
|
||||
count: number
|
||||
sort: string
|
||||
state?: FollowState
|
||||
actorType?: ActivityPubActorType
|
||||
search?: string
|
||||
}
|
||||
|
||||
export class InstanceListFollowingQueryBuilder extends InstanceListFollowsQueryBuilder <ListFollowingOptions> {
|
||||
|
||||
constructor (
|
||||
protected readonly sequelize: Sequelize,
|
||||
protected readonly options: ListFollowingOptions
|
||||
) {
|
||||
super(sequelize, options)
|
||||
}
|
||||
|
||||
async listFollowing () {
|
||||
this.buildListQuery()
|
||||
|
||||
const results = await this.runQuery({ nest: true })
|
||||
const modelBuilder = new ModelBuilder<MActorFollowActorsDefault>(this.sequelize)
|
||||
|
||||
return modelBuilder.createModels(results, 'ActorFollow')
|
||||
}
|
||||
|
||||
async countFollowing () {
|
||||
this.buildCountQuery()
|
||||
|
||||
const result = await this.runQuery()
|
||||
|
||||
return parseRowCountResult(result)
|
||||
}
|
||||
|
||||
protected getWhere () {
|
||||
let where = 'WHERE "ActorFollowModel"."actorId" = :followerId '
|
||||
this.replacements.followerId = this.options.followerId
|
||||
|
||||
if (this.options.state) {
|
||||
where += 'AND "ActorFollowModel"."state" = :state '
|
||||
this.replacements.state = this.options.state
|
||||
}
|
||||
|
||||
if (this.options.search) {
|
||||
const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')
|
||||
|
||||
where += `AND (` +
|
||||
`"ActorFollowing->Server"."host" ILIKE ${escapedLikeSearch} ` +
|
||||
`OR "ActorFollowing"."preferredUsername" ILIKE ${escapedLikeSearch} ` +
|
||||
`)`
|
||||
}
|
||||
|
||||
if (this.options.actorType) {
|
||||
where += `AND "ActorFollowing"."type" = :actorType `
|
||||
this.replacements.actorType = this.options.actorType
|
||||
}
|
||||
|
||||
return where
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
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.getSQLAttributes(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(', ')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Sequelize } from 'sequelize'
|
||||
import { AbstractRunQuery } from '@server/models/shared/index.js'
|
||||
import { ActorImageType } from '@peertube/peertube-models'
|
||||
import { getInstanceFollowsSort } from '../../../shared/index.js'
|
||||
import { ActorFollowTableAttributes } from './actor-follow-table-attributes.js'
|
||||
|
||||
type BaseOptions = {
|
||||
sort: string
|
||||
count: number
|
||||
start: number
|
||||
}
|
||||
|
||||
export abstract class InstanceListFollowsQueryBuilder <T extends BaseOptions> extends AbstractRunQuery {
|
||||
protected readonly tableAttributes = new ActorFollowTableAttributes()
|
||||
|
||||
protected innerQuery: string
|
||||
|
||||
constructor (
|
||||
protected readonly sequelize: Sequelize,
|
||||
protected readonly options: T
|
||||
) {
|
||||
super(sequelize)
|
||||
}
|
||||
|
||||
protected abstract getWhere (): string
|
||||
|
||||
protected getJoins () {
|
||||
return 'INNER JOIN "actor" "ActorFollower" ON "ActorFollower"."id" = "ActorFollowModel"."actorId" ' +
|
||||
'INNER JOIN "actor" "ActorFollowing" ON "ActorFollowing"."id" = "ActorFollowModel"."targetActorId" '
|
||||
}
|
||||
|
||||
protected getServerJoin (actorName: string) {
|
||||
return `LEFT JOIN "server" "${actorName}->Server" ON "${actorName}"."serverId" = "${actorName}->Server"."id" `
|
||||
}
|
||||
|
||||
protected getAvatarsJoin (actorName: string) {
|
||||
return `LEFT JOIN "actorImage" "${actorName}->Avatars" ON "${actorName}.id" = "${actorName}->Avatars"."actorId" ` +
|
||||
`AND "${actorName}->Avatars"."type" = ${ActorImageType.AVATAR}`
|
||||
}
|
||||
|
||||
private buildInnerQuery () {
|
||||
this.innerQuery = `${this.getInnerSelect()} ` +
|
||||
`FROM "actorFollow" AS "ActorFollowModel" ` +
|
||||
`${this.getJoins()} ` +
|
||||
`${this.getServerJoin('ActorFollowing')} ` +
|
||||
`${this.getServerJoin('ActorFollower')} ` +
|
||||
`${this.getWhere()} ` +
|
||||
`${this.getOrder()} ` +
|
||||
`LIMIT :limit OFFSET :offset `
|
||||
|
||||
this.replacements.limit = this.options.count
|
||||
this.replacements.offset = this.options.start
|
||||
}
|
||||
|
||||
protected buildListQuery () {
|
||||
this.buildInnerQuery()
|
||||
|
||||
this.query = `${this.getSelect()} ` +
|
||||
`FROM (${this.innerQuery}) AS "ActorFollowModel" ` +
|
||||
`${this.getAvatarsJoin('ActorFollower')} ` +
|
||||
`${this.getAvatarsJoin('ActorFollowing')} ` +
|
||||
`${this.getOrder()}`
|
||||
}
|
||||
|
||||
protected buildCountQuery () {
|
||||
this.query = `SELECT COUNT(*) AS "total" ` +
|
||||
`FROM "actorFollow" AS "ActorFollowModel" ` +
|
||||
`${this.getJoins()} ` +
|
||||
`${this.getServerJoin('ActorFollowing')} ` +
|
||||
`${this.getServerJoin('ActorFollower')} ` +
|
||||
`${this.getWhere()}`
|
||||
}
|
||||
|
||||
private getInnerSelect () {
|
||||
return this.buildSelect([
|
||||
this.tableAttributes.getFollowAttributes(),
|
||||
this.tableAttributes.getActorAttributes('ActorFollower'),
|
||||
this.tableAttributes.getActorAttributes('ActorFollowing'),
|
||||
this.tableAttributes.getServerAttributes('ActorFollower'),
|
||||
this.tableAttributes.getServerAttributes('ActorFollowing')
|
||||
])
|
||||
}
|
||||
|
||||
private getSelect () {
|
||||
return this.buildSelect([
|
||||
'"ActorFollowModel".*',
|
||||
this.tableAttributes.getAvatarAttributes('ActorFollower'),
|
||||
this.tableAttributes.getAvatarAttributes('ActorFollowing')
|
||||
])
|
||||
}
|
||||
|
||||
private getOrder () {
|
||||
const orders = getInstanceFollowsSort(this.options.sort)
|
||||
|
||||
return 'ORDER BY ' + orders.map(o => `"${o[0]}" ${o[1]}`).join(', ')
|
||||
}
|
||||
}
|
||||
新しい課題から参照
ユーザをブロックする