]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/activitypub/actor-follow.ts
Add more filters to admin follows table
[github/Chocobozzz/PeerTube.git] / server / models / activitypub / actor-follow.ts
index 8ef770cd4933d92eb7b11d8a7d6c313a2cbf982d..c65b975d23b8abce46c1663d7059e620b37940c0 100644 (file)
@@ -1,5 +1,5 @@
 import * as Bluebird from 'bluebird'
-import { values } from 'lodash'
+import { values, difference } from 'lodash'
 import {
   AfterCreate,
   AfterDestroy,
@@ -21,19 +21,21 @@ import { FollowState } from '../../../shared/models/actors'
 import { ActorFollow } from '../../../shared/models/actors/follow.model'
 import { logger } from '../../helpers/logger'
 import { getServerActor } from '../../helpers/utils'
-import { ACTOR_FOLLOW_SCORE, FOLLOW_STATES } from '../../initializers/constants'
+import { ACTOR_FOLLOW_SCORE, FOLLOW_STATES, SERVER_ACTOR_NAME } from '../../initializers/constants'
 import { ServerModel } from '../server/server'
-import { createSafeIn, getSort } from '../utils'
+import { createSafeIn, getSort, getFollowsSort } from '../utils'
 import { ActorModel, unusedActorAttributesForAPI } from './actor'
 import { VideoChannelModel } from '../video/video-channel'
 import { AccountModel } from '../account/account'
-import { IncludeOptions, Op, QueryTypes, Transaction } from 'sequelize'
+import { IncludeOptions, Op, QueryTypes, Transaction, WhereOptions } from 'sequelize'
 import {
   MActorFollowActorsDefault,
   MActorFollowActorsDefaultSubscription,
   MActorFollowFollowingHost,
+  MActorFollowFormattable,
   MActorFollowSubscriptions
 } from '@server/typings/models'
+import { ActivityPubActorType } from '@shared/models'
 
 @Table({
   tableName: 'actorFollow',
@@ -291,12 +293,39 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
     return ActorFollowModel.findAll(query)
   }
 
-  static listFollowingForApi (id: number, start: number, count: number, sort: string, search?: string) {
+  static listFollowingForApi (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 = {}
+    const followingServerWhere: WhereOptions = {}
+
+    if (search) {
+      Object.assign(followingServerWhere, {
+        host: {
+          [ Op.iLike ]: '%' + search + '%'
+        }
+      })
+    }
+
+    if (actorType) {
+      Object.assign(followingWhere, { type: actorType })
+    }
+
     const query = {
       distinct: true,
       offset: start,
       limit: count,
-      order: getSort(sort),
+      order: getFollowsSort(sort),
+      where: followWhere,
       include: [
         {
           model: ActorModel,
@@ -310,15 +339,12 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
           model: ActorModel,
           as: 'ActorFollowing',
           required: true,
+          where: followingWhere,
           include: [
             {
               model: ServerModel,
               required: true,
-              where: search ? {
-                host: {
-                  [Op.iLike]: '%' + search + '%'
-                }
-              } : undefined
+              where: followingServerWhere
             }
           ]
         }
@@ -334,26 +360,50 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
       })
   }
 
-  static listFollowersForApi (actorId: number, start: number, count: number, sort: string, search?: string) {
+  static listFollowersForApi (options: {
+    actorId: number,
+    start: number,
+    count: number,
+    sort: string,
+    state?: FollowState,
+    actorType?: ActivityPubActorType,
+    search?: string
+  }) {
+    const { actorId, start, count, sort, search, state, actorType } = options
+
+    const followWhere = state ? { state } : {}
+    const followerWhere: WhereOptions = {}
+    const followerServerWhere: WhereOptions = {}
+
+    if (search) {
+      Object.assign(followerServerWhere, {
+        host: {
+          [ Op.iLike ]: '%' + search + '%'
+        }
+      })
+    }
+
+    if (actorType) {
+      Object.assign(followerWhere, { type: actorType })
+    }
+
     const query = {
       distinct: true,
       offset: start,
       limit: count,
-      order: getSort(sort),
+      order: getFollowsSort(sort),
+      where: followWhere,
       include: [
         {
           model: ActorModel,
           required: true,
           as: 'ActorFollower',
+          where: followerWhere,
           include: [
             {
               model: ServerModel,
               required: true,
-              where: search ? {
-                host: {
-                  [ Op.iLike ]: '%' + search + '%'
-                }
-              } : undefined
+              where: followerServerWhere
             }
           ]
         },
@@ -434,6 +484,45 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
                            })
   }
 
+  static async keepUnfollowedInstance (hosts: string[]) {
+    const followerId = (await getServerActor()).id
+
+    const query = {
+      attributes: [ 'id' ],
+      where: {
+        actorId: followerId
+      },
+      include: [
+        {
+          attributes: [ 'id' ],
+          model: ActorModel.unscoped(),
+          required: true,
+          as: 'ActorFollowing',
+          where: {
+            preferredUsername: SERVER_ACTOR_NAME
+          },
+          include: [
+            {
+              attributes: [ 'host' ],
+              model: ServerModel.unscoped(),
+              required: true,
+              where: {
+                host: {
+                  [Op.in]: hosts
+                }
+              }
+            }
+          ]
+        }
+      ]
+    }
+
+    const res = await ActorFollowModel.findAll(query)
+    const followedHosts = res.map(row => row.ActorFollowing.Server.host)
+
+    return difference(hosts, followedHosts)
+  }
+
   static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
     return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
   }
@@ -534,8 +623,8 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
     }
 
     const selections: string[] = []
-    if (distinct === true) selections.push('DISTINCT("Follows"."' + columnUrl + '") AS "url"')
-    else selections.push('"Follows"."' + columnUrl + '" AS "url"')
+    if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
+    else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
 
     selections.push('COUNT(*) AS "total"')
 
@@ -545,7 +634,7 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
       let query = 'SELECT ' + selection + ' FROM "actor" ' +
         'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
         'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
-        'WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = \'accepted\' '
+        `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
 
       if (count !== undefined) query += 'LIMIT ' + count
       if (start !== undefined) query += ' OFFSET ' + start
@@ -559,7 +648,7 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
     }
 
     const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
-    const urls: string[] = followers.map(f => f.url)
+    const urls: string[] = followers.map(f => f.selectionUrl)
 
     return {
       data: urls,
@@ -580,7 +669,7 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
     return ActorFollowModel.findAll(query)
   }
 
-  toFormattedJSON (): ActorFollow {
+  toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
     const follower = this.ActorFollower.toFormattedJSON()
     const following = this.ActorFollowing.toFormattedJSON()