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 { getServerActor } from '../../helpers/utils'
24 import { ACTOR_FOLLOW_SCORE, FOLLOW_STATES, SERVER_ACTOR_NAME } from '../../initializers/constants'
25 import { ServerModel } from '../server/server'
26 import { createSafeIn, getFollowsSort, getSort } from '../utils'
27 import { ActorModel, unusedActorAttributesForAPI } from './actor'
28 import { VideoChannelModel } from '../video/video-channel'
29 import { AccountModel } from '../account/account'
30 import { IncludeOptions, Op, QueryTypes, Transaction, WhereOptions } from 'sequelize'
32 MActorFollowActorsDefault,
33 MActorFollowActorsDefaultSubscription,
34 MActorFollowFollowingHost,
35 MActorFollowFormattable,
36 MActorFollowSubscriptions
37 } from '@server/typings/models'
38 import { ActivityPubActorType } from '@shared/models'
39 import { VideoModel } from '@server/models/video/video'
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 (actorId: number, start: number, count: number, sort: string) {
449 order: getSort(sort),
455 attributes: [ 'id' ],
456 model: ActorModel.unscoped(),
457 as: 'ActorFollowing',
461 model: VideoChannelModel.unscoped(),
466 exclude: unusedActorAttributesForAPI
472 model: AccountModel.unscoped(),
477 exclude: unusedActorAttributesForAPI
491 return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
492 .then(({ rows, count }) => {
494 data: rows.map(r => r.ActorFollowing.VideoChannel),
500 static async keepUnfollowedInstance (hosts: string[]) {
501 const followerId = (await getServerActor()).id
504 attributes: [ 'id' ],
510 attributes: [ 'id' ],
511 model: ActorModel.unscoped(),
513 as: 'ActorFollowing',
515 preferredUsername: SERVER_ACTOR_NAME
519 attributes: [ 'host' ],
520 model: ServerModel.unscoped(),
533 const res = await ActorFollowModel.findAll(query)
534 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
536 return difference(hosts, followedHosts)
539 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
540 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
543 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
544 return ActorFollowModel.createListAcceptedFollowForApiQuery(
555 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
556 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
559 static async getStats () {
560 const serverActor = await getServerActor()
562 const totalInstanceFollowing = await ActorFollowModel.count({
564 actorId: serverActor.id
568 const totalInstanceFollowers = await ActorFollowModel.count({
570 targetActorId: serverActor.id
575 totalInstanceFollowing,
576 totalInstanceFollowers
580 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
581 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
583 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
584 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
585 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
589 type: QueryTypes.BULKUPDATE,
593 return ActorFollowModel.sequelize.query(query, options)
596 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
597 if (serverIds.length === 0) return
599 const me = await getServerActor()
600 const serverIdsString = createSafeIn(ActorFollowModel, serverIds)
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"."targetActorId" ' +
606 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
607 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
611 type: QueryTypes.BULKUPDATE,
615 return ActorFollowModel.sequelize.query(query, options)
618 private static async createListAcceptedFollowForApiQuery (
619 type: 'followers' | 'following',
627 let firstJoin: string
628 let secondJoin: string
630 if (type === 'followers') {
631 firstJoin = 'targetActorId'
632 secondJoin = 'actorId'
634 firstJoin = 'actorId'
635 secondJoin = 'targetActorId'
638 const selections: string[] = []
639 if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
640 else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
642 selections.push('COUNT(*) AS "total"')
644 const tasks: Bluebird<any>[] = []
646 for (const selection of selections) {
647 let query = 'SELECT ' + selection + ' FROM "actor" ' +
648 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
649 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
650 `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
652 if (count !== undefined) query += 'LIMIT ' + count
653 if (start !== undefined) query += ' OFFSET ' + start
657 type: QueryTypes.SELECT,
660 tasks.push(ActorFollowModel.sequelize.query(query, options))
663 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
664 const urls: string[] = followers.map(f => f.selectionUrl)
668 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
672 private static listBadActorFollows () {
682 return ActorFollowModel.findAll(query)
685 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
686 const follower = this.ActorFollower.toFormattedJSON()
687 const following = this.ActorFollowing.toFormattedJSON()
695 createdAt: this.createdAt,
696 updatedAt: this.updatedAt