1 import * as Sequelize from 'sequelize'
5 isAccountPublicKeyValid,
7 isAccountPrivateKeyValid,
8 isAccountFollowersCountValid,
9 isAccountFollowingCountValid,
12 isAccountSharedInboxValid,
13 isAccountFollowersValid,
14 isAccountFollowingValid,
16 } from '../../helpers'
18 import { addMethodsToModel, getSort } from '../utils'
24 } from './account-interface'
25 import { sendDeleteAccount } from '../../lib/activitypub/send-request'
26 import { CONSTRAINTS_FIELDS } from '../../initializers/constants'
28 let Account: Sequelize.Model<AccountInstance, AccountAttributes>
29 let loadAccountByPodAndUUID: AccountMethods.LoadAccountByPodAndUUID
30 let load: AccountMethods.Load
31 let loadApplication: AccountMethods.LoadApplication
32 let loadByUUID: AccountMethods.LoadByUUID
33 let loadByUrl: AccountMethods.LoadByUrl
34 let loadLocalByName: AccountMethods.LoadLocalByName
35 let loadByNameAndHost: AccountMethods.LoadByNameAndHost
36 let listOwned: AccountMethods.ListOwned
37 let listAcceptedFollowerUrlsForApi: AccountMethods.ListAcceptedFollowerUrlsForApi
38 let listAcceptedFollowingUrlsForApi: AccountMethods.ListAcceptedFollowingUrlsForApi
39 let listFollowingForApi: AccountMethods.ListFollowingForApi
40 let listFollowersForApi: AccountMethods.ListFollowersForApi
41 let isOwned: AccountMethods.IsOwned
42 let toActivityPubObject: AccountMethods.ToActivityPubObject
43 let toFormattedJSON: AccountMethods.ToFormattedJSON
44 let getFollowerSharedInboxUrls: AccountMethods.GetFollowerSharedInboxUrls
45 let getFollowingUrl: AccountMethods.GetFollowingUrl
46 let getFollowersUrl: AccountMethods.GetFollowersUrl
47 let getPublicKeyUrl: AccountMethods.GetPublicKeyUrl
49 export default function defineAccount (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
50 Account = sequelize.define<AccountInstance, AccountAttributes>('Account',
54 defaultValue: DataTypes.UUIDV4,
61 type: DataTypes.STRING,
65 const res = isUserUsernameValid(value)
66 if (res === false) throw new Error('Name is not valid.')
71 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
75 const res = isAccountUrlValid(value)
76 if (res === false) throw new Error('URL is not valid.')
81 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.PUBLIC_KEY.max),
84 publicKeyValid: value => {
85 const res = isAccountPublicKeyValid(value)
86 if (res === false) throw new Error('Public key is not valid.')
91 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.PRIVATE_KEY.max),
94 privateKeyValid: value => {
95 const res = isAccountPrivateKeyValid(value)
96 if (res === false) throw new Error('Private key is not valid.')
101 type: DataTypes.INTEGER,
104 followersCountValid: value => {
105 const res = isAccountFollowersCountValid(value)
106 if (res === false) throw new Error('Followers count is not valid.')
111 type: DataTypes.INTEGER,
114 followingCountValid: value => {
115 const res = isAccountFollowingCountValid(value)
116 if (res === false) throw new Error('Following count is not valid.')
121 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
124 inboxUrlValid: value => {
125 const res = isAccountInboxValid(value)
126 if (res === false) throw new Error('Inbox URL is not valid.')
131 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
134 outboxUrlValid: value => {
135 const res = isAccountOutboxValid(value)
136 if (res === false) throw new Error('Outbox URL is not valid.')
141 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
144 sharedInboxUrlValid: value => {
145 const res = isAccountSharedInboxValid(value)
146 if (res === false) throw new Error('Shared inbox URL is not valid.')
151 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
154 followersUrlValid: value => {
155 const res = isAccountFollowersValid(value)
156 if (res === false) throw new Error('Followers URL is not valid.')
161 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
164 followingUrlValid: value => {
165 const res = isAccountFollowingValid(value)
166 if (res === false) throw new Error('Following URL is not valid.')
180 fields: [ 'userId' ],
184 fields: [ 'applicationId' ],
188 fields: [ 'name', 'podId' ],
192 hooks: { afterDestroy }
196 const classMethods = [
198 loadAccountByPodAndUUID,
206 listAcceptedFollowerUrlsForApi,
207 listAcceptedFollowingUrlsForApi,
211 const instanceMethods = [
215 getFollowerSharedInboxUrls,
220 addMethodsToModel(Account, classMethods, instanceMethods)
225 // ---------------------------------------------------------------------------
227 function associate (models) {
228 Account.belongsTo(models.Pod, {
236 Account.belongsTo(models.User, {
244 Account.belongsTo(models.Application, {
246 name: 'applicationId',
252 Account.hasMany(models.VideoChannel, {
261 Account.hasMany(models.AccountFollow, {
270 Account.hasMany(models.AccountFollow, {
272 name: 'targetAccountId',
280 function afterDestroy (account: AccountInstance) {
281 if (account.isOwned()) {
282 return sendDeleteAccount(account, undefined)
288 toFormattedJSON = function (this: AccountInstance) {
298 toActivityPubObject = function (this: AccountInstance) {
299 const type = this.podId ? 'Application' as 'Application' : 'Person' as 'Person'
304 following: this.getFollowingUrl(),
305 followers: this.getFollowersUrl(),
306 inbox: this.inboxUrl,
307 outbox: this.outboxUrl,
308 preferredUsername: this.name,
312 sharedInbox: this.sharedInboxUrl
316 id: this.getPublicKeyUrl(),
318 publicKeyPem: this.publicKey
322 return activityPubContextify(json)
325 isOwned = function (this: AccountInstance) {
326 return this.podId === null
329 getFollowerSharedInboxUrls = function (this: AccountInstance) {
330 const query: Sequelize.FindOptions<AccountAttributes> = {
331 attributes: [ 'sharedInboxUrl' ],
334 model: Account['sequelize'].models.AccountFollow,
338 targetAccountId: this.id
344 return Account.findAll(query)
345 .then(accounts => accounts.map(a => a.sharedInboxUrl))
348 getFollowingUrl = function (this: AccountInstance) {
349 return this.url + '/followers'
352 getFollowersUrl = function (this: AccountInstance) {
353 return this.url + '/followers'
356 getPublicKeyUrl = function (this: AccountInstance) {
357 return this.url + '#main-key'
360 // ------------------------------ STATICS ------------------------------
362 listOwned = function () {
363 const query: Sequelize.FindOptions<AccountAttributes> = {
369 return Account.findAll(query)
372 listAcceptedFollowerUrlsForApi = function (id: number, start: number, count?: number) {
373 return createListAcceptedFollowForApiQuery('followers', id, start, count)
376 listAcceptedFollowingUrlsForApi = function (id: number, start: number, count?: number) {
377 return createListAcceptedFollowForApiQuery('following', id, start, count)
380 listFollowingForApi = function (id: number, start: number, count: number, sort: string) {
385 order: [ getSort(sort) ],
388 model: Account['sequelize'].models.AccountFollow,
393 model: Account['sequelize'].models.Account,
394 as: 'accountFollowing',
396 include: [ Account['sequelize'].models.Pod ]
403 return Account.findAndCountAll(query).then(({ rows, count }) => {
411 listFollowersForApi = function (id: number, start: number, count: number, sort: string) {
416 order: [ getSort(sort) ],
419 model: Account['sequelize'].models.AccountFollow,
424 model: Account['sequelize'].models.Account,
425 as: 'accountFollowers',
427 include: [ Account['sequelize'].models.Pod ]
434 return Account.findAndCountAll(query).then(({ rows, count }) => {
442 loadApplication = function () {
443 return Account.findOne({
446 model: Account['sequelize'].models.Application,
453 load = function (id: number) {
454 return Account.findById(id)
457 loadByUUID = function (uuid: string) {
458 const query: Sequelize.FindOptions<AccountAttributes> = {
464 return Account.findOne(query)
467 loadLocalByName = function (name: string) {
468 const query: Sequelize.FindOptions<AccountAttributes> = {
474 [Sequelize.Op.ne]: null
479 [Sequelize.Op.ne]: null
486 return Account.findOne(query)
489 loadByNameAndHost = function (name: string, host: string) {
490 const query: Sequelize.FindOptions<AccountAttributes> = {
496 model: Account['sequelize'].models.Pod,
505 return Account.findOne(query)
508 loadByUrl = function (url: string, transaction?: Sequelize.Transaction) {
509 const query: Sequelize.FindOptions<AccountAttributes> = {
516 return Account.findOne(query)
519 loadAccountByPodAndUUID = function (uuid: string, podId: number, transaction: Sequelize.Transaction) {
520 const query: Sequelize.FindOptions<AccountAttributes> = {
528 return Account.find(query)
531 // ------------------------------ UTILS ------------------------------
533 async function createListAcceptedFollowForApiQuery (type: 'followers' | 'following', id: number, start: number, count?: number) {
534 let firstJoin: string
535 let secondJoin: string
537 if (type === 'followers') {
538 firstJoin = 'targetAccountId'
539 secondJoin = 'accountId'
541 firstJoin = 'accountId'
542 secondJoin = 'targetAccountId'
545 const selections = [ '"Followers"."url" AS "url"', 'COUNT(*) AS "total"' ]
546 const tasks: Promise<any>[] = []
548 for (const selection of selections) {
549 let query = 'SELECT ' + selection + ' FROM "Account" ' +
550 'INNER JOIN "AccountFollow" ON "AccountFollow"."' + firstJoin + '" = "Account"."id" ' +
551 'INNER JOIN "Account" AS "Follows" ON "Followers"."id" = "Follows"."' + secondJoin + '" ' +
552 'WHERE "Account"."id" = $id AND "AccountFollow"."state" = \'accepted\' ' +
555 if (count !== undefined) query += ', ' + count
559 type: Sequelize.QueryTypes.SELECT
561 tasks.push(Account['sequelize'].query(query, options))
564 const [ followers, [ { total } ]] = await Promise.all(tasks)
565 const urls: string[] = followers.map(f => f.url)
569 total: parseInt(total, 10)