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