1 import { difference, values } from 'lodash'
2 import { IncludeOptions, Op, QueryTypes, Transaction, WhereOptions } from 'sequelize'
20 } from 'sequelize-typescript'
21 import { isActivityPubUrlValid } from '@server/helpers/custom-validators/activitypub/misc'
22 import { doesExist } from '@server/helpers/database-utils'
23 import { getServerActor } from '@server/models/application/application'
25 MActorFollowActorsDefault,
26 MActorFollowActorsDefaultSubscription,
27 MActorFollowFollowingHost,
28 MActorFollowFormattable,
29 MActorFollowSubscriptions
30 } from '@server/types/models'
31 import { AttributesOnly } from '@shared/core-utils'
32 import { ActivityPubActorType } from '@shared/models'
33 import { FollowState } from '../../../shared/models/actors'
34 import { ActorFollow } from '../../../shared/models/actors/follow.model'
35 import { logger } from '../../helpers/logger'
36 import { ACTOR_FOLLOW_SCORE, CONSTRAINTS_FIELDS, FOLLOW_STATES, SERVER_ACTOR_NAME } from '../../initializers/constants'
37 import { AccountModel } from '../account/account'
38 import { ServerModel } from '../server/server'
39 import { createSafeIn, getFollowsSort, getSort, searchAttribute, throwIfNotValid } from '../utils'
40 import { VideoChannelModel } from '../video/video-channel'
41 import { ActorModel, unusedActorAttributesForAPI } from './actor'
44 tableName: 'actorFollow',
50 fields: [ 'targetActorId' ]
53 fields: [ 'actorId', 'targetActorId' ],
65 export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowModel>>> {
68 @Column(DataType.ENUM(...values(FOLLOW_STATES)))
72 @Default(ACTOR_FOLLOW_SCORE.BASE)
74 @Max(ACTOR_FOLLOW_SCORE.MAX)
78 // Allow null because we added this column in PeerTube v3, and don't want to generate fake URLs of remote follows
80 @Is('ActorFollowUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
81 @Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
90 @ForeignKey(() => ActorModel)
94 @BelongsTo(() => ActorModel, {
102 ActorFollower: ActorModel
104 @ForeignKey(() => ActorModel)
106 targetActorId: number
108 @BelongsTo(() => ActorModel, {
110 name: 'targetActorId',
113 as: 'ActorFollowing',
116 ActorFollowing: ActorModel
120 static incrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
121 if (instance.state !== 'accepted') return undefined
124 ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction),
125 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction)
130 static decrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
132 ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction),
133 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction)
137 static removeFollowsOf (actorId: number, t?: Transaction) {
145 targetActorId: actorId
152 return ActorFollowModel.destroy(query)
155 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
156 static async removeBadActorFollows () {
157 const actorFollows = await ActorFollowModel.listBadActorFollows()
159 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
160 await Promise.all(actorFollowsRemovePromises)
162 const numberOfActorFollowsRemoved = actorFollows.length
164 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
167 static isFollowedBy (actorId: number, followerActorId: number) {
168 const query = 'SELECT 1 FROM "actorFollow" WHERE "actorId" = $followerActorId AND "targetActorId" = $actorId LIMIT 1'
170 return doesExist(query, { actorId, followerActorId })
173 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Promise<MActorFollowActorsDefault> {
177 targetActorId: targetActorId
194 return ActorFollowModel.findOne(query)
197 static loadByActorAndTargetNameAndHostForAPI (
202 ): Promise<MActorFollowActorsDefaultSubscription> {
203 const actorFollowingPartInclude: IncludeOptions = {
206 as: 'ActorFollowing',
208 preferredUsername: targetName
212 model: VideoChannelModel.unscoped(),
218 if (targetHost === null) {
219 actorFollowingPartInclude.where['serverId'] = null
221 actorFollowingPartInclude.include.push({
235 actorFollowingPartInclude,
245 return ActorFollowModel.findOne(query)
248 static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]): Promise<MActorFollowFollowingHost[]> {
249 const whereTab = targets
255 $preferredUsername$: t.name
267 $preferredUsername$: t.name
277 attributes: [ 'id' ],
290 attributes: [ 'preferredUsername' ],
291 model: ActorModel.unscoped(),
293 as: 'ActorFollowing',
296 attributes: [ 'host' ],
297 model: ServerModel.unscoped(),
305 return ActorFollowModel.findAll(query)
308 static listFollowingForApi (options: {
314 actorType?: ActivityPubActorType
317 const { id, start, count, sort, search, state, actorType } = options
319 const followWhere = state ? { state } : {}
320 const followingWhere: WhereOptions = {}
323 Object.assign(followWhere, {
325 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
326 searchAttribute(options.search, '$ActorFollowing.Server.host$')
332 Object.assign(followingWhere, { type: actorType })
339 order: getFollowsSort(sort),
352 as: 'ActorFollowing',
354 where: followingWhere,
365 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
366 .then(({ rows, count }) => {
374 static listFollowersForApi (options: {
380 actorType?: ActivityPubActorType
383 const { actorId, start, count, sort, search, state, actorType } = options
385 const followWhere = state ? { state } : {}
386 const followerWhere: WhereOptions = {}
389 Object.assign(followWhere, {
391 searchAttribute(search, '$ActorFollower.preferredUsername$'),
392 searchAttribute(search, '$ActorFollower.Server.host$')
398 Object.assign(followerWhere, { type: actorType })
405 order: getFollowsSort(sort),
412 where: followerWhere,
422 as: 'ActorFollowing',
431 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
432 .then(({ rows, count }) => {
440 static listSubscriptionsForApi (options: {
447 const { actorId, start, count, sort } = options
452 if (options.search) {
453 Object.assign(where, {
455 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
456 searchAttribute(options.search, '$ActorFollowing.VideoChannel.name$')
466 order: getSort(sort),
470 attributes: [ 'id' ],
471 model: ActorModel.unscoped(),
472 as: 'ActorFollowing',
476 model: VideoChannelModel.unscoped(),
481 exclude: unusedActorAttributesForAPI
487 model: AccountModel.unscoped(),
492 exclude: unusedActorAttributesForAPI
506 return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
507 .then(({ rows, count }) => {
509 data: rows.map(r => r.ActorFollowing.VideoChannel),
515 static async keepUnfollowedInstance (hosts: string[]) {
516 const followerId = (await getServerActor()).id
519 attributes: [ 'id' ],
525 attributes: [ 'id' ],
526 model: ActorModel.unscoped(),
528 as: 'ActorFollowing',
530 preferredUsername: SERVER_ACTOR_NAME
534 attributes: [ 'host' ],
535 model: ServerModel.unscoped(),
548 const res = await ActorFollowModel.findAll(query)
549 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
551 return difference(hosts, followedHosts)
554 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
555 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
558 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
559 return ActorFollowModel.createListAcceptedFollowForApiQuery(
570 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
571 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
574 static async getStats () {
575 const serverActor = await getServerActor()
577 const totalInstanceFollowing = await ActorFollowModel.count({
579 actorId: serverActor.id
583 const totalInstanceFollowers = await ActorFollowModel.count({
585 targetActorId: serverActor.id
590 totalInstanceFollowing,
591 totalInstanceFollowers
595 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
596 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
598 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
599 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
600 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
604 type: QueryTypes.BULKUPDATE,
608 return ActorFollowModel.sequelize.query(query, options)
611 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
612 if (serverIds.length === 0) return
614 const me = await getServerActor()
615 const serverIdsString = createSafeIn(ActorFollowModel.sequelize, serverIds)
617 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
619 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
620 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
621 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
622 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
626 type: QueryTypes.BULKUPDATE,
630 return ActorFollowModel.sequelize.query(query, options)
633 private static async createListAcceptedFollowForApiQuery (
634 type: 'followers' | 'following',
642 let firstJoin: string
643 let secondJoin: string
645 if (type === 'followers') {
646 firstJoin = 'targetActorId'
647 secondJoin = 'actorId'
649 firstJoin = 'actorId'
650 secondJoin = 'targetActorId'
653 const selections: string[] = []
654 if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
655 else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
657 selections.push('COUNT(*) AS "total"')
659 const tasks: Promise<any>[] = []
661 for (const selection of selections) {
662 let query = 'SELECT ' + selection + ' FROM "actor" ' +
663 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
664 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
665 `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
667 if (count !== undefined) query += 'LIMIT ' + count
668 if (start !== undefined) query += ' OFFSET ' + start
672 type: QueryTypes.SELECT,
675 tasks.push(ActorFollowModel.sequelize.query(query, options))
678 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
679 const urls: string[] = followers.map(f => f.selectionUrl)
683 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
687 private static listBadActorFollows () {
697 return ActorFollowModel.findAll(query)
700 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
701 const follower = this.ActorFollower.toFormattedJSON()
702 const following = this.ActorFollowing.toFormattedJSON()
710 createdAt: this.createdAt,
711 updatedAt: this.updatedAt