]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/account.ts
Stronger model typings
[github/Chocobozzz/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, 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 } 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: false
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 @BeforeDestroy
222 static async sendDeleteIfOwned (instance: AccountModel, options) {
223 if (!instance.Actor) {
224 instance.Actor = await instance.$get('Actor', { transaction: options.transaction }) as ActorModel
225 }
226
227 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
228 if (instance.isOwned()) {
229 return sendDeleteActor(instance.Actor, options.transaction)
230 }
231
232 return undefined
233 }
234
235 static load (id: number, transaction?: Transaction): Bluebird<MAccountDefault> {
236 return AccountModel.findByPk(id, { transaction })
237 }
238
239 static loadByNameWithHost (nameWithHost: string): Bluebird<MAccountDefault> {
240 const [ accountName, host ] = nameWithHost.split('@')
241
242 if (!host || host === WEBSERVER.HOST) return AccountModel.loadLocalByName(accountName)
243
244 return AccountModel.loadByNameAndHost(accountName, host)
245 }
246
247 static loadLocalByName (name: string): Bluebird<MAccountDefault> {
248 const query = {
249 where: {
250 [ Op.or ]: [
251 {
252 userId: {
253 [ Op.ne ]: null
254 }
255 },
256 {
257 applicationId: {
258 [ Op.ne ]: null
259 }
260 }
261 ]
262 },
263 include: [
264 {
265 model: ActorModel,
266 required: true,
267 where: {
268 preferredUsername: name
269 }
270 }
271 ]
272 }
273
274 return AccountModel.findOne(query)
275 }
276
277 static loadByNameAndHost (name: string, host: string): Bluebird<MAccountDefault> {
278 const query = {
279 include: [
280 {
281 model: ActorModel,
282 required: true,
283 where: {
284 preferredUsername: name
285 },
286 include: [
287 {
288 model: ServerModel,
289 required: true,
290 where: {
291 host
292 }
293 }
294 ]
295 }
296 ]
297 }
298
299 return AccountModel.findOne(query)
300 }
301
302 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MAccountDefault> {
303 const query = {
304 include: [
305 {
306 model: ActorModel,
307 required: true,
308 where: {
309 url
310 }
311 }
312 ],
313 transaction
314 }
315
316 return AccountModel.findOne(query)
317 }
318
319 static listForApi (start: number, count: number, sort: string) {
320 const query = {
321 offset: start,
322 limit: count,
323 order: getSort(sort)
324 }
325
326 return AccountModel.findAndCountAll(query)
327 .then(({ rows, count }) => {
328 return {
329 data: rows,
330 total: count
331 }
332 })
333 }
334
335 static listLocalsForSitemap (sort: string): Bluebird<MAccountActor[]> {
336 const query = {
337 attributes: [ ],
338 offset: 0,
339 order: getSort(sort),
340 include: [
341 {
342 attributes: [ 'preferredUsername', 'serverId' ],
343 model: ActorModel.unscoped(),
344 where: {
345 serverId: null
346 }
347 }
348 ]
349 }
350
351 return AccountModel
352 .unscoped()
353 .findAll(query)
354 }
355
356 toFormattedJSON (): Account {
357 const actor = this.Actor.toFormattedJSON()
358 const account = {
359 id: this.id,
360 displayName: this.getDisplayName(),
361 description: this.description,
362 createdAt: this.createdAt,
363 updatedAt: this.updatedAt,
364 userId: this.userId ? this.userId : undefined
365 }
366
367 return Object.assign(actor, account)
368 }
369
370 toFormattedSummaryJSON (): AccountSummary {
371 const actor = this.Actor.toFormattedJSON()
372
373 return {
374 id: this.id,
375 name: actor.name,
376 displayName: this.getDisplayName(),
377 url: actor.url,
378 host: actor.host,
379 avatar: actor.avatar
380 }
381 }
382
383 toActivityPubObject () {
384 const obj = this.Actor.toActivityPubObject(this.name, 'Account')
385
386 return Object.assign(obj, {
387 summary: this.description
388 })
389 }
390
391 isOwned () {
392 return this.Actor.isOwned()
393 }
394
395 isOutdated () {
396 return this.Actor.isOutdated()
397 }
398
399 getDisplayName () {
400 return this.name
401 }
402
403 isBlocked () {
404 return this.BlockedAccounts && this.BlockedAccounts.length !== 0
405 }
406 }