Fetch remote AP objects
[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, BelongsTo, Column, CreatedAt, DataType, Default, DefaultScope, ForeignKey, HasMany, HasOne, Is, IsUUID, Model, Scopes,
6   Table, UpdatedAt
7 } from 'sequelize-typescript'
8 import { ActivityPubActorType } from '../../../shared/models/activitypub'
9 import { Avatar } from '../../../shared/models/avatars/avatar.model'
10 import { activityPubContextify } from '../../helpers/activitypub'
11 import {
12   isActorFollowersCountValid, isActorFollowingCountValid, isActorPreferredUsernameValid, isActorPrivateKeyValid,
13   isActorPublicKeyValid
14 } from '../../helpers/custom-validators/activitypub/actor'
15 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
16 import { ACTIVITY_PUB, ACTIVITY_PUB_ACTOR_TYPES, CONFIG, CONSTRAINTS_FIELDS } from '../../initializers'
17 import { AccountModel } from '../account/account'
18 import { AvatarModel } from '../avatar/avatar'
19 import { ServerModel } from '../server/server'
20 import { throwIfNotValid } from '../utils'
21 import { VideoChannelModel } from '../video/video-channel'
22 import { ActorFollowModel } from './actor-follow'
23
24 enum ScopeNames {
25   FULL = 'FULL'
26 }
27
28 @DefaultScope({
29   include: [
30     {
31       model: () => ServerModel,
32       required: false
33     },
34     {
35       model: () => AvatarModel,
36       required: false
37     }
38   ]
39 })
40 @Scopes({
41   [ScopeNames.FULL]: {
42     include: [
43       {
44         model: () => AccountModel,
45         required: false
46       },
47       {
48         model: () => VideoChannelModel,
49         required: false
50       },
51       {
52         model: () => ServerModel,
53         required: false
54       },
55       {
56         model: () => AvatarModel,
57         required: false
58       }
59     ]
60   }
61 })
62 @Table({
63   tableName: 'actor',
64   indexes: [
65     {
66       fields: [ 'url' ]
67     },
68     {
69       fields: [ 'preferredUsername', 'serverId' ],
70       unique: true
71     }
72   ]
73 })
74 export class ActorModel extends Model<ActorModel> {
75
76   @AllowNull(false)
77   @Column(DataType.ENUM(values(ACTIVITY_PUB_ACTOR_TYPES)))
78   type: ActivityPubActorType
79
80   @AllowNull(false)
81   @Default(DataType.UUIDV4)
82   @IsUUID(4)
83   @Column(DataType.UUID)
84   uuid: string
85
86   @AllowNull(false)
87   @Is('ActorPreferredUsername', value => throwIfNotValid(value, isActorPreferredUsernameValid, 'actor preferred username'))
88   @Column
89   preferredUsername: string
90
91   @AllowNull(false)
92   @Is('ActorUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
93   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
94   url: string
95
96   @AllowNull(true)
97   @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPublicKeyValid, 'public key'))
98   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PUBLIC_KEY.max))
99   publicKey: string
100
101   @AllowNull(true)
102   @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPrivateKeyValid, 'private key'))
103   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PRIVATE_KEY.max))
104   privateKey: string
105
106   @AllowNull(false)
107   @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowersCountValid, 'followers count'))
108   @Column
109   followersCount: number
110
111   @AllowNull(false)
112   @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowingCountValid, 'following count'))
113   @Column
114   followingCount: number
115
116   @AllowNull(false)
117   @Is('ActorInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'inbox url'))
118   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
119   inboxUrl: string
120
121   @AllowNull(false)
122   @Is('ActorOutboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'outbox url'))
123   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
124   outboxUrl: string
125
126   @AllowNull(false)
127   @Is('ActorSharedInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'shared inbox url'))
128   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
129   sharedInboxUrl: string
130
131   @AllowNull(false)
132   @Is('ActorFollowersUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'followers url'))
133   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
134   followersUrl: string
135
136   @AllowNull(false)
137   @Is('ActorFollowingUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'following url'))
138   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
139   followingUrl: string
140
141   @CreatedAt
142   createdAt: Date
143
144   @UpdatedAt
145   updatedAt: Date
146
147   @ForeignKey(() => AvatarModel)
148   @Column
149   avatarId: number
150
151   @BelongsTo(() => AvatarModel, {
152     foreignKey: {
153       allowNull: true
154     },
155     onDelete: 'set null'
156   })
157   Avatar: AvatarModel
158
159   @HasMany(() => ActorFollowModel, {
160     foreignKey: {
161       name: 'actorId',
162       allowNull: false
163     },
164     onDelete: 'cascade'
165   })
166   AccountFollowing: ActorFollowModel[]
167
168   @HasMany(() => ActorFollowModel, {
169     foreignKey: {
170       name: 'targetActorId',
171       allowNull: false
172     },
173     as: 'followers',
174     onDelete: 'cascade'
175   })
176   AccountFollowers: ActorFollowModel[]
177
178   @ForeignKey(() => ServerModel)
179   @Column
180   serverId: number
181
182   @BelongsTo(() => ServerModel, {
183     foreignKey: {
184       allowNull: true
185     },
186     onDelete: 'cascade'
187   })
188   Server: ServerModel
189
190   @HasOne(() => AccountModel, {
191     foreignKey: {
192       allowNull: true
193     },
194     onDelete: 'cascade'
195   })
196   Account: AccountModel
197
198   @HasOne(() => VideoChannelModel, {
199     foreignKey: {
200       allowNull: true
201     },
202     onDelete: 'cascade'
203   })
204   VideoChannel: VideoChannelModel
205
206   static load (id: number) {
207     return ActorModel.scope(ScopeNames.FULL).findById(id)
208   }
209
210   static listByFollowersUrls (followersUrls: string[], transaction?: Sequelize.Transaction) {
211     const query = {
212       where: {
213         followersUrl: {
214           [ Sequelize.Op.in ]: followersUrls
215         }
216       },
217       transaction
218     }
219
220     return ActorModel.scope(ScopeNames.FULL).findAll(query)
221   }
222
223   static loadLocalByName (preferredUsername: string) {
224     const query = {
225       where: {
226         preferredUsername,
227         serverId: null
228       }
229     }
230
231     return ActorModel.scope(ScopeNames.FULL).findOne(query)
232   }
233
234   static loadByNameAndHost (preferredUsername: string, host: string) {
235     const query = {
236       where: {
237         preferredUsername
238       },
239       include: [
240         {
241           model: ServerModel,
242           required: true,
243           where: {
244             host
245           }
246         }
247       ]
248     }
249
250     return ActorModel.scope(ScopeNames.FULL).findOne(query)
251   }
252
253   static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
254     const query = {
255       where: {
256         url
257       },
258       transaction
259     }
260
261     return ActorModel.scope(ScopeNames.FULL).findOne(query)
262   }
263
264   toFormattedJSON () {
265     let avatar: Avatar = null
266     if (this.Avatar) {
267       avatar = this.Avatar.toFormattedJSON()
268     }
269
270     let score: number
271     if (this.Server) {
272       score = this.Server.score
273     }
274
275     return {
276       id: this.id,
277       url: this.url,
278       uuid: this.uuid,
279       host: this.getHost(),
280       score,
281       followingCount: this.followingCount,
282       followersCount: this.followersCount,
283       avatar
284     }
285   }
286
287   toActivityPubObject (name: string, type: 'Account' | 'Application' | 'VideoChannel') {
288     let activityPubType
289     if (type === 'Account') {
290       activityPubType = 'Person' as 'Person'
291     } else if (type === 'Application') {
292       activityPubType = 'Application' as 'Application'
293     } else { // VideoChannel
294       activityPubType = 'Group' as 'Group'
295     }
296
297     let icon = undefined
298     if (this.avatarId) {
299       const extension = extname(this.Avatar.filename)
300       icon = {
301         type: 'Image',
302         mediaType: extension === '.png' ? 'image/png' : 'image/jpeg',
303         url: this.getAvatarUrl()
304       }
305     }
306
307     const json = {
308       type: activityPubType,
309       id: this.url,
310       following: this.getFollowingUrl(),
311       followers: this.getFollowersUrl(),
312       inbox: this.inboxUrl,
313       outbox: this.outboxUrl,
314       preferredUsername: this.preferredUsername,
315       url: this.url,
316       name,
317       endpoints: {
318         sharedInbox: this.sharedInboxUrl
319       },
320       uuid: this.uuid,
321       publicKey: {
322         id: this.getPublicKeyUrl(),
323         owner: this.url,
324         publicKeyPem: this.publicKey
325       },
326       icon
327     }
328
329     return activityPubContextify(json)
330   }
331
332   getFollowerSharedInboxUrls (t: Sequelize.Transaction) {
333     const query = {
334       attributes: [ 'sharedInboxUrl' ],
335       include: [
336         {
337           model: ActorFollowModel,
338           required: true,
339           as: 'followers',
340           where: {
341             targetActorId: this.id
342           }
343         }
344       ],
345       transaction: t
346     }
347
348     return ActorModel.findAll(query)
349       .then(accounts => accounts.map(a => a.sharedInboxUrl))
350   }
351
352   getFollowingUrl () {
353     return this.url + '/following'
354   }
355
356   getFollowersUrl () {
357     return this.url + '/followers'
358   }
359
360   getPublicKeyUrl () {
361     return this.url + '#main-key'
362   }
363
364   isOwned () {
365     return this.serverId === null
366   }
367
368   getWebfingerUrl () {
369     return 'acct:' + this.preferredUsername + '@' + this.getHost()
370   }
371
372   getHost () {
373     return this.Server ? this.Server.host : CONFIG.WEBSERVER.HOST
374   }
375
376   getAvatarUrl () {
377     if (!this.avatarId) return undefined
378
379     return CONFIG.WEBSERVER.URL + this.Avatar.getWebserverPath()
380   }
381
382   isOutdated () {
383     if (this.isOwned()) return false
384
385     const now = Date.now()
386     const createdAtTime = this.createdAt.getTime()
387     const updatedAtTime = this.updatedAt.getTime()
388
389     return (now - createdAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL &&
390       (now - updatedAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL
391   }
392 }