aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/account/account.ts
blob: 8b0819f395c701dba485cbeae83566daf791487f (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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
import { join } from 'path'
import * as Sequelize from 'sequelize'
import { Avatar } from '../../../shared/models/avatars/avatar.model'
import {
  activityPubContextify,
  isAccountFollowersCountValid,
  isAccountFollowingCountValid,
  isAccountPrivateKeyValid,
  isAccountPublicKeyValid,
  isUserUsernameValid
} from '../../helpers'
import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
import { AVATARS_DIR } from '../../initializers'
import { CONFIG, CONSTRAINTS_FIELDS } from '../../initializers/constants'
import { sendDeleteAccount } from '../../lib/activitypub/send/send-delete'
import { addMethodsToModel } from '../utils'
import { AccountAttributes, AccountInstance, AccountMethods } from './account-interface'

let Account: Sequelize.Model<AccountInstance, AccountAttributes>
let load: AccountMethods.Load
let loadApplication: AccountMethods.LoadApplication
let loadByUUID: AccountMethods.LoadByUUID
let loadByUrl: AccountMethods.LoadByUrl
let loadLocalByName: AccountMethods.LoadLocalByName
let loadByNameAndHost: AccountMethods.LoadByNameAndHost
let listByFollowersUrls: AccountMethods.ListByFollowersUrls
let isOwned: AccountMethods.IsOwned
let toActivityPubObject: AccountMethods.ToActivityPubObject
let toFormattedJSON: AccountMethods.ToFormattedJSON
let getFollowerSharedInboxUrls: AccountMethods.GetFollowerSharedInboxUrls
let getFollowingUrl: AccountMethods.GetFollowingUrl
let getFollowersUrl: AccountMethods.GetFollowersUrl
let getPublicKeyUrl: AccountMethods.GetPublicKeyUrl

export default function defineAccount (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
  Account = sequelize.define<AccountInstance, AccountAttributes>('Account',
    {
      uuid: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        allowNull: false,
        validate: {
          isUUID: 4
        }
      },
      name: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          nameValid: value => {
            const res = isUserUsernameValid(value)
            if (res === false) throw new Error('Name is not valid.')
          }
        }
      },
      url: {
        type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
        allowNull: false,
        validate: {
          urlValid: value => {
            const res = isActivityPubUrlValid(value)
            if (res === false) throw new Error('URL is not valid.')
          }
        }
      },
      publicKey: {
        type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.PUBLIC_KEY.max),
        allowNull: true,
        validate: {
          publicKeyValid: value => {
            const res = isAccountPublicKeyValid(value)
            if (res === false) throw new Error('Public key is not valid.')
          }
        }
      },
      privateKey: {
        type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.PRIVATE_KEY.max),
        allowNull: true,
        validate: {
          privateKeyValid: value => {
            const res = isAccountPrivateKeyValid(value)
            if (res === false) throw new Error('Private key is not valid.')
          }
        }
      },
      followersCount: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
          followersCountValid: value => {
            const res = isAccountFollowersCountValid(value)
            if (res === false) throw new Error('Followers count is not valid.')
          }
        }
      },
      followingCount: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
          followingCountValid: value => {
            const res = isAccountFollowingCountValid(value)
            if (res === false) throw new Error('Following count is not valid.')
          }
        }
      },
      inboxUrl: {
        type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
        allowNull: false,
        validate: {
          inboxUrlValid: value => {
            const res = isActivityPubUrlValid(value)
            if (res === false) throw new Error('Inbox URL is not valid.')
          }
        }
      },
      outboxUrl: {
        type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
        allowNull: false,
        validate: {
          outboxUrlValid: value => {
            const res = isActivityPubUrlValid(value)
            if (res === false) throw new Error('Outbox URL is not valid.')
          }
        }
      },
      sharedInboxUrl: {
        type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
        allowNull: false,
        validate: {
          sharedInboxUrlValid: value => {
            const res = isActivityPubUrlValid(value)
            if (res === false) throw new Error('Shared inbox URL is not valid.')
          }
        }
      },
      followersUrl: {
        type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
        allowNull: false,
        validate: {
          followersUrlValid: value => {
            const res = isActivityPubUrlValid(value)
            if (res === false) throw new Error('Followers URL is not valid.')
          }
        }
      },
      followingUrl: {
        type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
        allowNull: false,
        validate: {
          followingUrlValid: value => {
            const res = isActivityPubUrlValid(value)
            if (res === false) throw new Error('Following URL is not valid.')
          }
        }
      }
    },
    {
      indexes: [
        {
          fields: [ 'name' ]
        },
        {
          fields: [ 'serverId' ]
        },
        {
          fields: [ 'userId' ],
          unique: true
        },
        {
          fields: [ 'applicationId' ],
          unique: true
        },
        {
          fields: [ 'name', 'serverId', 'applicationId' ],
          unique: true
        }
      ],
      hooks: { afterDestroy }
    }
  )

  const classMethods = [
    associate,
    loadApplication,
    load,
    loadByUUID,
    loadByUrl,
    loadLocalByName,
    loadByNameAndHost,
    listByFollowersUrls
  ]
  const instanceMethods = [
    isOwned,
    toActivityPubObject,
    toFormattedJSON,
    getFollowerSharedInboxUrls,
    getFollowingUrl,
    getFollowersUrl,
    getPublicKeyUrl
  ]
  addMethodsToModel(Account, classMethods, instanceMethods)

  return Account
}

