1 import * as Bluebird from 'bluebird'
2 import { values } 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 } from '../../initializers/constants'
25 import { ServerModel } from '../server/server'
26 import { createSafeIn, getSort } 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, Transaction, QueryTypes } from 'sequelize'
33 tableName: 'actorFollow',
39 fields: [ 'targetActorId' ]
42 fields: [ 'actorId', 'targetActorId' ],
50 export class ActorFollowModel extends Model<ActorFollowModel> {
53 @Column(DataType.ENUM(...values(FOLLOW_STATES)))
57 @Default(ACTOR_FOLLOW_SCORE.BASE)
59 @Max(ACTOR_FOLLOW_SCORE.MAX)
69 @ForeignKey(() => ActorModel)
73 @BelongsTo(() => ActorModel, {
81 ActorFollower: ActorModel
83 @ForeignKey(() => ActorModel)
87 @BelongsTo(() => ActorModel, {
89 name: 'targetActorId',
95 ActorFollowing: ActorModel
99 static incrementFollowerAndFollowingCount (instance: ActorFollowModel) {
100 if (instance.state !== 'accepted') return undefined
103 ActorModel.incrementFollows(instance.actorId, 'followingCount', 1),
104 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', 1)
109 static decrementFollowerAndFollowingCount (instance: ActorFollowModel) {
111 ActorModel.incrementFollows(instance.actorId, 'followingCount',-1),
112 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', -1)
116 static removeFollowsOf (actorId: number, t?: Transaction) {
124 targetActorId: actorId
131 return ActorFollowModel.destroy(query)
134 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
135 static async removeBadActorFollows () {
136 const actorFollows = await ActorFollowModel.listBadActorFollows()
138 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
139 await Promise.all(actorFollowsRemovePromises)
141 const numberOfActorFollowsRemoved = actorFollows.length
143 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
146 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction) {
150 targetActorId: targetActorId
167 return ActorFollowModel.findOne(query)
170 static loadByActorAndTargetNameAndHostForAPI (actorId: number, targetName: string, targetHost: string, t?: Transaction) {
171 const actorFollowingPartInclude: IncludeOptions = {
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
230 '$preferredUsername$': t.name
242 '$preferredUsername$': t.name
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 [Op.iLike]: '%' + search + '%'
317 return ActorFollowModel.findAndCountAll(query)
318 .then(({ rows, count }) => {
326 static listFollowersForApi (actorId: number, start: number, count: number, sort: string, search?: string) {
331 order: getSort(sort),
343 [ Op.iLike ]: '%' + search + '%'
351 as: 'ActorFollowing',
360 return ActorFollowModel.findAndCountAll(query)
361 .then(({ rows, count }) => {
369 static listSubscriptionsForApi (actorId: 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 listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
427 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
430 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
431 return ActorFollowModel.createListAcceptedFollowForApiQuery(
442 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: 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 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
468 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
470 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
471 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
472 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
476 type: QueryTypes.BULKUPDATE,
480 return ActorFollowModel.sequelize.query(query, options)
483 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
484 if (serverIds.length === 0) return
486 const me = await getServerActor()
487 const serverIdsString = createSafeIn(ActorFollowModel, serverIds)
489 const query = `UPDATE "actorFollow" SET "score" = "score" + ${value} ` +
491 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
492 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
493 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
494 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
498 type: QueryTypes.BULKUPDATE,
502 return ActorFollowModel.sequelize.query(query, options)
505 private static async createListAcceptedFollowForApiQuery (
506 type: 'followers' | 'following',
514 let firstJoin: string
515 let secondJoin: string
517 if (type === 'followers') {
518 firstJoin = 'targetActorId'
519 secondJoin = 'actorId'
521 firstJoin = 'actorId'
522 secondJoin = 'targetActorId'
525 const selections: string[] = []
526 if (distinct === true) selections.push('DISTINCT("Follows"."' + columnUrl + '") AS "url"')
527 else selections.push('"Follows"."' + columnUrl + '" AS "url"')
529 selections.push('COUNT(*) AS "total"')
531 const tasks: Bluebird<any>[] = []
533 for (let selection of selections) {
534 let query = 'SELECT ' + selection + ' FROM "actor" ' +
535 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
536 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
537 'WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = \'accepted\' '
539 if (count !== undefined) query += 'LIMIT ' + count
540 if (start !== undefined) query += ' OFFSET ' + start
544 type: QueryTypes.SELECT,
547 tasks.push(ActorFollowModel.sequelize.query(query, options))
550 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
551 const urls: string[] = followers.map(f => f.url)
555 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
559 private static listBadActorFollows () {
569 return ActorFollowModel.findAll(query)
572 toFormattedJSON (): ActorFollow {
573 const follower = this.ActorFollower.toFormattedJSON()
574 const following = this.ActorFollowing.toFormattedJSON()
582 createdAt: this.createdAt,
583 updatedAt: this.updatedAt