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 { ActorFollow } 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, unusedActorAttributesForAPI } from './actor'
30 import { VideoChannelModel } from '../video/video-channel'
31 import { IIncludeOptions } from '../../../node_modules/sequelize-typescript/lib/interfaces/IIncludeOptions'
32 import { AccountModel } from '../account/account'
35 tableName: 'actorFollow',
41 fields: [ 'targetActorId' ]
44 fields: [ 'actorId', 'targetActorId' ],
52 export class ActorFollowModel extends Model<ActorFollowModel> {
55 @Column(DataType.ENUM(values(FOLLOW_STATES)))
59 @Default(ACTOR_FOLLOW_SCORE.BASE)
61 @Max(ACTOR_FOLLOW_SCORE.MAX)
71 @ForeignKey(() => ActorModel)
75 @BelongsTo(() => ActorModel, {
83 ActorFollower: ActorModel
85 @ForeignKey(() => ActorModel)
89 @BelongsTo(() => ActorModel, {
91 name: 'targetActorId',
97 ActorFollowing: ActorModel
101 static incrementFollowerAndFollowingCount (instance: ActorFollowModel) {
102 if (instance.state !== 'accepted') return undefined
105 ActorModel.incrementFollows(instance.actorId, 'followingCount', 1),
106 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', 1)
111 static decrementFollowerAndFollowingCount (instance: ActorFollowModel) {
113 ActorModel.incrementFollows(instance.actorId, 'followingCount',-1),
114 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', -1)
118 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
119 static async removeBadActorFollows () {
120 const actorFollows = await ActorFollowModel.listBadActorFollows()
122 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
123 await Promise.all(actorFollowsRemovePromises)
125 const numberOfActorFollowsRemoved = actorFollows.length
127 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
130 static updateActorFollowsScore (goodInboxes: string[], badInboxes: string[], t: Sequelize.Transaction | undefined) {
131 if (goodInboxes.length === 0 && badInboxes.length === 0) return
133 logger.info('Updating %d good actor follows and %d bad actor follows scores.', goodInboxes.length, badInboxes.length)
135 if (goodInboxes.length !== 0) {
136 ActorFollowModel.incrementScores(goodInboxes, ACTOR_FOLLOW_SCORE.BONUS, t)
137 .catch(err => logger.error('Cannot increment scores of good actor follows.', { err }))
140 if (badInboxes.length !== 0) {
141 ActorFollowModel.incrementScores(badInboxes, ACTOR_FOLLOW_SCORE.PENALTY, t)
142 .catch(err => logger.error('Cannot decrement scores of bad actor follows.', { err }))
146 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Sequelize.Transaction) {
150 targetActorId: targetActorId
167 return ActorFollowModel.findOne(query)
170 static loadByActorAndTargetNameAndHostForAPI (actorId: number, targetName: string, targetHost: string, t?: Sequelize.Transaction) {
171 const actorFollowingPartInclude: IIncludeOptions = {
174 as: 'ActorFollowing',
176 preferredUsername: targetName
180 model: VideoChannelModel.unscoped(),
186 if (targetHost === null) {
187 actorFollowingPartInclude.where['serverId'] = null
189 actorFollowingPartInclude.include.push({
203 actorFollowingPartInclude,
213 return ActorFollowModel.findOne(query)
215 if (result && result.ActorFollowing.VideoChannel) {
216 result.ActorFollowing.VideoChannel.Actor = result.ActorFollowing
223 static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]) {
224 const whereTab = targets
228 [ Sequelize.Op.and ]: [
230 '$preferredUsername$': t.name
240 [ Sequelize.Op.and ]: [
242 '$preferredUsername$': t.name
254 [ Sequelize.Op.and ]: [
256 [ Sequelize.Op.or ]: whereTab
265 attributes: [ 'preferredUsername' ],
266 model: ActorModel.unscoped(),
268 as: 'ActorFollowing',
271 attributes: [ 'host' ],
272 model: ServerModel.unscoped(),
280 return ActorFollowModel.findAll(query)
283 static listFollowingForApi (id: number, start: number, count: number, sort: string, search?: string) {
288 order: getSort(sort),
300 as: 'ActorFollowing',
308 [Sequelize.Op.iLike]: '%' + search + '%'
317 return ActorFollowModel.findAndCountAll(query)
318 .then(({ rows, count }) => {
326 static listFollowersForApi (id: number, start: number, count: number, sort: string, search?: string) {
331 order: getSort(sort),
343 [ Sequelize.Op.iLike ]: '%' + search + '%'
351 as: 'ActorFollowing',
360 return ActorFollowModel.findAndCountAll(query)
361 .then(({ rows, count }) => {
369 static listSubscriptionsForApi (id: number, start: number, count: number, sort: string) {
375 order: getSort(sort),
381 attributes: [ 'id' ],
382 model: ActorModel.unscoped(),
383 as: 'ActorFollowing',
387 model: VideoChannelModel.unscoped(),
392 exclude: unusedActorAttributesForAPI
398 model: AccountModel.unscoped(),
403 exclude: unusedActorAttributesForAPI
417 return ActorFollowModel.findAndCountAll(query)
418 .then(({ rows, count }) => {
420 data: rows.map(r => r.ActorFollowing.VideoChannel),
426 static listAcceptedFollowerUrlsForApi (actorIds: number[], t: Sequelize.Transaction, start?: number, count?: number) {
427 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
430 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Sequelize.Transaction) {
431 return ActorFollowModel.createListAcceptedFollowForApiQuery(
442 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Sequelize.Transaction, start?: number, count?: number) {
443 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
446 static async getStats () {
447 const serverActor = await getServerActor()
449 const totalInstanceFollowing = await ActorFollowModel.count({
451 actorId: serverActor.id
455 const totalInstanceFollowers = await ActorFollowModel.count({
457 targetActorId: serverActor.id
462 totalInstanceFollowing,
463 totalInstanceFollowers
467 private static async createListAcceptedFollowForApiQuery (
468 type: 'followers' | 'following',
470 t: Sequelize.Transaction,
476 let firstJoin: string
477 let secondJoin: string
479 if (type === 'followers') {
480 firstJoin = 'targetActorId'
481 secondJoin = 'actorId'
483 firstJoin = 'actorId'
484 secondJoin = 'targetActorId'
487 const selections: string[] = []
488 if (distinct === true) selections.push('DISTINCT("Follows"."' + columnUrl + '") AS "url"')
489 else selections.push('"Follows"."' + columnUrl + '" AS "url"')
491 selections.push('COUNT(*) AS "total"')
493 const tasks: Bluebird<any>[] = []
495 for (let selection of selections) {
496 let query = 'SELECT ' + selection + ' FROM "actor" ' +
497 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
498 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
499 'WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = \'accepted\' '
501 if (count !== undefined) query += 'LIMIT ' + count
502 if (start !== undefined) query += ' OFFSET ' + start
506 type: Sequelize.QueryTypes.SELECT,
509 tasks.push(ActorFollowModel.sequelize.query(query, options))
512 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
513 const urls: string[] = followers.map(f => f.url)
517 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
521 private static incrementScores (inboxUrls: string[], value: number, t: Sequelize.Transaction | undefined) {
522 const inboxUrlsString = inboxUrls.map(url => `'${url}'`).join(',')
524 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
526 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
527 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
528 'WHERE "actor"."inboxUrl" IN (' + inboxUrlsString + ') OR "actor"."sharedInboxUrl" IN (' + inboxUrlsString + ')' +
531 const options = t ? {
532 type: Sequelize.QueryTypes.BULKUPDATE,
536 return ActorFollowModel.sequelize.query(query, options)
539 private static listBadActorFollows () {
543 [Sequelize.Op.lte]: 0
549 return ActorFollowModel.findAll(query)
552 toFormattedJSON (): ActorFollow {
553 const follower = this.ActorFollower.toFormattedJSON()
554 const following = this.ActorFollowing.toFormattedJSON()
562 createdAt: this.createdAt,
563 updatedAt: this.updatedAt