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