1 import { col, fn, literal, Op, QueryTypes, Transaction, where } 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: [ fn('lower', col('preferredUsername')), 'serverId' ],
134 name: 'actor_preferred_username_lower_server_id',
143 fields: [ fn('lower', col('preferredUsername')) ],
144 name: 'actor_preferred_username_lower',
151 fields: [ 'inboxUrl', 'sharedInboxUrl' ]
154 fields: [ 'sharedInboxUrl' ]
157 fields: [ 'serverId' ]
160 fields: [ 'followersUrl' ]
164 export class ActorModel extends Model<Partial<AttributesOnly<ActorModel>>> {
167 @Column(DataType.ENUM(...Object.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))
227 remoteCreatedAt: Date
235 @HasMany(() => ActorImageModel, {
243 type: ActorImageType.AVATAR
246 Avatars: ActorImageModel[]
248 @HasMany(() => ActorImageModel, {
256 type: ActorImageType.BANNER
259 Banners: 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 // ---------------------------------------------------------------------------
313 static getSQLAttributes (tableName: string, aliasPrefix = '') {
314 return buildSQLAttributes({
321 static getSQLAPIAttributes (tableName: string, aliasPrefix = '') {
322 return buildSQLAttributes({
326 excludeAttributes: unusedActorAttributesForAPI
330 // ---------------------------------------------------------------------------
332 static wherePreferredUsername (preferredUsername: string, colName = 'preferredUsername') {
333 return where(fn('lower', col(colName)), preferredUsername.toLowerCase())
336 // ---------------------------------------------------------------------------
338 static async load (id: number): Promise<MActor> {
339 const actorServer = await getServerActor()
340 if (id === actorServer.id) return actorServer
342 return ActorModel.unscoped().findByPk(id)
345 static loadFull (id: number): Promise<MActorFull> {
346 return ActorModel.scope(ScopeNames.FULL).findByPk(id)
349 static loadAccountActorFollowerUrlByVideoId (videoId: number, transaction: Transaction) {
350 const query = `SELECT "actor"."id" AS "id", "actor"."followersUrl" AS "followersUrl" ` +
352 `INNER JOIN "account" ON "actor"."id" = "account"."actorId" ` +
353 `INNER JOIN "videoChannel" ON "videoChannel"."accountId" = "account"."id" ` +
354 `INNER JOIN "video" ON "video"."channelId" = "videoChannel"."id" AND "video"."id" = :videoId`
357 type: QueryTypes.SELECT as QueryTypes.SELECT,
358 replacements: { videoId },
363 return ActorModel.sequelize.query<MActorId & MActorFollowersUrl>(query, options)
366 static listByFollowersUrls (followersUrls: string[], transaction?: Transaction): Promise<MActorFull[]> {
370 [Op.in]: followersUrls
376 return ActorModel.scope(ScopeNames.FULL).findAll(query)
379 static loadLocalByName (preferredUsername: string, transaction?: Transaction): Promise<MActorFull> {
384 this.wherePreferredUsername(preferredUsername, '"ActorModel"."preferredUsername"'),
393 return ActorModel.scope(ScopeNames.FULL).findOne(query)
396 return ModelCache.Instance.doCache({
397 cacheType: 'local-actor-name',
398 key: preferredUsername,
399 // The server actor never change, so we can easily cache it
400 whitelist: () => preferredUsername === SERVER_ACTOR_NAME,
405 static loadLocalUrlByName (preferredUsername: string, transaction?: Transaction): Promise<MActorUrl> {
408 attributes: [ 'url' ],
411 this.wherePreferredUsername(preferredUsername),
420 return ActorModel.unscoped().findOne(query)
423 return ModelCache.Instance.doCache({
424 cacheType: 'local-actor-url',
425 key: preferredUsername,
426 // The server actor never change, so we can easily cache it
427 whitelist: () => preferredUsername === SERVER_ACTOR_NAME,
432 static loadByNameAndHost (preferredUsername: string, host: string): Promise<MActorFull> {
434 where: this.wherePreferredUsername(preferredUsername, '"ActorModel"."preferredUsername"'),
446 return ActorModel.scope(ScopeNames.FULL).findOne(query)
449 static loadByUrl (url: string, transaction?: Transaction): Promise<MActorAccountChannelId> {
457 attributes: [ 'id' ],
458 model: AccountModel.unscoped(),
462 attributes: [ 'id' ],
463 model: VideoChannelModel.unscoped(),
469 return ActorModel.unscoped().findOne(query)
472 static loadByUrlAndPopulateAccountAndChannel (url: string, transaction?: Transaction): Promise<MActorFull> {
480 return ActorModel.scope(ScopeNames.FULL).findOne(query)
483 static rebuildFollowsCount (ofId: number, type: 'followers' | 'following', transaction?: Transaction) {
484 const sanitizedOfId = forceNumber(ofId)
485 const where = { id: sanitizedOfId }
487 let columnToUpdate: string
488 let columnOfCount: string
490 if (type === 'followers') {
491 columnToUpdate = 'followersCount'
492 columnOfCount = 'targetActorId'
494 columnToUpdate = 'followingCount'
495 columnOfCount = 'actorId'
498 return ActorModel.update({
499 [columnToUpdate]: literal(`(SELECT COUNT(*) FROM "actorFollow" WHERE "${columnOfCount}" = ${sanitizedOfId} AND "state" = 'accepted')`)
500 }, { where, transaction })
503 static loadAccountActorByVideoId (videoId: number, transaction: Transaction): Promise<MActor> {
507 attributes: [ 'id' ],
508 model: AccountModel.unscoped(),
512 attributes: [ 'id', 'accountId' ],
513 model: VideoChannelModel.unscoped(),
517 attributes: [ 'id', 'channelId' ],
518 model: VideoModel.unscoped(),
531 return ActorModel.unscoped().findOne(query)
534 getSharedInbox (this: MActorWithInboxes) {
535 return this.sharedInboxUrl || this.inboxUrl
538 toFormattedSummaryJSON (this: MActorSummaryFormattable) {
541 name: this.preferredUsername,
542 host: this.getHost(),
543 avatars: (this.Avatars || []).map(a => a.toFormattedJSON()),
545 // TODO: remove, deprecated in 4.2
546 avatar: this.hasImage(ActorImageType.AVATAR)
547 ? this.Avatars[0].toFormattedJSON()
552 toFormattedJSON (this: MActorFormattable) {
554 ...this.toFormattedSummaryJSON(),
557 hostRedundancyAllowed: this.getRedundancyAllowed(),
558 followingCount: this.followingCount,
559 followersCount: this.followersCount,
560 createdAt: this.getCreatedAt(),
562 banners: (this.Banners || []).map(b => b.toFormattedJSON()),
564 // TODO: remove, deprecated in 4.2
565 banner: this.hasImage(ActorImageType.BANNER)
566 ? this.Banners[0].toFormattedJSON()
571 toActivityPubObject (this: MActorAPChannel | MActorAPAccount, name: string) {
572 let icon: ActivityIconObject
573 let icons: ActivityIconObject[]
574 let image: ActivityIconObject
576 if (this.hasImage(ActorImageType.AVATAR)) {
577 icon = getBiggestActorImage(this.Avatars).toActivityPubObject()
578 icons = this.Avatars.map(a => a.toActivityPubObject())
581 if (this.hasImage(ActorImageType.BANNER)) {
582 const banner = getBiggestActorImage((this as MActorAPChannel).Banners)
583 const extension = getLowercaseExtension(banner.filename)
587 mediaType: MIMETYPES.IMAGE.EXT_MIMETYPE[extension],
588 height: banner.height,
590 url: ActorImageModel.getImageUrl(banner)
597 following: this.getFollowingUrl(),
598 followers: this.getFollowersUrl(),
599 playlists: this.getPlaylistsUrl(),
600 inbox: this.inboxUrl,
601 outbox: this.outboxUrl,
602 preferredUsername: this.preferredUsername,
606 sharedInbox: this.sharedInboxUrl
609 id: this.getPublicKeyUrl(),
611 publicKeyPem: this.publicKey
613 published: this.getCreatedAt().toISOString(),
621 return activityPubContextify(json, 'Actor')
624 getFollowerSharedInboxUrls (t: Transaction) {
626 attributes: [ 'sharedInboxUrl' ],
630 model: ActorFollowModel.unscoped(),
632 as: 'ActorFollowing',
635 targetActorId: this.id
642 return ActorModel.findAll(query)
643 .then(accounts => accounts.map(a => a.sharedInboxUrl))
647 return this.url + '/following'
651 return this.url + '/followers'
655 return this.url + '/playlists'
659 return this.url + '#main-key'
663 return this.serverId === null
666 getWebfingerUrl (this: MActorServer) {
667 return 'acct:' + this.preferredUsername + '@' + this.getHost()
671 return this.Server ? `${this.preferredUsername}@${this.Server.host}` : this.preferredUsername
674 getHost (this: MActorHost) {
675 return this.Server ? this.Server.host : WEBSERVER.HOST
678 getRedundancyAllowed () {
679 return this.Server ? this.Server.redundancyAllowed : false
682 hasImage (type: ActorImageType) {
683 const images = type === ActorImageType.AVATAR
687 return Array.isArray(images) && images.length !== 0
691 if (this.isOwned()) return false
693 return isOutdated(this, ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL)
696 getCreatedAt (this: MActorAPChannel | MActorAPAccount | MActorFormattable) {
697 return this.remoteCreatedAt || this.createdAt