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