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