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