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