]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/actor/actor-follow.ts
Fix videos history tests
[github/Chocobozzz/PeerTube.git] / server / models / actor / actor-follow.ts
index 283856d3ffa73b3482997400cdde6f9cc74dc4d4..0f4d3c0a6085cc314392c7d4c6ec6373984a56f5 100644 (file)
@@ -1,5 +1,5 @@
 import { difference, values } from 'lodash'
-import { IncludeOptions, Op, QueryTypes, Transaction, WhereOptions } from 'sequelize'
+import { Includeable, IncludeOptions, literal, Op, QueryTypes, Transaction, WhereOptions } from 'sequelize'
 import {
   AfterCreate,
   AfterDestroy,
@@ -19,20 +19,23 @@ import {
   UpdatedAt
 } from 'sequelize-typescript'
 import { isActivityPubUrlValid } from '@server/helpers/custom-validators/activitypub/misc'
+import { afterCommitIfTransaction } from '@server/helpers/database-utils'
 import { getServerActor } from '@server/models/application/application'
 import {
+  MActor,
+  MActorFollowActors,
   MActorFollowActorsDefault,
   MActorFollowActorsDefaultSubscription,
   MActorFollowFollowingHost,
   MActorFollowFormattable,
   MActorFollowSubscriptions
 } from '@server/types/models'
-import { AttributesOnly } from '@shared/core-utils'
 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'
 import { logger } from '../../helpers/logger'
-import { ACTOR_FOLLOW_SCORE, CONSTRAINTS_FIELDS, FOLLOW_STATES, SERVER_ACTOR_NAME } from '../../initializers/constants'
+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 { doesExist } from '../shared/query'
@@ -118,20 +121,60 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
   @AfterCreate
   @AfterUpdate
   static incrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
-    if (instance.state !== 'accepted') return undefined
-
-    return Promise.all([
-      ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction),
-      ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction)
-    ])
+    return afterCommitIfTransaction(options.transaction, () => {
+      return Promise.all([
+        ActorModel.rebuildFollowsCount(instance.actorId, 'following'),
+        ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers')
+      ])
+    })
   }
 
   @AfterDestroy
   static decrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
-    return Promise.all([
-      ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction),
-      ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction)
-    ])
+    return afterCommitIfTransaction(options.transaction, () => {
+      return Promise.all([
+        ActorModel.rebuildFollowsCount(instance.actorId, 'following'),
+        ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers')
+      ])
+    })
+  }
+
+  /*
+   * @deprecated Use `findOrCreateCustom` instead
+  */
+  static findOrCreate (): any {
+    throw new Error('Must not be called')
+  }
+
+  // findOrCreate has issues with actor follow hooks
+  static async findOrCreateCustom (options: {
+    byActor: MActor
+    targetActor: MActor
+    activityId: string
+    state: FollowState
+    transaction: Transaction
+  }): Promise<[ MActorFollowActors, boolean ]> {
+    const { byActor, targetActor, activityId, state, transaction } = options
+
+    let created = false
+    let actorFollow: MActorFollowActors = await ActorFollowModel.loadByActorAndTarget(byActor.id, targetActor.id, transaction)
+
+    if (!actorFollow) {
+      created = true
+
+      actorFollow = await ActorFollowModel.create({
+        actorId: byActor.id,
+        targetActorId: targetActor.id,
+        url: activityId,
+
+        state
+      }, { transaction })
+
+      actorFollow.ActorFollowing = targetActor
+      actorFollow.ActorFollower = byActor
+    }
+
+    return [ actorFollow, created ]
   }
 
   static removeFollowsOf (actorId: number, t?: Transaction) {
@@ -245,7 +288,7 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
     return ActorFollowModel.findOne(query)
   }
 
