]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/activitypub/actor.ts
Allow to auto follow a specific URL
[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
2c8776fc
C
465 static loadAccountActorByVideoId (videoId: number): Bluebird<MActor> {
466 const query = {
467 include: [
468 {
469 attributes: [ 'id' ],
470 model: AccountModel.unscoped(),
471 required: true,
472 include: [
473 {
474 attributes: [ 'id', 'accountId' ],
475 model: VideoChannelModel.unscoped(),
476 required: true,
477 include: [
478 {
479 attributes: [ 'id', 'channelId' ],
480 model: VideoModel.unscoped(),
481 where: {
482 id: videoId
483 }
484 }
485 ]
486 }
487 ]
488 }
489 ]
490 }
491
492 return ActorModel.unscoped().findOne(query)
493 }
494
47581df0
C
495 getSharedInbox (this: MActorWithInboxes) {
496 return this.sharedInboxUrl || this.inboxUrl
497 }
498
1ca9f7c3 499 toFormattedSummaryJSON (this: MActorSummaryFormattable) {
fadf619a
C
500 let avatar: Avatar = null
501 if (this.Avatar) {
c5911fd3 502 avatar = this.Avatar.toFormattedJSON()
fadf619a
C
503 }
504
fadf619a 505 return {
4cb6d457 506 url: this.url,
60650c77 507 name: this.preferredUsername,
e12a0092 508 host: this.getHost(),
1ca9f7c3
C
509 avatar
510 }
511 }
512
513 toFormattedJSON (this: MActorFormattable) {
514 const base = this.toFormattedSummaryJSON()
515
516 return Object.assign(base, {
517 id: this.id,
c48e82b5 518 hostRedundancyAllowed: this.getRedundancyAllowed(),
fadf619a
C
519 followingCount: this.followingCount,
520 followersCount: this.followersCount,
60650c77
C
521 createdAt: this.createdAt,
522 updatedAt: this.updatedAt
1ca9f7c3 523 })
fadf619a
C
524 }
525
8424c402 526 toActivityPubObject (this: MActorAP, name: string) {
a1587156
C
527 let icon: ActivityIconObject
528
c5911fd3
C
529 if (this.avatarId) {
530 const extension = extname(this.Avatar.filename)
a1587156 531
c5911fd3
C
532 icon = {
533 type: 'Image',
534 mediaType: extension === '.png' ? 'image/png' : 'image/jpeg',
535 url: this.getAvatarUrl()
536 }
537 }
538
fadf619a 539 const json = {
8424c402 540 type: this.type,
fadf619a
C
541 id: this.url,
542 following: this.getFollowingUrl(),
543 followers: this.getFollowersUrl(),
418d092a 544 playlists: this.getPlaylistsUrl(),
fadf619a
C
545 inbox: this.inboxUrl,
546 outbox: this.outboxUrl,
e12a0092 547 preferredUsername: this.preferredUsername,
fadf619a 548 url: this.url,
e12a0092 549 name,
fadf619a
C
550 endpoints: {
551 sharedInbox: this.sharedInboxUrl
552 },
fadf619a
C
553 publicKey: {
554 id: this.getPublicKeyUrl(),
555 owner: this.url,
556 publicKeyPem: this.publicKey
c5911fd3
C
557 },
558 icon
fadf619a
C
559 }
560
561 return activityPubContextify(json)
562 }
563
941c5eac 564 getFollowerSharedInboxUrls (t: Transaction) {
fadf619a
C
565 const query = {
566 attributes: [ 'sharedInboxUrl' ],
567 include: [
568 {
54e74059
C
569 attribute: [],
570 model: ActorFollowModel.unscoped(),
fadf619a 571 required: true,
d6e99e53 572 as: 'ActorFollowing',
fadf619a 573 where: {
54e74059 574 state: 'accepted',
50d6de9c 575 targetActorId: this.id
fadf619a
C
576 }
577 }
578 ],
579 transaction: t
580 }
581
582 return ActorModel.findAll(query)
583 .then(accounts => accounts.map(a => a.sharedInboxUrl))
584 }
585
586 getFollowingUrl () {
587 return this.url + '/following'
588 }
589
590 getFollowersUrl () {
591 return this.url + '/followers'
592 }
593
418d092a
C
594 getPlaylistsUrl () {
595 return this.url + '/playlists'
596 }
597
fadf619a
C
598 getPublicKeyUrl () {
599 return this.url + '#main-key'
600 }
601
602 isOwned () {
603 return this.serverId === null
604 }
e12a0092 605
1ca9f7c3 606 getWebfingerUrl (this: MActorServer) {
e12a0092
C
607 return 'acct:' + this.preferredUsername + '@' + this.getHost()
608 }
609
80e36cd9
AB
610 getIdentifier () {
611 return this.Server ? `${this.preferredUsername}@${this.Server.host}` : this.preferredUsername
612 }
613
1ca9f7c3 614 getHost (this: MActorHost) {
6dd9de95 615 return this.Server ? this.Server.host : WEBSERVER.HOST
e12a0092 616 }
c5911fd3 617
b5fecbf4 618 getRedundancyAllowed () {
c48e82b5
C
619 return this.Server ? this.Server.redundancyAllowed : false
620 }
621
c5911fd3
C
622 getAvatarUrl () {
623 if (!this.avatarId) return undefined
624
557b13ae 625 return WEBSERVER.URL + this.Avatar.getStaticPath()
c5911fd3 626 }
a5625b41
C
627
628 isOutdated () {
629 if (this.isOwned()) return false
630
9f79ade6 631 return isOutdated(this, ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL)
a5625b41 632 }
fadf619a 633}