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