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