]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/account.ts
Fix email footer
[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 if (instance.isOwned()) {
232 return sendDeleteActor(instance.Actor, options.transaction)
233 }
234
235 return undefined
236 }
237
238 static load (id: number, transaction?: Transaction): Bluebird<MAccountDefault> {
239 return AccountModel.findByPk(id, { transaction })
240 }
241
242 static loadByNameWithHost (nameWithHost: string): Bluebird<MAccountDefault> {
243 const [ accountName, host ] = nameWithHost.split('@')
244
245 if (!host || host === WEBSERVER.HOST) return AccountModel.loadLocalByName(accountName)
246
247 return AccountModel.loadByNameAndHost(accountName, host)
248 }
249
250 static loadLocalByName (name: string): Bluebird<MAccountDefault> {
251 const fun = () => {
252 const query = {
253 where: {
254 [Op.or]: [
255 {
256 userId: {
257 [Op.ne]: null
258 }
259 },
260 {
261 applicationId: {
262 [Op.ne]: null
263 }
264 }
265 ]
266 },
267 include: [
268 {
269 model: ActorModel,
270 required: true,
271 where: {
272 preferredUsername: name
273 }
274 }
275 ]
276 }
277
278 return AccountModel.findOne(query)
279 }
280
281 return ModelCache.Instance.doCache({
282 cacheType: 'local-account-name',
283 key: name,
284 fun,
285 // The server actor never change, so we can easily cache it
286 whitelist: () => name === SERVER_ACTOR_NAME
287 })
288 }
289
290 static loadByNameAndHost (name: string, host: string): Bluebird<MAccountDefault> {
291 const query = {
292 include: [
293 {
294 model: ActorModel,
295 required: true,
296 where: {
297 preferredUsername: name
298 },
299 include: [
300 {
301 model: ServerModel,
302 required: true,
303 where: {
304 host
305 }
306 }
307 ]
308 }
309 ]
310 }
311
312 return AccountModel.findOne(query)
313 }
314
315 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MAccountDefault> {
316 const query = {
317 include: [
318 {
319 model: ActorModel,
320 required: true,
321 where: {
322 url
323 }
324 }
325 ],
326 transaction
327 }
328
329 return AccountModel.findOne(query)
330 }
331
332 static listForApi (start: number, count: number, sort: string) {
333 const query = {
334 offset: start,
335 limit: count,
336 order: getSort(sort)
337 }
338
339 return AccountModel.findAndCountAll(query)
340 .then(({ rows, count }) => {
341 return {
342 data: rows,
343 total: count
344 }
345 })
346 }
347
348 static loadAccountIdFromVideo (videoId: number): Bluebird<MAccount> {
349 const query = {
350 include: [
351 {
352 attributes: [ 'id', 'accountId' ],
353 model: VideoChannelModel.unscoped(),
354 required: true,
355 include: [
356 {
357 attributes: [ 'id', 'channelId' ],
358 model: VideoModel.unscoped(),
359 where: {
360 id: videoId
361 }
362 }
363 ]
364 }
365 ]
366 }
367
368 return AccountModel.findOne(query)
369 }
370
371 static listLocalsForSitemap (sort: string): Bluebird<MAccountActor[]> {
372 const query = {
373 attributes: [ ],
374 offset: 0,
375 order: getSort(sort),
376 include: [
377 {
378 attributes: [ 'preferredUsername', 'serverId' ],
379 model: ActorModel.unscoped(),
380 where: {
381 serverId: null
382 }
383 }
384 ]
385 }
386
387 return AccountModel
388 .unscoped()
389 .findAll(query)
390 }
391
392 getClientUrl () {
393 return WEBSERVER.URL + '/accounts/' + this.Actor.getIdentifier()
394 }
395
396 toFormattedJSON (this: MAccountFormattable): Account {
397 const actor = this.Actor.toFormattedJSON()
398 const account = {
399 id: this.id,
400 displayName: this.getDisplayName(),
401 description: this.description,
402 createdAt: this.createdAt,
403 updatedAt: this.updatedAt,
404 userId: this.userId ? this.userId : undefined
405 }
406
407 return Object.assign(actor, account)
408 }
409
410 toFormattedSummaryJSON (this: MAccountSummaryFormattable): AccountSummary {
411 const actor = this.Actor.toFormattedSummaryJSON()
412
413 return {
414 id: this.id,
415 name: actor.name,
416 displayName: this.getDisplayName(),
417 url: actor.url,
418 host: actor.host,
419 avatar: actor.avatar
420 }
421 }
422
423 toActivityPubObject (this: MAccountAP) {
424 const obj = this.Actor.toActivityPubObject(this.name)
425
426 return Object.assign(obj, {
427 summary: this.description
428 })
429 }
430
431 isOwned () {
432 return this.Actor.isOwned()
433 }
434
435 isOutdated () {
436 return this.Actor.isOutdated()
437 }
438
439 getDisplayName () {
440 return this.name
441 }
442
443 isBlocked () {
444 return this.BlockedAccounts && this.BlockedAccounts.length !== 0
445 }
446 }