]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/user.ts
Update iso639 translations for french and deutch
[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 isUserNSFWPolicyValid,
25 isUserPasswordValid,
26 isUserRoleValid,
27 isUserUsernameValid,
28 isUserVideoQuotaValid
29 } from '../../helpers/custom-validators/users'
30 import { comparePassword, cryptPassword } from '../../helpers/peertube-crypto'
31 import { OAuthTokenModel } from '../oauth/oauth-token'
32 import { getSort, throwIfNotValid } from '../utils'
33 import { VideoChannelModel } from '../video/video-channel'
34 import { AccountModel } from './account'
35 import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
36 import { values } from 'lodash'
37 import { NSFW_POLICY_TYPES } from '../../initializers'
38
39 enum ScopeNames {
40 WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
41 }
42
43 @DefaultScope({
44 include: [
45 {
46 model: () => AccountModel,
47 required: true
48 }
49 ]
50 })
51 @Scopes({
52 [ScopeNames.WITH_VIDEO_CHANNEL]: {
53 include: [
54 {
55 model: () => AccountModel,
56 required: true,
57 include: [ () => VideoChannelModel ]
58 }
59 ]
60 }
61 })
62 @Table({
63 tableName: 'user',
64 indexes: [
65 {
66 fields: [ 'username' ],
67 unique: true
68 },
69 {
70 fields: [ 'email' ],
71 unique: true
72 }
73 ]
74 })
75 export 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)
93 @Is('UserNSFWPolicy', value => throwIfNotValid(value, isUserNSFWPolicyValid, 'NSFW policy'))
94 @Column(DataType.ENUM(values(NSFW_POLICY_TYPES)))
95 nsfwPolicy: NSFWPolicyType
96
97 @AllowNull(false)
98 @Default(true)
99 @Is('UserAutoPlayVideo', value => throwIfNotValid(value, isUserAutoPlayVideoValid, 'auto play video boolean'))
100 @Column
101 autoPlayVideo: boolean
102
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',
121 onDelete: 'cascade',
122 hooks: true
123 })
124 Account: AccountModel
125
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 }
142 }
143
144 static countTotal () {
145 return this.count()
146 }
147
148 static listForApi (start: number, count: number, sort: string) {
149 const query = {
150 offset: start,
151 limit: count,
152 order: getSort(sort)
153 }
154
155 return UserModel.findAndCountAll(query)
156 .then(({ rows, count }) => {
157 return {
158 data: rows,
159 total: count
160 }
161 })
162 }
163
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
185 static loadById (id: number) {
186 return UserModel.findById(id)
187 }
188
189 static loadByUsername (username: string) {
190 const query = {
191 where: {
192 username
193 }
194 }
195
196 return UserModel.findOne(query)
197 }
198
199 static loadByUsernameAndPopulateChannels (username: string) {
200 const query = {
201 where: {
202 username
203 }
204 }
205
206 return UserModel.scope(ScopeNames.WITH_VIDEO_CHANNEL).findOne(query)
207 }
208
209 static loadByEmail (email: string) {
210 const query = {
211 where: {
212 email
213 }
214 }
215
216 return UserModel.findOne(query)
217 }
218
219 static loadByUsernameOrEmail (username: string, email?: string) {
220 if (!email) email = username
221
222 const query = {
223 where: {
224 [ Sequelize.Op.or ]: [ { username }, { email } ]
225 }
226 }
227
228 return UserModel.findOne(query)
229 }
230
231 static getOriginalVideoFileTotalFromUser (user: UserModel) {
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
248
249 return parseInt(total, 10)
250 })
251 }
252
253 static async getStats () {
254 const totalUsers = await UserModel.count()
255
256 return {
257 totalUsers
258 }
259 }
260
261 hasRight (right: UserRight) {
262 return hasUserRight(this.role, right)
263 }
264
265 isPasswordMatch (password: string) {
266 return comparePassword(password, this.password)
267 }
268
269 toFormattedJSON (): User {
270 const json = {
271 id: this.id,
272 username: this.username,
273 email: this.email,
274 nsfwPolicy: this.nsfwPolicy,
275 autoPlayVideo: this.autoPlayVideo,
276 role: this.role,
277 roleLabel: USER_ROLE_LABELS[ this.role ],
278 videoQuota: this.videoQuota,
279 createdAt: this.createdAt,
280 account: this.Account.toFormattedJSON(),
281 videoChannels: []
282 }
283
284 if (Array.isArray(this.Account.VideoChannels) === true) {
285 json.videoChannels = this.Account.VideoChannels
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
290
291 return 1
292 })
293 }
294
295 return json
296 }
297
298 isAbleToUploadVideo (videoFile: Express.Multer.File) {
299 if (this.videoQuota === -1) return Promise.resolve(true)
300
301 return UserModel.getOriginalVideoFileTotalFromUser(this)
302 .then(totalBytes => {
303 return (videoFile.size + totalBytes) < this.videoQuota
304 })
305 }
306 }