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'
32 MAccountSummaryFormattable,
34 } from '../../types/models'
35 import { ActorModel } from '../actor/actor'
36 import { ActorFollowModel } from '../actor/actor-follow'
37 import { ActorImageModel } from '../actor/actor-image'
38 import { ApplicationModel } from '../application/application'
39 import { ServerModel } from '../server/server'
40 import { ServerBlocklistModel } from '../server/server-blocklist'
41 import { buildSQLAttributes, getSort, throwIfNotValid } from '../shared'
42 import { UserModel } from '../user/user'
43 import { VideoModel } from '../video/video'
44 import { VideoChannelModel } from '../video/video-channel'
45 import { VideoCommentModel } from '../video/video-comment'
46 import { VideoPlaylistModel } from '../video/video-playlist'
47 import { AccountBlocklistModel } from './account-blocklist'
49 export enum ScopeNames {
53 export type SummaryOptions = {
54 actorRequired?: boolean // Default: true
55 whereActor?: WhereOptions
56 whereServer?: WhereOptions
57 withAccountBlockerIds?: number[]
61 @DefaultScope(() => ({
64 model: ActorModel, // Default scope includes avatar and server
70 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
71 const serverInclude: IncludeOptions = {
72 attributes: [ 'host' ],
73 model: ServerModel.unscoped(),
74 required: !!options.whereServer,
75 where: options.whereServer
78 const actorInclude: Includeable = {
79 attributes: [ 'id', 'preferredUsername', 'url', 'serverId' ],
80 model: ActorModel.unscoped(),
81 required: options.actorRequired ?? true,
82 where: options.whereActor,
83 include: [ serverInclude ]
86 if (options.forCount !== true) {
87 actorInclude.include.push({
88 model: ActorImageModel,
94 const queryInclude: Includeable[] = [
98 const query: FindOptions = {
99 attributes: [ 'id', 'name', 'actorId' ]
102 if (options.withAccountBlockerIds) {
104 attributes: [ 'id' ],
105 model: AccountBlocklistModel.unscoped(),
110 [Op.in]: options.withAccountBlockerIds
115 serverInclude.include = [
117 attributes: [ 'id' ],
118 model: ServerBlocklistModel.unscoped(),
122 [Op.in]: options.withAccountBlockerIds
129 query.include = queryInclude
135 tableName: 'account',
138 fields: [ 'actorId' ],
142 fields: [ 'applicationId' ]
149 export class AccountModel extends Model<Partial<AttributesOnly<AccountModel>>> {
157 @Is('AccountDescription', value => throwIfNotValid(value, isAccountDescriptionValid, 'description', true))
158 @Column(DataType.STRING(CONSTRAINTS_FIELDS.USERS.DESCRIPTION.max))
167 @ForeignKey(() => ActorModel)
171 @BelongsTo(() => ActorModel, {
179 @ForeignKey(() => UserModel)
183 @BelongsTo(() => UserModel, {
191 @ForeignKey(() => ApplicationModel)
193 applicationId: number
195 @BelongsTo(() => ApplicationModel, {
201 Application: ApplicationModel
203 @HasMany(() => VideoChannelModel, {
210 VideoChannels: VideoChannelModel[]
212 @HasMany(() => VideoPlaylistModel, {
219 VideoPlaylists: VideoPlaylistModel[]
221 @HasMany(() => VideoCommentModel, {
228 VideoComments: VideoCommentModel[]
230 @HasMany(() => AccountBlocklistModel, {
232 name: 'targetAccountId',
238 BlockedBy: AccountBlocklistModel[]
241 static async sendDeleteIfOwned (instance: AccountModel, options) {
242 if (!instance.Actor) {
243 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
246 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
248 if (instance.isOwned()) {
249 return sendDeleteActor(instance.Actor, options.transaction)
255 // ---------------------------------------------------------------------------
257 static getSQLAttributes (tableName: string, aliasPrefix = '') {
258 return buildSQLAttributes({
265 // ---------------------------------------------------------------------------
267 static load (id: number, transaction?: Transaction): Promise<MAccountDefault> {
268 return AccountModel.findByPk(id, { transaction })
271 static loadByNameWithHost (nameWithHost: string): Promise<MAccountDefault> {
272 const [ accountName, host ] = nameWithHost.split('@')
274 if (!host || host === WEBSERVER.HOST) return AccountModel.loadLocalByName(accountName)
276 return AccountModel.loadByNameAndHost(accountName, host)
279 static loadLocalByName (name: string): Promise<MAccountDefault> {
300 where: ActorModel.wherePreferredUsername(name)
305 return AccountModel.findOne(query)
308 return ModelCache.Instance.doCache({
309 cacheType: 'local-account-name',
312 // The server actor never change, so we can easily cache it
313 whitelist: () => name === SERVER_ACTOR_NAME
317 static loadByNameAndHost (name: string, host: string): Promise<MAccountDefault> {
323 where: ActorModel.wherePreferredUsername(name),
337 return AccountModel.findOne(query)
340 static loadByUrl (url: string, transaction?: Transaction): Promise<MAccountDefault> {
354 return AccountModel.findOne(query)
357 static listForApi (start: number, count: number, sort: string) {
365 AccountModel.count(),
366 AccountModel.findAll(query)
367 ]).then(([ total, data ]) => ({ total, data }))
370 static loadAccountIdFromVideo (videoId: number): Promise<MAccount> {
374 attributes: [ 'id', 'accountId' ],
375 model: VideoChannelModel.unscoped(),
379 attributes: [ 'id', 'channelId' ],
380 model: VideoModel.unscoped(),
390 return AccountModel.findOne(query)
393 static listLocalsForSitemap (sort: string): Promise<MAccountActor[]> {
397 order: getSort(sort),
400 attributes: [ 'preferredUsername', 'serverId' ],
401 model: ActorModel.unscoped(),
414 toFormattedJSON (this: MAccountFormattable): Account {
416 ...this.Actor.toFormattedJSON(),
419 displayName: this.getDisplayName(),
420 description: this.description,
421 updatedAt: this.updatedAt,
422 userId: this.userId ?? undefined
426 toFormattedSummaryJSON (this: MAccountSummaryFormattable): AccountSummary {
427 const actor = this.Actor.toFormattedSummaryJSON()
431 displayName: this.getDisplayName(),
436 avatars: actor.avatars,
438 // TODO: remove, deprecated in 4.2
443 async toActivityPubObject (this: MAccountAP) {
444 const obj = await this.Actor.toActivityPubObject(this.name)
446 return Object.assign(obj, {
447 summary: this.description
452 return this.Actor.isOwned()
456 return this.Actor.isOutdated()
463 // Avoid error when running this method on MAccount... | MChannel...
464 getClientUrl (this: MAccountHost | MChannelHost) {
465 return WEBSERVER.URL + '/a/' + this.Actor.getIdentifier()
469 return this.BlockedBy && this.BlockedBy.length !== 0