Fix AP collections pagination
[oweals/peertube.git] / server / models / activitypub / actor.ts
1 import { values } from 'lodash'
2 import { extname } from 'path'
3 import * as Sequelize from 'sequelize'
4 import {
5   AllowNull,
6   BelongsTo,
7   Column,
8   CreatedAt,
9   DataType,
10   Default,
11   DefaultScope,
12   ForeignKey,
13   HasMany,
14   HasOne,
15   Is,
16   IsUUID,
17   Model,
18   Scopes,
19   Table,
20   UpdatedAt
21 } from 'sequelize-typescript'
22 import { ActivityPubActorType } from '../../../shared/models/activitypub'
23 import { Avatar } from '../../../shared/models/avatars/avatar.model'
24 import { activityPubContextify } from '../../helpers/activitypub'
25 import {
26   isActorFollowersCountValid,
27   isActorFollowingCountValid,
28   isActorPreferredUsernameValid,
29   isActorPrivateKeyValid,
30   isActorPublicKeyValid
31 } from '../../helpers/custom-validators/activitypub/actor'
32 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
33 import { ACTIVITY_PUB, ACTIVITY_PUB_ACTOR_TYPES, CONFIG, CONSTRAINTS_FIELDS } from '../../initializers'
34 import { AccountModel } from '../account/account'
35 import { AvatarModel } from '../avatar/avatar'
36 import { ServerModel } from '../server/server'
37 import { throwIfNotValid } from '../utils'
38 import { VideoChannelModel } from '../video/video-channel'
39 import { ActorFollowModel } from './actor-follow'
40 import { VideoModel } from '../video/video'
41
42 enum ScopeNames {
43   FULL = 'FULL'
44 }
45
46 export const unusedActorAttributesForAPI = [
47   'publicKey',
48   'privateKey',
49   'inboxUrl',
50   'outboxUrl',
51   'sharedInboxUrl',
52   'followersUrl',
53   'followingUrl',
54   'url',
55   'createdAt',
56   'updatedAt'
57 ]
58
59 @DefaultScope({
60   include: [
61     {
62       model: () => ServerModel,
63       required: false
64     },
65     {
66       model: () => AvatarModel,
67       required: false
68     }
69   ]
70 })
71 @Scopes({
72   [ScopeNames.FULL]: {
73     include: [
74       {
75         model: () => AccountModel.unscoped(),
76         required: false
77       },
78       {
79         model: () => VideoChannelModel.unscoped(),
80         required: false,
81         include: [
82           {
83             model: () => AccountModel,
84             required: true
85           }
86         ]
87       },
88       {
89         model: () => ServerModel,
90         required: false
91       },
92       {
93         model: () => AvatarModel,
94         required: false
95       }
96     ]
97   }
98 })
99 @Table({
100   tableName: 'actor',
101   indexes: [
102     {
103       fields: [ 'url' ],
104       unique: true
105     },
106     {
107       fields: [ 'preferredUsername', 'serverId' ],
108       unique: true
109     },
110     {
111       fields: [ 'inboxUrl', 'sharedInboxUrl' ]
112     },
113     {
114       fields: [ 'sharedInboxUrl' ]
115     },
116     {
117       fields: [ 'serverId' ]
118     },
119     {
120       fields: [ 'avatarId' ]
121     },
122     {
123       fields: [ 'uuid' ],
124       unique: true
125     },
126     {
127       fields: [ 'followersUrl' ]
128     }
129   ]
130 })
131 export class ActorModel extends Model<ActorModel> {
132
133   @AllowNull(false)
134   @Column(DataType.ENUM(values(ACTIVITY_PUB_ACTOR_TYPES)))
135   type: ActivityPubActorType
136
137   @AllowNull(false)
138   @Default(DataType.UUIDV4)
139   @IsUUID(4)
140   @Column(DataType.UUID)
141   uuid: string
142
143   @AllowNull(false)
144   @Is('ActorPreferredUsername', value => throwIfNotValid(value, isActorPreferredUsernameValid, 'actor preferred username'))
145   @Column
146   preferredUsername: string
147
148   @AllowNull(false)
149   @Is('ActorUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
150   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
151   url: string
152
153   @AllowNull(true)
154   @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPublicKeyValid, 'public key'))
155   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PUBLIC_KEY.max))
156   publicKey: string
157
158   @AllowNull(true)
159   @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPrivateKeyValid, 'private key'))
160   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PRIVATE_KEY.max))
161   privateKey: string
162
163   @AllowNull(false)
164   @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowersCountValid, 'followers count'))
165   @Column
166   followersCount: number
167
168   @AllowNull(false)
169   @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowingCountValid, 'following count'))
170   @Column
171   followingCount: number
172
173   @AllowNull(false)
174   @Is('ActorInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'inbox url'))
175   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
176   inboxUrl: string
177
178   @AllowNull(false)
179   @Is('ActorOutboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'outbox url'))
180   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
181   outboxUrl: string
182
183   @AllowNull(false)
184   @Is('ActorSharedInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'shared inbox url'))
185   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
186   sharedInboxUrl: string
187
188   @AllowNull(false)
189   @Is('ActorFollowersUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'followers url'))
190   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
191   followersUrl: string
192
193   @AllowNull(false)
194   @Is('ActorFollowingUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'following url'))
195   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
196   followingUrl: string
197
198   @CreatedAt
199   createdAt: Date
200
201   @UpdatedAt
202   updatedAt: Date
203
204   @ForeignKey(() => AvatarModel)
205   @Column
206   avatarId: number
207
208   @BelongsTo(() => AvatarModel, {
209     foreignKey: {
210       allowNull: true
211     },
212     onDelete: 'set null',
213     hooks: true
214   })
215   Avatar: AvatarModel
216
217   @HasMany(() => ActorFollowModel, {
218     foreignKey: {
219       name: 'actorId',
220       allowNull: false
221     },
222     onDelete: 'cascade'
223   })
224   ActorFollowing: ActorFollowModel[]
225
226   @HasMany(() => ActorFollowModel, {
227     foreignKey: {
228       name: 'targetActorId',
229       allowNull: false
230     },
231     as: 'ActorFollowers',
232     onDelete: 'cascade'
233   })
234   ActorFollowers: ActorFollowModel[]
235
236   @ForeignKey(() => ServerModel)
237   @Column
238   serverId: number
239
240   @BelongsTo(() => ServerModel, {
241     foreignKey: {
242       allowNull: true
243     },
244     onDelete: 'cascade'
245   })
246   Server: ServerModel
247
248   @HasOne(() => AccountModel, {
249     foreignKey: {
250       allowNull: true
251     },
252     onDelete: 'cascade',
253     hooks: true
254   })
255   Account: AccountModel
256
257   @HasOne(() => VideoChannelModel, {
258     foreignKey: {
259       allowNull: true
260     },
261     onDelete: 'cascade',
262     hooks: true
263   })
264   VideoChannel: VideoChannelModel
265
266   static load (id: number) {
267     return ActorModel.unscoped().findById(id)
268   }
269
270   static loadAccountActorByVideoId (videoId: number, transaction: Sequelize.Transaction) {
271     const query = {
272       include: [
273         {
274           attributes: [ 'id' ],
275           model: AccountModel.unscoped(),
276           required: true,
277           include: [
278             {
279               attributes: [ 'id' ],
280               model: VideoChannelModel.unscoped(),
281               required: true,
282               include: {
283                 attributes: [ 'id' ],
284                 model: VideoModel.unscoped(),
285                 required: true,
286                 where: {
287                   id: videoId
288                 }
289               }
290             }
291           ]
292         }
293       ],
294       transaction
295     }
296
297     return ActorModel.unscoped().findOne(query as any) // FIXME: typings
298   }
299
300   static isActorUrlExist (url: string) {
301     const query = {
302       raw: true,
303       where: {
304         url
305       }
306     }
307
308     return ActorModel.unscoped().findOne(query)
309       .then(a => !!a)
310   }
311
312   static listByFollowersUrls (followersUrls: string[], transaction?: Sequelize.Transaction) {
313     const query = {
314       where: {
315         followersUrl: {
316           [ Sequelize.Op.in ]: followersUrls
317         }
318       },
319       transaction
320     }
321
322     return ActorModel.scope(ScopeNames.FULL).findAll(query)
323   }
324
325   static loadLocalByName (preferredUsername: string, transaction?: Sequelize.Transaction) {
326     const query = {
327       where: {
328         preferredUsername,
329         serverId: null
330       },
331       transaction
332     }
333
334     return ActorModel.scope(ScopeNames.FULL).findOne(query)
335   }
336
337   static loadByNameAndHost (preferredUsername: string, host: string) {
338     const query = {
339       where: {
340         preferredUsername
341       },
342       include: [
343         {
344           model: ServerModel,
345           required: true,
346           where: {
347             host
348           }
349         }
350       ]
351     }
352
353     return ActorModel.scope(ScopeNames.FULL).findOne(query)
354   }
355
356   static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
357     const query = {
358       where: {
359         url
360       },
361       transaction,
362       include: [
363         {
364           attributes: [ 'id' ],
365           model: AccountModel.unscoped(),
366           required: false
367         },
368         {
369           attributes: [ 'id' ],
370           model: VideoChannelModel.unscoped(),
371           required: false
372         }
373       ]
374     }
375
376     return ActorModel.unscoped().findOne(query)
377   }
378
379   static loadByUrlAndPopulateAccountAndChannel (url: string, transaction?: Sequelize.Transaction) {
380     const query = {
381       where: {
382         url
383       },
384       transaction
385     }
386
387     return ActorModel.scope(ScopeNames.FULL).findOne(query)
388   }
389
390   static incrementFollows (id: number, column: 'followersCount' | 'followingCount', by: number) {
391     // FIXME: typings
392     return (ActorModel as any).increment(column, {
393       by,
394       where: {
395         id
396       }
397     })
398   }
399
400   toFormattedJSON () {
401     let avatar: Avatar = null
402     if (this.Avatar) {
403       avatar = this.Avatar.toFormattedJSON()
404     }
405
406     return {
407       id: this.id,
408       url: this.url,
409       uuid: this.uuid,
410       name: this.preferredUsername,
411       host: this.getHost(),
412       hostRedundancyAllowed: this.getRedundancyAllowed(),
413       followingCount: this.followingCount,
414       followersCount: this.followersCount,
415       avatar,
416       createdAt: this.createdAt,
417       updatedAt: this.updatedAt
418     }
419   }
420
421   toActivityPubObject (name: string, type: 'Account' | 'Application' | 'VideoChannel') {
422     let activityPubType
423     if (type === 'Account') {
424       activityPubType = 'Person' as 'Person'
425     } else if (type === 'Application') {
426       activityPubType = 'Application' as 'Application'
427     } else { // VideoChannel
428       activityPubType = 'Group' as 'Group'
429     }
430
431     let icon = undefined
432     if (this.avatarId) {
433       const extension = extname(this.Avatar.filename)
434       icon = {
435         type: 'Image',
436         mediaType: extension === '.png' ? 'image/png' : 'image/jpeg',
437         url: this.getAvatarUrl()
438       }
439     }
440
441     const json = {
442       type: activityPubType,
443       id: this.url,
444       following: this.getFollowingUrl(),
445       followers: this.getFollowersUrl(),
446       inbox: this.inboxUrl,
447       outbox: this.outboxUrl,
448       preferredUsername: this.preferredUsername,
449       url: this.url,
450       name,
451       endpoints: {
452         sharedInbox: this.sharedInboxUrl
453       },
454       uuid: this.uuid,
455       publicKey: {
456         id: this.getPublicKeyUrl(),
457         owner: this.url,
458         publicKeyPem: this.publicKey
459       },
460       icon
461     }
462
463     return activityPubContextify(json)
464   }
465
466   getFollowerSharedInboxUrls (t: Sequelize.Transaction) {
467     const query = {
468       attributes: [ 'sharedInboxUrl' ],
469       include: [
470         {
471           attribute: [],
472           model: ActorFollowModel.unscoped(),
473           required: true,
474           as: 'ActorFollowing',
475           where: {
476             state: 'accepted',
477             targetActorId: this.id
478           }
479         }
480       ],
481       transaction: t
482     }
483
484     return ActorModel.findAll(query)
485       .then(accounts => accounts.map(a => a.sharedInboxUrl))
486   }
487
488   getFollowingUrl () {
489     return this.url + '/following'
490   }
491
492   getFollowersUrl () {
493     return this.url + '/followers'
494   }
495
496   getPublicKeyUrl () {
497     return this.url + '#main-key'
498   }
499
500   isOwned () {
501     return this.serverId === null
502   }
503
504   getWebfingerUrl () {
505     return 'acct:' + this.preferredUsername + '@' + this.getHost()
506   }
507
508   getIdentifier () {
509     return this.Server ? `${this.preferredUsername}@${this.Server.host}` : this.preferredUsername
510   }
511
512   getHost () {
513     return this.Server ? this.Server.host : CONFIG.WEBSERVER.HOST
514   }
515
516   getRedundancyAllowed () {
517     return this.Server ? this.Server.redundancyAllowed : false
518   }
519
520   getAvatarUrl () {
521     if (!this.avatarId) return undefined
522
523     return CONFIG.WEBSERVER.URL + this.Avatar.getWebserverPath()
524   }
525
526   isOutdated () {
527     if (this.isOwned()) return false
528
529     const now = Date.now()
530     const createdAtTime = this.createdAt.getTime()
531     const updatedAtTime = this.updatedAt.getTime()
532
533     return (now - createdAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL &&
534       (now - updatedAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL
535   }
536 }