1 import { values } from 'lodash'
2 import { extname } from 'path'
18 } from 'sequelize-typescript'
19 import { ActivityPubActorType } from '../../../shared/models/activitypub'
20 import { Avatar } from '../../../shared/models/avatars/avatar.model'
21 import { activityPubContextify } from '../../helpers/activitypub'
23 isActorFollowersCountValid,
24 isActorFollowingCountValid,
25 isActorPreferredUsernameValid,
26 isActorPrivateKeyValid,
28 } from '../../helpers/custom-validators/activitypub/actor'
29 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
30 import { ACTIVITY_PUB, ACTIVITY_PUB_ACTOR_TYPES, CONSTRAINTS_FIELDS, SERVER_ACTOR_NAME, WEBSERVER } from '../../initializers/constants'
31 import { AccountModel } from '../account/account'
32 import { AvatarModel } from '../avatar/avatar'
33 import { ServerModel } from '../server/server'
34 import { isOutdated, throwIfNotValid } from '../utils'
35 import { VideoChannelModel } from '../video/video-channel'
36 import { ActorFollowModel } from './actor-follow'
37 import { VideoModel } from '../video/video'
40 MActorAccountChannelId,
46 MActorSummaryFormattable, MActorUrl,
48 } from '../../typings/models'
49 import * as Bluebird from 'bluebird'
50 import { Op, Transaction, literal } from 'sequelize'
56 export const unusedActorAttributesForAPI = [
69 @DefaultScope(() => ({
85 model: AccountModel.unscoped(),
89 model: VideoChannelModel.unscoped(),
117 fields: [ 'preferredUsername', 'serverId' ],
126 // fields: [ 'preferredUsername' ],
133 fields: [ 'inboxUrl', 'sharedInboxUrl' ]
136 fields: [ 'sharedInboxUrl' ]
139 fields: [ 'serverId' ]
142 fields: [ 'avatarId' ]
145 fields: [ 'followersUrl' ]
149 export class ActorModel extends Model<ActorModel> {
152 @Column(DataType.ENUM(...values(ACTIVITY_PUB_ACTOR_TYPES)))
153 type: ActivityPubActorType
156 @Is('ActorPreferredUsername', value => throwIfNotValid(value, isActorPreferredUsernameValid, 'actor preferred username'))
158 preferredUsername: string
161 @Is('ActorUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
162 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
166 @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPublicKeyValid, 'public key', true))
167 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PUBLIC_KEY.max))
171 @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPrivateKeyValid, 'private key', true))
172 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PRIVATE_KEY.max))
176 @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowersCountValid, 'followers count'))
178 followersCount: number
181 @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowingCountValid, 'following count'))
183 followingCount: number
186 @Is('ActorInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'inbox url'))
187 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
191 @Is('ActorOutboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'outbox url', true))
192 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
196 @Is('ActorSharedInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'shared inbox url', true))
197 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
198 sharedInboxUrl: string
201 @Is('ActorFollowersUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'followers url', true))
202 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
206 @Is('ActorFollowingUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'following url', true))
207 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
216 @ForeignKey(() => AvatarModel)
220 @BelongsTo(() => AvatarModel, {
224 onDelete: 'set null',
229 @HasMany(() => ActorFollowModel, {
234 as: 'ActorFollowings',
237 ActorFollowing: ActorFollowModel[]
239 @HasMany(() => ActorFollowModel, {
241 name: 'targetActorId',
244 as: 'ActorFollowers',
247 ActorFollowers: ActorFollowModel[]
249 @ForeignKey(() => ServerModel)
253 @BelongsTo(() => ServerModel, {
261 @HasOne(() => AccountModel, {
268 Account: AccountModel
270 @HasOne(() => VideoChannelModel, {
277 VideoChannel: VideoChannelModel
279 private static localNameCache: { [ id: string ]: any } = {}
280 private static localUrlCache: { [ id: string ]: any } = {}
282 static load (id: number): Bluebird<MActor> {
283 return ActorModel.unscoped().findByPk(id)
286 static loadFull (id: number): Bluebird<MActorFull> {
287 return ActorModel.scope(ScopeNames.FULL).findByPk(id)
290 static loadFromAccountByVideoId (videoId: number, transaction: Transaction): Bluebird<MActor> {
294 attributes: [ 'id' ],
295 model: AccountModel.unscoped(),
299 attributes: [ 'id' ],
300 model: VideoChannelModel.unscoped(),
304 attributes: [ 'id' ],
305 model: VideoModel.unscoped(),
319 return ActorModel.unscoped().findOne(query)
322 static isActorUrlExist (url: string) {
330 return ActorModel.unscoped().findOne(query)
334 static listByFollowersUrls (followersUrls: string[], transaction?: Transaction): Bluebird<MActorFull[]> {
338 [ Op.in ]: followersUrls
344 return ActorModel.scope(ScopeNames.FULL).findAll(query)
347 static loadLocalByName (preferredUsername: string, transaction?: Transaction): Bluebird<MActorFull> {
348 // The server actor never change, so we can easily cache it
349 if (preferredUsername === SERVER_ACTOR_NAME && ActorModel.localNameCache[preferredUsername]) {
350 return Bluebird.resolve(ActorModel.localNameCache[preferredUsername])
361 return ActorModel.scope(ScopeNames.FULL)
364 if (preferredUsername === SERVER_ACTOR_NAME) {
365 ActorModel.localNameCache[ preferredUsername ] = actor
372 static loadLocalUrlByName (preferredUsername: string, transaction?: Transaction): Bluebird<MActorUrl> {
373 // The server actor never change, so we can easily cache it
374 if (preferredUsername === SERVER_ACTOR_NAME && ActorModel.localUrlCache[preferredUsername]) {
375 return Bluebird.resolve(ActorModel.localUrlCache[preferredUsername])
379 attributes: [ 'url' ],
387 return ActorModel.unscoped()
390 if (preferredUsername === SERVER_ACTOR_NAME) {
391 ActorModel.localUrlCache[ preferredUsername ] = actor
398 static loadByNameAndHost (preferredUsername: string, host: string): Bluebird<MActorFull> {
414 return ActorModel.scope(ScopeNames.FULL).findOne(query)
417 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MActorAccountChannelId> {
425 attributes: [ 'id' ],
426 model: AccountModel.unscoped(),
430 attributes: [ 'id' ],
431 model: VideoChannelModel.unscoped(),
437 return ActorModel.unscoped().findOne(query)
440 static loadByUrlAndPopulateAccountAndChannel (url: string, transaction?: Transaction): Bluebird<MActorFull> {
448 return ActorModel.scope(ScopeNames.FULL).findOne(query)
451 static rebuildFollowsCount (ofId: number, type: 'followers' | 'following', transaction?: Transaction) {
452 const sanitizedOfId = parseInt(ofId + '', 10)
453 const where = { id: sanitizedOfId }
455 let columnToUpdate: string
456 let columnOfCount: string
458 if (type === 'followers') {
459 columnToUpdate = 'followersCount'
460 columnOfCount = 'targetActorId'
462 columnToUpdate = 'followingCount'
463 columnOfCount = 'actorId'
466 return ActorModel.update({
467 [columnToUpdate]: literal(`(SELECT COUNT(*) FROM "actorFollow" WHERE "${columnOfCount}" = ${sanitizedOfId})`)
468 }, { where, transaction })
471 getSharedInbox (this: MActorWithInboxes) {
472 return this.sharedInboxUrl || this.inboxUrl
475 toFormattedSummaryJSON (this: MActorSummaryFormattable) {
476 let avatar: Avatar = null
478 avatar = this.Avatar.toFormattedJSON()
483 name: this.preferredUsername,
484 host: this.getHost(),
489 toFormattedJSON (this: MActorFormattable) {
490 const base = this.toFormattedSummaryJSON()
492 return Object.assign(base, {
494 hostRedundancyAllowed: this.getRedundancyAllowed(),
495 followingCount: this.followingCount,
496 followersCount: this.followersCount,
497 createdAt: this.createdAt,
498 updatedAt: this.updatedAt
502 toActivityPubObject (this: MActorAP, name: string) {
505 const extension = extname(this.Avatar.filename)
508 mediaType: extension === '.png' ? 'image/png' : 'image/jpeg',
509 url: this.getAvatarUrl()
516 following: this.getFollowingUrl(),
517 followers: this.getFollowersUrl(),
518 playlists: this.getPlaylistsUrl(),
519 inbox: this.inboxUrl,
520 outbox: this.outboxUrl,
521 preferredUsername: this.preferredUsername,
525 sharedInbox: this.sharedInboxUrl
528 id: this.getPublicKeyUrl(),
530 publicKeyPem: this.publicKey
535 return activityPubContextify(json)
538 getFollowerSharedInboxUrls (t: Transaction) {
540 attributes: [ 'sharedInboxUrl' ],
544 model: ActorFollowModel.unscoped(),
546 as: 'ActorFollowing',
549 targetActorId: this.id
556 return ActorModel.findAll(query)
557 .then(accounts => accounts.map(a => a.sharedInboxUrl))
561 return this.url + '/following'
565 return this.url + '/followers'
569 return this.url + '/playlists'
573 return this.url + '#main-key'
577 return this.serverId === null
580 getWebfingerUrl (this: MActorServer) {
581 return 'acct:' + this.preferredUsername + '@' + this.getHost()
585 return this.Server ? `${this.preferredUsername}@${this.Server.host}` : this.preferredUsername
588 getHost (this: MActorHost) {
589 return this.Server ? this.Server.host : WEBSERVER.HOST
592 getRedundancyAllowed () {
593 return this.Server ? this.Server.redundancyAllowed : false
597 if (!this.avatarId) return undefined
599 return WEBSERVER.URL + this.Avatar.getStaticPath()
603 if (this.isOwned()) return false
605 return isOutdated(this, ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL)