1 import { literal, Op, QueryTypes, Transaction } from 'sequelize'
17 } from 'sequelize-typescript'
18 import { activityPubContextify } from '@server/lib/activitypub/context'
19 import { getBiggestActorImage } from '@server/lib/actor-image'
20 import { ModelCache } from '@server/models/shared/model-cache'
21 import { forceNumber, getLowercaseExtension } from '@shared/core-utils'
22 import { ActivityIconObject, ActivityPubActorType, ActorImageType } from '@shared/models'
23 import { AttributesOnly } from '@shared/typescript-utils'
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,
51 MActorSummaryFormattable,
54 } from '../../types/models'
55 import { AccountModel } from '../account/account'
56 import { getServerActor } from '../application/application'
57 import { ServerModel } from '../server/server'
58 import { buildSQLAttributes, isOutdated, throwIfNotValid } from '../shared'
59 import { VideoModel } from '../video/video'
60 import { VideoChannelModel } from '../video/video-channel'
61 import { ActorFollowModel } from './actor-follow'
62 import { ActorImageModel } from './actor-image'
68 export const unusedActorAttributesForAPI: (keyof AttributesOnly<ActorModel>)[] = [
78 @DefaultScope(() => ({
85 model: ActorImageModel,
95 model: AccountModel.unscoped(),
99 model: VideoChannelModel.unscoped(),
113 model: ActorImageModel,
118 model: ActorImageModel,
133 fields: [ 'preferredUsername', 'serverId' ],
142 fields: [ 'preferredUsername' ],
149 fields: [ 'inboxUrl', 'sharedInboxUrl' ]
152 fields: [ 'sharedInboxUrl' ]
155 fields: [ 'serverId' ]
158 fields: [ 'followersUrl' ]
162 export class ActorModel extends Model<Partial<AttributesOnly<ActorModel>>> {
165 @Column(DataType.ENUM(...Object.values(ACTIVITY_PUB_ACTOR_TYPES)))
166 type: ActivityPubActorType
169 @Is('ActorPreferredUsername', value => throwIfNotValid(value, isActorPreferredUsernameValid, 'actor preferred username'))
171 preferredUsername: string
174 @Is('ActorUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
175 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
179 @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPublicKeyValid, 'public key', true))
180 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PUBLIC_KEY.max))
184 @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPrivateKeyValid, 'private key', true))
185 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PRIVATE_KEY.max))
189 @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowersCountValid, 'followers count'))
191 followersCount: number
194 @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowingCountValid, 'following count'))
196 followingCount: number
199 @Is('ActorInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'inbox url'))
200 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
204 @Is('ActorOutboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'outbox url', true))
205 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
209 @Is('ActorSharedInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'shared inbox url', true))
210 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
211 sharedInboxUrl: string
214 @Is('ActorFollowersUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'followers url', true))
215 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
219 @Is('ActorFollowingUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'following url', true))
220 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
225 remoteCreatedAt: Date
233 @HasMany(() => ActorImageModel, {
241 type: ActorImageType.AVATAR
244 Avatars: ActorImageModel[]
246 @HasMany(() => ActorImageModel, {
254 type: ActorImageType.BANNER
257 Banners: ActorImageModel[]
259 @HasMany(() => ActorFollowModel, {
264 as: 'ActorFollowings',
267 ActorFollowing: ActorFollowModel[]
269 @HasMany(() => ActorFollowModel, {
271 name: 'targetActorId',
274 as: 'ActorFollowers',
277 ActorFollowers: ActorFollowModel[]
279 @ForeignKey(() => ServerModel)
283 @BelongsTo(() => ServerModel, {
291 @HasOne(() => AccountModel, {
298 Account: AccountModel
300 @HasOne(() => VideoChannelModel, {
307 VideoChannel: VideoChannelModel
309 // ---------------------------------------------------------------------------
311 static getSQLAttributes (tableName: string, aliasPrefix = '') {
312 return buildSQLAttributes({
319 static getSQLAPIAttributes (tableName: string, aliasPrefix = '') {
320 return buildSQLAttributes({
324 excludeAttributes: unusedActorAttributesForAPI
328 // ---------------------------------------------------------------------------
330 static async load (id: number): Promise<MActor> {
331 const actorServer = await getServerActor()
332 if (id === actorServer.id) return actorServer
334 return ActorModel.unscoped().findByPk(id)
337 static loadFull (id: number): Promise<MActorFull> {
338 return ActorModel.scope(ScopeNames.FULL).findByPk(id)
341 static loadAccountActorFollowerUrlByVideoId (videoId: number, transaction: Transaction) {
342 const query = `SELECT "actor"."id" AS "id", "actor"."followersUrl" AS "followersUrl" ` +
344 `INNER JOIN "account" ON "actor"."id" = "account"."actorId" ` +
345 `INNER JOIN "videoChannel" ON "videoChannel"."accountId" = "account"."id" ` +
346 `INNER JOIN "video" ON "video"."channelId" = "videoChannel"."id" AND "video"."id" = :videoId`
349 type: QueryTypes.SELECT as QueryTypes.SELECT,
350 replacements: { videoId },
355 return ActorModel.sequelize.query<MActorId & MActorFollowersUrl>(query, options)
358 static listByFollowersUrls (followersUrls: string[], transaction?: Transaction): Promise<MActorFull[]> {
362 [Op.in]: followersUrls
368 return ActorModel.scope(ScopeNames.FULL).findAll(query)
371 static loadLocalByName (preferredUsername: string, transaction?: Transaction): Promise<MActorFull> {
381 return ActorModel.scope(ScopeNames.FULL).findOne(query)
384 return ModelCache.Instance.doCache({
385 cacheType: 'local-actor-name',
386 key: preferredUsername,
387 // The server actor never change, so we can easily cache it
388 whitelist: () => preferredUsername === SERVER_ACTOR_NAME,
393 static loadLocalUrlByName (preferredUsername: string, transaction?: Transaction): Promise<MActorUrl> {
396 attributes: [ 'url' ],
404 return ActorModel.unscoped().findOne(query)
407 return ModelCache.Instance.doCache({
408 cacheType: 'local-actor-name',
409 key: preferredUsername,
410 // The server actor never change, so we can easily cache it
411 whitelist: () => preferredUsername === SERVER_ACTOR_NAME,
416 static loadByNameAndHost (preferredUsername: string, host: string): Promise<MActorFull> {
432 return ActorModel.scope(ScopeNames.FULL).findOne(query)
435 static loadByUrl (url: string, transaction?: Transaction): Promise<MActorAccountChannelId> {
443 attributes: [ 'id' ],
444 model: AccountModel.unscoped(),
448 attributes: [ 'id' ],
449 model: VideoChannelModel.unscoped(),
455 return ActorModel.unscoped().findOne(query)
458 static loadByUrlAndPopulateAccountAndChannel (url: string, transaction?: Transaction): Promise<MActorFull> {
466 return ActorModel.scope(ScopeNames.FULL).findOne(query)
469 static rebuildFollowsCount (ofId: number, type: 'followers' | 'following', transaction?: Transaction) {
470 const sanitizedOfId = forceNumber(ofId)
471 const where = { id: sanitizedOfId }
473 let columnToUpdate: string
474 let columnOfCount: string
476 if (type === 'followers') {
477 columnToUpdate = 'followersCount'
478 columnOfCount = 'targetActorId'
480 columnToUpdate = 'followingCount'
481 columnOfCount = 'actorId'
484 return ActorModel.update({
485 [columnToUpdate]: literal(`(SELECT COUNT(*) FROM "actorFollow" WHERE "${columnOfCount}" = ${sanitizedOfId} AND "state" = 'accepted')`)
486 }, { where, transaction })
489 static loadAccountActorByVideoId (videoId: number, transaction: Transaction): Promise<MActor> {
493 attributes: [ 'id' ],
494 model: AccountModel.unscoped(),
498 attributes: [ 'id', 'accountId' ],
499 model: VideoChannelModel.unscoped(),
503 attributes: [ 'id', 'channelId' ],
504 model: VideoModel.unscoped(),
517 return ActorModel.unscoped().findOne(query)
520 getSharedInbox (this: MActorWithInboxes) {
521 return this.sharedInboxUrl || this.inboxUrl
524 toFormattedSummaryJSON (this: MActorSummaryFormattable) {
527 name: this.preferredUsername,
528 host: this.getHost(),
529 avatars: (this.Avatars || []).map(a => a.toFormattedJSON()),
531 // TODO: remove, deprecated in 4.2
532 avatar: this.hasImage(ActorImageType.AVATAR)
533 ? this.Avatars[0].toFormattedJSON()
538 toFormattedJSON (this: MActorFormattable) {
540 ...this.toFormattedSummaryJSON(),
543 hostRedundancyAllowed: this.getRedundancyAllowed(),
544 followingCount: this.followingCount,
545 followersCount: this.followersCount,
546 createdAt: this.getCreatedAt(),
548 banners: (this.Banners || []).map(b => b.toFormattedJSON()),
550 // TODO: remove, deprecated in 4.2
551 banner: this.hasImage(ActorImageType.BANNER)
552 ? this.Banners[0].toFormattedJSON()
557 toActivityPubObject (this: MActorAPChannel | MActorAPAccount, name: string) {
558 let icon: ActivityIconObject
559 let icons: ActivityIconObject[]
560 let image: ActivityIconObject
562 if (this.hasImage(ActorImageType.AVATAR)) {
563 icon = getBiggestActorImage(this.Avatars).toActivityPubObject()
564 icons = this.Avatars.map(a => a.toActivityPubObject())
567 if (this.hasImage(ActorImageType.BANNER)) {
568 const banner = getBiggestActorImage((this as MActorAPChannel).Banners)
569 const extension = getLowercaseExtension(banner.filename)
573 mediaType: MIMETYPES.IMAGE.EXT_MIMETYPE[extension],
574 height: banner.height,
576 url: ActorImageModel.getImageUrl(banner)
583 following: this.getFollowingUrl(),
584 followers: this.getFollowersUrl(),
585 playlists: this.getPlaylistsUrl(),
586 inbox: this.inboxUrl,
587 outbox: this.outboxUrl,
588 preferredUsername: this.preferredUsername,
592 sharedInbox: this.sharedInboxUrl
595 id: this.getPublicKeyUrl(),
597 publicKeyPem: this.publicKey
599 published: this.getCreatedAt().toISOString(),
607 return activityPubContextify(json, 'Actor')
610 getFollowerSharedInboxUrls (t: Transaction) {
612 attributes: [ 'sharedInboxUrl' ],
616 model: ActorFollowModel.unscoped(),
618 as: 'ActorFollowing',
621 targetActorId: this.id
628 return ActorModel.findAll(query)
629 .then(accounts => accounts.map(a => a.sharedInboxUrl))
633 return this.url + '/following'
637 return this.url + '/followers'
641 return this.url + '/playlists'
645 return this.url + '#main-key'
649 return this.serverId === null
652 getWebfingerUrl (this: MActorServer) {
653 return 'acct:' + this.preferredUsername + '@' + this.getHost()
657 return this.Server ? `${this.preferredUsername}@${this.Server.host}` : this.preferredUsername
660 getHost (this: MActorHost) {
661 return this.Server ? this.Server.host : WEBSERVER.HOST
664 getRedundancyAllowed () {
665 return this.Server ? this.Server.redundancyAllowed : false
668 hasImage (type: ActorImageType) {
669 const images = type === ActorImageType.AVATAR
673 return Array.isArray(images) && images.length !== 0
677 if (this.isOwned()) return false
679 return isOutdated(this, ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL)
682 getCreatedAt (this: MActorAPChannel | MActorAPAccount | MActorFormattable) {
683 return this.remoteCreatedAt || this.createdAt