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 { afterCommitIfTransaction } from '@server/helpers/database-utils'
23 import { getServerActor } from '@server/models/application/application'
27 MActorFollowActorsDefault,
28 MActorFollowActorsDefaultSubscription,
29 MActorFollowFollowingHost,
30 MActorFollowFormattable,
31 MActorFollowSubscriptions
32 } from '@server/types/models'
33 import { AttributesOnly } from '@shared/typescript-utils'
34 import { ActivityPubActorType } from '@shared/models'
35 import { FollowState } from '../../../shared/models/actors'
36 import { ActorFollow } from '../../../shared/models/actors/follow.model'
37 import { logger } from '../../helpers/logger'
38 import { ACTOR_FOLLOW_SCORE, CONSTRAINTS_FIELDS, FOLLOW_STATES, SERVER_ACTOR_NAME } from '../../initializers/constants'
39 import { AccountModel } from '../account/account'
40 import { ServerModel } from '../server/server'
41 import { doesExist } from '../shared/query'
42 import { createSafeIn, getFollowsSort, getSort, searchAttribute, throwIfNotValid } from '../utils'
43 import { VideoChannelModel } from '../video/video-channel'
44 import { ActorModel, unusedActorAttributesForAPI } from './actor'
47 tableName: 'actorFollow',
53 fields: [ 'targetActorId' ]
56 fields: [ 'actorId', 'targetActorId' ],
68 export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowModel>>> {
71 @Column(DataType.ENUM(...values(FOLLOW_STATES)))
75 @Default(ACTOR_FOLLOW_SCORE.BASE)
77 @Max(ACTOR_FOLLOW_SCORE.MAX)
81 // Allow null because we added this column in PeerTube v3, and don't want to generate fake URLs of remote follows
83 @Is('ActorFollowUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
84 @Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
93 @ForeignKey(() => ActorModel)
97 @BelongsTo(() => ActorModel, {
105 ActorFollower: ActorModel
107 @ForeignKey(() => ActorModel)
109 targetActorId: number
111 @BelongsTo(() => ActorModel, {
113 name: 'targetActorId',
116 as: 'ActorFollowing',
119 ActorFollowing: ActorModel
123 static incrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
124 return afterCommitIfTransaction(options.transaction, () => {
126 ActorModel.rebuildFollowsCount(instance.actorId, 'following'),
127 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers')
133 static decrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
134 return afterCommitIfTransaction(options.transaction, () => {
136 ActorModel.rebuildFollowsCount(instance.actorId, 'following'),
137 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers')
143 * @deprecated Use `findOrCreateCustom` instead
145 static findOrCreate (): any {
146 throw new Error('Must not be called')
149 // findOrCreate has issues with actor follow hooks
150 static async findOrCreateCustom (options: {
155 transaction: Transaction
156 }): Promise<[ MActorFollowActors, boolean ]> {
157 const { byActor, targetActor, activityId, state, transaction } = options
160 let actorFollow: MActorFollowActors = await ActorFollowModel.loadByActorAndTarget(byActor.id, targetActor.id, transaction)
165 actorFollow = await ActorFollowModel.create({
167 targetActorId: targetActor.id,
173 actorFollow.ActorFollowing = targetActor
174 actorFollow.ActorFollower = byActor
177 return [ actorFollow, created ]
180 static removeFollowsOf (actorId: number, t?: Transaction) {
188 targetActorId: actorId
195 return ActorFollowModel.destroy(query)
198 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
199 static async removeBadActorFollows () {
200 const actorFollows = await ActorFollowModel.listBadActorFollows()
202 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
203 await Promise.all(actorFollowsRemovePromises)
205 const numberOfActorFollowsRemoved = actorFollows.length
207 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
210 static isFollowedBy (actorId: number, followerActorId: number) {
211 const query = 'SELECT 1 FROM "actorFollow" WHERE "actorId" = $followerActorId AND "targetActorId" = $actorId LIMIT 1'
213 return doesExist(query, { actorId, followerActorId })
216 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Promise<MActorFollowActorsDefault> {
220 targetActorId: targetActorId
237 return ActorFollowModel.findOne(query)
240 static loadByActorAndTargetNameAndHostForAPI (
245 ): Promise<MActorFollowActorsDefaultSubscription> {
246 const actorFollowingPartInclude: IncludeOptions = {
249 as: 'ActorFollowing',
251 preferredUsername: targetName
255 model: VideoChannelModel.unscoped(),
261 if (targetHost === null) {
262 actorFollowingPartInclude.where['serverId'] = null
264 actorFollowingPartInclude.include.push({
278 actorFollowingPartInclude,
288 return ActorFollowModel.findOne(query)
291 static listSubscriptionsOf (actorId: number, targets: { name: string, host?: string }[]): Promise<MActorFollowFollowingHost[]> {
292 const whereTab = targets
298 $preferredUsername$: t.name
310 $preferredUsername$: t.name
320 attributes: [ 'id' ],
333 attributes: [ 'preferredUsername' ],
334 model: ActorModel.unscoped(),
336 as: 'ActorFollowing',
339 attributes: [ 'host' ],
340 model: ServerModel.unscoped(),
348 return ActorFollowModel.findAll(query)
351 static listInstanceFollowingForApi (options: {
357 actorType?: ActivityPubActorType
360 const { id, start, count, sort, search, state, actorType } = options
362 const followWhere = state ? { state } : {}
363 const followingWhere: WhereOptions = {}
366 Object.assign(followWhere, {
368 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
369 searchAttribute(options.search, '$ActorFollowing.Server.host$')
375 Object.assign(followingWhere, { type: actorType })
382 order: getFollowsSort(sort),
395 as: 'ActorFollowing',
397 where: followingWhere,
408 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
409 .then(({ rows, count }) => {
417 static listFollowersForApi (options: {
423 actorType?: ActivityPubActorType
426 const { actorIds, start, count, sort, search, state, actorType } = options
428 const followWhere = state ? { state } : {}
429 const followerWhere: WhereOptions = {}
432 Object.assign(followWhere, {
434 searchAttribute(search, '$ActorFollower.preferredUsername$'),
435 searchAttribute(search, '$ActorFollower.Server.host$')
441 Object.assign(followerWhere, { type: actorType })
448 order: getFollowsSort(sort),
459 as: 'ActorFollowing',
470 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
471 .then(({ rows, count }) => {
479 static listSubscriptionsForApi (options: {
486 const { actorId, start, count, sort } = options
491 if (options.search) {
492 Object.assign(where, {
494 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
495 searchAttribute(options.search, '$ActorFollowing.VideoChannel.name$')
505 order: getSort(sort),
509 attributes: [ 'id' ],
510 model: ActorModel.unscoped(),
511 as: 'ActorFollowing',
515 model: VideoChannelModel.unscoped(),
520 exclude: unusedActorAttributesForAPI
526 model: AccountModel.unscoped(),
531 exclude: unusedActorAttributesForAPI
545 return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
546 .then(({ rows, count }) => {
548 data: rows.map(r => r.ActorFollowing.VideoChannel),
554 static async keepUnfollowedInstance (hosts: string[]) {
555 const followerId = (await getServerActor()).id
558 attributes: [ 'id' ],
564 attributes: [ 'id' ],
565 model: ActorModel.unscoped(),
567 as: 'ActorFollowing',
569 preferredUsername: SERVER_ACTOR_NAME
573 attributes: [ 'host' ],
574 model: ServerModel.unscoped(),
587 const res = await ActorFollowModel.findAll(query)
588 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
590 return difference(hosts, followedHosts)
593 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
594 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
597 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
598 return ActorFollowModel.createListAcceptedFollowForApiQuery(
609 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
610 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
613 static async getStats () {
614 const serverActor = await getServerActor()
616 const totalInstanceFollowing = await ActorFollowModel.count({
618 actorId: serverActor.id
622 const totalInstanceFollowers = await ActorFollowModel.count({
624 targetActorId: serverActor.id
629 totalInstanceFollowing,
630 totalInstanceFollowers
634 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
635 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
637 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
638 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
639 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
643 type: QueryTypes.BULKUPDATE,
647 return ActorFollowModel.sequelize.query(query, options)
650 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
651 if (serverIds.length === 0) return
653 const me = await getServerActor()
654 const serverIdsString = createSafeIn(ActorFollowModel.sequelize, serverIds)
656 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
658 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
659 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
660 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
661 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
665 type: QueryTypes.BULKUPDATE,
669 return ActorFollowModel.sequelize.query(query, options)
672 private static async createListAcceptedFollowForApiQuery (
673 type: 'followers' | 'following',
681 let firstJoin: string
682 let secondJoin: string
684 if (type === 'followers') {
685 firstJoin = 'targetActorId'
686 secondJoin = 'actorId'
688 firstJoin = 'actorId'
689 secondJoin = 'targetActorId'
692 const selections: string[] = []
693 if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
694 else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
696 selections.push('COUNT(*) AS "total"')
698 const tasks: Promise<any>[] = []
700 for (const selection of selections) {
701 let query = 'SELECT ' + selection + ' FROM "actor" ' +
702 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
703 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
704 `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
706 if (count !== undefined) query += 'LIMIT ' + count
707 if (start !== undefined) query += ' OFFSET ' + start
711 type: QueryTypes.SELECT,
714 tasks.push(ActorFollowModel.sequelize.query(query, options))
717 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
718 const urls: string[] = followers.map(f => f.selectionUrl)
722 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
726 private static listBadActorFollows () {
736 return ActorFollowModel.findAll(query)
739 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
740 const follower = this.ActorFollower.toFormattedJSON()
741 const following = this.ActorFollowing.toFormattedJSON()
749 createdAt: this.createdAt,
750 updatedAt: this.updatedAt