1 import * as Bluebird from 'bluebird'
2 import { values } from 'lodash'
3 import * as Sequelize from 'sequelize'
20 } from 'sequelize-typescript'
21 import { FollowState } from '../../../shared/models/actors'
22 import { AccountFollow } from '../../../shared/models/actors/follow.model'
23 import { logger } from '../../helpers/logger'
24 import { getServerActor } from '../../helpers/utils'
25 import { ACTOR_FOLLOW_SCORE } from '../../initializers'
26 import { FOLLOW_STATES } from '../../initializers/constants'
27 import { ServerModel } from '../server/server'
28 import { getSort } from '../utils'
29 import { ActorModel } from './actor'
30 import { VideoChannelModel } from '../video/video-channel'
31 import { IIncludeOptions } from '../../../node_modules/sequelize-typescript/lib/interfaces/IIncludeOptions'
34 tableName: 'actorFollow',
40 fields: [ 'targetActorId' ]
43 fields: [ 'actorId', 'targetActorId' ],
51 export class ActorFollowModel extends Model<ActorFollowModel> {
54 @Column(DataType.ENUM(values(FOLLOW_STATES)))
58 @Default(ACTOR_FOLLOW_SCORE.BASE)
60 @Max(ACTOR_FOLLOW_SCORE.MAX)
70 @ForeignKey(() => ActorModel)
74 @BelongsTo(() => ActorModel, {
82 ActorFollower: ActorModel
84 @ForeignKey(() => ActorModel)
88 @BelongsTo(() => ActorModel, {
90 name: 'targetActorId',
96 ActorFollowing: ActorModel
100 static incrementFollowerAndFollowingCount (instance: ActorFollowModel) {
101 if (instance.state !== 'accepted') return undefined
104 ActorModel.incrementFollows(instance.actorId, 'followingCount', 1),
105 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', 1)
110 static decrementFollowerAndFollowingCount (instance: ActorFollowModel) {
112 ActorModel.incrementFollows(instance.actorId, 'followingCount',-1),
113 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', -1)
117 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
118 static async removeBadActorFollows () {
119 const actorFollows = await ActorFollowModel.listBadActorFollows()
121 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
122 await Promise.all(actorFollowsRemovePromises)
124 const numberOfActorFollowsRemoved = actorFollows.length
126 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
129 static updateActorFollowsScore (goodInboxes: string[], badInboxes: string[], t: Sequelize.Transaction | undefined) {
130 if (goodInboxes.length === 0 && badInboxes.length === 0) return
132 logger.info('Updating %d good actor follows and %d bad actor follows scores.', goodInboxes.length, badInboxes.length)
134 if (goodInboxes.length !== 0) {
135 ActorFollowModel.incrementScores(goodInboxes, ACTOR_FOLLOW_SCORE.BONUS, t)
136 .catch(err => logger.error('Cannot increment scores of good actor follows.', { err }))
139 if (badInboxes.length !== 0) {
140 ActorFollowModel.incrementScores(badInboxes, ACTOR_FOLLOW_SCORE.PENALTY, t)
141 .catch(err => logger.error('Cannot decrement scores of bad actor follows.', { err }))
145 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Sequelize.Transaction) {
149 targetActorId: targetActorId
166 return ActorFollowModel.findOne(query)
169 static loadByActorAndTargetNameAndHost (actorId: number, targetName: string, targetHost: string, t?: Sequelize.Transaction) {
170 const actorFollowingPartInclude: IIncludeOptions = {
173 as: 'ActorFollowing',
175 preferredUsername: targetName
179 model: VideoChannelModel,
185 if (targetHost === null) {
186 actorFollowingPartInclude.where['serverId'] = null
188 actorFollowingPartInclude.include.push({
207 actorFollowingPartInclude
212 return ActorFollowModel.findOne(query)
215 static listFollowingForApi (id: number, start: number, count: number, sort: string) {
220 order: getSort(sort),
232 as: 'ActorFollowing',
234 include: [ ServerModel ]
239 return ActorFollowModel.findAndCountAll(query)
240 .then(({ rows, count }) => {
248 static listSubscriptionsForApi (id: number, start: number, count: number, sort: string) {
253 order: getSort(sort),
260 as: 'ActorFollowing',
264 model: VideoChannelModel,
272 return ActorFollowModel.findAndCountAll(query)
273 .then(({ rows, count }) => {
275 data: rows.map(r => r.ActorFollowing.VideoChannel),
281 static listFollowersForApi (id: number, start: number, count: number, sort: string) {
286 order: getSort(sort),
292 include: [ ServerModel ]
296 as: 'ActorFollowing',
305 return ActorFollowModel.findAndCountAll(query)
306 .then(({ rows, count }) => {
314 static listAcceptedFollowerUrlsForApi (actorIds: number[], t: Sequelize.Transaction, start?: number, count?: number) {
315 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
318 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Sequelize.Transaction) {
319 return ActorFollowModel.createListAcceptedFollowForApiQuery(
330 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Sequelize.Transaction, start?: number, count?: number) {
331 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
334 static async getStats () {
335 const serverActor = await getServerActor()
337 const totalInstanceFollowing = await ActorFollowModel.count({
339 actorId: serverActor.id
343 const totalInstanceFollowers = await ActorFollowModel.count({
345 targetActorId: serverActor.id
350 totalInstanceFollowing,
351 totalInstanceFollowers
355 private static async createListAcceptedFollowForApiQuery (
356 type: 'followers' | 'following',
358 t: Sequelize.Transaction,
364 let firstJoin: string
365 let secondJoin: string
367 if (type === 'followers') {
368 firstJoin = 'targetActorId'
369 secondJoin = 'actorId'
371 firstJoin = 'actorId'
372 secondJoin = 'targetActorId'
375 const selections: string[] = []
376 if (distinct === true) selections.push('DISTINCT("Follows"."' + columnUrl + '") AS "url"')
377 else selections.push('"Follows"."' + columnUrl + '" AS "url"')
379 selections.push('COUNT(*) AS "total"')
381 const tasks: Bluebird<any>[] = []
383 for (let selection of selections) {
384 let query = 'SELECT ' + selection + ' FROM "actor" ' +
385 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
386 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
387 'WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = \'accepted\' '
389 if (count !== undefined) query += 'LIMIT ' + count
390 if (start !== undefined) query += ' OFFSET ' + start
394 type: Sequelize.QueryTypes.SELECT,
397 tasks.push(ActorFollowModel.sequelize.query(query, options))
400 const [ followers, [ { total } ] ] = await Promise.all(tasks)
401 const urls: string[] = followers.map(f => f.url)
405 total: parseInt(total, 10)
409 private static incrementScores (inboxUrls: string[], value: number, t: Sequelize.Transaction | undefined) {
410 const inboxUrlsString = inboxUrls.map(url => `'${url}'`).join(',')
412 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
414 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
415 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
416 'WHERE "actor"."inboxUrl" IN (' + inboxUrlsString + ') OR "actor"."sharedInboxUrl" IN (' + inboxUrlsString + ')' +
419 const options = t ? {
420 type: Sequelize.QueryTypes.BULKUPDATE,
424 return ActorFollowModel.sequelize.query(query, options)
427 private static listBadActorFollows () {
431 [Sequelize.Op.lte]: 0
437 return ActorFollowModel.findAll(query)
440 toFormattedJSON (): AccountFollow {
441 const follower = this.ActorFollower.toFormattedJSON()
442 const following = this.ActorFollowing.toFormattedJSON()
450 createdAt: this.createdAt,
451 updatedAt: this.updatedAt