1 import * as Bluebird from 'bluebird'
2 import { difference, values } from 'lodash'
19 } from 'sequelize-typescript'
20 import { FollowState } from '../../../shared/models/actors'
21 import { ActorFollow } from '../../../shared/models/actors/follow.model'
22 import { logger } from '../../helpers/logger'
23 import { ACTOR_FOLLOW_SCORE, FOLLOW_STATES, SERVER_ACTOR_NAME } from '../../initializers/constants'
24 import { ServerModel } from '../server/server'
25 import { createSafeIn, getFollowsSort, getSort, searchAttribute } from '../utils'
26 import { ActorModel, unusedActorAttributesForAPI } from './actor'
27 import { VideoChannelModel } from '../video/video-channel'
28 import { AccountModel } from '../account/account'
29 import { IncludeOptions, Op, QueryTypes, Transaction, WhereOptions } from 'sequelize'
31 MActorFollowActorsDefault,
32 MActorFollowActorsDefaultSubscription,
33 MActorFollowFollowingHost,
34 MActorFollowFormattable,
35 MActorFollowSubscriptions
36 } from '@server/types/models'
37 import { ActivityPubActorType } from '@shared/models'
38 import { VideoModel } from '@server/models/video/video'
39 import { getServerActor } from '@server/models/application/application'
42 tableName: 'actorFollow',
48 fields: [ 'targetActorId' ]
51 fields: [ 'actorId', 'targetActorId' ],
59 export class ActorFollowModel extends Model<ActorFollowModel> {
62 @Column(DataType.ENUM(...values(FOLLOW_STATES)))
66 @Default(ACTOR_FOLLOW_SCORE.BASE)
68 @Max(ACTOR_FOLLOW_SCORE.MAX)
78 @ForeignKey(() => ActorModel)
82 @BelongsTo(() => ActorModel, {
90 ActorFollower: ActorModel
92 @ForeignKey(() => ActorModel)
96 @BelongsTo(() => ActorModel, {
98 name: 'targetActorId',
101 as: 'ActorFollowing',
104 ActorFollowing: ActorModel
108 static incrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
109 if (instance.state !== 'accepted') return undefined
112 ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction),
113 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction)
118 static decrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
120 ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction),
121 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction)
125 static removeFollowsOf (actorId: number, t?: Transaction) {
133 targetActorId: actorId
140 return ActorFollowModel.destroy(query)
143 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
144 static async removeBadActorFollows () {
145 const actorFollows = await ActorFollowModel.listBadActorFollows()
147 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
148 await Promise.all(actorFollowsRemovePromises)
150 const numberOfActorFollowsRemoved = actorFollows.length
152 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
155 static isFollowedBy (actorId: number, followerActorId: number) {
156 const query = 'SELECT 1 FROM "actorFollow" WHERE "actorId" = $followerActorId AND "targetActorId" = $actorId LIMIT 1'
158 type: QueryTypes.SELECT as QueryTypes.SELECT,
159 bind: { actorId, followerActorId },
163 return VideoModel.sequelize.query(query, options)
164 .then(results => results.length === 1)
167 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Bluebird<MActorFollowActorsDefault> {
171 targetActorId: targetActorId
188 return ActorFollowModel.findOne(query)
191 static loadByActorAndTargetNameAndHostForAPI (
196 ): Bluebird<MActorFollowActorsDefaultSubscription> {
197 const actorFollowingPartInclude: IncludeOptions = {
200 as: 'ActorFollowing',
202 preferredUsername: targetName
206 model: VideoChannelModel.unscoped(),
212 if (targetHost === null) {
213 actorFollowingPartInclude.where['serverId'] = null
215 actorFollowingPartInclude.include.push({
229 actorFollowingPartInclude,
239 return ActorFollowModel.findOne(query)
241 if (result?.ActorFollowing.VideoChannel) {
242 result.ActorFollowing.VideoChannel.Actor = result.ActorFollowing
249 static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]): Bluebird<MActorFollowFollowingHost[]> {
250 const whereTab = targets
256 $preferredUsername$: t.name
268 $preferredUsername$: t.name
291 attributes: [ 'preferredUsername' ],
292 model: ActorModel.unscoped(),
294 as: 'ActorFollowing',
297 attributes: [ 'host' ],
298 model: ServerModel.unscoped(),
306 return ActorFollowModel.findAll(query)
309 static listFollowingForApi (options: {
315 actorType?: ActivityPubActorType
318 const { id, start, count, sort, search, state, actorType } = options
320 const followWhere = state ? { state } : {}
321 const followingWhere: WhereOptions = {}
322 const followingServerWhere: WhereOptions = {}
325 Object.assign(followingServerWhere, {
327 [Op.iLike]: '%' + search + '%'
333 Object.assign(followingWhere, { type: actorType })
340 order: getFollowsSort(sort),
353 as: 'ActorFollowing',
355 where: followingWhere,
360 where: followingServerWhere
367 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
368 .then(({ rows, count }) => {
376 static listFollowersForApi (options: {
382 actorType?: ActivityPubActorType
385 const { actorId, start, count, sort, search, state, actorType } = options
387 const followWhere = state ? { state } : {}
388 const followerWhere: WhereOptions = {}
389 const followerServerWhere: WhereOptions = {}
392 Object.assign(followerServerWhere, {
394 [Op.iLike]: '%' + search + '%'
400 Object.assign(followerWhere, { type: actorType })
407 order: getFollowsSort(sort),
414 where: followerWhere,
419 where: followerServerWhere
425 as: 'ActorFollowing',
434 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
435 .then(({ rows, count }) => {
443 static listSubscriptionsForApi (options: {
450 const { actorId, start, count, sort } = options
455 if (options.search) {
456 Object.assign(where, {
458 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
459 searchAttribute(options.search, '$ActorFollowing.VideoChannel.name$')
469 order: getSort(sort),
473 attributes: [ 'id' ],
474 model: ActorModel.unscoped(),
475 as: 'ActorFollowing',
479 model: VideoChannelModel.unscoped(),
484 exclude: unusedActorAttributesForAPI
490 model: AccountModel.unscoped(),
495 exclude: unusedActorAttributesForAPI
509 return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
510 .then(({ rows, count }) => {
512 data: rows.map(r => r.ActorFollowing.VideoChannel),
518 static async keepUnfollowedInstance (hosts: string[]) {
519 const followerId = (await getServerActor()).id
522 attributes: [ 'id' ],
528 attributes: [ 'id' ],
529 model: ActorModel.unscoped(),
531 as: 'ActorFollowing',
533 preferredUsername: SERVER_ACTOR_NAME
537 attributes: [ 'host' ],
538 model: ServerModel.unscoped(),
551 const res = await ActorFollowModel.findAll(query)
552 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
554 return difference(hosts, followedHosts)
557 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
558 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
561 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
562 return ActorFollowModel.createListAcceptedFollowForApiQuery(
573 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
574 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
577 static async getStats () {
578 const serverActor = await getServerActor()
580 const totalInstanceFollowing = await ActorFollowModel.count({
582 actorId: serverActor.id
586 const totalInstanceFollowers = await ActorFollowModel.count({
588 targetActorId: serverActor.id
593 totalInstanceFollowing,
594 totalInstanceFollowers
598 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
599 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
601 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
602 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
603 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
607 type: QueryTypes.BULKUPDATE,
611 return ActorFollowModel.sequelize.query(query, options)
614 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
615 if (serverIds.length === 0) return
617 const me = await getServerActor()
618 const serverIdsString = createSafeIn(ActorFollowModel, serverIds)
620 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
622 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
623 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
624 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
625 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
629 type: QueryTypes.BULKUPDATE,
633 return ActorFollowModel.sequelize.query(query, options)
636 private static async createListAcceptedFollowForApiQuery (
637 type: 'followers' | 'following',
645 let firstJoin: string
646 let secondJoin: string
648 if (type === 'followers') {
649 firstJoin = 'targetActorId'
650 secondJoin = 'actorId'
652 firstJoin = 'actorId'
653 secondJoin = 'targetActorId'
656 const selections: string[] = []
657 if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
658 else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
660 selections.push('COUNT(*) AS "total"')
662 const tasks: Bluebird<any>[] = []
664 for (const selection of selections) {
665 let query = 'SELECT ' + selection + ' FROM "actor" ' +
666 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
667 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
668 `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
670 if (count !== undefined) query += 'LIMIT ' + count
671 if (start !== undefined) query += ' OFFSET ' + start
675 type: QueryTypes.SELECT,
678 tasks.push(ActorFollowModel.sequelize.query(query, options))
681 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
682 const urls: string[] = followers.map(f => f.selectionUrl)
686 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
690 private static listBadActorFollows () {
700 return ActorFollowModel.findAll(query)
703 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
704 const follower = this.ActorFollower.toFormattedJSON()
705 const following = this.ActorFollowing.toFormattedJSON()
713 createdAt: this.createdAt,
714 updatedAt: this.updatedAt