]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/account.ts
Refractor validators
[github/Chocobozzz/PeerTube.git] / server / models / account / account.ts
1 import * as Sequelize from 'sequelize'
2 import {
3 activityPubContextify,
4 isAccountFollowersCountValid,
5 isAccountFollowingCountValid,
6 isAccountPrivateKeyValid,
7 isAccountPublicKeyValid,
8 isUserUsernameValid
9 } from '../../helpers'
10 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
11 import { CONFIG, CONSTRAINTS_FIELDS } from '../../initializers/constants'
12 import { sendDeleteAccount } from '../../lib/activitypub/send/send-delete'
13
14 import { addMethodsToModel } from '../utils'
15 import { AccountAttributes, AccountInstance, AccountMethods } from './account-interface'
16
17 let Account: Sequelize.Model<AccountInstance, AccountAttributes>
18 let load: AccountMethods.Load
19 let loadApplication: AccountMethods.LoadApplication
20 let loadByUUID: AccountMethods.LoadByUUID
21 let loadByUrl: AccountMethods.LoadByUrl
22 let loadLocalByName: AccountMethods.LoadLocalByName
23 let loadByNameAndHost: AccountMethods.LoadByNameAndHost
24 let listByFollowersUrls: AccountMethods.ListByFollowersUrls
25 let isOwned: AccountMethods.IsOwned
26 let toActivityPubObject: AccountMethods.ToActivityPubObject
27 let toFormattedJSON: AccountMethods.ToFormattedJSON
28 let getFollowerSharedInboxUrls: AccountMethods.GetFollowerSharedInboxUrls
29 let getFollowingUrl: AccountMethods.GetFollowingUrl
30 let getFollowersUrl: AccountMethods.GetFollowersUrl
31 let getPublicKeyUrl: AccountMethods.GetPublicKeyUrl
32
33 export default function defineAccount (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
34 Account = sequelize.define<AccountInstance, AccountAttributes>('Account',
35 {
36 uuid: {
37 type: DataTypes.UUID,
38 defaultValue: DataTypes.UUIDV4,
39 allowNull: false,
40 validate: {
41 isUUID: 4
42 }
43 },
44 name: {
45 type: DataTypes.STRING,
46 allowNull: false,
47 validate: {
48 nameValid: value => {
49 const res = isUserUsernameValid(value)
50 if (res === false) throw new Error('Name is not valid.')
51 }
52 }
53 },
54 url: {
55 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
56 allowNull: false,
57 validate: {
58 urlValid: value => {
59 const res = isActivityPubUrlValid(value)
60 if (res === false) throw new Error('URL is not valid.')
61 }
62 }
63 },
64 publicKey: {
65 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.PUBLIC_KEY.max),
66 allowNull: true,
67 validate: {
68 publicKeyValid: value => {
69 const res = isAccountPublicKeyValid(value)
70 if (res === false) throw new Error('Public key is not valid.')
71 }
72 }
73 },
74 privateKey: {
75 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.PRIVATE_KEY.max),
76 allowNull: true,
77 validate: {
78 privateKeyValid: value => {
79 const res = isAccountPrivateKeyValid(value)
80 if (res === false) throw new Error('Private key is not valid.')
81 }
82 }
83 },
84 followersCount: {
85 type: DataTypes.INTEGER,
86 allowNull: false,
87 validate: {
88 followersCountValid: value => {
89 const res = isAccountFollowersCountValid(value)
90 if (res === false) throw new Error('Followers count is not valid.')
91 }
92 }
93 },
94 followingCount: {
95 type: DataTypes.INTEGER,
96 allowNull: false,
97 validate: {
98 followingCountValid: value => {
99 const res = isAccountFollowingCountValid(value)
100 if (res === false) throw new Error('Following count is not valid.')
101 }
102 }
103 },
104 inboxUrl: {
105 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
106 allowNull: false,
107 validate: {
108 inboxUrlValid: value => {
109 const res = isActivityPubUrlValid(value)
110 if (res === false) throw new Error('Inbox URL is not valid.')
111 }
112 }
113 },
114 outboxUrl: {
115 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
116 allowNull: false,
117 validate: {
118 outboxUrlValid: value => {
119 const res = isActivityPubUrlValid(value)
120 if (res === false) throw new Error('Outbox URL is not valid.')
121 }
122 }
123 },
124 sharedInboxUrl: {
125 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
126 allowNull: false,
127 validate: {
128 sharedInboxUrlValid: value => {
129 const res = isActivityPubUrlValid(value)
130 if (res === false) throw new Error('Shared inbox URL is not valid.')
131 }
132 }
133 },
134 followersUrl: {
135 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
136 allowNull: false,
137 validate: {
138 followersUrlValid: value => {
139 const res = isActivityPubUrlValid(value)
140 if (res === false) throw new Error('Followers URL is not valid.')
141 }
142 }
143 },
144 followingUrl: {
145 type: DataTypes.STRING(CONSTRAINTS_FIELDS.ACCOUNTS.URL.max),
146 allowNull: false,
147 validate: {
148 followingUrlValid: value => {
149 const res = isActivityPubUrlValid(value)
150 if (res === false) throw new Error('Following URL is not valid.')
151 }
152 }
153 }
154 },
155 {
156 indexes: [
157 {
158 fields: [ 'name' ]
159 },
160 {
161 fields: [ 'serverId' ]
162 },
163 {
164 fields: [ 'userId' ],
165 unique: true
166 },
167 {
168 fields: [ 'applicationId' ],
169 unique: true
170 },
171 {
172 fields: [ 'name', 'serverId', 'applicationId' ],
173 unique: true
174 }
175 ],
176 hooks: { afterDestroy }
177 }
178 )
179
180 const classMethods = [
181 associate,
182 loadApplication,
183 load,
184 loadByUUID,
185 loadByUrl,
186 loadLocalByName,
187 loadByNameAndHost,
188 listByFollowersUrls
189 ]
190 const instanceMethods = [
191 isOwned,
192 toActivityPubObject,
193 toFormattedJSON,
194 getFollowerSharedInboxUrls,
195 getFollowingUrl,
196 getFollowersUrl,
197 getPublicKeyUrl
198 ]
199 addMethodsToModel(Account, classMethods, instanceMethods)
200
201 return Account
202 }
203
204 // ---------------------------------------------------------------------------
205
206 function associate (models) {
207 Account.belongsTo(models.Server, {
208 foreignKey: {
209 name: 'serverId',
210 allowNull: true
211 },
212 onDelete: 'cascade'
213 })
214
215 Account.belongsTo(models.User, {
216 foreignKey: {
217 name: 'userId',
218 allowNull: true
219 },
220 onDelete: 'cascade'
221 })
222
223 Account.belongsTo(models.Application, {
224 foreignKey: {
225 name: 'applicationId',
226 allowNull: true
227 },
228 onDelete: 'cascade'
229 })
230
231 Account.hasMany(models.VideoChannel, {
232 foreignKey: {
233 name: 'accountId',
234 allowNull: false
235 },
236 onDelete: 'cascade',
237 hooks: true
238 })
239
240 Account.hasMany(models.AccountFollow, {
241 foreignKey: {
242 name: 'accountId',
243 allowNull: false
244 },
245 onDelete: 'cascade'
246 })
247
248 Account.hasMany(models.AccountFollow, {
249 foreignKey: {
250 name: 'targetAccountId',
251 allowNull: false
252 },
253 as: 'followers',
254 onDelete: 'cascade'
255 })
256 }
257
258 function afterDestroy (account: AccountInstance) {
259 if (account.isOwned()) {
260 return sendDeleteAccount(account, undefined)
261 }
262
263 return undefined
264 }
265
266 toFormattedJSON = function (this: AccountInstance) {
267 let host = CONFIG.WEBSERVER.HOST
268 let score: number
269
270 if (this.Server) {
271 host = this.Server.host
272 score = this.Server.score as number
273 }
274
275 const json = {
276 id: this.id,
277 host,
278 score,
279 name: this.name,
280 createdAt: this.createdAt,
281 updatedAt: this.updatedAt
282 }
283
284 return json
285 }
286
287 toActivityPubObject = function (this: AccountInstance) {
288 const type = this.serverId ? 'Application' as 'Application' : 'Person' as 'Person'
289
290 const json = {
291 type,
292 id: this.url,
293 following: this.getFollowingUrl(),
294 followers: this.getFollowersUrl(),
295 inbox: this.inboxUrl,
296 outbox: this.outboxUrl,
297 preferredUsername: this.name,
298 url: this.url,
299 name: this.name,
300 endpoints: {
301 sharedInbox: this.sharedInboxUrl
302 },
303 uuid: this.uuid,
304 publicKey: {
305 id: this.getPublicKeyUrl(),
306 owner: this.url,
307 publicKeyPem: this.publicKey
308 }
309 }
310
311 return activityPubContextify(json)
312 }
313
314 isOwned = function (this: AccountInstance) {
315 return this.serverId === null
316 }
317
318 getFollowerSharedInboxUrls = function (this: AccountInstance) {
319 const query: Sequelize.FindOptions<AccountAttributes> = {
320 attributes: [ 'sharedInboxUrl' ],
321 include: [
322 {
323 model: Account['sequelize'].models.AccountFollow,
324 required: true,
325 as: 'followers',
326 where: {
327 targetAccountId: this.id
328 }
329 }
330 ]
331 }
332
333 return Account.findAll(query)
334 .then(accounts => accounts.map(a => a.sharedInboxUrl))
335 }
336
337 getFollowingUrl = function (this: AccountInstance) {
338 return this.url + '/following'
339 }
340
341 getFollowersUrl = function (this: AccountInstance) {
342 return this.url + '/followers'
343 }
344
345 getPublicKeyUrl = function (this: AccountInstance) {
346 return this.url + '#main-key'
347 }
348
349 // ------------------------------ STATICS ------------------------------
350
351 loadApplication = function () {
352 return Account.findOne({
353 include: [
354 {
355 model: Account['sequelize'].models.Application,
356 required: true
357 }
358 ]
359 })
360 }
361
362 load = function (id: number) {
363 return Account.findById(id)
364 }
365
366 loadByUUID = function (uuid: string) {
367 const query: Sequelize.FindOptions<AccountAttributes> = {
368 where: {
369 uuid
370 }
371 }
372
373 return Account.findOne(query)
374 }
375
376 loadLocalByName = function (name: string) {
377 const query: Sequelize.FindOptions<AccountAttributes> = {
378 where: {
379 name,
380 [Sequelize.Op.or]: [
381 {
382 userId: {
383 [Sequelize.Op.ne]: null
384 }
385 },
386 {
387 applicationId: {
388 [Sequelize.Op.ne]: null
389 }
390 }
391 ]
392 }
393 }
394
395 return Account.findOne(query)
396 }
397
398 loadByNameAndHost = function (name: string, host: string) {
399 const query: Sequelize.FindOptions<AccountAttributes> = {
400 where: {
401 name
402 },
403 include: [
404 {
405 model: Account['sequelize'].models.Server,
406 required: true,
407 where: {
408 host
409 }
410 }
411 ]
412 }
413
414 return Account.findOne(query)
415 }
416
417 loadByUrl = function (url: string, transaction?: Sequelize.Transaction) {
418 const query: Sequelize.FindOptions<AccountAttributes> = {
419 where: {
420 url
421 },
422 transaction
423 }
424
425 return Account.findOne(query)
426 }
427
428 listByFollowersUrls = function (followersUrls: string[], transaction?: Sequelize.Transaction) {
429 const query: Sequelize.FindOptions<AccountAttributes> = {
430 where: {
431 followersUrl: {
432 [Sequelize.Op.in]: followersUrls
433 }
434 },
435 transaction
436 }
437
438 return Account.findAll(query)
439 }