1 import { difference } from 'lodash'
2 import { Attributes, FindOptions, Includeable, IncludeOptions, Op, QueryTypes, Transaction, WhereAttributeHash } 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 { FollowState } from '../../../shared/models/actors'
35 import { ActorFollow } from '../../../shared/models/actors/follow.model'
36 import { logger } from '../../helpers/logger'
37 import { ACTOR_FOLLOW_SCORE, CONSTRAINTS_FIELDS, FOLLOW_STATES, SERVER_ACTOR_NAME, SORTABLE_COLUMNS } from '../../initializers/constants'
38 import { AccountModel } from '../account/account'
39 import { ServerModel } from '../server/server'
40 import { doesExist } from '../shared/query'
41 import { createSafeIn, getSort, searchAttribute, throwIfNotValid } from '../utils'
42 import { VideoChannelModel } from '../video/video-channel'
43 import { ActorModel, unusedActorAttributesForAPI } from './actor'
44 import { InstanceListFollowersQueryBuilder, ListFollowersOptions } from './sql/instance-list-followers-query-builder'
45 import { InstanceListFollowingQueryBuilder, ListFollowingOptions } from './sql/instance-list-following-query-builder'
48 tableName: 'actorFollow',
54 fields: [ 'targetActorId' ]
57 fields: [ 'actorId', 'targetActorId' ],
69 export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowModel>>> {
72 @Column(DataType.ENUM(...Object.values(FOLLOW_STATES)))
76 @Default(ACTOR_FOLLOW_SCORE.BASE)
78 @Max(ACTOR_FOLLOW_SCORE.MAX)
82 // Allow null because we added this column in PeerTube v3, and don't want to generate fake URLs of remote follows
84 @Is('ActorFollowUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
85 @Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
94 @ForeignKey(() => ActorModel)
98 @BelongsTo(() => ActorModel, {
106 ActorFollower: ActorModel
108 @ForeignKey(() => ActorModel)
110 targetActorId: number
112 @BelongsTo(() => ActorModel, {
114 name: 'targetActorId',
117 as: 'ActorFollowing',
120 ActorFollowing: ActorModel
124 static incrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
125 return afterCommitIfTransaction(options.transaction, () => {
127 ActorModel.rebuildFollowsCount(instance.actorId, 'following'),
128 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers')
134 static decrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
135 return afterCommitIfTransaction(options.transaction, () => {
137 ActorModel.rebuildFollowsCount(instance.actorId, 'following'),
138 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers')
144 * @deprecated Use `findOrCreateCustom` instead
146 static findOrCreate (): any {
147 throw new Error('Must not be called')
150 // findOrCreate has issues with actor follow hooks
151 static async findOrCreateCustom (options: {
156 transaction: Transaction
157 }): Promise<[ MActorFollowActors, boolean ]> {
158 const { byActor, targetActor, activityId, state, transaction } = options
161 let actorFollow: MActorFollowActors = await ActorFollowModel.loadByActorAndTarget(byActor.id, targetActor.id, transaction)
166 actorFollow = await ActorFollowModel.create({
168 targetActorId: targetActor.id,
174 actorFollow.ActorFollowing = targetActor
175 actorFollow.ActorFollower = byActor
178 return [ actorFollow, created ]
181 static removeFollowsOf (actorId: number, t?: Transaction) {
189 targetActorId: actorId
196 return ActorFollowModel.destroy(query)
199 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
200 static async removeBadActorFollows () {
201 const actorFollows = await ActorFollowModel.listBadActorFollows()
203 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
204 await Promise.all(actorFollowsRemovePromises)
206 const numberOfActorFollowsRemoved = actorFollows.length
208 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
211 static isFollowedBy (actorId: number, followerActorId: number) {
212 const query = `SELECT 1 FROM "actorFollow" ` +
213 `WHERE "actorId" = $followerActorId AND "targetActorId" = $actorId AND "state" = 'accepted' ` +
216 return doesExist(query, { actorId, followerActorId })
219 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Promise<MActorFollowActorsDefault> {
240 return ActorFollowModel.findOne(query)
243 static loadByActorAndTargetNameAndHostForAPI (options: {
248 transaction?: Transaction
249 }): Promise<MActorFollowActorsDefaultSubscription> {
250 const { actorId, targetHost, targetName, state, transaction } = options
252 const actorFollowingPartInclude: IncludeOptions = {
255 as: 'ActorFollowing',
257 preferredUsername: targetName
261 model: VideoChannelModel.unscoped(),
267 if (targetHost === null) {
268 actorFollowingPartInclude.where['serverId'] = null
270 actorFollowingPartInclude.include.push({
279 const where: WhereAttributeHash<Attributes<ActorFollowModel>> = { actorId }
280 if (state) where.state = state
282 const query: FindOptions<Attributes<ActorFollowModel>> = {
285 actorFollowingPartInclude,
295 return ActorFollowModel.findOne(query)
298 static listSubscriptionsOf (actorId: number, targets: { name: string, host?: string }[]): Promise<MActorFollowFollowingHost[]> {
299 const whereTab = targets
305 $preferredUsername$: t.name
317 $preferredUsername$: t.name
327 attributes: [ 'id' ],
341 attributes: [ 'preferredUsername' ],
342 model: ActorModel.unscoped(),
344 as: 'ActorFollowing',
347 attributes: [ 'host' ],
348 model: ServerModel.unscoped(),
356 return ActorFollowModel.findAll(query)
359 static listInstanceFollowingForApi (options: ListFollowingOptions) {
361 new InstanceListFollowingQueryBuilder(this.sequelize, options).countFollowing(),
362 new InstanceListFollowingQueryBuilder(this.sequelize, options).listFollowing()
363 ]).then(([ total, data ]) => ({ total, data }))
366 static listFollowersForApi (options: ListFollowersOptions) {
368 new InstanceListFollowersQueryBuilder(this.sequelize, options).countFollowers(),
369 new InstanceListFollowersQueryBuilder(this.sequelize, options).listFollowers()
370 ]).then(([ total, data ]) => ({ total, data }))
373 static listSubscriptionsForApi (options: {
380 const { actorId, start, count, sort } = options
386 if (options.search) {
387 Object.assign(where, {
389 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
390 searchAttribute(options.search, '$ActorFollowing.VideoChannel.name$')
395 const getQuery = (forCount: boolean) => {
396 let channelInclude: Includeable[] = []
398 if (forCount !== true) {
402 exclude: unusedActorAttributesForAPI
408 model: AccountModel.unscoped(),
413 exclude: unusedActorAttributesForAPI
424 attributes: forCount === true
426 : SORTABLE_COLUMNS.USER_SUBSCRIPTIONS,
430 order: getSort(sort),
434 attributes: [ 'id' ],
435 model: ActorModel.unscoped(),
436 as: 'ActorFollowing',
440 model: VideoChannelModel.unscoped(),
442 include: channelInclude
451 ActorFollowModel.count(getQuery(true)),
452 ActorFollowModel.findAll<MActorFollowSubscriptions>(getQuery(false))
453 ]).then(([ total, rows ]) => ({
455 data: rows.map(r => r.ActorFollowing.VideoChannel)
459 static async keepUnfollowedInstance (hosts: string[]) {
460 const followerId = (await getServerActor()).id
463 attributes: [ 'id' ],
469 attributes: [ 'id' ],
470 model: ActorModel.unscoped(),
472 as: 'ActorFollowing',
474 preferredUsername: SERVER_ACTOR_NAME
478 attributes: [ 'host' ],
479 model: ServerModel.unscoped(),
492 const res = await ActorFollowModel.findAll(query)
493 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
495 return difference(hosts, followedHosts)
498 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
499 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
502 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
503 return ActorFollowModel.createListAcceptedFollowForApiQuery(
514 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
515 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
518 static async getStats () {
519 const serverActor = await getServerActor()
521 const totalInstanceFollowing = await ActorFollowModel.count({
523 actorId: serverActor.id,
528 const totalInstanceFollowers = await ActorFollowModel.count({
530 targetActorId: serverActor.id,
536 totalInstanceFollowing,
537 totalInstanceFollowers
541 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
542 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
544 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
545 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
546 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
550 type: QueryTypes.BULKUPDATE,
554 return ActorFollowModel.sequelize.query(query, options)
557 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
558 if (serverIds.length === 0) return
560 const me = await getServerActor()
561 const serverIdsString = createSafeIn(ActorFollowModel.sequelize, serverIds)
563 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
565 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
566 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
567 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
568 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
572 type: QueryTypes.BULKUPDATE,
576 return ActorFollowModel.sequelize.query(query, options)
579 private static async createListAcceptedFollowForApiQuery (
580 type: 'followers' | 'following',
588 let firstJoin: string
589 let secondJoin: string
591 if (type === 'followers') {
592 firstJoin = 'targetActorId'
593 secondJoin = 'actorId'
595 firstJoin = 'actorId'
596 secondJoin = 'targetActorId'
599 const selections: string[] = []
600 if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
601 else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
603 selections.push('COUNT(*) AS "total"')
605 const tasks: Promise<any>[] = []
607 for (const selection of selections) {
608 let query = 'SELECT ' + selection + ' FROM "actor" ' +
609 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
610 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
611 `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
613 if (count !== undefined) query += 'LIMIT ' + count
614 if (start !== undefined) query += ' OFFSET ' + start
618 type: QueryTypes.SELECT,
621 tasks.push(ActorFollowModel.sequelize.query(query, options))
624 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
625 const urls: string[] = followers.map(f => f.selectionUrl)
629 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
633 private static listBadActorFollows () {
643 return ActorFollowModel.findAll(query)
646 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
647 const follower = this.ActorFollower.toFormattedJSON()
648 const following = this.ActorFollowing.toFormattedJSON()
656 createdAt: this.createdAt,
657 updatedAt: this.updatedAt