]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/account/user.ts
Fix tests
[github/Chocobozzz/PeerTube.git] / server / models / account / user.ts
CommitLineData
e02643f3 1import * as Sequelize from 'sequelize'
3fd3ab2d 2import {
a73c582e
C
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
3fd3ab2d 19} from 'sequelize-typescript'
e34c85e5 20import { hasUserRight, USER_ROLE_LABELS, UserRight } from '../../../shared'
ba75d268 21import { User, UserRole } from '../../../shared/models/users'
65fcc311 22import {
a73c582e 23 isUserAutoPlayVideoValid,
eacb25c4 24 isUserBlockedReasonValid,
e6921918 25 isUserBlockedValid,
0883b324 26 isUserNSFWPolicyValid,
a73c582e
C
27 isUserPasswordValid,
28 isUserRoleValid,
29 isUserUsernameValid,
50d6de9c 30 isUserVideoQuotaValid
3fd3ab2d 31} from '../../helpers/custom-validators/users'
da854ddd 32import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
3fd3ab2d
C
33import { OAuthTokenModel } from '../oauth/oauth-token'
34import { getSort, throwIfNotValid } from '../utils'
35import { VideoChannelModel } from '../video/video-channel'
36import { AccountModel } from './account'
0883b324
C
37import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
38import { values } from 'lodash'
39import { NSFW_POLICY_TYPES } from '../../initializers'
3fd3ab2d 40
9c2e0dbf
C
41enum ScopeNames {
42 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
43}
44
d48ff09d
C
45@DefaultScope({
46 include: [
47 {
48 model: () => AccountModel,
49 required: true
50 }
51 ]
52})
53@Scopes({
9c2e0dbf 54 [ScopeNames.WITH_VIDEO_CHANNEL]: {
d48ff09d
C
55 include: [
56 {
57 model: () => AccountModel,
58 required: true,
59 include: [ () => VideoChannelModel ]
60 }
61 ]
62 }
63})
3fd3ab2d
C
64@Table({
65 tableName: 'user',
66 indexes: [
feb4bdfd 67 {
3fd3ab2d
C
68 fields: [ 'username' ],
69 unique: true
feb4bdfd
C
70 },
71 {
3fd3ab2d
C
72 fields: [ 'email' ],
73 unique: true
feb4bdfd 74 }
e02643f3 75 ]
3fd3ab2d
C
76})
77export 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)
0883b324
C
95 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
96 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
97 nsfwPolicy: NSFWPolicyType
3fd3ab2d 98
7efe153b
AL
99 @AllowNull(false)
100 @Default(true)
101 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
102 @Column
103 autoPlayVideo: boolean
104
e6921918
C
105 @AllowNull(false)
106 @Default(false)
107 @Is('UserBlocked', value => throwIfNotValid(value, isUserBlockedValid, 'blocked boolean'))
108 @Column
109 blocked: boolean
110
eacb25c4
C
111 @AllowNull(true)
112 @Default(null)
113 @Is('UserBlockedReason', value => throwIfNotValid(value, isUserBlockedReasonValid, 'blocked reason'))
114 @Column
115 blockedReason: string
116
3fd3ab2d
C
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',
f05a1c30
C
135 onDelete: 'cascade',
136 hooks: true
3fd3ab2d
C
137 })
138 Account: AccountModel
69b0a27c 139
3fd3ab2d
C
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 }
59557c46 156 }
26d7d31b 157
3fd3ab2d
C
158 static countTotal () {
159 return this.count()
160 }
954605a8 161
3fd3ab2d
C
162 static listForApi (start: number, count: number, sort: string) {
163 const query = {
a76138ff
C
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 },
3fd3ab2d
C
183 offset: start,
184 limit: count,
6ff9c676 185 order: getSort(sort)
3fd3ab2d 186 }
72c7248b 187
3fd3ab2d
C
188 return UserModel.findAndCountAll(query)
189 .then(({ rows, count }) => {
a76138ff
C
190 console.log(rows[0])
191 console.log(rows[0]['videoQuotaUsed'])
192 console.log(rows[0].get('videoQuotaUsed'))
3fd3ab2d
C
193 return {
194 data: rows,
195 total: count
196 }
72c7248b 197 })
72c7248b
C
198 }
199
ba75d268
C
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
3fd3ab2d 221 static loadById (id: number) {
d48ff09d 222 return UserModel.findById(id)
3fd3ab2d 223 }
feb4bdfd 224
3fd3ab2d
C
225 static loadByUsername (username: string) {
226 const query = {
227 where: {
228 username
d48ff09d 229 }
3fd3ab2d 230 }
089ff2f2 231
3fd3ab2d 232 return UserModel.findOne(query)
feb4bdfd
C
233 }
234
3fd3ab2d
C
235 static loadByUsernameAndPopulateChannels (username: string) {
236 const query = {
237 where: {
238 username
d48ff09d 239 }
3fd3ab2d 240 }
9bd26629 241
9c2e0dbf 242 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
feb4bdfd
C
243 }
244
ecb4e35f
C
245 static loadByEmail (email: string) {
246 const query = {
247 where: {
248 email
249 }
250 }
251
252 return UserModel.findOne(query)
253 }
254
ba12e8b3
C
255 static loadByUsernameOrEmail (username: string, email?: string) {
256 if (!email) email = username
257
3fd3ab2d 258 const query = {
3fd3ab2d
C
259 where: {
260 [ Sequelize.Op.or ]: [ { username }, { email } ]
261 }
6fcd19ba 262 }
69b0a27c 263
d48ff09d 264 return UserModel.findOne(query)
72c7248b
C
265 }
266
ce5496d6 267 static getOriginalVideoFileTotalFromUser (user: UserModel) {
3fd3ab2d
C
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" ' +
a76138ff 274 'WHERE "account"."userId" = $userId GROUP BY "video"."id") t'
3fd3ab2d
C
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
68a3b9f2 283
3fd3ab2d
C
284 return parseInt(total, 10)
285 })
72c7248b
C
286 }
287
09cababd
C
288 static async getStats () {
289 const totalUsers = await UserModel.count()
290
291 return {
292 totalUsers
293 }
294 }
295
3fd3ab2d
C
296 hasRight (right: UserRight) {
297 return hasUserRight(this.role, right)
298 }
72c7248b 299
3fd3ab2d
C
300 isPasswordMatch (password: string) {
301 return comparePassword(password, this.password)
feb4bdfd
C
302 }
303
c5911fd3 304 toFormattedJSON (): User {
a76138ff
C
305 const videoQuotaUsed = this.get('videoQuotaUsed')
306
3fd3ab2d
C
307 const json = {
308 id: this.id,
309 username: this.username,
310 email: this.email,
0883b324 311 nsfwPolicy: this.nsfwPolicy,
7efe153b 312 autoPlayVideo: this.autoPlayVideo,
3fd3ab2d
C
313 role: this.role,
314 roleLabel: USER_ROLE_LABELS[ this.role ],
315 videoQuota: this.videoQuota,
316 createdAt: this.createdAt,
eacb25c4
C
317 blocked: this.blocked,
318 blockedReason: this.blockedReason,
c5911fd3 319 account: this.Account.toFormattedJSON(),
a76138ff
C
320 videoChannels: [],
321 videoQuotaUsed: videoQuotaUsed !== undefined ? parseInt(videoQuotaUsed, 10) : undefined
3fd3ab2d
C
322 }
323
324 if (Array.isArray(this.Account.VideoChannels) === true) {
c5911fd3 325 json.videoChannels = this.Account.VideoChannels
3fd3ab2d
C
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
ad4a8a1c 330
3fd3ab2d
C
331 return 1
332 })
ad4a8a1c 333 }
3fd3ab2d
C
334
335 return json
ad4a8a1c
C
336 }
337
a84b8fa5 338 isAbleToUploadVideo (videoFile: { size: number }) {
3fd3ab2d 339 if (this.videoQuota === -1) return Promise.resolve(true)
b0f9f39e 340
3fd3ab2d
C
341 return UserModel.getOriginalVideoFileTotalFromUser(this)
342 .then(totalBytes => {
343 return (videoFile.size + totalBytes) < this.videoQuota
344 })
b0f9f39e 345 }
b0f9f39e 346}