Move to eslint
[oweals/peertube.git] / server / models / account / account.ts
1 import {
2   AllowNull,
3   BeforeDestroy,
4   BelongsTo,
5   Column,
6   CreatedAt,
7   DataType,
8   Default,
9   DefaultScope,
10   ForeignKey,
11   HasMany,
12   Is,
13   Model,
14   Scopes,
15   Table,
16   UpdatedAt
17 } from 'sequelize-typescript'
18 import { Account, AccountSummary } from '../../../shared/models/actors'
19 import { isAccountDescriptionValid } from '../../helpers/custom-validators/accounts'
20 import { sendDeleteActor } from '../../lib/activitypub/send'
21 import { ActorModel } from '../activitypub/actor'
22 import { ApplicationModel } from '../application/application'
23 import { ServerModel } from '../server/server'
24 import { getSort, throwIfNotValid } from '../utils'
25 import { VideoChannelModel } from '../video/video-channel'
26 import { VideoCommentModel } from '../video/video-comment'
27 import { UserModel } from './user'
28 import { AvatarModel } from '../avatar/avatar'
29 import { VideoPlaylistModel } from '../video/video-playlist'
30 import { CONSTRAINTS_FIELDS, SERVER_ACTOR_NAME, WEBSERVER } from '../../initializers/constants'
31 import { FindOptions, IncludeOptions, Op, Transaction, WhereOptions } from 'sequelize'
32 import { AccountBlocklistModel } from './account-blocklist'
33 import { ServerBlocklistModel } from '../server/server-blocklist'
34 import { ActorFollowModel } from '../activitypub/actor-follow'
35 import { MAccountActor, MAccountDefault, MAccountSummaryFormattable, MAccountFormattable, MAccountAP } from '../../typings/models'
36 import * as Bluebird from 'bluebird'
37
38 export enum ScopeNames {
39   SUMMARY = 'SUMMARY'
40 }
41
42 export type SummaryOptions = {
43   whereActor?: WhereOptions
44   withAccountBlockerIds?: number[]
45 }
46
47 @DefaultScope(() => ({
48   include: [
49     {
50       model: ActorModel, // Default scope includes avatar and server
51       required: true
52     }
53   ]
54 }))
55 @Scopes(() => ({
56   [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
57     const whereActor = options.whereActor || undefined
58
59     const serverInclude: IncludeOptions = {
60       attributes: [ 'host' ],
61       model: ServerModel.unscoped(),
62       required: false
63     }
64
65     const query: FindOptions = {
66       attributes: [ 'id', 'name' ],
67       include: [
68         {
69           attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
70           model: ActorModel.unscoped(),
71           required: true,
72           where: whereActor,
73           include: [
74             serverInclude,
75
76             {
77               model: AvatarModel.unscoped(),
78               required: false
79             }
80           ]
81         }
82       ]
83     }
84
85     if (options.withAccountBlockerIds) {
86       query.include.push({
87         attributes: [ 'id' ],
88         model: AccountBlocklistModel.unscoped(),
89         as: 'BlockedAccounts',
90         required: false,
91         where: {
92           accountId: {
93             [Op.in]: options.withAccountBlockerIds
94           }
95         }
96       })
97
98       serverInclude.include = [
99         {
100           attributes: [ 'id' ],
101           model: ServerBlocklistModel.unscoped(),
102           required: false,
103           where: {
104             accountId: {
105               [Op.in]: options.withAccountBlockerIds
106             }
107           }
108         }
109       ]
110     }
111
112     return query
113   }
114 }))
115 @Table({
116   tableName: 'account',
117   indexes: [
118     {
119       fields: [ 'actorId' ],
120       unique: true
121     },
122     {
123       fields: [ 'applicationId' ]
124     },
125     {
126       fields: [ 'userId' ]
127     }
128   ]
129 })
130 export class AccountModel extends Model<AccountModel> {
131
132   @AllowNull(false)
133   @Column
134   name: string
135
136   @AllowNull(true)
137   @Default(null)
138   @Is('AccountDescription', value => throwIfNotValid(value, isAccountDescriptionValid, 'description', true))
139   @Column(DataType.STRING(CONSTRAINTS_FIELDS.USERS.DESCRIPTION.max))
140   description: string
141
142   @CreatedAt
143   createdAt: Date
144
145   @UpdatedAt
146   updatedAt: Date
147
148   @ForeignKey(() => ActorModel)
149   @Column
150   actorId: number
151
152   @BelongsTo(() => ActorModel, {
153     foreignKey: {
154       allowNull: false
155     },
156     onDelete: 'cascade'
157   })
158   Actor: ActorModel
159
160   @ForeignKey(() => UserModel)
161   @Column
162   userId: number
163
164   @BelongsTo(() => UserModel, {
165     foreignKey: {
166       allowNull: true
167     },
168     onDelete: 'cascade'
169   })
170   User: UserModel
171
172   @ForeignKey(() => ApplicationModel)
173   @Column
174   applicationId: number
175
176   @BelongsTo(() => ApplicationModel, {
177     foreignKey: {
178       allowNull: true
179     },
180     onDelete: 'cascade'
181   })
182   Application: ApplicationModel
183
184   @HasMany(() => VideoChannelModel, {
185     foreignKey: {
186       allowNull: false
187     },
188     onDelete: 'cascade',
189     hooks: true
190   })
191   VideoChannels: VideoChannelModel[]
192
193   @HasMany(() => VideoPlaylistModel, {
194     foreignKey: {
195       allowNull: false
196     },
197     onDelete: 'cascade',
198     hooks: true
199   })
200   VideoPlaylists: VideoPlaylistModel[]
201
202   @HasMany(() => VideoCommentModel, {
203     foreignKey: {
204       allowNull: true
205     },
206     onDelete: 'cascade',
207     hooks: true
208   })
209   VideoComments: VideoCommentModel[]
210
211   @HasMany(() => AccountBlocklistModel, {
212     foreignKey: {
213       name: 'targetAccountId',
214       allowNull: false
215     },
216     as: 'BlockedAccounts',
217     onDelete: 'CASCADE'
218   })
219   BlockedAccounts: AccountBlocklistModel[]
220
221   private static cache: { [ id: string ]: any } = {}
222
223   @BeforeDestroy
224   static async sendDeleteIfOwned (instance: AccountModel, options) {
225     if (!instance.Actor) {
226       instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
227     }
228
229     await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
230     if (instance.isOwned()) {
231       return sendDeleteActor(instance.Actor, options.transaction)
232     }
233
234     return undefined
235   }
236
237   static load (id: number, transaction?: Transaction): Bluebird<MAccountDefault> {
238     return AccountModel.findByPk(id, { transaction })
239   }
240
241   static loadByNameWithHost (nameWithHost: string): Bluebird<MAccountDefault> {
242     const [ accountName, host ] = nameWithHost.split('@')
243
244     if (!host || host === WEBSERVER.HOST) return AccountModel.loadLocalByName(accountName)
245
246     return AccountModel.loadByNameAndHost(accountName, host)
247   }
248
249   static loadLocalByName (name: string): Bluebird<MAccountDefault> {
250     // The server actor never change, so we can easily cache it
251     if (name === SERVER_ACTOR_NAME && AccountModel.cache[name]) {
252       return Bluebird.resolve(AccountModel.cache[name])
253     }
254
255     const query = {
256       where: {
257         [Op.or]: [
258           {
259             userId: {
260               [Op.ne]: null
261             }
262           },
263           {
264             applicationId: {
265               [Op.ne]: null
266             }
267           }
268         ]
269       },
270       include: [
271         {
272           model: ActorModel,
273           required: true,
274           where: {
275             preferredUsername: name
276           }
277         }
278       ]
279     }
280
281     return AccountModel.findOne(query)
282       .then(account => {
283         if (name === SERVER_ACTOR_NAME) {
284           AccountModel.cache[name] = account
285         }
286
287         return account
288       })
289   }
290
291   static loadByNameAndHost (name: string, host: string): Bluebird<MAccountDefault> {
292     const query = {
293       include: [
294         {
295           model: ActorModel,
296           required: true,
297           where: {
298             preferredUsername: name
299           },
300           include: [
301             {
302               model: ServerModel,
303               required: true,
304               where: {
305                 host
306               }
307             }
308           ]
309         }
310       ]
311     }
312
313     return AccountModel.findOne(query)
314   }
315
316   static loadByUrl (url: string, transaction?: Transaction): Bluebird<MAccountDefault> {
317     const query = {
318       include: [
319         {
320           model: ActorModel,
321           required: true,
322           where: {
323             url
324           }
325         }
326       ],
327       transaction
328     }
329
330     return AccountModel.findOne(query)
331   }
332
333   static listForApi (start: number, count: number, sort: string) {
334     const query = {
335       offset: start,
336       limit: count,
337       order: getSort(sort)
338     }
339
340     return AccountModel.findAndCountAll(query)
341       .then(({ rows, count }) => {
342         return {
343           data: rows,
344           total: count
345         }
346       })
347   }
348
349   static listLocalsForSitemap (sort: string): Bluebird<MAccountActor[]> {
350     const query = {
351       attributes: [ ],
352       offset: 0,
353       order: getSort(sort),
354       include: [
355         {
356           attributes: [ 'preferredUsername', 'serverId' ],
357           model: ActorModel.unscoped(),
358           where: {
359             serverId: null
360           }
361         }
362       ]
363     }
364
365     return AccountModel
366       .unscoped()
367       .findAll(query)
368   }
369
370   toFormattedJSON (this: MAccountFormattable): Account {
371     const actor = this.Actor.toFormattedJSON()
372     const account = {
373       id: this.id,
374       displayName: this.getDisplayName(),
375       description: this.description,
376       createdAt: this.createdAt,
377       updatedAt: this.updatedAt,
378       userId: this.userId ? this.userId : undefined
379     }
380
381     return Object.assign(actor, account)
382   }
383
384   toFormattedSummaryJSON (this: MAccountSummaryFormattable): AccountSummary {
385     const actor = this.Actor.toFormattedSummaryJSON()
386
387     return {
388       id: this.id,
389       name: actor.name,
390       displayName: this.getDisplayName(),
391       url: actor.url,
392       host: actor.host,
393       avatar: actor.avatar
394     }
395   }
396
397   toActivityPubObject (this: MAccountAP) {
398     const obj = this.Actor.toActivityPubObject(this.name)
399
400     return Object.assign(obj, {
401       summary: this.description
402     })
403   }
404
405   isOwned () {
406     return this.Actor.isOwned()
407   }
408
409   isOutdated () {
410     return this.Actor.isOutdated()
411   }
412
413   getDisplayName () {
414     return this.name
415   }
416
417   isBlocked () {
418     return this.BlockedAccounts && this.BlockedAccounts.length !== 0
419   }
420 }