]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/user.ts
4b13e47a0dc306d76a62acc3a61da8979e2cb2ee
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
1 import * as Sequelize from 'sequelize'
2 import {
3 AllowNull,
4 BeforeCreate,
5 BeforeUpdate,
6 Column,
7 CreatedAt,
8 DataType,
9 Default,
10 DefaultScope,
11 HasMany,
12 HasOne,
13 Is,
14 IsEmail,
15 Model,
16 Scopes,
17 Table,
18 UpdatedAt
19 } from 'sequelize-typescript'
20 import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
21 import { User, UserRole } from '../../../shared/models/users'
22 import {
23 isUserAutoPlayVideoValid,
24 isUserBlockedReasonValid,
25 isUserBlockedValid,
26 isUserNSFWPolicyValid,
27 isUserEmailVerifiedValid,
28 isUserPasswordValid,
29 isUserRoleValid,
30 isUserUsernameValid,
31 isUserVideoQuotaValid,
32 isUserVideoQuotaDailyValid
33 } from '../../helpers/custom-validators/users'
34 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
35 import { OAuthTokenModel } from '../oauth/oauth-token'
36 import { getSort, throwIfNotValid } from '../utils'
37 import { VideoChannelModel } from '../video/video-channel'
38 import { AccountModel } from './account'
39 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
40 import { values } from 'lodash'
41 import { NSFW_POLICY_TYPES } from '../../initializers'
42 import { VideoFileModel } from '../video/video-file'
43
44 enum ScopeNames {
45 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
46 }
47
48 @DefaultScope({
49 include: [
50 {
51 model: () => AccountModel,
52 required: true
53 }
54 ]
55 })
56 @Scopes({
57 [ScopeNames.WITH_VIDEO_CHANNEL]: {
58 include: [
59 {
60 model: () => AccountModel,
61 required: true,
62 include: [ () => VideoChannelModel ]
63 }
64 ]
65 }
66 })
67 @Table({
68 tableName: 'user',
69 indexes: [
70 {
71 fields: [ 'username' ],
72 unique: true
73 },
74 {
75 fields: [ 'email' ],
76 unique: true
77 }
78 ]
79 })
80 export class UserModel extends Model<UserModel> {
81
82 @AllowNull(false)
83 @Is('UserPassword', value => throwIfNotValid(value, isUserPasswordValid, 'user password'))
84 @Column
85 password: string
86
87 @AllowNull(false)
88 @Is('UserPassword', value => throwIfNotValid(value, isUserUsernameValid, 'user name'))
89 @Column
90 username: string
91
92 @AllowNull(false)
93 @IsEmail
94 @Column(DataType.STRING(400))
95 email: string
96
97 @AllowNull(true)
98 @Default(null)
99 @Is('UserEmailVerified', value => throwIfNotValid(value, isUserEmailVerifiedValid, 'email verified boolean'))
100 @Column
101 emailVerified: boolean
102
103 @AllowNull(false)
104 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
105 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
106 nsfwPolicy: NSFWPolicyType
107
108 @AllowNull(false)
109 @Default(true)
110 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
111 @Column
112 autoPlayVideo: boolean
113
114 @AllowNull(false)
115 @Default(false)
116 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
117 @Column
118 blocked: boolean
119
120 @AllowNull(true)
121 @Default(null)
122 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
123 @Column
124 blockedReason: string
125
126 @AllowNull(false)
127 @Is('UserRole', value => throwIfNotValid(value, isUserRoleValid, 'role'))
128 @Column
129 role: number
130
131 @AllowNull(false)
132 @Is('UserVideoQuota', value => throwIfNotValid(value, isUserVideoQuotaValid, 'video quota'))
133 @Column(DataType.BIGINT)
134 videoQuota: number
135
136 @AllowNull(false)
137 @Is('UserVideoQuotaDaily', value => throwIfNotValid(value, isUserVideoQuotaDailyValid, 'video quota daily'))
138 @Column(DataType.BIGINT)
139 videoQuotaDaily: number
140
141 @CreatedAt
142 createdAt: Date
143
144 @UpdatedAt
145 updatedAt: Date
146
147 @HasOne(() => AccountModel, {
148 foreignKey: 'userId',
149 onDelete: 'cascade',
150 hooks: true
151 })
152 Account: AccountModel
153
154 @HasMany(() => OAuthTokenModel, {
155 foreignKey: 'userId',
156 onDelete: 'cascade'
157 })
158 OAuthTokens: OAuthTokenModel[]
159
160 @BeforeCreate
161 @BeforeUpdate
162 static cryptPasswordIfNeeded (instance: UserModel) {
163 if (instance.changed('password')) {
164 return cryptPassword(instance.password)
165 .then(hash => {
166 instance.password = hash
167 return undefined
168 })
169 }
170 }
171
172 static countTotal () {
173 return this.count()
174 }
175
176 static listForApi (start: number, count: number, sort: string) {
177 const query = {
178 attributes: {
179 include: [
180 [
181 Sequelize.literal(
182 '(' +
183 'SELECT COALESCE(SUM("size"), 0) ' +
184 'FROM (' +
185 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
186 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
187 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
188 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
189 'WHERE "account"."userId" = "UserModel"."id" GROUP BY "video"."id"' +
190 ') t' +
191 ')'
192 ),
193 'videoQuotaUsed'
194 ] as any // FIXME: typings
195 ]
196 },
197 offset: start,
198 limit: count,
199 order: getSort(sort)
200 }
201
202 return UserModel.findAndCountAll(query)
203 .then(({ rows, count }) => {
204 return {
205 data: rows,
206 total: count
207 }
208 })
209 }
210
211 static listEmailsWithRight (right: UserRight) {
212 const roles = Object.keys(USER_ROLE_LABELS)
213 .map(k => parseInt(k, 10) as UserRole)
214 .filter(role => hasUserRight(role, right))
215
216 const query = {
217 attribute: [ 'email' ],
218 where: {
219 role: {
220 [Sequelize.Op.in]: roles
221 }
222 }
223 }
224
225 return UserModel.unscoped()
226 .findAll(query)
227 .then(u => u.map(u => u.email))
228 }
229
230 static loadById (id: number) {
231 return UserModel.findById(id)
232 }
233
234 static loadByUsername (username: string) {
235 const query = {
236 where: {
237 username
238 }
239 }
240
241 return UserModel.findOne(query)
242 }
243
244 static loadByUsernameAndPopulateChannels (username: string) {
245 const query = {
246 where: {
247 username
248 }
249 }
250
251 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
252 }
253
254 static loadByEmail (email: string) {
255 const query = {
256 where: {
257 email
258 }
259 }
260
261 return UserModel.findOne(query)
262 }
263
264 static loadByUsernameOrEmail (username: string, email?: string) {
265 if (!email) email = username
266
267 const query = {
268 where: {
269 [ Sequelize.Op.or ]: [ { username }, { email } ]
270 }
271 }
272
273 return UserModel.findOne(query)
274 }
275
276 static getOriginalVideoFileTotalFromUser (user: UserModel) {
277 // Don't use sequelize because we need to use a sub query
278 const query = UserModel.generateUserQuotaBaseSQL()
279
280 return UserModel.getTotalRawQuery(query, user.id)
281 }
282
283 // Returns cumulative size of all video files uploaded in the last 24 hours.
284 static getOriginalVideoFileTotalDailyFromUser (user: UserModel) {
285 // Don't use sequelize because we need to use a sub query
286 const query = UserModel.generateUserQuotaBaseSQL('"video"."createdAt" > now() - interval \'24 hours\'')
287
288 return UserModel.getTotalRawQuery(query, user.id)
289 }
290
291 static async getStats () {
292 const totalUsers = await UserModel.count()
293
294 return {
295 totalUsers
296 }
297 }
298
299 hasRight (right: UserRight) {
300 return hasUserRight(this.role, right)
301 }
302
303 isPasswordMatch (password: string) {
304 return comparePassword(password, this.password)
305 }
306
307 toFormattedJSON (): User {
308 const videoQuotaUsed = this.get('videoQuotaUsed')
309 const videoQuotaUsedDaily = this.get('videoQuotaUsedDaily')
310
311 const json = {
312 id: this.id,
313 username: this.username,
314 email: this.email,
315 emailVerified: this.emailVerified,
316 nsfwPolicy: this.nsfwPolicy,
317 autoPlayVideo: this.autoPlayVideo,
318 role: this.role,
319 roleLabel: USER_ROLE_LABELS[ this.role ],
320 videoQuota: this.videoQuota,
321 videoQuotaDaily: this.videoQuotaDaily,
322 createdAt: this.createdAt,
323 blocked: this.blocked,
324 blockedReason: this.blockedReason,
325 account: this.Account.toFormattedJSON(),
326 videoChannels: [],
327 videoQuotaUsed: videoQuotaUsed !== undefined
328 ? parseInt(videoQuotaUsed, 10)
329 : undefined,
330 videoQuotaUsedDaily: videoQuotaUsedDaily !== undefined
331 ? parseInt(videoQuotaUsedDaily, 10)
332 : undefined
333 }
334
335 if (Array.isArray(this.Account.VideoChannels) === true) {
336 json.videoChannels = this.Account.VideoChannels
337 .map(c => c.toFormattedJSON())
338 .sort((v1, v2) => {
339 if (v1.createdAt < v2.createdAt) return -1
340 if (v1.createdAt === v2.createdAt) return 0
341
342 return 1
343 })
344 }
345
346 return json
347 }
348
349 async isAbleToUploadVideo (videoFile: { size: number }) {
350 if (this.videoQuota === -1 && this.videoQuotaDaily === -1) return Promise.resolve(true)
351
352 const [ totalBytes, totalBytesDaily ] = await Promise.all([
353 UserModel.getOriginalVideoFileTotalFromUser(this),
354 UserModel.getOriginalVideoFileTotalDailyFromUser(this)
355 ])
356
357 const uploadedTotal = videoFile.size + totalBytes
358 const uploadedDaily = videoFile.size + totalBytesDaily
359 if (this.videoQuotaDaily === -1) {
360 return uploadedTotal < this.videoQuota
361 }
362 if (this.videoQuota === -1) {
363 return uploadedDaily < this.videoQuotaDaily
364 }
365
366 return (uploadedTotal < this.videoQuota) &&
367 (uploadedDaily < this.videoQuotaDaily)
368 }
369
370 private static generateUserQuotaBaseSQL (where?: string) {
371 const andWhere = where ? 'AND ' + where : ''
372
373 return 'SELECT SUM("size") AS "total" ' +
374 'FROM (' +
375 'SELECT MAX("videoFile"."size") AS "size" FROM "videoFile" ' +
376 'INNER JOIN "video" ON "videoFile"."videoId" = "video"."id" ' +
377 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
378 'INNER JOIN "account" ON "videoChannel"."accountId" = "account"."id" ' +
379 'WHERE "account"."userId" = $userId ' + andWhere +
380 'GROUP BY "video"."id"' +
381 ') t'
382 }
383
384 private static getTotalRawQuery (query: string, userId: number) {
385 const options = {
386 bind: { userId },
387 type: Sequelize.QueryTypes.SELECT
388 }
389
390 return UserModel.sequelize.query(query, options)
391 .then(([ { total } ]) => {
392 if (total === null) return 0
393
394 return parseInt(total, 10)
395 })
396 }
397
398 static autocomplete (search: string) {
399 return UserModel.findAll({
400 where: {
401 username: {
402 [Sequelize.Op.like]: `%${search}%`
403 }
404 }
405 })
406 .then(u => u.map(u => u.username))
407 }
408 }