1 import { FindOptions, Includeable, IncludeOptions, Op, Transaction, WhereOptions } from 'sequelize'
18 } from 'sequelize-typescript'
19 import { ModelCache } from '@server/models/shared/model-cache'
20 import { AttributesOnly } from '@shared/typescript-utils'
21 import { Account, AccountSummary } from '../../../shared/models/actors'
22 import { isAccountDescriptionValid } from '../../helpers/custom-validators/accounts'
23 import { CONSTRAINTS_FIELDS, SERVER_ACTOR_NAME, WEBSERVER } from '../../initializers/constants'
24 import { sendDeleteActor } from '../../lib/activitypub/send/send-delete'
31 MAccountSummaryFormattable,
33 } from '../../types/models'
34 import { ActorModel } from '../actor/actor'
35 import { ActorFollowModel } from '../actor/actor-follow'
36 import { ActorImageModel } from '../actor/actor-image'
37 import { ApplicationModel } from '../application/application'
38 import { ServerModel } from '../server/server'
39 import { ServerBlocklistModel } from '../server/server-blocklist'
40 import { UserModel } from '../user/user'
41 import { buildSQLAttributes, getSort, throwIfNotValid } from '../shared'
42 import { VideoModel } from '../video/video'
43 import { VideoChannelModel } from '../video/video-channel'
44 import { VideoCommentModel } from '../video/video-comment'
45 import { VideoPlaylistModel } from '../video/video-playlist'
46 import { AccountBlocklistModel } from './account-blocklist'
48 export enum ScopeNames {
52 export type SummaryOptions = {
53 actorRequired?: boolean // Default: true
54 whereActor?: WhereOptions
55 whereServer?: WhereOptions
56 withAccountBlockerIds?: number[]
60 @DefaultScope(() => ({
63 model: ActorModel, // Default scope includes avatar and server
69 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
70 const serverInclude: IncludeOptions = {
71 attributes: [ 'host' ],
72 model: ServerModel.unscoped(),
73 required: !!options.whereServer,
74 where: options.whereServer
77 const actorInclude: Includeable = {
78 attributes: [ 'id', 'preferredUsername', 'url', 'serverId' ],
79 model: ActorModel.unscoped(),
80 required: options.actorRequired ?? true,
81 where: options.whereActor,
82 include: [ serverInclude ]
85 if (options.forCount !== true) {
86 actorInclude.include.push({
87 model: ActorImageModel,
93 const queryInclude: Includeable[] = [
97 const query: FindOptions = {
98 attributes: [ 'id', 'name', 'actorId' ]
101 if (options.withAccountBlockerIds) {
103 attributes: [ 'id' ],
104 model: AccountBlocklistModel.unscoped(),
109 [Op.in]: options.withAccountBlockerIds
114 serverInclude.include = [
116 attributes: [ 'id' ],
117 model: ServerBlocklistModel.unscoped(),
121 [Op.in]: options.withAccountBlockerIds
128 query.include = queryInclude
134 tableName: 'account',
137 fields: [ 'actorId' ],
141 fields: [ 'applicationId' ]
148 export class AccountModel extends Model<Partial<AttributesOnly<AccountModel>>> {
156 @Is('AccountDescription', value => throwIfNotValid(value, isAccountDescriptionValid, 'description', true))
157 @Column(DataType.STRING(CONSTRAINTS_FIELDS.USERS.DESCRIPTION.max))
166 @ForeignKey(() => ActorModel)
170 @BelongsTo(() => ActorModel, {
178 @ForeignKey(() => UserModel)
182 @BelongsTo(() => UserModel, {
190 @ForeignKey(() => ApplicationModel)
192 applicationId: number
194 @BelongsTo(() => ApplicationModel, {
200 Application: ApplicationModel
202 @HasMany(() => VideoChannelModel, {
209 VideoChannels: VideoChannelModel[]
211 @HasMany(() => VideoPlaylistModel, {
218 VideoPlaylists: VideoPlaylistModel[]
220 @HasMany(() => VideoCommentModel, {
227 VideoComments: VideoCommentModel[]
229 @HasMany(() => AccountBlocklistModel, {
231 name: 'targetAccountId',
237 BlockedBy: AccountBlocklistModel[]
240 static async sendDeleteIfOwned (instance: AccountModel, options) {
241 if (!instance.Actor) {
242 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
245 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
247 if (instance.isOwned()) {
248 return sendDeleteActor(instance.Actor, options.transaction)
254 // ---------------------------------------------------------------------------
256 static getSQLAttributes (tableName: string, aliasPrefix = '') {
257 return buildSQLAttributes({
264 // ---------------------------------------------------------------------------
266 static load (id: number, transaction?: Transaction): Promise<MAccountDefault> {
267 return AccountModel.findByPk(id, { transaction })
270 static loadByNameWithHost (nameWithHost: string): Promise<MAccountDefault> {
271 const [ accountName, host ] = nameWithHost.split('@')
273 if (!host || host === WEBSERVER.HOST) return AccountModel.loadLocalByName(accountName)
275 return AccountModel.loadByNameAndHost(accountName, host)
278 static loadLocalByName (name: string): Promise<MAccountDefault> {
300 preferredUsername: name
306 return AccountModel.findOne(query)
309 return ModelCache.Instance.doCache({
310 cacheType: 'local-account-name',
313 // The server actor never change, so we can easily cache it
314 whitelist: () => name === SERVER_ACTOR_NAME
318 static loadByNameAndHost (name: string, host: string): Promise<MAccountDefault> {
325 preferredUsername: name
340 return AccountModel.findOne(query)
343 static loadByUrl (url: string, transaction?: Transaction): Promise<MAccountDefault> {
357 return AccountModel.findOne(query)
360 static listForApi (start: number, count: number, sort: string) {
368 AccountModel.count(),
369 AccountModel.findAll(query)
370 ]).then(([ total, data ]) => ({ total, data }))
373 static loadAccountIdFromVideo (videoId: number): Promise<MAccount> {
377 attributes: [ 'id', 'accountId' ],
378 model: VideoChannelModel.unscoped(),
382 attributes: [ 'id', 'channelId' ],
383 model: VideoModel.unscoped(),
393 return AccountModel.findOne(query)
396 static listLocalsForSitemap (sort: string): Promise<MAccountActor[]> {
400 order: getSort(sort),
403 attributes: [ 'preferredUsername', 'serverId' ],
404 model: ActorModel.unscoped(),
418 return WEBSERVER.URL + '/accounts/' + this.Actor.getIdentifier()
421 toFormattedJSON (this: MAccountFormattable): Account {
423 ...this.Actor.toFormattedJSON(),
426 displayName: this.getDisplayName(),
427 description: this.description,
428 updatedAt: this.updatedAt,
429 userId: this.userId ?? undefined
433 toFormattedSummaryJSON (this: MAccountSummaryFormattable): AccountSummary {
434 const actor = this.Actor.toFormattedSummaryJSON()
438 displayName: this.getDisplayName(),
443 avatars: actor.avatars,
445 // TODO: remove, deprecated in 4.2
450 toActivityPubObject (this: MAccountAP) {
451 const obj = this.Actor.toActivityPubObject(this.name)
453 return Object.assign(obj, {
454 summary: this.description
459 return this.Actor.isOwned()
463 return this.Actor.isOutdated()
470 getLocalUrl (this: MAccountActor | MChannelActor) {
471 return WEBSERVER.URL + `/accounts/` + this.Actor.preferredUsername
475 return this.BlockedBy && this.BlockedBy.length !== 0