// ---------------------------------------------------------------------------

function associate (models) {
  Account.belongsTo(models.Server, {
    foreignKey: {
      name: 'serverId',
      allowNull: true
    },
    onDelete: 'cascade'
  })

  Account.belongsTo(models.User, {
    foreignKey: {
      name: 'userId',
      allowNull: true
    },
    onDelete: 'cascade'
  })

  Account.belongsTo(models.Application, {
    foreignKey: {
      name: 'applicationId',
      allowNull: true
    },
    onDelete: 'cascade'
  })

  Account.hasMany(models.VideoChannel, {
    foreignKey: {
      name: 'accountId',
      allowNull: false
    },
    onDelete: 'cascade',
    hooks: true
  })

  Account.hasMany(models.AccountFollow, {
    foreignKey: {
      name: 'accountId',
      allowNull: false
    },
    onDelete: 'cascade'
  })

  Account.hasMany(models.AccountFollow, {
    foreignKey: {
      name: 'targetAccountId',
      allowNull: false
    },
    as: 'followers',
    onDelete: 'cascade'
  })

  Account.hasOne(models.Avatar, {
    foreignKey: {
      name: 'avatarId',
      allowNull: true
    },
    onDelete: 'cascade'
  })
}

function afterDestroy (account: AccountInstance) {
  if (account.isOwned()) {
    return sendDeleteAccount(account, undefined)
  }

  return undefined
}

toFormattedJSON = function (this: AccountInstance) {
  let host = CONFIG.WEBSERVER.HOST
  let score: number
  let avatar: Avatar = null

  if (this.Avatar) {
    avatar = {
      path: join(AVATARS_DIR.ACCOUNT, this.Avatar.filename),
      createdAt: this.Avatar.createdAt,
      updatedAt: this.Avatar.updatedAt
    }
  }

  if (this.Server) {
    host = this.Server.host
    score = this.Server.score as number
  }

  const json = {
    id: this.id,
    uuid: this.uuid,
    host,
    score,
    name: this.name,
    followingCount: this.followingCount,
    followersCount: this.followersCount,
    createdAt: this.createdAt,
    updatedAt: this.updatedAt,
    avatar
  }

  return json
}

toActivityPubObject = function (this: AccountInstance) {
  const type = this.serverId ? 'Application' as 'Application' : 'Person' as 'Person'

  const json = {
    type,
    id: this.url,
    following: this.getFollowingUrl(),
    followers: this.getFollowersUrl(),
    inbox: this.inboxUrl,
    outbox: this.outboxUrl,
    preferredUsername: this.name,
    url: this.url,
    name: this.name,
    endpoints: {
      sharedInbox: this.sharedInboxUrl
    },
    uuid: this.uuid,
    publicKey: {
      id: this.getPublicKeyUrl(),
      owner: this.url,
      publicKeyPem: this.publicKey
    }
  }

  return activityPubContextify(json)
}

isOwned = function (this: AccountInstance) {
  return this.serverId === null
}

getFollowerSharedInboxUrls = function (this: AccountInstance, t: Sequelize.Transaction) {
  const query: Sequelize.FindOptions<AccountAttributes> = {
    attributes: [ 'sharedInboxUrl' ],
    include: [
      {
        model: Account['sequelize'].models.AccountFollow,
        required: true,
        as: 'followers',
        where: {
          targetAccountId: this.id
        }
      }
    ],
    transaction: t
  }

  return Account.findAll(query)
    .then(accounts => accounts.map(a => a.sharedInboxUrl))
}

getFollowingUrl = function (this: AccountInstance) {
  return this.url + '/following'
}

getFollowersUrl = function (this: AccountInstance) {
  return this.url + '/followers'
}

getPublicKeyUrl = function (this: AccountInstance) {
  return this.url + '#main-key'
}

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

loadApplication = function () {
  return Account.findOne({
    include: [
      {
        model: Account['sequelize'].models.Application,
        required: true
      }
    ]
  })
}

load = function (id: number) {
  return Account.findById(id)
}

loadByUUID = function (uuid: string) {
  const query: Sequelize.FindOptions<AccountAttributes> = {
    where: {
      uuid
    }
  }

  return Account.findOne(query)
}

loadLocalByName = function (name: string) {
  const query: Sequelize.FindOptions<AccountAttributes> = {
    where: {
      name,
      [Sequelize.Op.or]: [
        {
          userId: {
            [Sequelize.Op.ne]: null
          }
        },
        {
          applicationId: {
            [Sequelize.Op.ne]: null
          }
        }
      ]
    }
  }

  return Account.findOne(query)
}

loadByNameAndHost = function (name: string, host: string) {
  const query: Sequelize.FindOptions<AccountAttributes> = {
    where: {
      name
    },
    include: [
      {
        model: Account['sequelize'].models.Server,
        required: true,
        where: {
          host
        }
      }
    ]
  }

  return Account.findOne(query)
}

loadByUrl = function (url: string, transaction?: Sequelize.Transaction) {
  const query: Sequelize.FindOptions<AccountAttributes> = {
    where: {
      url
    },
    transaction
  }

  return Account.findOne(query)
}

listByFollowersUrls = function (followersUrls: string[], transaction?: Sequelize.Transaction) {
  const query: Sequelize.FindOptions<AccountAttributes> = {
    where: {
      followersUrl: {
        [Sequelize.Op.in]: followersUrls
      }
    },
    transaction
  }

  return Account.findAll(query)
}