-  static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]): Promise<MActorFollowFollowingHost[]> {
+  static listSubscriptionsOf (actorId: number, targets: { name: string, host?: string }[]): Promise<MActorFollowFollowingHost[]> {
     const whereTab = targets
       .map(t => {
         if (t.host) {
@@ -305,7 +348,7 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
     return ActorFollowModel.findAll(query)
   }
 
-  static listFollowingForApi (options: {
+  static listInstanceFollowingForApi (options: {
     id: number
     start: number
     count: number
@@ -332,47 +375,50 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
       Object.assign(followingWhere, { type: actorType })
     }
 
-    const query = {
-      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
+    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
+              }
+            ]
+          }
+        ]
+      }
     }
 
-    return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
-      .then(({ rows, count }) => {
-        return {
-          data: rows,
-          total: count
-        }
-      })
+    return Promise.all([
+      ActorFollowModel.count(getQuery(true)),
+      ActorFollowModel.findAll<MActorFollowActorsDefault>(getQuery(false))
+    ]).then(([ total, data ]) => ({ total, data }))
   }
 
   static listFollowersForApi (options: {
-    actorId: number
+    actorIds: number[]
     start: number
     count: number
     sort: string
@@ -380,17 +426,23 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
     actorType?: ActivityPubActorType
     search?: string
   }) {
-    const { actorId, start, count, sort, search, state, actorType } = options
+    const { actorIds, start, count, sort, search, state, actorType } = options
 
     const followWhere = state ? { state } : {}
     const followerWhere: WhereOptions = {}
 
     if (search) {
-      Object.assign(followWhere, {
-        [Op.or]: [
-          searchAttribute(search, '$ActorFollower.preferredUsername$'),
-          searchAttribute(search, '$ActorFollower.Server.host$')
-        ]
+      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}` +
+            `)`
+          )
+        }
       })
     }
 
@@ -398,43 +450,43 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
       Object.assign(followerWhere, { type: actorType })
     }
 
-    const query = {
-      distinct: true,
-      offset: start,
-      limit: count,
-      order: getFollowsSort(sort),
-      where: followWhere,
-      include: [
-        {
-          model: ActorModel,
-          required: true,
-          as: 'ActorFollower',
-          where: followerWhere,
-          include: [
-            {
-              model: ServerModel,
-              required: true
+    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
+              }
             }
-          ]
-        },
-        {
-          model: ActorModel,
-          as: 'ActorFollowing',
-          required: true,
-          where: {
-            id: actorId
           }
-        }
-      ]
+        ]
+      }
     }
 
-    return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
-                           .then(({ rows, count }) => {
-                             return {
-                               data: rows,
-                               total: count
-                             }
-                           })
+    return Promise.all([
+      ActorFollowModel.count(getQuery(true)),
+      ActorFollowModel.findAll<MActorFollowActorsDefault>(getQuery(false))
+    ]).then(([ total, data ]) => ({ total, data }))
   }
 
   static listSubscriptionsForApi (options: {
@@ -458,58 +510,68 @@ export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowMo
       })
     }
 
-    const query = {
-      attributes: [],
-      distinct: true,
-      offset: start,
-      limit: count,
-      order: getSort(sort),
-      where,
-      include: [
-        {
-          attributes: [ 'id' ],
-          model: ActorModel.unscoped(),
-          as: 'ActorFollowing',
-          required: true,
-          include: [
-            {
-              model: VideoChannelModel.unscoped(),
-              required: true,
-              include: [
-                {
-                  attributes: {
-                    exclude: unusedActorAttributesForAPI
-                  },
-                  model: ActorModel,
-                  required: true
+    const getQuery = (forCount: boolean) => {
+      let channelInclude: Includeable[] = []
+
+      if (forCount !== true) {
+        channelInclude = [
+          {
+            attributes: {
+              exclude: unusedActorAttributesForAPI
+            },
+            model: ActorModel,
+            required: true
+          },
+          {
+            model: AccountModel.unscoped(),
+            required: true,
+            include: [
+              {
+                attributes: {
+                  exclude: unusedActorAttributesForAPI
                 },
-                {
-                  model: AccountModel.unscoped(),
-                  required: true,
-                  include: [
-                    {
-                      attributes: {
-                        exclude: unusedActorAttributesForAPI
-                      },
-                      model: ActorModel,
-                      required: true
-                    }
-                  ]
-                }
-              ]
-            }
-          ]
-        }
-      ]
+                model: ActorModel,
+                required: true
+              }
+            ]
+          }
+        ]
+      }
+
+      return {
+        attributes: forCount === true
+          ? []
+          : SORTABLE_COLUMNS.USER_SUBSCRIPTIONS,
+        distinct: true,
+        offset: start,
+        limit: count,
+        order: getSort(sort),
+        where,
+        include: [
+          {
+            attributes: [ 'id' ],
+            model: ActorModel.unscoped(),
+            as: 'ActorFollowing',
+            required: true,
+            include: [
+              {
+                model: VideoChannelModel.unscoped(),
+                required: true,
+                include: channelInclude
+              }
+            ]
+          }
+        ]
+      }
     }
 
-    return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
-                           .then(({ rows, count }) => {
-                             return {
-                               data: rows.map(r => r.ActorFollowing.VideoChannel),
-                               total: count
-                             }
-                           })
+    return Promise.all([
+      ActorFollowModel.count(getQuery(true)),
+      ActorFollowModel.findAll<MActorFollowSubscriptions>(getQuery(false))
+    ]).then(([ total, rows ]) => ({
+      total,
+      data: rows.map(r => r.ActorFollowing.VideoChannel)
+    }))
   }
 
   static async keepUnfollowedInstance (hosts: string[]) {