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'
39 import { afterCommitIfTransaction } from '@server/helpers/database-utils'
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 loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Bluebird<MActorFollowActorsDefault> {
159 targetActorId: targetActorId
176 return ActorFollowModel.findOne(query)
179 static loadByActorAndTargetNameAndHostForAPI (
184 ): Bluebird<MActorFollowActorsDefaultSubscription> {
185 const actorFollowingPartInclude: IncludeOptions = {
188 as: 'ActorFollowing',
190 preferredUsername: targetName
194 model: VideoChannelModel.unscoped(),
200 if (targetHost === null) {
201 actorFollowingPartInclude.where['serverId'] = null
203 actorFollowingPartInclude.include.push({
217 actorFollowingPartInclude,
227 return ActorFollowModel.findOne(query)
229 if (result && result.ActorFollowing.VideoChannel) {
230 result.ActorFollowing.VideoChannel.Actor = result.ActorFollowing
237 static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]): Bluebird<MActorFollowFollowingHost[]> {
238 const whereTab = targets
244 '$preferredUsername$': t.name
256 '$preferredUsername$': t.name
279 attributes: [ 'preferredUsername' ],
280 model: ActorModel.unscoped(),
282 as: 'ActorFollowing',
285 attributes: [ 'host' ],
286 model: ServerModel.unscoped(),
294 return ActorFollowModel.findAll(query)
297 static listFollowingForApi (options: {
303 actorType?: ActivityPubActorType,
306 const { id, start, count, sort, search, state, actorType } = options
308 const followWhere = state ? { state } : {}
309 const followingWhere: WhereOptions = {}
310 const followingServerWhere: WhereOptions = {}
313 Object.assign(followingServerWhere, {
315 [ Op.iLike ]: '%' + search + '%'
321 Object.assign(followingWhere, { type: actorType })
328 order: getFollowsSort(sort),
341 as: 'ActorFollowing',
343 where: followingWhere,
348 where: followingServerWhere
355 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
356 .then(({ rows, count }) => {
364 static listFollowersForApi (options: {
370 actorType?: ActivityPubActorType,
373 const { actorId, start, count, sort, search, state, actorType } = options
375 const followWhere = state ? { state } : {}
376 const followerWhere: WhereOptions = {}
377 const followerServerWhere: WhereOptions = {}
380 Object.assign(followerServerWhere, {
382 [ Op.iLike ]: '%' + search + '%'
388 Object.assign(followerWhere, { type: actorType })
395 order: getFollowsSort(sort),
402 where: followerWhere,
407 where: followerServerWhere
413 as: 'ActorFollowing',
422 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
423 .then(({ rows, count }) => {
431 static listSubscriptionsForApi (actorId: number, start: number, count: number, sort: string) {
437 order: getSort(sort),
443 attributes: [ 'id' ],
444 model: ActorModel.unscoped(),
445 as: 'ActorFollowing',
449 model: VideoChannelModel.unscoped(),
454 exclude: unusedActorAttributesForAPI
460 model: AccountModel.unscoped(),
465 exclude: unusedActorAttributesForAPI
479 return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
480 .then(({ rows, count }) => {
482 data: rows.map(r => r.ActorFollowing.VideoChannel),
488 static async keepUnfollowedInstance (hosts: string[]) {
489 const followerId = (await getServerActor()).id
492 attributes: [ 'id' ],
498 attributes: [ 'id' ],
499 model: ActorModel.unscoped(),
501 as: 'ActorFollowing',
503 preferredUsername: SERVER_ACTOR_NAME
507 attributes: [ 'host' ],
508 model: ServerModel.unscoped(),
521 const res = await ActorFollowModel.findAll(query)
522 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
524 return difference(hosts, followedHosts)
527 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
528 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
531 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
532 return ActorFollowModel.createListAcceptedFollowForApiQuery(
543 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
544 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
547 static async getStats () {
548 const serverActor = await getServerActor()
550 const totalInstanceFollowing = await ActorFollowModel.count({
552 actorId: serverActor.id
556 const totalInstanceFollowers = await ActorFollowModel.count({
558 targetActorId: serverActor.id
563 totalInstanceFollowing,
564 totalInstanceFollowers
568 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
569 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
571 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
572 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
573 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
577 type: QueryTypes.BULKUPDATE,
581 return ActorFollowModel.sequelize.query(query, options)
584 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
585 if (serverIds.length === 0) return
587 const me = await getServerActor()
588 const serverIdsString = createSafeIn(ActorFollowModel, serverIds)
590 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
592 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
593 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
594 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
595 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
599 type: QueryTypes.BULKUPDATE,
603 return ActorFollowModel.sequelize.query(query, options)
606 private static async createListAcceptedFollowForApiQuery (
607 type: 'followers' | 'following',
615 let firstJoin: string
616 let secondJoin: string
618 if (type === 'followers') {
619 firstJoin = 'targetActorId'
620 secondJoin = 'actorId'
622 firstJoin = 'actorId'
623 secondJoin = 'targetActorId'
626 const selections: string[] = []
627 if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
628 else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
630 selections.push('COUNT(*) AS "total"')
632 const tasks: Bluebird<any>[] = []
634 for (let selection of selections) {
635 let query = 'SELECT ' + selection + ' FROM "actor" ' +
636 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
637 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
638 `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
640 if (count !== undefined) query += 'LIMIT ' + count
641 if (start !== undefined) query += ' OFFSET ' + start
645 type: QueryTypes.SELECT,
648 tasks.push(ActorFollowModel.sequelize.query(query, options))
651 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
652 const urls: string[] = followers.map(f => f.selectionUrl)
656 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
660 private static listBadActorFollows () {
670 return ActorFollowModel.findAll(query)
673 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
674 const follower = this.ActorFollower.toFormattedJSON()
675 const following = this.ActorFollowing.toFormattedJSON()
683 createdAt: this.createdAt,
684 updatedAt: this.updatedAt