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 { AttributesOnly } from '@shared/core-utils'
32 import { ActivityPubActorType } from '@shared/models'
33 import { FollowState } from '../../../shared/models/actors'
34 import { ActorFollow } from '../../../shared/models/actors/follow.model'
35 import { logger } from '../../helpers/logger'
36 import { ACTOR_FOLLOW_SCORE, CONSTRAINTS_FIELDS, FOLLOW_STATES, SERVER_ACTOR_NAME } from '../../initializers/constants'
37 import { AccountModel } from '../account/account'
38 import { ServerModel } from '../server/server'
39 import { createSafeIn, getFollowsSort, getSort, searchAttribute, throwIfNotValid } from '../utils'
40 import { VideoChannelModel } from '../video/video-channel'
41 import { ActorModel, unusedActorAttributesForAPI } from './actor'
44 tableName: 'actorFollow',
50 fields: [ 'targetActorId' ]
53 fields: [ 'actorId', 'targetActorId' ],
65 export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowModel>>> {
68 @Column(DataType.ENUM(...values(FOLLOW_STATES)))
72 @Default(ACTOR_FOLLOW_SCORE.BASE)
74 @Max(ACTOR_FOLLOW_SCORE.MAX)
78 // Allow null because we added this column in PeerTube v3, and don't want to generate fake URLs of remote follows
80 @Is('ActorFollowUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
81 @Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max))
90 @ForeignKey(() => ActorModel)
94 @BelongsTo(() => ActorModel, {
102 ActorFollower: ActorModel
104 @ForeignKey(() => ActorModel)
106 targetActorId: number
108 @BelongsTo(() => ActorModel, {
110 name: 'targetActorId',
113 as: 'ActorFollowing',
116 ActorFollowing: ActorModel
120 static incrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
121 if (instance.state !== 'accepted') return undefined
124 ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction),
125 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction)
130 static decrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
132 ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction),
133 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction)
137 static removeFollowsOf (actorId: number, t?: Transaction) {
145 targetActorId: actorId
152 return ActorFollowModel.destroy(query)
155 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
156 static async removeBadActorFollows () {
157 const actorFollows = await ActorFollowModel.listBadActorFollows()
159 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
160 await Promise.all(actorFollowsRemovePromises)
162 const numberOfActorFollowsRemoved = actorFollows.length
164 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
167 static isFollowedBy (actorId: number, followerActorId: number) {
168 const query = 'SELECT 1 FROM "actorFollow" WHERE "actorId" = $followerActorId AND "targetActorId" = $actorId LIMIT 1'
170 type: QueryTypes.SELECT as QueryTypes.SELECT,
171 bind: { actorId, followerActorId },
175 return VideoModel.sequelize.query(query, options)
176 .then(results => results.length === 1)
179 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Promise<MActorFollowActorsDefault> {
183 targetActorId: targetActorId
200 return ActorFollowModel.findOne(query)
203 static loadByActorAndTargetNameAndHostForAPI (
208 ): Promise<MActorFollowActorsDefaultSubscription> {
209 const actorFollowingPartInclude: IncludeOptions = {
212 as: 'ActorFollowing',
214 preferredUsername: targetName
218 model: VideoChannelModel.unscoped(),
224 if (targetHost === null) {
225 actorFollowingPartInclude.where['serverId'] = null
227 actorFollowingPartInclude.include.push({
241 actorFollowingPartInclude,
251 return ActorFollowModel.findOne(query)
254 static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]): Promise<MActorFollowFollowingHost[]> {
255 const whereTab = targets
261 $preferredUsername$: t.name
273 $preferredUsername$: t.name
283 attributes: [ 'id' ],
296 attributes: [ 'preferredUsername' ],
297 model: ActorModel.unscoped(),
299 as: 'ActorFollowing',
302 attributes: [ 'host' ],
303 model: ServerModel.unscoped(),
311 return ActorFollowModel.findAll(query)
314 static listFollowingForApi (options: {
320 actorType?: ActivityPubActorType
323 const { id, start, count, sort, search, state, actorType } = options
325 const followWhere = state ? { state } : {}
326 const followingWhere: WhereOptions = {}
327 const followingServerWhere: WhereOptions = {}
330 Object.assign(followingServerWhere, {
332 [Op.iLike]: '%' + search + '%'
338 Object.assign(followingWhere, { type: actorType })
345 order: getFollowsSort(sort),
358 as: 'ActorFollowing',
360 where: followingWhere,
365 where: followingServerWhere
372 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
373 .then(({ rows, count }) => {
381 static listFollowersForApi (options: {
387 actorType?: ActivityPubActorType
390 const { actorId, start, count, sort, search, state, actorType } = options
392 const followWhere = state ? { state } : {}
393 const followerWhere: WhereOptions = {}
394 const followerServerWhere: WhereOptions = {}
397 Object.assign(followerServerWhere, {
399 [Op.iLike]: '%' + search + '%'
405 Object.assign(followerWhere, { type: actorType })
412 order: getFollowsSort(sort),
419 where: followerWhere,
424 where: followerServerWhere
430 as: 'ActorFollowing',
439 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
440 .then(({ rows, count }) => {
448 static listSubscriptionsForApi (options: {
455 const { actorId, start, count, sort } = options
460 if (options.search) {
461 Object.assign(where, {
463 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
464 searchAttribute(options.search, '$ActorFollowing.VideoChannel.name$')
474 order: getSort(sort),
478 attributes: [ 'id' ],
479 model: ActorModel.unscoped(),
480 as: 'ActorFollowing',
484 model: VideoChannelModel.unscoped(),
489 exclude: unusedActorAttributesForAPI
495 model: AccountModel.unscoped(),
500 exclude: unusedActorAttributesForAPI
514 return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
515 .then(({ rows, count }) => {
517 data: rows.map(r => r.ActorFollowing.VideoChannel),
523 static async keepUnfollowedInstance (hosts: string[]) {
524 const followerId = (await getServerActor()).id
527 attributes: [ 'id' ],
533 attributes: [ 'id' ],
534 model: ActorModel.unscoped(),
536 as: 'ActorFollowing',
538 preferredUsername: SERVER_ACTOR_NAME
542 attributes: [ 'host' ],
543 model: ServerModel.unscoped(),
556 const res = await ActorFollowModel.findAll(query)
557 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
559 return difference(hosts, followedHosts)
562 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
563 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
566 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
567 return ActorFollowModel.createListAcceptedFollowForApiQuery(
578 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
579 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
582 static async getStats () {
583 const serverActor = await getServerActor()
585 const totalInstanceFollowing = await ActorFollowModel.count({
587 actorId: serverActor.id
591 const totalInstanceFollowers = await ActorFollowModel.count({
593 targetActorId: serverActor.id
598 totalInstanceFollowing,
599 totalInstanceFollowers
603 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
604 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
606 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
607 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
608 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
612 type: QueryTypes.BULKUPDATE,
616 return ActorFollowModel.sequelize.query(query, options)
619 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
620 if (serverIds.length === 0) return
622 const me = await getServerActor()
623 const serverIdsString = createSafeIn(ActorFollowModel.sequelize, serverIds)
625 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
627 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
628 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
629 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
630 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
634 type: QueryTypes.BULKUPDATE,
638 return ActorFollowModel.sequelize.query(query, options)
641 private static async createListAcceptedFollowForApiQuery (
642 type: 'followers' | 'following',
650 let firstJoin: string
651 let secondJoin: string
653 if (type === 'followers') {
654 firstJoin = 'targetActorId'
655 secondJoin = 'actorId'
657 firstJoin = 'actorId'
658 secondJoin = 'targetActorId'
661 const selections: string[] = []
662 if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
663 else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
665 selections.push('COUNT(*) AS "total"')
667 const tasks: Promise<any>[] = []
669 for (const selection of selections) {
670 let query = 'SELECT ' + selection + ' FROM "actor" ' +
671 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
672 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
673 `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
675 if (count !== undefined) query += 'LIMIT ' + count
676 if (start !== undefined) query += ' OFFSET ' + start
680 type: QueryTypes.SELECT,
683 tasks.push(ActorFollowModel.sequelize.query(query, options))
686 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
687 const urls: string[] = followers.map(f => f.selectionUrl)
691 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
695 private static listBadActorFollows () {
705 return ActorFollowModel.findAll(query)
708 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
709 const follower = this.ActorFollower.toFormattedJSON()
710 const following = this.ActorFollowing.toFormattedJSON()
718 createdAt: this.createdAt,
719 updatedAt: this.updatedAt