]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/actor/actor.ts
Update changelog
[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'
b49f22d8 19import { ModelCache } from '@server/models/model-cache'
6b5f72be
C
20import { getLowercaseExtension } from '@shared/core-utils'
21import { AttributesOnly } from '@shared/typescript-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
06c27593 499 static loadAccountActorByVideoId (videoId: number, transaction: Transaction): 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 }
06c27593
C
523 ],
524 transaction
2c8776fc
C
525 }
526
527 return ActorModel.unscoped().findOne(query)
528 }
529
47581df0
C
530 getSharedInbox (this: MActorWithInboxes) {
531 return this.sharedInboxUrl || this.inboxUrl
532 }
533
1ca9f7c3 534 toFormattedSummaryJSON (this: MActorSummaryFormattable) {
f4796856 535 let avatar: ActorImage = null
fadf619a 536 if (this.Avatar) {
c5911fd3 537 avatar = this.Avatar.toFormattedJSON()
fadf619a
C
538 }
539
fadf619a 540 return {
4cb6d457 541 url: this.url,
60650c77 542 name: this.preferredUsername,
e12a0092 543 host: this.getHost(),
1ca9f7c3
C
544 avatar
545 }
546 }
547
548 toFormattedJSON (this: MActorFormattable) {
549 const base = this.toFormattedSummaryJSON()
550
2cb03dc1 551 let banner: ActorImage = null
91723454 552 if (this.Banner) {
2cb03dc1
C
553 banner = this.Banner.toFormattedJSON()
554 }
555
1ca9f7c3
C
556 return Object.assign(base, {
557 id: this.id,
c48e82b5 558 hostRedundancyAllowed: this.getRedundancyAllowed(),
fadf619a
C
559 followingCount: this.followingCount,
560 followersCount: this.followersCount,
2cb03dc1 561 banner,
e024fd6a 562 createdAt: this.getCreatedAt()
1ca9f7c3 563 })
fadf619a
C
564 }
565
2cb03dc1 566 toActivityPubObject (this: MActorAPChannel | MActorAPAccount, name: string) {
a1587156 567 let icon: ActivityIconObject
2cb03dc1 568 let image: ActivityIconObject
a1587156 569
c5911fd3 570 if (this.avatarId) {
ea54cd04 571 const extension = getLowercaseExtension(this.Avatar.filename)
a1587156 572
c5911fd3
C
573 icon = {
574 type: 'Image',
2cb03dc1 575 mediaType: MIMETYPES.IMAGE.EXT_MIMETYPE[extension],
84531547
C
576 height: this.Avatar.height,
577 width: this.Avatar.width,
c5911fd3
C
578 url: this.getAvatarUrl()
579 }
580 }
581
2cb03dc1 582 if (this.bannerId) {
84531547 583 const banner = (this as MActorAPChannel).Banner
ea54cd04 584 const extension = getLowercaseExtension(banner.filename)
2cb03dc1
C
585
586 image = {
587 type: 'Image',
588 mediaType: MIMETYPES.IMAGE.EXT_MIMETYPE[extension],
84531547
C
589 height: banner.height,
590 width: banner.width,
2cb03dc1
C
591 url: this.getBannerUrl()
592 }
593 }
594
fadf619a 595 const json = {
8424c402 596 type: this.type,
fadf619a
C
597 id: this.url,
598 following: this.getFollowingUrl(),
599 followers: this.getFollowersUrl(),
418d092a 600 playlists: this.getPlaylistsUrl(),
fadf619a
C
601 inbox: this.inboxUrl,
602 outbox: this.outboxUrl,
e12a0092 603 preferredUsername: this.preferredUsername,
fadf619a 604 url: this.url,
e12a0092 605 name,
fadf619a
C
606 endpoints: {
607 sharedInbox: this.sharedInboxUrl
608 },
fadf619a
C
609 publicKey: {
610 id: this.getPublicKeyUrl(),
611 owner: this.url,
612 publicKeyPem: this.publicKey
c5911fd3 613 },
a66c2e32 614 published: this.getCreatedAt().toISOString(),
2cb03dc1
C
615 icon,
616 image
fadf619a
C
617 }
618
619 return activityPubContextify(json)
620 }
621
941c5eac 622 getFollowerSharedInboxUrls (t: Transaction) {
fadf619a
C
623 const query = {
624 attributes: [ 'sharedInboxUrl' ],
625 include: [
626 {
54e74059
C
627 attribute: [],
628 model: ActorFollowModel.unscoped(),
fadf619a 629 required: true,
d6e99e53 630 as: 'ActorFollowing',
fadf619a 631 where: {
54e74059 632 state: 'accepted',
50d6de9c 633 targetActorId: this.id
fadf619a
C
634 }
635 }
636 ],
637 transaction: t
638 }
639
640 return ActorModel.findAll(query)
641 .then(accounts => accounts.map(a => a.sharedInboxUrl))
642 }
643
644 getFollowingUrl () {
645 return this.url + '/following'
646 }
647
648 getFollowersUrl () {
649 return this.url + '/followers'
650 }
651
418d092a
C
652 getPlaylistsUrl () {
653 return this.url + '/playlists'
654 }
655
fadf619a
C
656 getPublicKeyUrl () {
657 return this.url + '#main-key'
658 }
659
660 isOwned () {
661 return this.serverId === null
662 }
e12a0092 663
1ca9f7c3 664 getWebfingerUrl (this: MActorServer) {
e12a0092
C
665 return 'acct:' + this.preferredUsername + '@' + this.getHost()
666 }
667
80e36cd9
AB
668 getIdentifier () {
669 return this.Server ? `${this.preferredUsername}@${this.Server.host}` : this.preferredUsername
670 }
671
1ca9f7c3 672 getHost (this: MActorHost) {
6dd9de95 673 return this.Server ? this.Server.host : WEBSERVER.HOST
e12a0092 674 }
c5911fd3 675
b5fecbf4 676 getRedundancyAllowed () {
c48e82b5
C
677 return this.Server ? this.Server.redundancyAllowed : false
678 }
679
c5911fd3
C
680 getAvatarUrl () {
681 if (!this.avatarId) return undefined
682
557b13ae 683 return WEBSERVER.URL + this.Avatar.getStaticPath()
c5911fd3 684 }
a5625b41 685
2cb03dc1
C
686 getBannerUrl () {
687 if (!this.bannerId) return undefined
688
689 return WEBSERVER.URL + this.Banner.getStaticPath()
690 }
691
a5625b41
C
692 isOutdated () {
693 if (this.isOwned()) return false
694
9f79ade6 695 return isOutdated(this, ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL)
a5625b41 696 }
a66c2e32
C
697
698 getCreatedAt (this: MActorAPChannel | MActorAPAccount | MActorFormattable) {
699 return this.remoteCreatedAt || this.createdAt
700 }
fadf619a 701}