1 import { difference, values } from 'lodash'
2 import { IncludeOptions, Op, QueryTypes, Transaction, WhereOptions } from 'sequelize'
20 } from 'sequelize-typescript'
21 import { isActivityPubUrlValid } from '@server/helpers/custom-validators/activitypub/misc'
22 import { afterCommitIfTransaction } from '@server/helpers/database-utils'
23 import { getServerActor } from '@server/models/application/application'
27 MActorFollowActorsDefault,
28 MActorFollowActorsDefaultSubscription,
29 MActorFollowFollowingHost,
30 MActorFollowFormattable,
31 MActorFollowSubscriptions
32 } from '@server/types/models'
33 import { AttributesOnly } from '@shared/core-utils'
34 import { ActivityPubActorType } from '@shared/models'
35 import { FollowState } from '../../../shared/models/actors'
36 import { ActorFollow } from '../../../shared/models/actors/follow.model'
37 import { logger } from '../../helpers/logger'
38 import { ACTOR_FOLLOW_SCORE, CONSTRAINTS_FIELDS, FOLLOW_STATES, SERVER_ACTOR_NAME } from '../../initializers/constants'
39 import { AccountModel } from '../account/account'
40 import { ServerModel } from '../server/server'
41 import { doesExist } from '../shared/query'
42 import { createSafeIn, getFollowsSort, getSort, searchAttribute, throwIfNotValid } from '../utils'
43 import { VideoChannelModel } from '../video/video-channel'
44 import { ActorModel, unusedActorAttributesForAPI } from './actor'
47 tableName: 'actorFollow',
53 fields: [ 'targetActorId' ]
56 fields: [ 'actorId', 'targetActorId' ],
68 export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowModel>>> {
71 @Column(DataType.ENUM(...values(FOLLOW_STATES)))
75 @Default(ACTOR_FOLLOW_SCORE.BASE)
77 @Max(ACTOR_FOLLOW_SCORE.MAX)
81 // Allow null because we added this column in PeerTube v3, and don't want to generate fake URLs of remote follows
83 @Is('ActorFollowUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
84 @Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
93 @ForeignKey(() => ActorModel)
97 @BelongsTo(() => ActorModel, {
105 ActorFollower: ActorModel
107 @ForeignKey(() => ActorModel)
109 targetActorId: number
111 @BelongsTo(() => ActorModel, {
113 name: 'targetActorId',
116 as: 'ActorFollowing',
119 ActorFollowing: ActorModel
123 static incrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
124 return afterCommitIfTransaction(options.transaction, () => {
126 ActorModel.rebuildFollowsCount(instance.actorId, 'following'),
127 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers')
133 static decrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
134 return afterCommitIfTransaction(options.transaction, () => {
136 ActorModel.rebuildFollowsCount(instance.actorId, 'following'),
137 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers')
143 * @deprecated Use `findOrCreateCustom` instead
145 static findOrCreate (): any {
146 throw new Error('Should not be called')
149 // findOrCreate has issues with actor follow hooks
150 static async findOrCreateCustom (options: {
155 transaction: Transaction
156 }): Promise<[ MActorFollowActors, boolean ]> {
157 const { byActor, targetActor, activityId, state, transaction } = options
160 let actorFollow: MActorFollowActors = await ActorFollowModel.loadByActorAndTarget(byActor.id, targetActor.id, transaction)
165 actorFollow = await ActorFollowModel.create({
167 targetActorId: targetActor.id,
173 actorFollow.ActorFollowing = targetActor
174 actorFollow.ActorFollower = byActor
177 return [ actorFollow, created ]
180 static removeFollowsOf (actorId: number, t?: Transaction) {
188 targetActorId: actorId
195 return ActorFollowModel.destroy(query)
198 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
199 static async removeBadActorFollows () {
200 const actorFollows = await ActorFollowModel.listBadActorFollows()
202 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
203 await Promise.all(actorFollowsRemovePromises)
205 const numberOfActorFollowsRemoved = actorFollows.length
207 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
210 static isFollowedBy (actorId: number, followerActorId: number) {
211 const query = 'SELECT 1 FROM "actorFollow" WHERE "actorId" = $followerActorId AND "targetActorId" = $actorId LIMIT 1'
213 return doesExist(query, { actorId, followerActorId })
216 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Promise<MActorFollowActorsDefault> {
220 targetActorId: targetActorId
237 return ActorFollowModel.findOne(query)
240 static loadByActorAndTargetNameAndHostForAPI (
245 ): Promise<MActorFollowActorsDefaultSubscription> {
246 const actorFollowingPartInclude: IncludeOptions = {
249 as: 'ActorFollowing',
251 preferredUsername: targetName
255 model: VideoChannelModel.unscoped(),
261 if (targetHost === null) {
262 actorFollowingPartInclude.where['serverId'] = null
264 actorFollowingPartInclude.include.push({
278 actorFollowingPartInclude,
288 return ActorFollowModel.findOne(query)
291 static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]): Promise<MActorFollowFollowingHost[]> {
292 const whereTab = targets
298 $preferredUsername$: t.name
310 $preferredUsername$: t.name
320 attributes: [ 'id' ],
333 attributes: [ 'preferredUsername' ],
334 model: ActorModel.unscoped(),
336 as: 'ActorFollowing',
339 attributes: [ 'host' ],
340 model: ServerModel.unscoped(),
348 return ActorFollowModel.findAll(query)
351 static listFollowingForApi (options: {
357 actorType?: ActivityPubActorType
360 const { id, start, count, sort, search, state, actorType } = options
362 const followWhere = state ? { state } : {}
363 const followingWhere: WhereOptions = {}
366 Object.assign(followWhere, {
368 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
369 searchAttribute(options.search, '$ActorFollowing.Server.host$')
375 Object.assign(followingWhere, { type: actorType })
382 order: getFollowsSort(sort),
395 as: 'ActorFollowing',
397 where: followingWhere,
408 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
409 .then(({ rows, count }) => {
417 static listFollowersForApi (options: {
423 actorType?: ActivityPubActorType
426 const { actorId, start, count, sort, search, state, actorType } = options
428 const followWhere = state ? { state } : {}
429 const followerWhere: WhereOptions = {}
432 Object.assign(followWhere, {
434 searchAttribute(search, '$ActorFollower.preferredUsername$'),
435 searchAttribute(search, '$ActorFollower.Server.host$')
441 Object.assign(followerWhere, { type: actorType })
448 order: getFollowsSort(sort),
455 where: followerWhere,
465 as: 'ActorFollowing',
474 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
475 .then(({ rows, count }) => {
483 static listSubscriptionsForApi (options: {
490 const { actorId, start, count, sort } = options
495 if (options.search) {
496 Object.assign(where, {
498 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
499 searchAttribute(options.search, '$ActorFollowing.VideoChannel.name$')
509 order: getSort(sort),
513 attributes: [ 'id' ],
514 model: ActorModel.unscoped(),
515 as: 'ActorFollowing',
519 model: VideoChannelModel.unscoped(),
524 exclude: unusedActorAttributesForAPI
530 model: AccountModel.unscoped(),
535 exclude: unusedActorAttributesForAPI
549 return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
550 .then(({ rows, count }) => {
552 data: rows.map(r => r.ActorFollowing.VideoChannel),
558 static async keepUnfollowedInstance (hosts: string[]) {
559 const followerId = (await getServerActor()).id
562 attributes: [ 'id' ],
568 attributes: [ 'id' ],
569 model: ActorModel.unscoped(),
571 as: 'ActorFollowing',
573 preferredUsername: SERVER_ACTOR_NAME
577 attributes: [ 'host' ],
578 model: ServerModel.unscoped(),
591 const res = await ActorFollowModel.findAll(query)
592 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
594 return difference(hosts, followedHosts)
597 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
598 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
601 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
602 return ActorFollowModel.createListAcceptedFollowForApiQuery(
613 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
614 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
617 static async getStats () {
618 const serverActor = await getServerActor()
620 const totalInstanceFollowing = await ActorFollowModel.count({
622 actorId: serverActor.id
626 const totalInstanceFollowers = await ActorFollowModel.count({
628 targetActorId: serverActor.id
633 totalInstanceFollowing,
634 totalInstanceFollowers
638 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
639 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
641 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
642 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
643 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
647 type: QueryTypes.BULKUPDATE,
651 return ActorFollowModel.sequelize.query(query, options)
654 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
655 if (serverIds.length === 0) return
657 const me = await getServerActor()
658 const serverIdsString = createSafeIn(ActorFollowModel.sequelize, serverIds)
660 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
662 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
663 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
664 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
665 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
669 type: QueryTypes.BULKUPDATE,
673 return ActorFollowModel.sequelize.query(query, options)
676 private static async createListAcceptedFollowForApiQuery (
677 type: 'followers' | 'following',
685 let firstJoin: string
686 let secondJoin: string
688 if (type === 'followers') {
689 firstJoin = 'targetActorId'
690 secondJoin = 'actorId'
692 firstJoin = 'actorId'
693 secondJoin = 'targetActorId'
696 const selections: string[] = []
697 if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
698 else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
700 selections.push('COUNT(*) AS "total"')
702 const tasks: Promise<any>[] = []
704 for (const selection of selections) {
705 let query = 'SELECT ' + selection + ' FROM "actor" ' +
706 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
707 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
708 `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
710 if (count !== undefined) query += 'LIMIT ' + count
711 if (start !== undefined) query += ' OFFSET ' + start
715 type: QueryTypes.SELECT,
718 tasks.push(ActorFollowModel.sequelize.query(query, options))
721 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
722 const urls: string[] = followers.map(f => f.selectionUrl)
726 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
730 private static listBadActorFollows () {
740 return ActorFollowModel.findAll(query)
743 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
744 const follower = this.ActorFollower.toFormattedJSON()
745 const following = this.ActorFollowing.toFormattedJSON()
753 createdAt: this.createdAt,
754 updatedAt: this.updatedAt