e24d91df3fcac9b814bc5135034d3acd81e483ee
[oweals/peertube.git] / client / src / app / shared / users / user.service.ts
1 import { from, Observable, of } from 'rxjs'
2 import { catchError, concatMap, map, share, shareReplay, tap, toArray } from 'rxjs/operators'
3 import { HttpClient, HttpParams } from '@angular/common/http'
4 import { Injectable } from '@angular/core'
5 import { ResultList, User, UserCreate, UserRole, UserUpdate, UserUpdateMe, UserVideoQuota } from '../../../../../shared'
6 import { environment } from '../../../environments/environment'
7 import { RestExtractor, RestPagination, RestService } from '../rest'
8 import { Avatar } from '../../../../../shared/models/avatars/avatar.model'
9 import { SortMeta } from 'primeng/api'
10 import { BytesPipe } from 'ngx-pipes'
11 import { I18n } from '@ngx-translate/i18n-polyfill'
12 import { UserRegister } from '@shared/models/users/user-register.model'
13
14 @Injectable()
15 export class UserService {
16   static BASE_USERS_URL = environment.apiUrl + '/api/v1/users/'
17
18   private bytesPipe = new BytesPipe()
19
20   private userCache: { [ id: number ]: Observable<User> } = {}
21
22   constructor (
23     private authHttp: HttpClient,
24     private restExtractor: RestExtractor,
25     private restService: RestService,
26     private i18n: I18n
27   ) { }
28
29   changePassword (currentPassword: string, newPassword: string) {
30     const url = UserService.BASE_USERS_URL + 'me'
31     const body: UserUpdateMe = {
32       currentPassword,
33       password: newPassword
34     }
35
36     return this.authHttp.put(url, body)
37                .pipe(
38                  map(this.restExtractor.extractDataBool),
39                  catchError(err => this.restExtractor.handleError(err))
40                )
41   }
42
43   changeEmail (password: string, newEmail: string) {
44     const url = UserService.BASE_USERS_URL + 'me'
45     const body: UserUpdateMe = {
46       currentPassword: password,
47       email: newEmail
48     }
49
50     return this.authHttp.put(url, body)
51                .pipe(
52                  map(this.restExtractor.extractDataBool),
53                  catchError(err => this.restExtractor.handleError(err))
54                )
55   }
56
57   updateMyProfile (profile: UserUpdateMe) {
58     const url = UserService.BASE_USERS_URL + 'me'
59
60     return this.authHttp.put(url, profile)
61                .pipe(
62                  map(this.restExtractor.extractDataBool),
63                  catchError(err => this.restExtractor.handleError(err))
64                )
65   }
66
67   deleteMe () {
68     const url = UserService.BASE_USERS_URL + 'me'
69
70     return this.authHttp.delete(url)
71                .pipe(
72                  map(this.restExtractor.extractDataBool),
73                  catchError(err => this.restExtractor.handleError(err))
74                )
75   }
76
77   changeAvatar (avatarForm: FormData) {
78     const url = UserService.BASE_USERS_URL + 'me/avatar/pick'
79
80     return this.authHttp.post<{ avatar: Avatar }>(url, avatarForm)
81                .pipe(catchError(err => this.restExtractor.handleError(err)))
82   }
83
84   signup (userCreate: UserRegister) {
85     return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate)
86                .pipe(
87                  map(this.restExtractor.extractDataBool),
88                  catchError(err => this.restExtractor.handleError(err))
89                )
90   }
91
92   getMyVideoQuotaUsed () {
93     const url = UserService.BASE_USERS_URL + 'me/video-quota-used'
94
95     return this.authHttp.get<UserVideoQuota>(url)
96                .pipe(catchError(err => this.restExtractor.handleError(err)))
97   }
98
99   askResetPassword (email: string) {
100     const url = UserService.BASE_USERS_URL + '/ask-reset-password'
101
102     return this.authHttp.post(url, { email })
103                .pipe(
104                  map(this.restExtractor.extractDataBool),
105                  catchError(err => this.restExtractor.handleError(err))
106                )
107   }
108
109   resetPassword (userId: number, verificationString: string, password: string) {
110     const url = `${UserService.BASE_USERS_URL}/${userId}/reset-password`
111     const body = {
112       verificationString,
113       password
114     }
115
116     return this.authHttp.post(url, body)
117                .pipe(
118                  map(this.restExtractor.extractDataBool),
119                  catchError(res => this.restExtractor.handleError(res))
120                )
121   }
122
123   verifyEmail (userId: number, verificationString: string, isPendingEmail: boolean) {
124     const url = `${UserService.BASE_USERS_URL}/${userId}/verify-email`
125     const body = {
126       verificationString,
127       isPendingEmail
128     }
129
130     return this.authHttp.post(url, body)
131                .pipe(
132                  map(this.restExtractor.extractDataBool),
133                  catchError(res => this.restExtractor.handleError(res))
134                )
135   }
136
137   askSendVerifyEmail (email: string) {
138     const url = UserService.BASE_USERS_URL + '/ask-send-verify-email'
139
140     return this.authHttp.post(url, { email })
141                .pipe(
142                  map(this.restExtractor.extractDataBool),
143                  catchError(err => this.restExtractor.handleError(err))
144                )
145   }
146
147   autocomplete (search: string): Observable<string[]> {
148     const url = UserService.BASE_USERS_URL + 'autocomplete'
149     const params = new HttpParams().append('search', search)
150
151     return this.authHttp
152       .get<string[]>(url, { params })
153       .pipe(catchError(res => this.restExtractor.handleError(res)))
154   }
155
156   getNewUsername (oldDisplayName: string, newDisplayName: string, currentUsername: string) {
157     // Don't update display name, the user seems to have changed it
158     if (this.displayNameToUsername(oldDisplayName) !== currentUsername) return currentUsername
159
160     return this.displayNameToUsername(newDisplayName)
161   }
162
163   displayNameToUsername (displayName: string) {
164     if (!displayName) return ''
165
166     return displayName
167       .toLowerCase()
168       .replace(/\s/g, '_')
169       .replace(/[^a-z0-9_.]/g, '')
170   }
171
172   /* ###### Admin methods ###### */
173
174   addUser (userCreate: UserCreate) {
175     return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
176                .pipe(
177                  map(this.restExtractor.extractDataBool),
178                  catchError(err => this.restExtractor.handleError(err))
179                )
180   }
181
182   updateUser (userId: number, userUpdate: UserUpdate) {
183     return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
184                .pipe(
185                  map(this.restExtractor.extractDataBool),
186                  catchError(err => this.restExtractor.handleError(err))
187                )
188   }
189
190   updateUsers (users: User[], userUpdate: UserUpdate) {
191     return from(users)
192       .pipe(
193         concatMap(u => this.authHttp.put(UserService.BASE_USERS_URL + u.id, userUpdate)),
194         toArray(),
195         catchError(err => this.restExtractor.handleError(err))
196       )
197   }
198
199   getUserWithCache (userId: number) {
200     if (!this.userCache[userId]) {
201       this.userCache[ userId ] = this.getUser(userId).pipe(shareReplay())
202     }
203
204     return this.userCache[userId]
205   }
206
207   getUser (userId: number) {
208     return this.authHttp.get<User>(UserService.BASE_USERS_URL + userId)
209                .pipe(catchError(err => this.restExtractor.handleError(err)))
210   }
211
212   getUsers (pagination: RestPagination, sort: SortMeta, search?: string): Observable<ResultList<User>> {
213     let params = new HttpParams()
214     params = this.restService.addRestGetParams(params, pagination, sort)
215
216     if (search) params = params.append('search', search)
217
218     return this.authHttp.get<ResultList<User>>(UserService.BASE_USERS_URL, { params })
219                .pipe(
220                  map(res => this.restExtractor.convertResultListDateToHuman(res)),
221                  map(res => this.restExtractor.applyToResultListData(res, this.formatUser.bind(this))),
222                  catchError(err => this.restExtractor.handleError(err))
223                )
224   }
225
226   removeUser (usersArg: User | User[]) {
227     const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
228
229     return from(users)
230       .pipe(
231         concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
232         toArray(),
233         catchError(err => this.restExtractor.handleError(err))
234       )
235   }
236
237   banUsers (usersArg: User | User[], reason?: string) {
238     const body = reason ? { reason } : {}
239     const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
240
241     return from(users)
242       .pipe(
243         concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
244         toArray(),
245         catchError(err => this.restExtractor.handleError(err))
246       )
247   }
248
249   unbanUsers (usersArg: User | User[]) {
250     const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
251
252     return from(users)
253       .pipe(
254         concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
255         toArray(),
256         catchError(err => this.restExtractor.handleError(err))
257       )
258   }
259
260   private formatUser (user: User) {
261     let videoQuota
262     if (user.videoQuota === -1) {
263       videoQuota = this.i18n('Unlimited')
264     } else {
265       videoQuota = this.bytesPipe.transform(user.videoQuota, 0)
266     }
267
268     const videoQuotaUsed = this.bytesPipe.transform(user.videoQuotaUsed, 0)
269
270     const roleLabels: { [ id in UserRole ]: string } = {
271       [UserRole.USER]: this.i18n('User'),
272       [UserRole.ADMINISTRATOR]: this.i18n('Administrator'),
273       [UserRole.MODERATOR]: this.i18n('Moderator')
274     }
275
276     return Object.assign(user, {
277       roleLabel: roleLabels[user.role],
278       videoQuota,
279       videoQuotaUsed
280     })
281   }
282 }