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