1 import { values } from 'lodash'
2 import { extname } from 'path'
3 import { literal, Op, Transaction } from 'sequelize'
19 } from 'sequelize-typescript'
20 import { ModelCache } from '@server/models/model-cache'
21 import { ActivityIconObject, ActivityPubActorType } from '../../../shared/models/activitypub'
22 import { ActorImage } from '../../../shared/models/actors/actor-image.model'
23 import { activityPubContextify } from '../../helpers/activitypub'
25 isActorFollowersCountValid,
26 isActorFollowingCountValid,
27 isActorPreferredUsernameValid,
28 isActorPrivateKeyValid,
30 } from '../../helpers/custom-validators/activitypub/actor'
31 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
34 ACTIVITY_PUB_ACTOR_TYPES,
39 } from '../../initializers/constants'
42 MActorAccountChannelId,
49 MActorSummaryFormattable,
52 } from '../../types/models'
53 import { AccountModel } from '../account/account'
54 import { ActorImageModel } from '../account/actor-image'
55 import { ServerModel } from '../server/server'
56 import { isOutdated, throwIfNotValid } from '../utils'
57 import { VideoModel } from '../video/video'
58 import { VideoChannelModel } from '../video/video-channel'
59 import { ActorFollowModel } from './actor-follow'
65 export const unusedActorAttributesForAPI = [
77 @DefaultScope(() => ({
84 model: ActorImageModel,
94 model: AccountModel.unscoped(),
98 model: VideoChannelModel.unscoped(),
112 model: ActorImageModel,
117 model: ActorImageModel,
132 fields: [ 'preferredUsername', 'serverId' ],
141 fields: [ 'preferredUsername' ],
148 fields: [ 'inboxUrl', 'sharedInboxUrl' ]
151 fields: [ 'sharedInboxUrl' ]
154 fields: [ 'serverId' ]
157 fields: [ 'avatarId' ]
160 fields: [ 'followersUrl' ]
164 export class ActorModel extends Model {
167 @Column(DataType.ENUM(...values(ACTIVITY_PUB_ACTOR_TYPES)))
168 type: ActivityPubActorType
171 @Is('ActorPreferredUsername', value => throwIfNotValid(value, isActorPreferredUsernameValid, 'actor preferred username'))
173 preferredUsername: string
176 @Is('ActorUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
177 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
181 @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPublicKeyValid, 'public key', true))
182 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PUBLIC_KEY.max))
186 @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPrivateKeyValid, 'private key', true))
187 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PRIVATE_KEY.max))
191 @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowersCountValid, 'followers count'))
193 followersCount: number
196 @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowingCountValid, 'following count'))
198 followingCount: number
201 @Is('ActorInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'inbox url'))
202 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
206 @Is('ActorOutboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'outbox url', true))
207 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
211 @Is('ActorSharedInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'shared inbox url', true))
212 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
213 sharedInboxUrl: string
216 @Is('ActorFollowersUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'followers url', true))
217 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
221 @Is('ActorFollowingUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'following url', true))
222 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
231 @ForeignKey(() => ActorImageModel)
235 @ForeignKey(() => ActorImageModel)
239 @BelongsTo(() => ActorImageModel, {
245 onDelete: 'set null',
248 Avatar: ActorImageModel
250 @BelongsTo(() => ActorImageModel, {
256 onDelete: 'set null',
259 Banner: ActorImageModel
261 @HasMany(() => ActorFollowModel, {
266 as: 'ActorFollowings',
269 ActorFollowing: ActorFollowModel[]
271 @HasMany(() => ActorFollowModel, {
273 name: 'targetActorId',
276 as: 'ActorFollowers',
279 ActorFollowers: ActorFollowModel[]
281 @ForeignKey(() => ServerModel)
285 @BelongsTo(() => ServerModel, {
293 @HasOne(() => AccountModel, {
300 Account: AccountModel
302 @HasOne(() => VideoChannelModel, {
309 VideoChannel: VideoChannelModel
311 static load (id: number): Promise<MActor> {
312 return ActorModel.unscoped().findByPk(id)
315 static loadFull (id: number): Promise<MActorFull> {
316 return ActorModel.scope(ScopeNames.FULL).findByPk(id)
319 static loadFromAccountByVideoId (videoId: number, transaction: Transaction): Promise<MActor> {
323 attributes: [ 'id' ],
324 model: AccountModel.unscoped(),
328 attributes: [ 'id' ],
329 model: VideoChannelModel.unscoped(),
333 attributes: [ 'id' ],
334 model: VideoModel.unscoped(),
348 return ActorModel.unscoped().findOne(query)
351 static isActorUrlExist (url: string) {
359 return ActorModel.unscoped().findOne(query)
363 static listByFollowersUrls (followersUrls: string[], transaction?: Transaction): Promise<MActorFull[]> {
367 [Op.in]: followersUrls
373 return ActorModel.scope(ScopeNames.FULL).findAll(query)
376 static loadLocalByName (preferredUsername: string, transaction?: Transaction): Promise<MActorFull> {
386 return ActorModel.scope(ScopeNames.FULL)
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,
399 static loadLocalUrlByName (preferredUsername: string, transaction?: Transaction): Promise<MActorUrl> {
402 attributes: [ 'url' ],
410 return ActorModel.unscoped()
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,
423 static loadByNameAndHost (preferredUsername: string, host: string): Promise<MActorFull> {
439 return ActorModel.scope(ScopeNames.FULL).findOne(query)
442 static loadByUrl (url: string, transaction?: Transaction): Promise<MActorAccountChannelId> {
450 attributes: [ 'id' ],
451 model: AccountModel.unscoped(),
455 attributes: [ 'id' ],
456 model: VideoChannelModel.unscoped(),
462 return ActorModel.unscoped().findOne(query)
465 static loadByUrlAndPopulateAccountAndChannel (url: string, transaction?: Transaction): Promise<MActorFull> {
473 return ActorModel.scope(ScopeNames.FULL).findOne(query)
476 static rebuildFollowsCount (ofId: number, type: 'followers' | 'following', transaction?: Transaction) {
477 const sanitizedOfId = parseInt(ofId + '', 10)
478 const where = { id: sanitizedOfId }
480 let columnToUpdate: string
481 let columnOfCount: string
483 if (type === 'followers') {
484 columnToUpdate = 'followersCount'
485 columnOfCount = 'targetActorId'
487 columnToUpdate = 'followingCount'
488 columnOfCount = 'actorId'
491 return ActorModel.update({
492 [columnToUpdate]: literal(`(SELECT COUNT(*) FROM "actorFollow" WHERE "${columnOfCount}" = ${sanitizedOfId})`)
493 }, { where, transaction })
496 static loadAccountActorByVideoId (videoId: number): Promise<MActor> {
500 attributes: [ 'id' ],
501 model: AccountModel.unscoped(),
505 attributes: [ 'id', 'accountId' ],
506 model: VideoChannelModel.unscoped(),
510 attributes: [ 'id', 'channelId' ],
511 model: VideoModel.unscoped(),
523 return ActorModel.unscoped().findOne(query)
526 getSharedInbox (this: MActorWithInboxes) {
527 return this.sharedInboxUrl || this.inboxUrl
530 toFormattedSummaryJSON (this: MActorSummaryFormattable) {
531 let avatar: ActorImage = null
533 avatar = this.Avatar.toFormattedJSON()
538 name: this.preferredUsername,
539 host: this.getHost(),
544 toFormattedJSON (this: MActorFormattable) {
545 const base = this.toFormattedSummaryJSON()
547 let banner: ActorImage = null
549 banner = this.Banner.toFormattedJSON()
552 return Object.assign(base, {
554 hostRedundancyAllowed: this.getRedundancyAllowed(),
555 followingCount: this.followingCount,
556 followersCount: this.followersCount,
558 createdAt: this.createdAt,
559 updatedAt: this.updatedAt
563 toActivityPubObject (this: MActorAPChannel | MActorAPAccount, name: string) {
564 let icon: ActivityIconObject
565 let image: ActivityIconObject
568 const extension = extname(this.Avatar.filename)
572 mediaType: MIMETYPES.IMAGE.EXT_MIMETYPE[extension],
573 url: this.getAvatarUrl()
578 const extension = extname((this as MActorAPChannel).Banner.filename)
582 mediaType: MIMETYPES.IMAGE.EXT_MIMETYPE[extension],
583 url: this.getBannerUrl()
590 following: this.getFollowingUrl(),
591 followers: this.getFollowersUrl(),
592 playlists: this.getPlaylistsUrl(),
593 inbox: this.inboxUrl,
594 outbox: this.outboxUrl,
595 preferredUsername: this.preferredUsername,
599 sharedInbox: this.sharedInboxUrl
602 id: this.getPublicKeyUrl(),
604 publicKeyPem: this.publicKey
610 return activityPubContextify(json)
613 getFollowerSharedInboxUrls (t: Transaction) {
615 attributes: [ 'sharedInboxUrl' ],
619 model: ActorFollowModel.unscoped(),
621 as: 'ActorFollowing',
624 targetActorId: this.id
631 return ActorModel.findAll(query)
632 .then(accounts => accounts.map(a => a.sharedInboxUrl))
636 return this.url + '/following'
640 return this.url + '/followers'
644 return this.url + '/playlists'
648 return this.url + '#main-key'
652 return this.serverId === null
655 getWebfingerUrl (this: MActorServer) {
656 return 'acct:' + this.preferredUsername + '@' + this.getHost()
660 return this.Server ? `${this.preferredUsername}@${this.Server.host}` : this.preferredUsername
663 getHost (this: MActorHost) {
664 return this.Server ? this.Server.host : WEBSERVER.HOST
667 getRedundancyAllowed () {
668 return this.Server ? this.Server.redundancyAllowed : false
672 if (!this.avatarId) return undefined
674 return WEBSERVER.URL + this.Avatar.getStaticPath()
678 if (!this.bannerId) return undefined
680 return WEBSERVER.URL + this.Banner.getStaticPath()
684 if (this.isOwned()) return false
686 return isOutdated(this, ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL)