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