1 import * as Bluebird from 'bluebird'
2 import { values, difference } 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, getSort, getFollowsSort } 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'
41 tableName: 'actorFollow',
47 fields: [ 'targetActorId' ]
50 fields: [ 'actorId', 'targetActorId' ],
58 export class ActorFollowModel extends Model<ActorFollowModel> {
61 @Column(DataType.ENUM(...values(FOLLOW_STATES)))
65 @Default(ACTOR_FOLLOW_SCORE.BASE)
67 @Max(ACTOR_FOLLOW_SCORE.MAX)
77 @ForeignKey(() => ActorModel)
81 @BelongsTo(() => ActorModel, {
89 ActorFollower: ActorModel
91 @ForeignKey(() => ActorModel)
95 @BelongsTo(() => ActorModel, {
97 name: 'targetActorId',
100 as: 'ActorFollowing',
103 ActorFollowing: ActorModel
107 static incrementFollowerAndFollowingCount (instance: ActorFollowModel) {
108 if (instance.state !== 'accepted') return undefined
111 ActorModel.incrementFollows(instance.actorId, 'followingCount', 1),
112 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', 1)
117 static decrementFollowerAndFollowingCount (instance: ActorFollowModel) {
119 ActorModel.incrementFollows(instance.actorId, 'followingCount',-1),
120 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', -1)
124 static removeFollowsOf (actorId: number, t?: Transaction) {
132 targetActorId: actorId
139 return ActorFollowModel.destroy(query)
142 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
143 static async removeBadActorFollows () {
144 const actorFollows = await ActorFollowModel.listBadActorFollows()
146 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
147 await Promise.all(actorFollowsRemovePromises)
149 const numberOfActorFollowsRemoved = actorFollows.length
151 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
154 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Bluebird<MActorFollowActorsDefault> {
158 targetActorId: targetActorId
175 return ActorFollowModel.findOne(query)
178 static loadByActorAndTargetNameAndHostForAPI (
183 ): Bluebird<MActorFollowActorsDefaultSubscription> {
184 const actorFollowingPartInclude: IncludeOptions = {
187 as: 'ActorFollowing',
189 preferredUsername: targetName
193 model: VideoChannelModel.unscoped(),
199 if (targetHost === null) {
200 actorFollowingPartInclude.where['serverId'] = null
202 actorFollowingPartInclude.include.push({
216 actorFollowingPartInclude,
226 return ActorFollowModel.findOne(query)
228 if (result && result.ActorFollowing.VideoChannel) {
229 result.ActorFollowing.VideoChannel.Actor = result.ActorFollowing
236 static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]): Bluebird<MActorFollowFollowingHost[]> {
237 const whereTab = targets
243 '$preferredUsername$': t.name
255 '$preferredUsername$': t.name
278 attributes: [ 'preferredUsername' ],
279 model: ActorModel.unscoped(),
281 as: 'ActorFollowing',
284 attributes: [ 'host' ],
285 model: ServerModel.unscoped(),
293 return ActorFollowModel.findAll(query)
296 static listFollowingForApi (options: {
302 actorType?: ActivityPubActorType,
305 const { id, start, count, sort, search, state, actorType } = options
307 const followWhere = state ? { state } : {}
308 const followingWhere: WhereOptions = {}
309 const followingServerWhere: WhereOptions = {}
312 Object.assign(followingServerWhere, {
314 [ Op.iLike ]: '%' + search + '%'
320 Object.assign(followingWhere, { type: actorType })
327 order: getFollowsSort(sort),
340 as: 'ActorFollowing',
342 where: followingWhere,
347 where: followingServerWhere
354 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
355 .then(({ rows, count }) => {
363 static listFollowersForApi (options: {
369 actorType?: ActivityPubActorType,
372 const { actorId, start, count, sort, search, state, actorType } = options
374 const followWhere = state ? { state } : {}
375 const followerWhere: WhereOptions = {}
376 const followerServerWhere: WhereOptions = {}
379 Object.assign(followerServerWhere, {
381 [ Op.iLike ]: '%' + search + '%'
387 Object.assign(followerWhere, { type: actorType })
394 order: getFollowsSort(sort),
401 where: followerWhere,
406 where: followerServerWhere
412 as: 'ActorFollowing',
421 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
422 .then(({ rows, count }) => {
430 static listSubscriptionsForApi (actorId: number, start: number, count: number, sort: string) {
436 order: getSort(sort),
442 attributes: [ 'id' ],
443 model: ActorModel.unscoped(),
444 as: 'ActorFollowing',
448 model: VideoChannelModel.unscoped(),
453 exclude: unusedActorAttributesForAPI
459 model: AccountModel.unscoped(),
464 exclude: unusedActorAttributesForAPI
478 return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
479 .then(({ rows, count }) => {
481 data: rows.map(r => r.ActorFollowing.VideoChannel),
487 static async keepUnfollowedInstance (hosts: string[]) {
488 const followerId = (await getServerActor()).id
491 attributes: [ 'id' ],
497 attributes: [ 'id' ],
498 model: ActorModel.unscoped(),
500 as: 'ActorFollowing',
502 preferredUsername: SERVER_ACTOR_NAME
506 attributes: [ 'host' ],
507 model: ServerModel.unscoped(),
520 const res = await ActorFollowModel.findAll(query)
521 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
523 return difference(hosts, followedHosts)
526 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
527 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
530 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
531 return ActorFollowModel.createListAcceptedFollowForApiQuery(
542 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
543 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
546 static async getStats () {
547 const serverActor = await getServerActor()
549 const totalInstanceFollowing = await ActorFollowModel.count({
551 actorId: serverActor.id
555 const totalInstanceFollowers = await ActorFollowModel.count({
557 targetActorId: serverActor.id
562 totalInstanceFollowing,
563 totalInstanceFollowers
567 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
568 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
570 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
571 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
572 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
576 type: QueryTypes.BULKUPDATE,
580 return ActorFollowModel.sequelize.query(query, options)
583 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
584 if (serverIds.length === 0) return
586 const me = await getServerActor()
587 const serverIdsString = createSafeIn(ActorFollowModel, serverIds)
589 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
591 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
592 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
593 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
594 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
598 type: QueryTypes.BULKUPDATE,
602 return ActorFollowModel.sequelize.query(query, options)
605 private static async createListAcceptedFollowForApiQuery (
606 type: 'followers' | 'following',
614 let firstJoin: string
615 let secondJoin: string
617 if (type === 'followers') {
618 firstJoin = 'targetActorId'
619 secondJoin = 'actorId'
621 firstJoin = 'actorId'
622 secondJoin = 'targetActorId'
625 const selections: string[] = []
626 if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
627 else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
629 selections.push('COUNT(*) AS "total"')
631 const tasks: Bluebird<any>[] = []
633 for (let selection of selections) {
634 let query = 'SELECT ' + selection + ' FROM "actor" ' +
635 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
636 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
637 `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
639 if (count !== undefined) query += 'LIMIT ' + count
640 if (start !== undefined) query += ' OFFSET ' + start
644 type: QueryTypes.SELECT,
647 tasks.push(ActorFollowModel.sequelize.query(query, options))
650 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
651 const urls: string[] = followers.map(f => f.selectionUrl)
655 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
659 private static listBadActorFollows () {
669 return ActorFollowModel.findAll(query)
672 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
673 const follower = this.ActorFollower.toFormattedJSON()
674 const following = this.ActorFollowing.toFormattedJSON()
682 createdAt: this.createdAt,
683 updatedAt: this.updatedAt