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 { getServerActor } from '@server/models/application/application'
23 import { VideoModel } from '@server/models/video/video'
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 type: QueryTypes.SELECT as QueryTypes.SELECT,
171 bind: { actorId, followerActorId },
175 return VideoModel.sequelize.query(query, options)
176 .then(results => results.length === 1)
179 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Promise<MActorFollowActorsDefault> {
183 targetActorId: targetActorId
200 return ActorFollowModel.findOne(query)
203 static loadByActorAndTargetNameAndHostForAPI (
208 ): Promise<MActorFollowActorsDefaultSubscription> {
209 const actorFollowingPartInclude: IncludeOptions = {
212 as: 'ActorFollowing',
214 preferredUsername: targetName
218 model: VideoChannelModel.unscoped(),
224 if (targetHost === null) {
225 actorFollowingPartInclude.where['serverId'] = null
227 actorFollowingPartInclude.include.push({
241 actorFollowingPartInclude,
251 return ActorFollowModel.findOne(query)
254 static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]): Promise<MActorFollowFollowingHost[]> {
255 const whereTab = targets
261 $preferredUsername$: t.name
273 $preferredUsername$: t.name
283 attributes: [ 'id' ],
296 attributes: [ 'preferredUsername' ],
297 model: ActorModel.unscoped(),
299 as: 'ActorFollowing',
302 attributes: [ 'host' ],
303 model: ServerModel.unscoped(),
311 return ActorFollowModel.findAll(query)
314 static listFollowingForApi (options: {
320 actorType?: ActivityPubActorType
323 const { id, start, count, sort, search, state, actorType } = options
325 const followWhere = state ? { state } : {}
326 const followingWhere: WhereOptions = {}
329 Object.assign(followWhere, {
331 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
332 searchAttribute(options.search, '$ActorFollowing.Server.host$')
338 Object.assign(followingWhere, { type: actorType })
345 order: getFollowsSort(sort),
358 as: 'ActorFollowing',
360 where: followingWhere,
371 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
372 .then(({ rows, count }) => {
380 static listFollowersForApi (options: {
386 actorType?: ActivityPubActorType
389 const { actorId, start, count, sort, search, state, actorType } = options
391 const followWhere = state ? { state } : {}
392 const followerWhere: WhereOptions = {}
395 Object.assign(followWhere, {
397 searchAttribute(search, '$ActorFollower.preferredUsername$'),
398 searchAttribute(search, '$ActorFollower.Server.host$')
404 Object.assign(followerWhere, { type: actorType })
411 order: getFollowsSort(sort),
418 where: followerWhere,
428 as: 'ActorFollowing',
437 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
438 .then(({ rows, count }) => {
446 static listSubscriptionsForApi (options: {
453 const { actorId, start, count, sort } = options
458 if (options.search) {
459 Object.assign(where, {
461 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
462 searchAttribute(options.search, '$ActorFollowing.VideoChannel.name$')
472 order: getSort(sort),
476 attributes: [ 'id' ],
477 model: ActorModel.unscoped(),
478 as: 'ActorFollowing',
482 model: VideoChannelModel.unscoped(),
487 exclude: unusedActorAttributesForAPI
493 model: AccountModel.unscoped(),
498 exclude: unusedActorAttributesForAPI
512 return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
513 .then(({ rows, count }) => {
515 data: rows.map(r => r.ActorFollowing.VideoChannel),
521 static async keepUnfollowedInstance (hosts: string[]) {
522 const followerId = (await getServerActor()).id
525 attributes: [ 'id' ],
531 attributes: [ 'id' ],
532 model: ActorModel.unscoped(),
534 as: 'ActorFollowing',
536 preferredUsername: SERVER_ACTOR_NAME
540 attributes: [ 'host' ],
541 model: ServerModel.unscoped(),
554 const res = await ActorFollowModel.findAll(query)
555 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
557 return difference(hosts, followedHosts)
560 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
561 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
564 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
565 return ActorFollowModel.createListAcceptedFollowForApiQuery(
576 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
577 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
580 static async getStats () {
581 const serverActor = await getServerActor()
583 const totalInstanceFollowing = await ActorFollowModel.count({
585 actorId: serverActor.id
589 const totalInstanceFollowers = await ActorFollowModel.count({
591 targetActorId: serverActor.id
596 totalInstanceFollowing,
597 totalInstanceFollowers
601 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
602 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
604 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
605 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
606 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
610 type: QueryTypes.BULKUPDATE,
614 return ActorFollowModel.sequelize.query(query, options)
617 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
618 if (serverIds.length === 0) return
620 const me = await getServerActor()
621 const serverIdsString = createSafeIn(ActorFollowModel.sequelize, serverIds)
623 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
625 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
626 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
627 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
628 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
632 type: QueryTypes.BULKUPDATE,
636 return ActorFollowModel.sequelize.query(query, options)
639 private static async createListAcceptedFollowForApiQuery (
640 type: 'followers' | 'following',
648 let firstJoin: string
649 let secondJoin: string
651 if (type === 'followers') {
652 firstJoin = 'targetActorId'
653 secondJoin = 'actorId'
655 firstJoin = 'actorId'
656 secondJoin = 'targetActorId'
659 const selections: string[] = []
660 if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
661 else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
663 selections.push('COUNT(*) AS "total"')
665 const tasks: Promise<any>[] = []
667 for (const selection of selections) {
668 let query = 'SELECT ' + selection + ' FROM "actor" ' +
669 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
670 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
671 `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
673 if (count !== undefined) query += 'LIMIT ' + count
674 if (start !== undefined) query += ' OFFSET ' + start
678 type: QueryTypes.SELECT,
681 tasks.push(ActorFollowModel.sequelize.query(query, options))
684 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
685 const urls: string[] = followers.map(f => f.selectionUrl)
689 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
693 private static listBadActorFollows () {
703 return ActorFollowModel.findAll(query)
706 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
707 const follower = this.ActorFollower.toFormattedJSON()
708 const following = this.ActorFollowing.toFormattedJSON()
716 createdAt: this.createdAt,
717 updatedAt: this.updatedAt