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