aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/actor/sql/instance-list-followers-query-builder.ts
blob: 4a17a8f11213a23bef7dd252da6a58226bb2b35e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { Sequelize } from 'sequelize'
import { ModelBuilder } from '@server/models/shared'
import { parseRowCountResult } from '@server/models/utils'
import { MActorFollowActorsDefault } from '@server/types/models'
import { ActivityPubActorType, FollowState } from '@shared/models'
import { InstanceListFollowsQueryBuilder } from './shared/instance-list-follows-query-builder'

export interface ListFollowersOptions {
  actorIds: number[]
  start: number
  count: number
  sort: string
  state?: FollowState
  actorType?: ActivityPubActorType
  search?: string
}

export class InstanceListFollowersQueryBuilder extends InstanceListFollowsQueryBuilder <ListFollowersOptions> {

  constructor (
    protected readonly sequelize: Sequelize,
    protected readonly options: ListFollowersOptions
  ) {
    super(sequelize, options)
  }

  async listFollowers () {
    this.buildListQuery()

    const results = await this.runQuery({ nest: true })
    const modelBuilder = new ModelBuilder<MActorFollowActorsDefault>(this.sequelize)

    return modelBuilder.createModels(results, 'ActorFollow')
  }

  async countFollowers () {
    this.buildCountQuery()

    const result = await this.runQuery()

    return parseRowCountResult(result)
  }

  protected getWhere () {
    let where = 'WHERE "ActorFollowing"."id" IN (:actorIds) '
    this.replacements.actorIds = this.options.actorIds

    if (this.options.state) {
      where += 'AND "ActorFollowModel"."state" = :state '
      this.replacements.state = this.options.state
    }

    if (this.options.search) {
      const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')

      where += `AND (` +
        `"ActorFollower->Server"."host" ILIKE ${escapedLikeSearch} ` +
        `OR "ActorFollower"."preferredUsername" ILIKE ${escapedLikeSearch} ` +
      `)`
    }

    if (this.options.actorType) {
      where += `AND "ActorFollower"."type" = :actorType `
      this.replacements.actorType = this.options.actorType
    }

    return where
  }
}