1 import * as Bluebird from 'bluebird'
2 import { values } from 'lodash'
3 import * as Sequelize from 'sequelize'
5 AfterCreate, AfterDestroy, AfterUpdate, AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, ForeignKey, IsInt, Max, Model,
7 } from 'sequelize-typescript'
8 import { FollowState } from '../../../shared/models/actors'
9 import { AccountFollow } from '../../../shared/models/actors/follow.model'
10 import { logger } from '../../helpers/logger'
11 import { getServerActor } from '../../helpers/utils'
12 import { ACTOR_FOLLOW_SCORE } from '../../initializers'
13 import { FOLLOW_STATES } from '../../initializers/constants'
14 import { ServerModel } from '../server/server'
15 import { getSort } from '../utils'
16 import { ActorModel } from './actor'
19 tableName: 'actorFollow',
25 fields: [ 'targetActorId' ]
28 fields: [ 'actorId', 'targetActorId' ],
36 export class ActorFollowModel extends Model<ActorFollowModel> {
39 @Column(DataType.ENUM(values(FOLLOW_STATES)))
43 @Default(ACTOR_FOLLOW_SCORE.BASE)
45 @Max(ACTOR_FOLLOW_SCORE.MAX)
55 @ForeignKey(() => ActorModel)
59 @BelongsTo(() => ActorModel, {
67 ActorFollower: ActorModel
69 @ForeignKey(() => ActorModel)
73 @BelongsTo(() => ActorModel, {
75 name: 'targetActorId',
81 ActorFollowing: ActorModel
85 static incrementFollowerAndFollowingCount (instance: ActorFollowModel) {
86 if (instance.state !== 'accepted') return undefined
89 ActorModel.incrementFollows(instance.actorId, 'followingCount', 1),
90 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', 1)
95 static decrementFollowerAndFollowingCount (instance: ActorFollowModel) {
97 ActorModel.incrementFollows(instance.actorId, 'followingCount',-1),
98 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', -1)
102 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
103 static async removeBadActorFollows () {
104 const actorFollows = await ActorFollowModel.listBadActorFollows()
106 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
107 await Promise.all(actorFollowsRemovePromises)
109 const numberOfActorFollowsRemoved = actorFollows.length
111 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
114 static updateActorFollowsScore (goodInboxes: string[], badInboxes: string[], t: Sequelize.Transaction | undefined) {
115 if (goodInboxes.length === 0 && badInboxes.length === 0) return
117 logger.info('Updating %d good actor follows and %d bad actor follows scores.', goodInboxes.length, badInboxes.length)
119 if (goodInboxes.length !== 0) {
120 ActorFollowModel.incrementScores(goodInboxes, ACTOR_FOLLOW_SCORE.BONUS, t)
121 .catch(err => logger.error('Cannot increment scores of good actor follows.', { err }))
124 if (badInboxes.length !== 0) {
125 ActorFollowModel.incrementScores(badInboxes, ACTOR_FOLLOW_SCORE.PENALTY, t)
126 .catch(err => logger.error('Cannot decrement scores of bad actor follows.', { err }))
130 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Sequelize.Transaction) {
134 targetActorId: targetActorId
151 return ActorFollowModel.findOne(query)
154 static loadByActorAndTargetHost (actorId: number, targetHost: string, t?: Sequelize.Transaction) {
168 as: 'ActorFollowing',
183 return ActorFollowModel.findOne(query)
186 static listFollowingForApi (id: number, start: number, count: number, sort: string) {
191 order: getSort(sort),
203 as: 'ActorFollowing',
205 include: [ ServerModel ]
210 return ActorFollowModel.findAndCountAll(query)
211 .then(({ rows, count }) => {
219 static listFollowersForApi (id: number, start: number, count: number, sort: string) {
224 order: getSort(sort),
230 include: [ ServerModel ]
234 as: 'ActorFollowing',
243 return ActorFollowModel.findAndCountAll(query)
244 .then(({ rows, count }) => {
252 static listAcceptedFollowerUrlsForApi (actorIds: number[], t: Sequelize.Transaction, start?: number, count?: number) {
253 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
256 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Sequelize.Transaction) {
257 return ActorFollowModel.createListAcceptedFollowForApiQuery(
268 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Sequelize.Transaction, start?: number, count?: number) {
269 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
272 static async getStats () {
273 const serverActor = await getServerActor()
275 const totalInstanceFollowing = await ActorFollowModel.count({
277 actorId: serverActor.id
281 const totalInstanceFollowers = await ActorFollowModel.count({
283 targetActorId: serverActor.id
288 totalInstanceFollowing,
289 totalInstanceFollowers
293 private static async createListAcceptedFollowForApiQuery (
294 type: 'followers' | 'following',
296 t: Sequelize.Transaction,
302 let firstJoin: string
303 let secondJoin: string
305 if (type === 'followers') {
306 firstJoin = 'targetActorId'
307 secondJoin = 'actorId'
309 firstJoin = 'actorId'
310 secondJoin = 'targetActorId'
313 const selections: string[] = []
314 if (distinct === true) selections.push('DISTINCT("Follows"."' + columnUrl + '") AS "url"')
315 else selections.push('"Follows"."' + columnUrl + '" AS "url"')
317 selections.push('COUNT(*) AS "total"')
319 const tasks: Bluebird<any>[] = []
321 for (let selection of selections) {
322 let query = 'SELECT ' + selection + ' FROM "actor" ' +
323 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
324 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
325 'WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = \'accepted\' '
327 if (count !== undefined) query += 'LIMIT ' + count
328 if (start !== undefined) query += ' OFFSET ' + start
332 type: Sequelize.QueryTypes.SELECT,
335 tasks.push(ActorFollowModel.sequelize.query(query, options))
338 const [ followers, [ { total } ] ] = await Promise.all(tasks)
339 const urls: string[] = followers.map(f => f.url)
343 total: parseInt(total, 10)
347 private static incrementScores (inboxUrls: string[], value: number, t: Sequelize.Transaction | undefined) {
348 const inboxUrlsString = inboxUrls.map(url => `'${url}'`).join(',')
350 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
352 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
353 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
354 'WHERE "actor"."inboxUrl" IN (' + inboxUrlsString + ') OR "actor"."sharedInboxUrl" IN (' + inboxUrlsString + ')' +
357 const options = t ? {
358 type: Sequelize.QueryTypes.BULKUPDATE,
362 return ActorFollowModel.sequelize.query(query, options)
365 private static listBadActorFollows () {
369 [Sequelize.Op.lte]: 0
375 return ActorFollowModel.findAll(query)
378 toFormattedJSON (): AccountFollow {
379 const follower = this.ActorFollower.toFormattedJSON()
380 const following = this.ActorFollowing.toFormattedJSON()
388 createdAt: this.createdAt,
389 updatedAt: this.updatedAt