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 } 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 } from 'sequelize'
32 MActorFollowActorsDefault,
33 MActorFollowActorsDefaultSubscription,
34 MActorFollowFollowingHost,
35 MActorFollowFormattable,
36 MActorFollowSubscriptions
37 } from '@server/typings/models'
40 tableName: 'actorFollow',
46 fields: [ 'targetActorId' ]
49 fields: [ 'actorId', 'targetActorId' ],
57 export class ActorFollowModel extends Model<ActorFollowModel> {
60 @Column(DataType.ENUM(...values(FOLLOW_STATES)))
64 @Default(ACTOR_FOLLOW_SCORE.BASE)
66 @Max(ACTOR_FOLLOW_SCORE.MAX)
76 @ForeignKey(() => ActorModel)
80 @BelongsTo(() => ActorModel, {
88 ActorFollower: ActorModel
90 @ForeignKey(() => ActorModel)
94 @BelongsTo(() => ActorModel, {
96 name: 'targetActorId',
102 ActorFollowing: ActorModel
106 static incrementFollowerAndFollowingCount (instance: ActorFollowModel) {
107 if (instance.state !== 'accepted') return undefined
110 ActorModel.incrementFollows(instance.actorId, 'followingCount', 1),
111 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', 1)
116 static decrementFollowerAndFollowingCount (instance: ActorFollowModel) {
118 ActorModel.incrementFollows(instance.actorId, 'followingCount',-1),
119 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', -1)
123 static removeFollowsOf (actorId: number, t?: Transaction) {
131 targetActorId: actorId
138 return ActorFollowModel.destroy(query)
141 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
142 static async removeBadActorFollows () {
143 const actorFollows = await ActorFollowModel.listBadActorFollows()
145 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
146 await Promise.all(actorFollowsRemovePromises)
148 const numberOfActorFollowsRemoved = actorFollows.length
150 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
153 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Bluebird<MActorFollowActorsDefault> {
157 targetActorId: targetActorId
174 return ActorFollowModel.findOne(query)
177 static loadByActorAndTargetNameAndHostForAPI (
182 ): Bluebird<MActorFollowActorsDefaultSubscription> {
183 const actorFollowingPartInclude: IncludeOptions = {
186 as: 'ActorFollowing',
188 preferredUsername: targetName
192 model: VideoChannelModel.unscoped(),
198 if (targetHost === null) {
199 actorFollowingPartInclude.where['serverId'] = null
201 actorFollowingPartInclude.include.push({
215 actorFollowingPartInclude,
225 return ActorFollowModel.findOne(query)
227 if (result && result.ActorFollowing.VideoChannel) {
228 result.ActorFollowing.VideoChannel.Actor = result.ActorFollowing
235 static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]): Bluebird<MActorFollowFollowingHost[]> {
236 const whereTab = targets
242 '$preferredUsername$': t.name
254 '$preferredUsername$': t.name
277 attributes: [ 'preferredUsername' ],
278 model: ActorModel.unscoped(),
280 as: 'ActorFollowing',
283 attributes: [ 'host' ],
284 model: ServerModel.unscoped(),
292 return ActorFollowModel.findAll(query)
295 static listFollowingForApi (id: number, start: number, count: number, sort: string, search?: string) {
300 order: getSort(sort),
312 as: 'ActorFollowing',
320 [Op.iLike]: '%' + search + '%'
329 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
330 .then(({ rows, count }) => {
338 static listFollowersForApi (actorId: number, start: number, count: number, sort: string, search?: string) {
343 order: getSort(sort),
355 [ Op.iLike ]: '%' + search + '%'
363 as: 'ActorFollowing',
372 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
373 .then(({ rows, count }) => {
381 static listSubscriptionsForApi (actorId: number, start: number, count: number, sort: string) {
387 order: getSort(sort),
393 attributes: [ 'id' ],
394 model: ActorModel.unscoped(),
395 as: 'ActorFollowing',
399 model: VideoChannelModel.unscoped(),
404 exclude: unusedActorAttributesForAPI
410 model: AccountModel.unscoped(),
415 exclude: unusedActorAttributesForAPI
429 return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
430 .then(({ rows, count }) => {
432 data: rows.map(r => r.ActorFollowing.VideoChannel),
438 static async keepUnfollowedInstance (hosts: string[]) {
439 const followerId = (await getServerActor()).id
442 attributes: [ 'id' ],
448 attributes: [ 'id' ],
449 model: ActorModel.unscoped(),
451 as: 'ActorFollowing',
453 preferredUsername: SERVER_ACTOR_NAME
457 attributes: [ 'host' ],
458 model: ServerModel.unscoped(),
471 const res = await ActorFollowModel.findAll(query)
472 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
474 return difference(hosts, followedHosts)
477 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
478 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
481 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
482 return ActorFollowModel.createListAcceptedFollowForApiQuery(
493 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
494 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
497 static async getStats () {
498 const serverActor = await getServerActor()
500 const totalInstanceFollowing = await ActorFollowModel.count({
502 actorId: serverActor.id
506 const totalInstanceFollowers = await ActorFollowModel.count({
508 targetActorId: serverActor.id
513 totalInstanceFollowing,
514 totalInstanceFollowers
518 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
519 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
521 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
522 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
523 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
527 type: QueryTypes.BULKUPDATE,
531 return ActorFollowModel.sequelize.query(query, options)
534 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
535 if (serverIds.length === 0) return
537 const me = await getServerActor()
538 const serverIdsString = createSafeIn(ActorFollowModel, serverIds)
540 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
542 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
543 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
544 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
545 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
549 type: QueryTypes.BULKUPDATE,
553 return ActorFollowModel.sequelize.query(query, options)
556 private static async createListAcceptedFollowForApiQuery (
557 type: 'followers' | 'following',
565 let firstJoin: string
566 let secondJoin: string
568 if (type === 'followers') {
569 firstJoin = 'targetActorId'
570 secondJoin = 'actorId'
572 firstJoin = 'actorId'
573 secondJoin = 'targetActorId'
576 const selections: string[] = []
577 if (distinct === true) selections.push('DISTINCT("Follows"."' + columnUrl + '") AS "url"')
578 else selections.push('"Follows"."' + columnUrl + '" AS "url"')
580 selections.push('COUNT(*) AS "total"')
582 const tasks: Bluebird<any>[] = []
584 for (let selection of selections) {
585 let query = 'SELECT ' + selection + ' FROM "actor" ' +
586 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
587 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
588 'WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = \'accepted\' '
590 if (count !== undefined) query += 'LIMIT ' + count
591 if (start !== undefined) query += ' OFFSET ' + start
595 type: QueryTypes.SELECT,
598 tasks.push(ActorFollowModel.sequelize.query(query, options))
601 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
602 const urls: string[] = followers.map(f => f.url)
606 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
610 private static listBadActorFollows () {
620 return ActorFollowModel.findAll(query)
623 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
624 const follower = this.ActorFollower.toFormattedJSON()
625 const following = this.ActorFollowing.toFormattedJSON()
633 createdAt: this.createdAt,
634 updatedAt: this.updatedAt