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, FOLLOW_STATES } from '../../initializers/constants'
26 import { ServerModel } from '../server/server'
27 import { getSort } from '../utils'
28 import { ActorModel, unusedActorAttributesForAPI } from './actor'
29 import { VideoChannelModel } from '../video/video-channel'
30 import { IIncludeOptions } from '../../../node_modules/sequelize-typescript/lib/interfaces/IIncludeOptions'
31 import { AccountModel } from '../account/account'
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 loadByActorAndTarget (actorId: number, targetActorId: number, t?: Sequelize.Transaction) {
133 targetActorId: targetActorId
150 return ActorFollowModel.findOne(query)
153 static loadByActorAndTargetNameAndHostForAPI (actorId: number, targetName: string, targetHost: string, t?: Sequelize.Transaction) {
154 const actorFollowingPartInclude: IIncludeOptions = {
157 as: 'ActorFollowing',
159 preferredUsername: targetName
163 model: VideoChannelModel.unscoped(),
169 if (targetHost === null) {
170 actorFollowingPartInclude.where['serverId'] = null
172 actorFollowingPartInclude.include.push({
186 actorFollowingPartInclude,
196 return ActorFollowModel.findOne(query)
198 if (result && result.ActorFollowing.VideoChannel) {
199 result.ActorFollowing.VideoChannel.Actor = result.ActorFollowing
206 static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]) {
207 const whereTab = targets
211 [ Sequelize.Op.and ]: [
213 '$preferredUsername$': t.name
223 [ Sequelize.Op.and ]: [
225 '$preferredUsername$': t.name
237 [ Sequelize.Op.and ]: [
239 [ Sequelize.Op.or ]: whereTab
248 attributes: [ 'preferredUsername' ],
249 model: ActorModel.unscoped(),
251 as: 'ActorFollowing',
254 attributes: [ 'host' ],
255 model: ServerModel.unscoped(),
263 return ActorFollowModel.findAll(query)
266 static listFollowingForApi (id: number, start: number, count: number, sort: string, search?: string) {
271 order: getSort(sort),
283 as: 'ActorFollowing',
291 [Sequelize.Op.iLike]: '%' + search + '%'
300 return ActorFollowModel.findAndCountAll(query)
301 .then(({ rows, count }) => {
309 static listFollowersForApi (actorId: number, start: number, count: number, sort: string, search?: string) {
314 order: getSort(sort),
326 [ Sequelize.Op.iLike ]: '%' + search + '%'
334 as: 'ActorFollowing',
343 return ActorFollowModel.findAndCountAll(query)
344 .then(({ rows, count }) => {
352 static listSubscriptionsForApi (actorId: number, start: number, count: number, sort: string) {
358 order: getSort(sort),
364 attributes: [ 'id' ],
365 model: ActorModel.unscoped(),
366 as: 'ActorFollowing',
370 model: VideoChannelModel.unscoped(),
375 exclude: unusedActorAttributesForAPI
381 model: AccountModel.unscoped(),
386 exclude: unusedActorAttributesForAPI
400 return ActorFollowModel.findAndCountAll(query)
401 .then(({ rows, count }) => {
403 data: rows.map(r => r.ActorFollowing.VideoChannel),
409 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Sequelize.Transaction, start?: number, count?: number) {
410 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
413 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Sequelize.Transaction) {
414 return ActorFollowModel.createListAcceptedFollowForApiQuery(
425 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Sequelize.Transaction, start?: number, count?: number) {
426 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
429 static async getStats () {
430 const serverActor = await getServerActor()
432 const totalInstanceFollowing = await ActorFollowModel.count({
434 actorId: serverActor.id
438 const totalInstanceFollowers = await ActorFollowModel.count({
440 targetActorId: serverActor.id
445 totalInstanceFollowing,
446 totalInstanceFollowers
450 static updateFollowScore (inboxUrl: string, value: number, t?: Sequelize.Transaction) {
451 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
453 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
454 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
455 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
459 type: Sequelize.QueryTypes.BULKUPDATE,
463 return ActorFollowModel.sequelize.query(query, options)
466 private static async createListAcceptedFollowForApiQuery (
467 type: 'followers' | 'following',
469 t: Sequelize.Transaction,
475 let firstJoin: string
476 let secondJoin: string
478 if (type === 'followers') {
479 firstJoin = 'targetActorId'
480 secondJoin = 'actorId'
482 firstJoin = 'actorId'
483 secondJoin = 'targetActorId'
486 const selections: string[] = []
487 if (distinct === true) selections.push('DISTINCT("Follows"."' + columnUrl + '") AS "url"')
488 else selections.push('"Follows"."' + columnUrl + '" AS "url"')
490 selections.push('COUNT(*) AS "total"')
492 const tasks: Bluebird<any>[] = []
494 for (let selection of selections) {
495 let query = 'SELECT ' + selection + ' FROM "actor" ' +
496 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
497 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
498 'WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = \'accepted\' '
500 if (count !== undefined) query += 'LIMIT ' + count
501 if (start !== undefined) query += ' OFFSET ' + start
505 type: Sequelize.QueryTypes.SELECT,
508 tasks.push(ActorFollowModel.sequelize.query(query, options))
511 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
512 const urls: string[] = followers.map(f => f.url)
516 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
520 private static listBadActorFollows () {
524 [Sequelize.Op.lte]: 0
530 return ActorFollowModel.findAll(query)
533 toFormattedJSON (): ActorFollow {
534 const follower = this.ActorFollower.toFormattedJSON()
535 const following = this.ActorFollowing.toFormattedJSON()
543 createdAt: this.createdAt,
544 updatedAt: this.updatedAt