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 { getServerActor } from '@server/models/application/application'
23 import { VideoModel } from '@server/models/video/video'
25 MActorFollowActorsDefault,
26 MActorFollowActorsDefaultSubscription,
27 MActorFollowFollowingHost,
28 MActorFollowFormattable,
29 MActorFollowSubscriptions
30 } from '@server/types/models'
31 import { ActivityPubActorType } from '@shared/models'
32 import { FollowState } from '../../../shared/models/actors'
33 import { ActorFollow } from '../../../shared/models/actors/follow.model'
34 import { logger } from '../../helpers/logger'
35 import { ACTOR_FOLLOW_SCORE, CONSTRAINTS_FIELDS, FOLLOW_STATES, SERVER_ACTOR_NAME } from '../../initializers/constants'
36 import { AccountModel } from '../account/account'
37 import { ServerModel } from '../server/server'
38 import { createSafeIn, getFollowsSort, getSort, searchAttribute, throwIfNotValid } from '../utils'
39 import { VideoChannelModel } from '../video/video-channel'
40 import { ActorModel, unusedActorAttributesForAPI } from './actor'
43 tableName: 'actorFollow',
49 fields: [ 'targetActorId' ]
52 fields: [ 'actorId', 'targetActorId' ],
64 export class ActorFollowModel extends Model {
67 @Column(DataType.ENUM(...values(FOLLOW_STATES)))
71 @Default(ACTOR_FOLLOW_SCORE.BASE)
73 @Max(ACTOR_FOLLOW_SCORE.MAX)
77 // Allow null because we added this column in PeerTube v3, and don't want to generate fake URLs of remote follows
79 @Is('ActorFollowUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
80 @Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
89 @ForeignKey(() => ActorModel)
93 @BelongsTo(() => ActorModel, {
101 ActorFollower: ActorModel
103 @ForeignKey(() => ActorModel)
105 targetActorId: number
107 @BelongsTo(() => ActorModel, {
109 name: 'targetActorId',
112 as: 'ActorFollowing',
115 ActorFollowing: ActorModel
119 static incrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
120 if (instance.state !== 'accepted') return undefined
123 ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction),
124 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction)
129 static decrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
131 ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction),
132 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction)
136 static removeFollowsOf (actorId: number, t?: Transaction) {
144 targetActorId: actorId
151 return ActorFollowModel.destroy(query)
154 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
155 static async removeBadActorFollows () {
156 const actorFollows = await ActorFollowModel.listBadActorFollows()
158 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
159 await Promise.all(actorFollowsRemovePromises)
161 const numberOfActorFollowsRemoved = actorFollows.length
163 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
166 static isFollowedBy (actorId: number, followerActorId: number) {
167 const query = 'SELECT 1 FROM "actorFollow" WHERE "actorId" = $followerActorId AND "targetActorId" = $actorId LIMIT 1'
169 type: QueryTypes.SELECT as QueryTypes.SELECT,
170 bind: { actorId, followerActorId },
174 return VideoModel.sequelize.query(query, options)
175 .then(results => results.length === 1)
178 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Promise<MActorFollowActorsDefault> {
182 targetActorId: targetActorId
199 return ActorFollowModel.findOne(query)
202 static loadByActorAndTargetNameAndHostForAPI (
207 ): Promise<MActorFollowActorsDefaultSubscription> {
208 const actorFollowingPartInclude: IncludeOptions = {
211 as: 'ActorFollowing',
213 preferredUsername: targetName
217 model: VideoChannelModel.unscoped(),
223 if (targetHost === null) {
224 actorFollowingPartInclude.where['serverId'] = null
226 actorFollowingPartInclude.include.push({
240 actorFollowingPartInclude,
250 return ActorFollowModel.findOne(query)
253 static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]): Promise<MActorFollowFollowingHost[]> {
254 const whereTab = targets
260 $preferredUsername$: t.name
272 $preferredUsername$: t.name
282 attributes: [ 'id' ],
295 attributes: [ 'preferredUsername' ],
296 model: ActorModel.unscoped(),
298 as: 'ActorFollowing',
301 attributes: [ 'host' ],
302 model: ServerModel.unscoped(),
310 return ActorFollowModel.findAll(query)
313 static listFollowingForApi (options: {
319 actorType?: ActivityPubActorType
322 const { id, start, count, sort, search, state, actorType } = options
324 const followWhere = state ? { state } : {}
325 const followingWhere: WhereOptions = {}
326 const followingServerWhere: WhereOptions = {}
329 Object.assign(followingServerWhere, {
331 [Op.iLike]: '%' + search + '%'
337 Object.assign(followingWhere, { type: actorType })
344 order: getFollowsSort(sort),
357 as: 'ActorFollowing',
359 where: followingWhere,
364 where: followingServerWhere
371 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
372 .then(({ rows, count }) => {
380 static listFollowersForApi (options: {
386 actorType?: ActivityPubActorType
389 const { actorId, start, count, sort, search, state, actorType } = options
391 const followWhere = state ? { state } : {}
392 const followerWhere: WhereOptions = {}
393 const followerServerWhere: WhereOptions = {}
396 Object.assign(followerServerWhere, {
398 [Op.iLike]: '%' + search + '%'
404 Object.assign(followerWhere, { type: actorType })
411 order: getFollowsSort(sort),
418 where: followerWhere,
423 where: followerServerWhere
429 as: 'ActorFollowing',
438 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
439 .then(({ rows, count }) => {
447 static listSubscriptionsForApi (options: {
454 const { actorId, start, count, sort } = options
459 if (options.search) {
460 Object.assign(where, {
462 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
463 searchAttribute(options.search, '$ActorFollowing.VideoChannel.name$')
473 order: getSort(sort),
477 attributes: [ 'id' ],
478 model: ActorModel.unscoped(),
479 as: 'ActorFollowing',
483 model: VideoChannelModel.unscoped(),
488 exclude: unusedActorAttributesForAPI
494 model: AccountModel.unscoped(),
499 exclude: unusedActorAttributesForAPI
513 return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
514 .then(({ rows, count }) => {
516 data: rows.map(r => r.ActorFollowing.VideoChannel),
522 static async keepUnfollowedInstance (hosts: string[]) {
523 const followerId = (await getServerActor()).id
526 attributes: [ 'id' ],
532 attributes: [ 'id' ],
533 model: ActorModel.unscoped(),
535 as: 'ActorFollowing',
537 preferredUsername: SERVER_ACTOR_NAME
541 attributes: [ 'host' ],
542 model: ServerModel.unscoped(),
555 const res = await ActorFollowModel.findAll(query)
556 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
558 return difference(hosts, followedHosts)
561 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
562 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
565 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
566 return ActorFollowModel.createListAcceptedFollowForApiQuery(
577 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
578 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
581 static async getStats () {
582 const serverActor = await getServerActor()
584 const totalInstanceFollowing = await ActorFollowModel.count({
586 actorId: serverActor.id
590 const totalInstanceFollowers = await ActorFollowModel.count({
592 targetActorId: serverActor.id
597 totalInstanceFollowing,
598 totalInstanceFollowers
602 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
603 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
605 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
606 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
607 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
611 type: QueryTypes.BULKUPDATE,
615 return ActorFollowModel.sequelize.query(query, options)
618 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
619 if (serverIds.length === 0) return
621 const me = await getServerActor()
622 const serverIdsString = createSafeIn(ActorFollowModel, serverIds)
624 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
626 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
627 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
628 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
629 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
633 type: QueryTypes.BULKUPDATE,
637 return ActorFollowModel.sequelize.query(query, options)
640 private static async createListAcceptedFollowForApiQuery (
641 type: 'followers' | 'following',
649 let firstJoin: string
650 let secondJoin: string
652 if (type === 'followers') {
653 firstJoin = 'targetActorId'
654 secondJoin = 'actorId'
656 firstJoin = 'actorId'
657 secondJoin = 'targetActorId'
660 const selections: string[] = []
661 if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
662 else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
664 selections.push('COUNT(*) AS "total"')
666 const tasks: Promise<any>[] = []
668 for (const selection of selections) {
669 let query = 'SELECT ' + selection + ' FROM "actor" ' +
670 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
671 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
672 `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
674 if (count !== undefined) query += 'LIMIT ' + count
675 if (start !== undefined) query += ' OFFSET ' + start
679 type: QueryTypes.SELECT,
682 tasks.push(ActorFollowModel.sequelize.query(query, options))
685 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
686 const urls: string[] = followers.map(f => f.selectionUrl)
690 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
694 private static listBadActorFollows () {
704 return ActorFollowModel.findAll(query)
707 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
708 const follower = this.ActorFollower.toFormattedJSON()
709 const following = this.ActorFollowing.toFormattedJSON()
717 createdAt: this.createdAt,
718 updatedAt: this.updatedAt