]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/user/user.ts
c1e7abea6cafcb19533a0ce157e1c71b95ed2aab
[github/Chocobozzz/PeerTube.git] / server / models / user / user.ts
1 import * as Sequelize from 'sequelize'
2 import * as Promise from 'bluebird'
3
4 import { getSort, addMethodsToModel } from '../utils'
5 import {
6 cryptPassword,
7 comparePassword,
8 isUserPasswordValid,
9 isUserUsernameValid,
10 isUserDisplayNSFWValid,
11 isUserVideoQuotaValid,
12 isUserRoleValid
13 } from '../../helpers'
14 import { UserRight, USER_ROLE_LABELS, hasUserRight } from '../../../shared'
15
16 import {
17 UserInstance,
18 UserAttributes,
19
20 UserMethods
21 } from './user-interface'
22
23 let User: Sequelize.Model<UserInstance, UserAttributes>
24 let isPasswordMatch: UserMethods.IsPasswordMatch
25 let hasRight: UserMethods.HasRight
26 let toFormattedJSON: UserMethods.ToFormattedJSON
27 let countTotal: UserMethods.CountTotal
28 let getByUsername: UserMethods.GetByUsername
29 let listForApi: UserMethods.ListForApi
30 let loadById: UserMethods.LoadById
31 let loadByUsername: UserMethods.LoadByUsername
32 let loadByUsernameAndPopulateChannels: UserMethods.LoadByUsernameAndPopulateChannels
33 let loadByUsernameOrEmail: UserMethods.LoadByUsernameOrEmail
34 let isAbleToUploadVideo: UserMethods.IsAbleToUploadVideo
35
36 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
37 User = sequelize.define<UserInstance, UserAttributes>('User',
38 {
39 password: {
40 type: DataTypes.STRING,
41 allowNull: false,
42 validate: {
43 passwordValid: value => {
44 const res = isUserPasswordValid(value)
45 if (res === false) throw new Error('Password not valid.')
46 }
47 }
48 },
49 username: {
50 type: DataTypes.STRING,
51 allowNull: false,
52 validate: {
53 usernameValid: value => {
54 const res = isUserUsernameValid(value)
55 if (res === false) throw new Error('Username not valid.')
56 }
57 }
58 },
59 email: {
60 type: DataTypes.STRING(400),
61 allowNull: false,
62 validate: {
63 isEmail: true
64 }
65 },
66 displayNSFW: {
67 type: DataTypes.BOOLEAN,
68 allowNull: false,
69 defaultValue: false,
70 validate: {
71 nsfwValid: value => {
72 const res = isUserDisplayNSFWValid(value)
73 if (res === false) throw new Error('Display NSFW is not valid.')
74 }
75 }
76 },
77 role: {
78 type: DataTypes.INTEGER,
79 allowNull: false,
80 validate: {
81 roleValid: value => {
82 const res = isUserRoleValid(value)
83 if (res === false) throw new Error('Role is not valid.')
84 }
85 }
86 },
87 videoQuota: {
88 type: DataTypes.BIGINT,
89 allowNull: false,
90 validate: {
91 videoQuotaValid: value => {
92 const res = isUserVideoQuotaValid(value)
93 if (res === false) throw new Error('Video quota is not valid.')
94 }
95 }
96 }
97 },
98 {
99 indexes: [
100 {
101 fields: [ 'username' ],
102 unique: true
103 },
104 {
105 fields: [ 'email' ],
106 unique: true
107 }
108 ],
109 hooks: {
110 beforeCreate: beforeCreateOrUpdate,
111 beforeUpdate: beforeCreateOrUpdate
112 }
113 }
114 )
115
116 const classMethods = [
117 associate,
118
119 countTotal,
120 getByUsername,
121 listForApi,
122 loadById,
123 loadByUsername,
124 loadByUsernameAndPopulateChannels,
125 loadByUsernameOrEmail
126 ]
127 const instanceMethods = [
128 hasRight,
129 isPasswordMatch,
130 toFormattedJSON,
131 isAbleToUploadVideo
132 ]
133 addMethodsToModel(User, classMethods, instanceMethods)
134
135 return User
136 }
137
138 function beforeCreateOrUpdate (user: UserInstance) {
139 return cryptPassword(user.password).then(hash => {
140 user.password = hash
141 return undefined
142 })
143 }
144
145 // ------------------------------ METHODS ------------------------------
146
147 hasRight = function (this: UserInstance, right: UserRight) {
148 return hasUserRight(this.role, right)
149 }
150
151 isPasswordMatch = function (this: UserInstance, password: string) {
152 return comparePassword(password, this.password)
153 }
154
155 toFormattedJSON = function (this: UserInstance) {
156 const json = {
157 id: this.id,
158 username: this.username,
159 email: this.email,
160 displayNSFW: this.displayNSFW,
161 role: this.role,
162 roleLabel: USER_ROLE_LABELS[this.role],
163 videoQuota: this.videoQuota,
164 createdAt: this.createdAt,
165 author: {
166 id: this.Author.id,
167 uuid: this.Author.uuid
168 }
169 }
170
171 if (Array.isArray(this.Author.VideoChannels) === true) {
172 const videoChannels = this.Author.VideoChannels
173 .map(c => c.toFormattedJSON())
174 .sort((v1, v2) => {
175 if (v1.createdAt < v2.createdAt) return -1
176 if (v1.createdAt === v2.createdAt) return 0
177
178 return 1
179 })
180
181 json['videoChannels'] = videoChannels
182 }
183
184 return json
185 }
186
187 isAbleToUploadVideo = function (this: UserInstance, videoFile: Express.Multer.File) {
188 if (this.videoQuota === -1) return Promise.resolve(true)
189
190 return getOriginalVideoFileTotalFromUser(this).then(totalBytes => {
191 return (videoFile.size + totalBytes) < this.videoQuota
192 })
193 }
194
195 // ------------------------------ STATICS ------------------------------
196
197 function associate (models) {
198 User.hasOne(models.Author, {
199 foreignKey: 'userId',
200 onDelete: 'cascade'
201 })
202
203 User.hasMany(models.OAuthToken, {
204 foreignKey: 'userId',
205 onDelete: 'cascade'
206 })
207 }
208
209 countTotal = function () {
210 return this.count()
211 }
212
213 getByUsername = function (username: string) {
214 const query = {
215 where: {
216 username: username
217 },
218 include: [ { model: User['sequelize'].models.Author, required: true } ]
219 }
220
221 return User.findOne(query)
222 }
223
224 listForApi = function (start: number, count: number, sort: string) {
225 const query = {
226 offset: start,
227 limit: count,
228 order: [ getSort(sort) ],
229 include: [ { model: User['sequelize'].models.Author, required: true } ]
230 }
231
232 return User.findAndCountAll(query).then(({ rows, count }) => {
233 return {
234 data: rows,
235 total: count
236 }
237 })
238 }
239
240 loadById = function (id: number) {
241 const options = {
242 include: [ { model: User['sequelize'].models.Author, required: true } ]
243 }
244
245 return User.findById(id, options)
246 }
247
248 loadByUsername = function (username: string) {
249 const query = {
250 where: {
251 username
252 },
253 include: [ { model: User['sequelize'].models.Author, required: true } ]
254 }
255
256 return User.findOne(query)
257 }
258
259 loadByUsernameAndPopulateChannels = function (username: string) {
260 const query = {
261 where: {
262 username
263 },
264 include: [
265 {
266 model: User['sequelize'].models.Author,
267 required: true,
268 include: [ User['sequelize'].models.VideoChannel ]
269 }
270 ]
271 }
272
273 return User.findOne(query)
274 }
275
276 loadByUsernameOrEmail = function (username: string, email: string) {
277 const query = {
278 include: [ { model: User['sequelize'].models.Author, required: true } ],
279 where: {
280 [Sequelize.Op.or]: [ { username }, { email } ]
281 }
282 }
283
284 // FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18387
285 return (User as any).findOne(query)
286 }
287
288 // ---------------------------------------------------------------------------
289
290 function getOriginalVideoFileTotalFromUser (user: UserInstance) {
291 // Don't use sequelize because we need to use a sub query
292 const query = 'SELECT SUM("size") AS "total" FROM ' +
293 '(SELECT MAX("VideoFiles"."size") AS "size" FROM "VideoFiles" ' +
294 'INNER JOIN "Videos" ON "VideoFiles"."videoId" = "Videos"."id" ' +
295 'INNER JOIN "VideoChannels" ON "VideoChannels"."id" = "Videos"."channelId" ' +
296 'INNER JOIN "Authors" ON "VideoChannels"."authorId" = "Authors"."id" ' +
297 'INNER JOIN "Users" ON "Authors"."userId" = "Users"."id" ' +
298 'WHERE "Users"."id" = $userId GROUP BY "Videos"."id") t'
299
300 const options = {
301 bind: { userId: user.id },
302 type: Sequelize.QueryTypes.SELECT
303 }
304 return User['sequelize'].query(query, options).then(([ { total } ]) => {
305 if (total === null) return 0
306
307 return parseInt(total, 10)
308 })
309 }