]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/actor/actor.ts
Merge branch 'release/3.2.0' into develop
[github/Chocobozzz/PeerTube.git] / server / models / actor / actor.ts
CommitLineData
50d6de9c 1import { values } from 'lodash'
47564bbe 2import { extname } from 'path'
b49f22d8 3import { literal, Op, Transaction } from 'sequelize'
fadf619a 4import {
2422c46b
C
5 AllowNull,
6 BelongsTo,
7 Column,
8 CreatedAt,
9 DataType,
2422c46b
C
10 DefaultScope,
11 ForeignKey,
12 HasMany,
13 HasOne,
14 Is,
2422c46b
C
15 Model,
16 Scopes,
17 Table,
18 UpdatedAt
fadf619a 19} from 'sequelize-typescript'
b49f22d8 20import { ModelCache } from '@server/models/model-cache'
16c016e8 21import { AttributesOnly } from '@shared/core-utils'
a1587156 22import { ActivityIconObject, ActivityPubActorType } from '../../../shared/models/activitypub'
f4796856 23import { ActorImage } from '../../../shared/models/actors/actor-image.model'
da854ddd 24import { activityPubContextify } from '../../helpers/activitypub'
fadf619a 25import {
2422c46b
C
26 isActorFollowersCountValid,
27 isActorFollowingCountValid,
28 isActorPreferredUsernameValid,
29 isActorPrivateKeyValid,
da854ddd
C
30 isActorPublicKeyValid
31} from '../../helpers/custom-validators/activitypub/actor'
32import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
2cb03dc1
C
33import {
34 ACTIVITY_PUB,
35 ACTIVITY_PUB_ACTOR_TYPES,
36 CONSTRAINTS_FIELDS,
37 MIMETYPES,
38 SERVER_ACTOR_NAME,
39 WEBSERVER
40} from '../../initializers/constants'
1ca9f7c3
C
41import {
42 MActor,
43 MActorAccountChannelId,
2cb03dc1
C
44 MActorAPAccount,
45 MActorAPChannel,
1ca9f7c3 46 MActorFormattable,
b5fecbf4
C
47 MActorFull,
48 MActorHost,
1ca9f7c3 49 MActorServer,
b49f22d8
C
50 MActorSummaryFormattable,
51 MActorUrl,
47581df0 52 MActorWithInboxes
26d6bf65 53} from '../../types/models'
b49f22d8 54import { AccountModel } from '../account/account'
b49f22d8
C
55import { ServerModel } from '../server/server'
56import { isOutdated, throwIfNotValid } from '../utils'
57import { VideoModel } from '../video/video'
58import { VideoChannelModel } from '../video/video-channel'
59import { ActorFollowModel } from './actor-follow'
7d9ba5c0 60import { ActorImageModel } from './actor-image'
fadf619a 61
50d6de9c
C
62enum ScopeNames {
63 FULL = 'FULL'
64}
65
f37dc0dd
C
66export const unusedActorAttributesForAPI = [
67 'publicKey',
68 'privateKey',
69 'inboxUrl',
70 'outboxUrl',
71 'sharedInboxUrl',
72 'followersUrl',
a66c2e32 73 'followingUrl'
f37dc0dd
C
74]
75
3acc5084 76@DefaultScope(() => ({
ce33ee01
C
77 include: [
78 {
3acc5084 79 model: ServerModel,
ce33ee01 80 required: false
c5911fd3
C
81 },
82 {
f4796856
C
83 model: ActorImageModel,
84 as: 'Avatar',
c5911fd3 85 required: false
ce33ee01
C
86 }
87 ]
3acc5084
C
88}))
89@Scopes(() => ({
50d6de9c
C
90 [ScopeNames.FULL]: {
91 include: [
92 {
3acc5084 93 model: AccountModel.unscoped(),
50d6de9c
C
94 required: false
95 },
96 {
3acc5084 97 model: VideoChannelModel.unscoped(),
c48e82b5
C
98 required: false,
99 include: [
100 {
3acc5084 101 model: AccountModel,
c48e82b5
C
102 required: true
103 }
104 ]
ce33ee01
C
105 },
106 {
3acc5084 107 model: ServerModel,
ce33ee01 108 required: false
c5911fd3
C
109 },
110 {
f4796856
C
111 model: ActorImageModel,
112 as: 'Avatar',
c5911fd3 113 required: false
2cb03dc1
C
114 },
115 {
116 model: ActorImageModel,
117 as: 'Banner',
118 required: false
50d6de9c 119 }
3acc5084 120 ]
50d6de9c 121 }
3acc5084 122}))
fadf619a 123@Table({
50d6de9c
C
124 tableName: 'actor',
125 indexes: [
2ccaeeb3 126 {
8cd72bd3
C
127 fields: [ 'url' ],
128 unique: true
2ccaeeb3 129 },
50d6de9c 130 {
e12a0092 131 fields: [ 'preferredUsername', 'serverId' ],
77e08517
C
132 unique: true,
133 where: {
134 serverId: {
135 [Op.ne]: null
136 }
137 }
138 },
0f06c4de
C
139 {
140 fields: [ 'preferredUsername' ],
141 unique: true,
142 where: {
143 serverId: null
144 }
145 },
6502c3d4
C
146 {
147 fields: [ 'inboxUrl', 'sharedInboxUrl' ]
57c36b27 148 },
a3d1026b
C
149 {
150 fields: [ 'sharedInboxUrl' ]
151 },
57c36b27
C
152 {
153 fields: [ 'serverId' ]
154 },
155 {
156 fields: [ 'avatarId' ]
8cd72bd3 157 },
8cd72bd3
C
158 {
159 fields: [ 'followersUrl' ]
50d6de9c
C
160 }
161 ]
fadf619a 162})
16c016e8 163export class ActorModel extends Model<Partial<AttributesOnly<ActorModel>>> {
fadf619a 164
50d6de9c 165 @AllowNull(false)
3acc5084 166 @Column(DataType.ENUM(...values(ACTIVITY_PUB_ACTOR_TYPES)))
50d6de9c
C
167 type: ActivityPubActorType
168
fadf619a 169 @AllowNull(false)
e12a0092 170 @Is('ActorPreferredUsername', value => throwIfNotValid(value, isActorPreferredUsernameValid, 'actor preferred username'))
fadf619a 171 @Column
e12a0092 172 preferredUsername: string
fadf619a
C
173
174 @AllowNull(false)
175 @Is('ActorUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
01de67b9 176 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
fadf619a
C
177 url: string
178
179 @AllowNull(true)
1735c825 180 @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPublicKeyValid, 'public key', true))
01de67b9 181 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PUBLIC_KEY.max))
fadf619a
C
182 publicKey: string
183
184 @AllowNull(true)
1735c825 185 @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPrivateKeyValid, 'private key', true))
01de67b9 186 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PRIVATE_KEY.max))
fadf619a
C
187 privateKey: string
188
189 @AllowNull(false)
190 @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowersCountValid, 'followers count'))
191 @Column
192 followersCount: number
193
194 @AllowNull(false)
195 @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowingCountValid, 'following count'))
196 @Column
197 followingCount: number
198
199 @AllowNull(false)
200 @Is('ActorInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'inbox url'))
01de67b9 201 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
fadf619a
C
202 inboxUrl: string
203
0b5c385b
C
204 @AllowNull(true)
205 @Is('ActorOutboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'outbox url', true))
01de67b9 206 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
fadf619a
C
207 outboxUrl: string
208
47581df0
C
209 @AllowNull(true)
210 @Is('ActorSharedInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'shared inbox url', true))
01de67b9 211 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
fadf619a
C
212 sharedInboxUrl: string
213
0b5c385b
C
214 @AllowNull(true)
215 @Is('ActorFollowersUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'followers url', true))
01de67b9 216 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
fadf619a
C
217 followersUrl: string
218
0b5c385b
C
219 @AllowNull(true)
220 @Is('ActorFollowingUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'following url', true))
01de67b9 221 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
fadf619a
C
222 followingUrl: string
223
a66c2e32
C
224 @AllowNull(true)
225 @Column
226 remoteCreatedAt: Date
227
fadf619a
C
228 @CreatedAt
229 createdAt: Date
230
231 @UpdatedAt
232 updatedAt: Date
233
f4796856 234 @ForeignKey(() => ActorImageModel)
fadf619a
C
235 @Column
236 avatarId: number
237
f4796856
C
238 @ForeignKey(() => ActorImageModel)
239 @Column
240 bannerId: number
241
242 @BelongsTo(() => ActorImageModel, {
243 foreignKey: {
244 name: 'avatarId',
245 allowNull: true
246 },
247 as: 'Avatar',
248 onDelete: 'set null',
249 hooks: true
250 })
251 Avatar: ActorImageModel
252
253 @BelongsTo(() => ActorImageModel, {
fadf619a 254 foreignKey: {
f4796856 255 name: 'bannerId',
fadf619a
C
256 allowNull: true
257 },
f4796856 258 as: 'Banner',
f05a1c30
C
259 onDelete: 'set null',
260 hooks: true
fadf619a 261 })
f4796856 262 Banner: ActorImageModel
fadf619a 263
50d6de9c 264 @HasMany(() => ActorFollowModel, {
fadf619a 265 foreignKey: {
50d6de9c 266 name: 'actorId',
fadf619a
C
267 allowNull: false
268 },
cef534ed 269 as: 'ActorFollowings',
fadf619a
C
270 onDelete: 'cascade'
271 })
54e74059 272 ActorFollowing: ActorFollowModel[]
fadf619a 273
50d6de9c 274 @HasMany(() => ActorFollowModel, {
fadf619a 275 foreignKey: {
50d6de9c 276 name: 'targetActorId',
fadf619a
C
277 allowNull: false
278 },
54e74059 279 as: 'ActorFollowers',
fadf619a
C
280 onDelete: 'cascade'
281 })
54e74059 282 ActorFollowers: ActorFollowModel[]
fadf619a
C
283
284 @ForeignKey(() => ServerModel)
285 @Column
286 serverId: number
287
288 @BelongsTo(() => ServerModel, {
289 foreignKey: {
290 allowNull: true
291 },
292 onDelete: 'cascade'
293 })
294 Server: ServerModel
295
50d6de9c
C
296 @HasOne(() => AccountModel, {
297 foreignKey: {
c5a893d5
C
298 allowNull: true
299 },
300 onDelete: 'cascade',
301 hooks: true
50d6de9c
C
302 })
303 Account: AccountModel
304
305 @HasOne(() => VideoChannelModel, {
306 foreignKey: {
c5a893d5
C
307 allowNull: true
308 },
309 onDelete: 'cascade',
310 hooks: true
50d6de9c
C
311 })
312 VideoChannel: VideoChannelModel
313
b49f22d8 314 static load (id: number): Promise<MActor> {
9b39106d 315 return ActorModel.unscoped().findByPk(id)
50d6de9c
C
316 }
317
b49f22d8 318 static loadFull (id: number): Promise<MActorFull> {
453e83ea
C
319 return ActorModel.scope(ScopeNames.FULL).findByPk(id)
320 }
321
b49f22d8 322 static loadFromAccountByVideoId (videoId: number, transaction: Transaction): Promise<MActor> {
e5565833
C
323 const query = {
324 include: [
325 {
326 attributes: [ 'id' ],
327 model: AccountModel.unscoped(),
328 required: true,
329 include: [
330 {
331 attributes: [ 'id' ],
332 model: VideoChannelModel.unscoped(),
333 required: true,
3acc5084
C
334 include: [
335 {
336 attributes: [ 'id' ],
337 model: VideoModel.unscoped(),
338 required: true,
339 where: {
340 id: videoId
341 }
e5565833 342 }
3acc5084 343 ]
e5565833
C
344 }
345 ]
346 }
347 ],
348 transaction
349 }
350
3acc5084 351 return ActorModel.unscoped().findOne(query)
e5565833
C
352 }
353
d4defe07
C
354 static isActorUrlExist (url: string) {
355 const query = {
356 raw: true,
357 where: {
358 url
359 }
360 }
361
362 return ActorModel.unscoped().findOne(query)
363 .then(a => !!a)
364 }
365
b49f22d8 366 static listByFollowersUrls (followersUrls: string[], transaction?: Transaction): Promise<MActorFull[]> {
fadf619a
C
367 const query = {
368 where: {
369 followersUrl: {
a1587156 370 [Op.in]: followersUrls
fadf619a
C
371 }
372 },
373 transaction
374 }
375
50d6de9c
C
376 return ActorModel.scope(ScopeNames.FULL).findAll(query)
377 }
378
b49f22d8 379 static loadLocalByName (preferredUsername: string, transaction?: Transaction): Promise<MActorFull> {
0ffd6d32
C
380 const fun = () => {
381 const query = {
382 where: {
383 preferredUsername,
384 serverId: null
385 },
386 transaction
387 }
e4a686b4 388
0ffd6d32
C
389 return ActorModel.scope(ScopeNames.FULL)
390 .findOne(query)
50d6de9c
C
391 }
392
0ffd6d32
C
393 return ModelCache.Instance.doCache({
394 cacheType: 'local-actor-name',
395 key: preferredUsername,
396 // The server actor never change, so we can easily cache it
397 whitelist: () => preferredUsername === SERVER_ACTOR_NAME,
398 fun
399 })
0374b6b5
C
400 }
401
b49f22d8 402 static loadLocalUrlByName (preferredUsername: string, transaction?: Transaction): Promise<MActorUrl> {
0ffd6d32
C
403 const fun = () => {
404 const query = {
405 attributes: [ 'url' ],
406 where: {
407 preferredUsername,
408 serverId: null
409 },
410 transaction
411 }
0374b6b5 412
0ffd6d32
C
413 return ActorModel.unscoped()
414 .findOne(query)
0374b6b5
C
415 }
416
0ffd6d32
C
417 return ModelCache.Instance.doCache({
418 cacheType: 'local-actor-name',
419 key: preferredUsername,
420 // The server actor never change, so we can easily cache it
421 whitelist: () => preferredUsername === SERVER_ACTOR_NAME,
422 fun
423 })
50d6de9c
C
424 }
425
b49f22d8 426 static loadByNameAndHost (preferredUsername: string, host: string): Promise<MActorFull> {
50d6de9c
C
427 const query = {
428 where: {
e12a0092 429 preferredUsername
50d6de9c
C
430 },
431 include: [
432 {
433 model: ServerModel,
434 required: true,
435 where: {
436 host
437 }
438 }
439 ]
440 }
441
442 return ActorModel.scope(ScopeNames.FULL).findOne(query)
443 }
444
b49f22d8 445 static loadByUrl (url: string, transaction?: Transaction): Promise<MActorAccountChannelId> {
e587e0ec
C
446 const query = {
447 where: {
448 url
449 },
450 transaction,
451 include: [
452 {
453 attributes: [ 'id' ],
454 model: AccountModel.unscoped(),
455 required: false
456 },
457 {
458 attributes: [ 'id' ],
459 model: VideoChannelModel.unscoped(),
460 required: false
461 }
462 ]
463 }
464
465 return ActorModel.unscoped().findOne(query)
466 }
467
b49f22d8 468 static loadByUrlAndPopulateAccountAndChannel (url: string, transaction?: Transaction): Promise<MActorFull> {
50d6de9c
C
469 const query = {
470 where: {
471 url
472 },
473 transaction
474 }
475
476 return ActorModel.scope(ScopeNames.FULL).findOne(query)
fadf619a
C
477 }
478
e6122097
C
479 static rebuildFollowsCount (ofId: number, type: 'followers' | 'following', transaction?: Transaction) {
480 const sanitizedOfId = parseInt(ofId + '', 10)
481 const where = { id: sanitizedOfId }
482
483 let columnToUpdate: string
484 let columnOfCount: string
485
486 if (type === 'followers') {
487 columnToUpdate = 'followersCount'
488 columnOfCount = 'targetActorId'
489 } else {
490 columnToUpdate = 'followingCount'
491 columnOfCount = 'actorId'
492 }
493
494 return ActorModel.update({
495 [columnToUpdate]: literal(`(SELECT COUNT(*) FROM "actorFollow" WHERE "${columnOfCount}" = ${sanitizedOfId})`)
496 }, { where, transaction })
32b2b43c
C
497 }
498
b49f22d8 499 static loadAccountActorByVideoId (videoId: number): Promise<MActor> {
2c8776fc
C
500 const query = {
501 include: [
502 {
503 attributes: [ 'id' ],
504 model: AccountModel.unscoped(),
505 required: true,
506 include: [
507 {
508 attributes: [ 'id', 'accountId' ],
509 model: VideoChannelModel.unscoped(),
510 required: true,
511 include: [
512 {
513 attributes: [ 'id', 'channelId' ],
514 model: VideoModel.unscoped(),
515 where: {
516 id: videoId
517 }
518 }
519 ]
520 }
521 ]
522 }
523 ]
524 }
525
526 return ActorModel.unscoped().findOne(query)
527 }
528
47581df0
C
529 getSharedInbox (this: MActorWithInboxes) {
530 return this.sharedInboxUrl || this.inboxUrl
531 }
532
1ca9f7c3 533 toFormattedSummaryJSON (this: MActorSummaryFormattable) {
f4796856 534 let avatar: ActorImage = null
fadf619a 535 if (this.Avatar) {
c5911fd3 536 avatar = this.Avatar.toFormattedJSON()
fadf619a
C
537 }
538
fadf619a 539 return {
4cb6d457 540 url: this.url,
60650c77 541 name: this.preferredUsername,
e12a0092 542 host: this.getHost(),
1ca9f7c3
C
543 avatar
544 }
545 }
546
547 toFormattedJSON (this: MActorFormattable) {
548 const base = this.toFormattedSummaryJSON()
549
2cb03dc1 550 let banner: ActorImage = null
91723454 551 if (this.Banner) {
2cb03dc1
C
552 banner = this.Banner.toFormattedJSON()
553 }
554
1ca9f7c3
C
555 return Object.assign(base, {
556 id: this.id,
c48e82b5 557 hostRedundancyAllowed: this.getRedundancyAllowed(),
fadf619a
C
558 followingCount: this.followingCount,
559 followersCount: this.followersCount,
2cb03dc1 560 banner,
e024fd6a 561 createdAt: this.getCreatedAt()
1ca9f7c3 562 })
fadf619a
C
563 }
564
2cb03dc1 565 toActivityPubObject (this: MActorAPChannel | MActorAPAccount, name: string) {
a1587156 566 let icon: ActivityIconObject
2cb03dc1 567 let image: ActivityIconObject
a1587156 568
c5911fd3
C
569 if (this.avatarId) {
570 const extension = extname(this.Avatar.filename)
a1587156 571
c5911fd3
C
572 icon = {
573 type: 'Image',
2cb03dc1 574 mediaType: MIMETYPES.IMAGE.EXT_MIMETYPE[extension],
84531547
C
575 height: this.Avatar.height,
576 width: this.Avatar.width,
c5911fd3
C
577 url: this.getAvatarUrl()
578 }
579 }
580
2cb03dc1 581 if (this.bannerId) {
84531547
C
582 const banner = (this as MActorAPChannel).Banner
583 const extension = extname(banner.filename)
2cb03dc1
C
584
585 image = {
586 type: 'Image',
587 mediaType: MIMETYPES.IMAGE.EXT_MIMETYPE[extension],
84531547
C
588 height: banner.height,
589 width: banner.width,
2cb03dc1
C
590 url: this.getBannerUrl()
591 }
592 }
593
fadf619a 594 const json = {
8424c402 595 type: this.type,
fadf619a
C
596 id: this.url,
597 following: this.getFollowingUrl(),
598 followers: this.getFollowersUrl(),
418d092a 599 playlists: this.getPlaylistsUrl(),
fadf619a
C
600 inbox: this.inboxUrl,
601 outbox: this.outboxUrl,
e12a0092 602 preferredUsername: this.preferredUsername,
fadf619a 603 url: this.url,
e12a0092 604 name,
fadf619a
C
605 endpoints: {
606 sharedInbox: this.sharedInboxUrl
607 },
fadf619a
C
608 publicKey: {
609 id: this.getPublicKeyUrl(),
610 owner: this.url,
611 publicKeyPem: this.publicKey
c5911fd3 612 },
a66c2e32 613 published: this.getCreatedAt().toISOString(),
2cb03dc1
C
614 icon,
615 image
fadf619a
C
616 }
617
618 return activityPubContextify(json)
619 }
620
941c5eac 621 getFollowerSharedInboxUrls (t: Transaction) {
fadf619a
C
622 const query = {
623 attributes: [ 'sharedInboxUrl' ],
624 include: [
625 {
54e74059
C
626 attribute: [],
627 model: ActorFollowModel.unscoped(),
fadf619a 628 required: true,
d6e99e53 629 as: 'ActorFollowing',
fadf619a 630 where: {
54e74059 631 state: 'accepted',
50d6de9c 632 targetActorId: this.id
fadf619a
C
633 }
634 }
635 ],
636 transaction: t
637 }
638
639 return ActorModel.findAll(query)
640 .then(accounts => accounts.map(a => a.sharedInboxUrl))
641 }
642
643 getFollowingUrl () {
644 return this.url + '/following'
645 }
646
647 getFollowersUrl () {
648 return this.url + '/followers'
649 }
650
418d092a
C
651 getPlaylistsUrl () {
652 return this.url + '/playlists'
653 }
654
fadf619a
C
655 getPublicKeyUrl () {
656 return this.url + '#main-key'
657 }
658
659 isOwned () {
660 return this.serverId === null
661 }
e12a0092 662
1ca9f7c3 663 getWebfingerUrl (this: MActorServer) {
e12a0092
C
664 return 'acct:' + this.preferredUsername + '@' + this.getHost()
665 }
666
80e36cd9
AB
667 getIdentifier () {
668 return this.Server ? `${this.preferredUsername}@${this.Server.host}` : this.preferredUsername
669 }
670
1ca9f7c3 671 getHost (this: MActorHost) {
6dd9de95 672 return this.Server ? this.Server.host : WEBSERVER.HOST
e12a0092 673 }
c5911fd3 674
b5fecbf4 675 getRedundancyAllowed () {
c48e82b5
C
676 return this.Server ? this.Server.redundancyAllowed : false
677 }
678
c5911fd3
C
679 getAvatarUrl () {
680 if (!this.avatarId) return undefined
681
557b13ae 682 return WEBSERVER.URL + this.Avatar.getStaticPath()
c5911fd3 683 }
a5625b41 684
2cb03dc1
C
685 getBannerUrl () {
686 if (!this.bannerId) return undefined
687
688 return WEBSERVER.URL + this.Banner.getStaticPath()
689 }
690
a5625b41
C
691 isOutdated () {
692 if (this.isOwned()) return false
693
9f79ade6 694 return isOutdated(this, ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL)
a5625b41 695 }
a66c2e32
C
696
697 getCreatedAt (this: MActorAPChannel | MActorAPAccount | MActorFormattable) {
698 return this.remoteCreatedAt || this.createdAt
699 }
fadf619a 700}