]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/activitypub/actor.ts
Merge branch 'develop' into pr/1217
[github/Chocobozzz/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 as: 'ActorFollowings',
223 onDelete: 'cascade'
224 })
225 ActorFollowing: ActorFollowModel[]
226
227 @HasMany(() => ActorFollowModel, {
228 foreignKey: {
229 name: 'targetActorId',
230 allowNull: false
231 },
232 as: 'ActorFollowers',
233 onDelete: 'cascade'
234 })
235 ActorFollowers: ActorFollowModel[]
236
237 @ForeignKey(() => ServerModel)
238 @Column
239 serverId: number
240
241 @BelongsTo(() => ServerModel, {
242 foreignKey: {
243 allowNull: true
244 },
245 onDelete: 'cascade'
246 })
247 Server: ServerModel
248
249 @HasOne(() => AccountModel, {
250 foreignKey: {
251 allowNull: true
252 },
253 onDelete: 'cascade',
254 hooks: true
255 })
256 Account: AccountModel
257
258 @HasOne(() => VideoChannelModel, {
259 foreignKey: {
260 allowNull: true
261 },
262 onDelete: 'cascade',
263 hooks: true
264 })
265 VideoChannel: VideoChannelModel
266
267 static load (id: number) {
268 return ActorModel.unscoped().findById(id)
269 }
270
271 static loadAccountActorByVideoId (videoId: number, transaction: Sequelize.Transaction) {
272 const query = {
273 include: [
274 {
275 attributes: [ 'id' ],
276 model: AccountModel.unscoped(),
277 required: true,
278 include: [
279 {
280 attributes: [ 'id' ],
281 model: VideoChannelModel.unscoped(),
282 required: true,
283 include: {
284 attributes: [ 'id' ],
285 model: VideoModel.unscoped(),
286 required: true,
287 where: {
288 id: videoId
289 }
290 }
291 }
292 ]
293 }
294 ],
295 transaction
296 }
297
298 return ActorModel.unscoped().findOne(query as any) // FIXME: typings
299 }
300
301 static isActorUrlExist (url: string) {
302 const query = {
303 raw: true,
304 where: {
305 url
306 }
307 }
308
309 return ActorModel.unscoped().findOne(query)
310 .then(a => !!a)
311 }
312
313 static listByFollowersUrls (followersUrls: string[], transaction?: Sequelize.Transaction) {
314 const query = {
315 where: {
316 followersUrl: {
317 [ Sequelize.Op.in ]: followersUrls
318 }
319 },
320 transaction
321 }
322
323 return ActorModel.scope(ScopeNames.FULL).findAll(query)
324 }
325
326 static loadLocalByName (preferredUsername: string, transaction?: Sequelize.Transaction) {
327 const query = {
328 where: {
329 preferredUsername,
330 serverId: null
331 },
332 transaction
333 }
334
335 return ActorModel.scope(ScopeNames.FULL).findOne(query)
336 }
337
338 static loadByNameAndHost (preferredUsername: string, host: string) {
339 const query = {
340 where: {
341 preferredUsername
342 },
343 include: [
344 {
345 model: ServerModel,
346 required: true,
347 where: {
348 host
349 }
350 }
351 ]
352 }
353
354 return ActorModel.scope(ScopeNames.FULL).findOne(query)
355 }
356
357 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
358 const query = {
359 where: {
360 url
361 },
362 transaction,
363 include: [
364 {
365 attributes: [ 'id' ],
366 model: AccountModel.unscoped(),
367 required: false
368 },
369 {
370 attributes: [ 'id' ],
371 model: VideoChannelModel.unscoped(),
372 required: false
373 }
374 ]
375 }
376
377 return ActorModel.unscoped().findOne(query)
378 }
379
380 static loadByUrlAndPopulateAccountAndChannel (url: string, transaction?: Sequelize.Transaction) {
381 const query = {
382 where: {
383 url
384 },
385 transaction
386 }
387
388 return ActorModel.scope(ScopeNames.FULL).findOne(query)
389 }
390
391 static incrementFollows (id: number, column: 'followersCount' | 'followingCount', by: number) {
392 // FIXME: typings
393 return (ActorModel as any).increment(column, {
394 by,
395 where: {
396 id
397 }
398 })
399 }
400
401 toFormattedJSON () {
402 let avatar: Avatar = null
403 if (this.Avatar) {
404 avatar = this.Avatar.toFormattedJSON()
405 }
406
407 return {
408 id: this.id,
409 url: this.url,
410 uuid: this.uuid,
411 name: this.preferredUsername,
412 host: this.getHost(),
413 hostRedundancyAllowed: this.getRedundancyAllowed(),
414 followingCount: this.followingCount,
415 followersCount: this.followersCount,
416 avatar,
417 createdAt: this.createdAt,
418 updatedAt: this.updatedAt
419 }
420 }
421
422 toActivityPubObject (name: string, type: 'Account' | 'Application' | 'VideoChannel') {
423 let activityPubType
424 if (type === 'Account') {
425 activityPubType = 'Person' as 'Person'
426 } else if (type === 'Application') {
427 activityPubType = 'Application' as 'Application'
428 } else { // VideoChannel
429 activityPubType = 'Group' as 'Group'
430 }
431
432 let icon = undefined
433 if (this.avatarId) {
434 const extension = extname(this.Avatar.filename)
435 icon = {
436 type: 'Image',
437 mediaType: extension === '.png' ? 'image/png' : 'image/jpeg',
438 url: this.getAvatarUrl()
439 }
440 }
441
442 const json = {
443 type: activityPubType,
444 id: this.url,
445 following: this.getFollowingUrl(),
446 followers: this.getFollowersUrl(),
447 inbox: this.inboxUrl,
448 outbox: this.outboxUrl,
449 preferredUsername: this.preferredUsername,
450 url: this.url,
451 name,
452 endpoints: {
453 sharedInbox: this.sharedInboxUrl
454 },
455 uuid: this.uuid,
456 publicKey: {
457 id: this.getPublicKeyUrl(),
458 owner: this.url,
459 publicKeyPem: this.publicKey
460 },
461 icon
462 }
463
464 return activityPubContextify(json)
465 }
466
467 getFollowerSharedInboxUrls (t: Sequelize.Transaction) {
468 const query = {
469 attributes: [ 'sharedInboxUrl' ],
470 include: [
471 {
472 attribute: [],
473 model: ActorFollowModel.unscoped(),
474 required: true,
475 as: 'ActorFollowing',
476 where: {
477 state: 'accepted',
478 targetActorId: this.id
479 }
480 }
481 ],
482 transaction: t
483 }
484
485 return ActorModel.findAll(query)
486 .then(accounts => accounts.map(a => a.sharedInboxUrl))
487 }
488
489 getFollowingUrl () {
490 return this.url + '/following'
491 }
492
493 getFollowersUrl () {
494 return this.url + '/followers'
495 }
496
497 getPublicKeyUrl () {
498 return this.url + '#main-key'
499 }
500
501 isOwned () {
502 return this.serverId === null
503 }
504
505 getWebfingerUrl () {
506 return 'acct:' + this.preferredUsername + '@' + this.getHost()
507 }
508
509 getIdentifier () {
510 return this.Server ? `${this.preferredUsername}@${this.Server.host}` : this.preferredUsername
511 }
512
513 getHost () {
514 return this.Server ? this.Server.host : CONFIG.WEBSERVER.HOST
515 }
516
517 getRedundancyAllowed () {
518 return this.Server ? this.Server.redundancyAllowed : false
519 }
520
521 getAvatarUrl () {
522 if (!this.avatarId) return undefined
523
524 return CONFIG.WEBSERVER.URL + this.Avatar.getWebserverPath()
525 }
526
527 isOutdated () {
528 if (this.isOwned()) return false
529
530 const now = Date.now()
531 const createdAtTime = this.createdAt.getTime()
532 const updatedAtTime = this.updatedAt.getTime()
533
534 return (now - createdAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL &&
535 (now - updatedAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL
536 }
537 }