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