]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/actor/actor-follow.ts
More robust quota check
[github/Chocobozzz/PeerTube.git] / server / models / actor / actor-follow.ts
index 0f4d3c0a6085cc314392c7d4c6ec6373984a56f5..71ce9fa6fb2887d298cecd999ac6e2bfb6e9c692 100644 (file)
@@ -1,5 +1,5 @@
-import { difference, values } from 'lodash'
-import { Includeable, IncludeOptions, literal, Op, QueryTypes, Transaction, WhereOptions } from 'sequelize'
+import { difference } from 'lodash'
+import { Attributes, FindOptions, Includeable, IncludeOptions, Op, QueryTypes, Transaction, WhereAttributeHash } from 'sequelize'
 import {
   AfterCreate,
   AfterDestroy,
@@ -30,7 +30,6 @@ import {
   MActorFollowFormattable,
   MActorFollowSubscriptions
 } from '@server/types/models'
-import { ActivityPubActorType } from '@shared/models'
 import { AttributesOnly } from '@shared/typescript-utils'
 import { FollowState } from '../../../shared/models/actors'
 import { ActorFollow } from '../../../shared/models/actors/follow.model'
@@ -38,10 +37,12 @@ import { logger } from '../../helpers/logger'
 import { ACTOR_FOLLOW_SCORE, CONSTRAINTS_FIELDS, FOLLOW_STATES, SERVER_ACTOR_NAME, SORTABLE_COLUMNS } from '../../initializers/constants'
 import { AccountModel } from '../account/account'
 import { ServerModel } from '../server/server'
+import { buildSQLAttributes, createSafeIn, getSort, searchAttribute, throwIfNotValid } from '../shared'
 import { doesExist } from '../shared/query'
-import { createSafeIn, getFollowsSort, getSort, searchAttribute, throwIfNotValid } from '../utils'
 import { VideoChannelModel } from '../video/video-channel'
 import { ActorModel, unusedActorAttributesForAPI } from './actor'
+import { InstanceListFollowersQueryBuilder, ListFollowersOptions } from './sql/instance-list-followers-query-builder'
+import { InstanceListFollowingQueryBuilder, ListFollowingOptions } from './sql/instance-list-following-query-builder'
 
 @Table({
   tableName: 'actorFollow',
@@ -68,7 +69,7 @@ import { ActorModel, unusedActorAttributesForAPI } from './actor'
 export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowModel>>> {
 
   @AllowNull(false)
-  @Column(DataType.ENUM(...values(FOLLOW_STATES)))
+  @Column(DataType.ENUM(...Object.values(FOLLOW_STATES)))
   state: FollowState
 
   @AllowNull(false)
@@ -139,6 +140,18 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
     })
   }
 
+  // ---------------------------------------------------------------------------
+
+  static getSQLAttributes (tableName: string, aliasPrefix = '') {
+    return buildSQLAttributes({
+      model: this,
+      tableName,
+      aliasPrefix
+    })
+  }
+
+  // ---------------------------------------------------------------------------
+
   /*
    * @deprecated Use `findOrCreateCustom` instead
   */
@@ -208,16 +221,18 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
   }
 
   static isFollowedBy (actorId: number, followerActorId: number) {
-    const query = 'SELECT 1 FROM "actorFollow" WHERE "actorId" = $followerActorId AND "targetActorId" = $actorId LIMIT 1'
+    const query = `SELECT 1 FROM "actorFollow" ` +
+      `WHERE "actorId" = $followerActorId AND "targetActorId" = $actorId AND "state" = 'accepted' ` +
+      `LIMIT 1`
 
-    return doesExist(query, { actorId, followerActorId })
+    return doesExist(this.sequelize, query, { actorId, followerActorId })
   }
 
   static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Promise<MActorFollowActorsDefault> {
     const query = {
       where: {
         actorId,
-        targetActorId: targetActorId
+        targetActorId
       },
       include: [
         {
@@ -237,19 +252,20 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
     return ActorFollowModel.findOne(query)
   }
 
-  static loadByActorAndTargetNameAndHostForAPI (
-    actorId: number,
-    targetName: string,
-    targetHost: string,
-    t?: Transaction
-  ): Promise<MActorFollowActorsDefaultSubscription> {
+  static loadByActorAndTargetNameAndHostForAPI (options: {
+    actorId: number
+    targetName: string
+    targetHost: string
+    state?: FollowState
+    transaction?: Transaction
+  }): Promise<MActorFollowActorsDefaultSubscription> {
+    const { actorId, targetHost, targetName, state, transaction } = options
+
     const actorFollowingPartInclude: IncludeOptions = {
       model: ActorModel,
       required: true,
       as: 'ActorFollowing',
-      where: {
-        preferredUsername: targetName
-      },
+      where: ActorModel.wherePreferredUsername(targetName),
       include: [
         {
           model: VideoChannelModel.unscoped(),
@@ -270,10 +286,11 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
       })
     }
 
-    const query = {
-      where: {
-        actorId
-      },
+    const where: WhereAttributeHash<Attributes<ActorFollowModel>> = { actorId }
+    if (state) where.state = state
+
+    const query: FindOptions<Attributes<ActorFollowModel>> = {
+      where,
       include: [
         actorFollowingPartInclude,
         {
@@ -282,7 +299,7 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
           as: 'ActorFollower'
         }
       ],
-      transaction: t
+      transaction
     }
 
     return ActorFollowModel.findOne(query)
@@ -294,24 +311,16 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
         if (t.host) {
           return {
             [Op.and]: [
-              {
-                $preferredUsername$: t.name
-              },
-              {
-                $host$: t.host
-              }
+              ActorModel.wherePreferredUsername(t.name),
+              { $host$: t.host }
             ]
           }
         }
 
         return {
           [Op.and]: [
-            {
-              $preferredUsername$: t.name
-            },
-            {
-              $serverId$: null
-            }
+            ActorModel.wherePreferredUsername(t.name),
+            { $serverId$: null }
           ]
         }
       })
@@ -324,6 +333,7 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
             [Op.or]: whereTab
           },
           {
+            state: 'accepted',
             actorId
           }
         ]
@@ -348,144 +358,17 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
     return ActorFollowModel.findAll(query)
   }
 
-  static listInstanceFollowingForApi (options: {
-    id: number
-    start: number
-    count: number
-    sort: string
-    state?: FollowState
-    actorType?: ActivityPubActorType
-    search?: string
-  }) {
-    const { id, start, count, sort, search, state, actorType } = options
-
-    const followWhere = state ? { state } : {}
-    const followingWhere: WhereOptions = {}
-
-    if (search) {
-      Object.assign(followWhere, {
-        [Op.or]: [
-          searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
-          searchAttribute(options.search, '$ActorFollowing.Server.host$')
-        ]
-      })
-    }
-
-    if (actorType) {
-      Object.assign(followingWhere, { type: actorType })
-    }
-
-    const getQuery = (forCount: boolean) => {
-      const actorModel = forCount
-        ? ActorModel.unscoped()
-        : ActorModel
-
-      return {
-        distinct: true,
-        offset: start,
-        limit: count,
-        order: getFollowsSort(sort),
-        where: followWhere,
-        include: [
-          {
-            model: actorModel,
-            required: true,
-            as: 'ActorFollower',
-            where: {
-              id
-            }
-          },
-          {
-            model: actorModel,
-            as: 'ActorFollowing',
-            required: true,
-            where: followingWhere,
-            include: [
-              {
-                model: ServerModel,
-                required: true
-              }
-            ]
-          }
-        ]
-      }
-    }
-
+  static listInstanceFollowingForApi (options: ListFollowingOptions) {
     return Promise.all([
-      ActorFollowModel.count(getQuery(true)),
-      ActorFollowModel.findAll<MActorFollowActorsDefault>(getQuery(false))
+      new InstanceListFollowingQueryBuilder(this.sequelize, options).countFollowing(),
+      new InstanceListFollowingQueryBuilder(this.sequelize, options).listFollowing()
     ]).then(([ total, data ]) => ({ total, data }))
   }
 
-  static listFollowersForApi (options: {
-    actorIds: number[]
-    start: number
-    count: number
-    sort: string
-    state?: FollowState
-    actorType?: ActivityPubActorType
-    search?: string
-  }) {
-    const { actorIds, start, count, sort, search, state, actorType } = options
-
-    const followWhere = state ? { state } : {}
-    const followerWhere: WhereOptions = {}
-
-    if (search) {
-      const escapedSearch = ActorFollowModel.sequelize.escape('%' + search + '%')
-
-      Object.assign(followerWhere, {
-        id: {
-          [Op.in]: literal(
-            `(` +
-              `SELECT "actor".id FROM actor LEFT JOIN server on server.id = actor."serverId" ` +
-              `WHERE "preferredUsername" ILIKE ${escapedSearch} OR "host" ILIKE ${escapedSearch}` +
-            `)`
-          )
-        }
-      })
-    }
-
-    if (actorType) {
-      Object.assign(followerWhere, { type: actorType })
-    }
-
-    const getQuery = (forCount: boolean) => {
-      const actorModel = forCount
-        ? ActorModel.unscoped()
-        : ActorModel
-
-      return {
-        distinct: true,
-
-        offset: start,
-        limit: count,
-        order: getFollowsSort(sort),
-        where: followWhere,
-        include: [
-          {
-            model: actorModel,
-            required: true,
-            as: 'ActorFollower',
-            where: followerWhere
-          },
-          {
-            model: actorModel,
-            as: 'ActorFollowing',
-            required: true,
-            where: {
-              id: {
-                [Op.in]: actorIds
-              }
-            }
-          }
-        ]
-      }
-    }
-
+  static listFollowersForApi (options: ListFollowersOptions) {
     return Promise.all([
-      ActorFollowModel.count(getQuery(true)),
-      ActorFollowModel.findAll<MActorFollowActorsDefault>(getQuery(false))
+      new InstanceListFollowersQueryBuilder(this.sequelize, options).countFollowers(),
+      new InstanceListFollowersQueryBuilder(this.sequelize, options).listFollowers()
     ]).then(([ total, data ]) => ({ total, data }))
   }
 
@@ -498,7 +381,8 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
   }) {
     const { actorId, start, count, sort } = options
     const where = {
-      actorId: actorId
+      state: 'accepted',
+      actorId
     }
 
     if (options.search) {
@@ -638,13 +522,15 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
 
     const totalInstanceFollowing = await ActorFollowModel.count({
       where: {
-        actorId: serverActor.id
+        actorId: serverActor.id,
+        state: 'accepted'
       }
     })
 
     const totalInstanceFollowers = await ActorFollowModel.count({
       where: {
-        targetActorId: serverActor.id
+        targetActorId: serverActor.id,
+        state: 'accepted'
       }
     })