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