aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/account/account-follow.ts
blob: 8a7474c9ddacefc0b1a805706ea5ac5dabe40220 (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import { values } from 'lodash'
import * as Sequelize from 'sequelize'

import { addMethodsToModel, getSort } from '../utils'
import { AccountFollowAttributes, AccountFollowInstance, AccountFollowMethods } from './account-follow-interface'
import { FOLLOW_STATES } from '../../initializers/constants'

let AccountFollow: Sequelize.Model<AccountFollowInstance, AccountFollowAttributes>
let loadByAccountAndTarget: AccountFollowMethods.LoadByAccountAndTarget
let listFollowingForApi: AccountFollowMethods.ListFollowingForApi
let listFollowersForApi: AccountFollowMethods.ListFollowersForApi
let listAcceptedFollowerUrlsForApi: AccountFollowMethods.ListAcceptedFollowerUrlsForApi
let listAcceptedFollowingUrlsForApi: AccountFollowMethods.ListAcceptedFollowingUrlsForApi
let listAcceptedFollowerSharedInboxUrls: AccountFollowMethods.ListAcceptedFollowerSharedInboxUrls

export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
  AccountFollow = sequelize.define<AccountFollowInstance, AccountFollowAttributes>('AccountFollow',
    {
      state: {
        type: DataTypes.ENUM(values(FOLLOW_STATES)),
        allowNull: false
      }
    },
    {
      indexes: [
        {
          fields: [ 'accountId' ]
        },
        {
          fields: [ 'targetAccountId' ]
        },
        {
          fields: [ 'accountId', 'targetAccountId' ],
          unique: true
        }
      ]
    }
  )

  const classMethods = [
    associate,
    loadByAccountAndTarget,
    listFollowingForApi,
    listFollowersForApi,
    listAcceptedFollowerUrlsForApi,
    listAcceptedFollowingUrlsForApi,
    listAcceptedFollowerSharedInboxUrls
  ]
  addMethodsToModel(AccountFollow, classMethods)

  return AccountFollow
}

// ------------------------------ STATICS ------------------------------

function associate (models) {
  AccountFollow.belongsTo(models.Account, {
    foreignKey: {
      name: 'accountId',
      allowNull: false
    },
    as: 'AccountFollower',
    onDelete: 'CASCADE'
  })

  AccountFollow.belongsTo(models.Account, {
    foreignKey: {
      name: 'targetAccountId',
      allowNull: false
    },
    as: 'AccountFollowing',
    onDelete: 'CASCADE'
  })
}

loadByAccountAndTarget = function (accountId: number, targetAccountId: number) {
  const query = {
    where: {
      accountId,
      targetAccountId
    }
  }

  return AccountFollow.findOne(query)
}

listFollowingForApi = function (id: number, start: number, count: number, sort: string) {
  const query = {
    distinct: true,
    offset: start,
    limit: count,
    order: [ getSort(sort) ],
    include: [
      {
        model: AccountFollow[ 'sequelize' ].models.Account,
        required: true,
        as: 'AccountFollower',
        where: {
          id
        }
      },
      {
        model: AccountFollow['sequelize'].models.Account,
        as: 'AccountFollowing',
        required: true,
        include: [ AccountFollow['sequelize'].models.Server ]
      }
    ]
  }

  return AccountFollow.findAndCountAll(query).then(({ rows, count }) => {
    return {
      data: rows.map(r => r.AccountFollowing),
      total: count
    }
  })
}

listFollowersForApi = function (id: number, start: number, count: number, sort: string) {
  const query = {
    distinct: true,
    offset: start,
    limit: count,
    order: [ getSort(sort) ],
    include: [
      {
        model: AccountFollow[ 'sequelize' ].models.Account,
        required: true,
        as: 'AccountFollower',
        include: [ AccountFollow['sequelize'].models.Server ]
      },
      {
        model: AccountFollow['sequelize'].models.Account,
        as: 'AccountFollowing',
        required: true,
        where: {
          id
        }
      }
    ]
  }

  return AccountFollow.findAndCountAll(query).then(({ rows, count }) => {
    return {
      data: rows.map(r => r.AccountFollower),
      total: count
    }
  })
}

listAcceptedFollowerUrlsForApi = function (accountIds: number[], start?: number, count?: number) {
  return createListAcceptedFollowForApiQuery('followers', accountIds, start, count)
}

listAcceptedFollowerSharedInboxUrls = function (accountIds: number[]) {
  return createListAcceptedFollowForApiQuery('followers', accountIds, undefined, undefined, 'sharedInboxUrl')
}

listAcceptedFollowingUrlsForApi = function (accountIds: number[], start?: number, count?: number) {
  return createListAcceptedFollowForApiQuery('following', accountIds, start, count)
}

// ------------------------------ UTILS ------------------------------

async function createListAcceptedFollowForApiQuery (
  type: 'followers' | 'following',
  accountIds: number[],
  start?: number,
  count?: number,
  columnUrl = 'url'
) {
  let firstJoin: string
  let secondJoin: string

  if (type === 'followers') {
    firstJoin = 'targetAccountId'
    secondJoin = 'accountId'
  } else {
    firstJoin = 'accountId'
    secondJoin = 'targetAccountId'
  }

  const selections = [ '"Follows"."' + columnUrl + '" AS "url"', 'COUNT(*) AS "total"' ]
  const tasks: Promise<any>[] = []

  for (const selection of selections) {
    let query = 'SELECT ' + selection + ' FROM "Accounts" ' +
      'INNER JOIN "AccountFollows" ON "AccountFollows"."' + firstJoin + '" = "Accounts"."id" ' +
      'INNER JOIN "Accounts" AS "Follows" ON "AccountFollows"."' + secondJoin + '" = "Follows"."id" ' +
      'WHERE "Accounts"."id" IN ($accountIds) AND "AccountFollows"."state" = \'accepted\' '

    if (start !== undefined) query += 'LIMIT ' + start
    if (count !== undefined) query += ', ' + count

    const options = {
      bind: { accountIds: accountIds.join(',') },
      type: Sequelize.QueryTypes.SELECT
    }
    tasks.push(AccountFollow['sequelize'].query(query, options))
  }

  const [ followers, [ { total } ]] = await Promise.all(tasks)
  const urls: string[] = followers.map(f => f.url)

  return {
    data: urls,
    total: parseInt(total, 10)
  }
}