]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/users/user.service.ts
a8a774eca5811a21caea01354b6ea19fc8a762af
[github/Chocobozzz/PeerTube.git] / client / src / app / core / users / user.service.ts
1 import { SortMeta } from 'primeng/api'
2 import { from, Observable, of } from 'rxjs'
3 import { catchError, concatMap, filter, first, map, shareReplay, throttleTime, toArray } from 'rxjs/operators'
4 import { HttpClient, HttpParams } from '@angular/common/http'
5 import { Injectable } from '@angular/core'
6 import { AuthService } from '@app/core/auth'
7 import { getBytes } from '@root-helpers/bytes'
8 import { UserLocalStorageKeys } from '@root-helpers/users'
9 import {
10 ActorImage,
11 ResultList,
12 User as UserServerModel,
13 UserCreate,
14 UserRegister,
15 UserRole,
16 UserUpdate,
17 UserUpdateMe,
18 UserVideoQuota
19 } from '@shared/models'
20 import { environment } from '../../../environments/environment'
21 import { RestExtractor, RestPagination, RestService } from '../rest'
22 import { LocalStorageService, SessionStorageService } from '../wrappers/storage.service'
23 import { User } from './user.model'
24
25 @Injectable()
26 export class UserService {
27 static BASE_USERS_URL = environment.apiUrl + '/api/v1/users/'
28
29 private userCache: { [ id: number ]: Observable<UserServerModel> } = {}
30
31 constructor (
32 private authHttp: HttpClient,
33 private authService: AuthService,
34 private restExtractor: RestExtractor,
35 private restService: RestService,
36 private localStorageService: LocalStorageService,
37 private sessionStorageService: SessionStorageService
38 ) { }
39
40 changePassword (currentPassword: string, newPassword: string) {
41 const url = UserService.BASE_USERS_URL + 'me'
42 const body: UserUpdateMe = {
43 currentPassword,
44 password: newPassword
45 }
46
47 return this.authHttp.put(url, body)
48 .pipe(
49 map(this.restExtractor.extractDataBool),
50 catchError(err => this.restExtractor.handleError(err))
51 )
52 }
53
54 changeEmail (password: string, newEmail: string) {
55 const url = UserService.BASE_USERS_URL + 'me'
56 const body: UserUpdateMe = {
57 currentPassword: password,
58 email: newEmail
59 }
60
61 return this.authHttp.put(url, body)
62 .pipe(
63 map(this.restExtractor.extractDataBool),
64 catchError(err => this.restExtractor.handleError(err))
65 )
66 }
67
68 updateMyProfile (profile: UserUpdateMe) {
69 const url = UserService.BASE_USERS_URL + 'me'
70
71 return this.authHttp.put(url, profile)
72 .pipe(
73 map(this.restExtractor.extractDataBool),
74 catchError(err => this.restExtractor.handleError(err))
75 )
76 }
77
78 updateMyAnonymousProfile (profile: UserUpdateMe) {
79 const localStorageKeys: { [ id in keyof UserUpdateMe ]: string } = {
80 nsfwPolicy: UserLocalStorageKeys.NSFW_POLICY,
81 webTorrentEnabled: UserLocalStorageKeys.WEBTORRENT_ENABLED,
82 autoPlayNextVideo: UserLocalStorageKeys.AUTO_PLAY_VIDEO,
83 autoPlayNextVideoPlaylist: UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST,
84 theme: UserLocalStorageKeys.THEME,
85 videoLanguages: UserLocalStorageKeys.VIDEO_LANGUAGES
86 }
87
88 const obj = Object.keys(localStorageKeys)
89 .filter(key => key in profile)
90 .map(key => ([ localStorageKeys[key], profile[key] ]))
91
92 for (const [ key, value ] of obj) {
93 try {
94 if (value === undefined) {
95 this.localStorageService.removeItem(key)
96 continue
97 }
98
99 const localStorageValue = typeof value === 'string'
100 ? value
101 : JSON.stringify(value)
102
103 this.localStorageService.setItem(key, localStorageValue)
104 } catch (err) {
105 console.error(`Cannot set ${key}->${value} in localStorage. Likely due to a value impossible to stringify.`, err)
106 }
107 }
108 }
109
110 listenAnonymousUpdate () {
111 return this.localStorageService.watch([
112 UserLocalStorageKeys.NSFW_POLICY,
113 UserLocalStorageKeys.WEBTORRENT_ENABLED,
114 UserLocalStorageKeys.AUTO_PLAY_VIDEO,
115 UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST,
116 UserLocalStorageKeys.THEME,
117 UserLocalStorageKeys.VIDEO_LANGUAGES
118 ]).pipe(
119 throttleTime(200),
120 filter(() => this.authService.isLoggedIn() !== true),
121 map(() => this.getAnonymousUser())
122 )
123 }
124
125 deleteMe () {
126 const url = UserService.BASE_USERS_URL + 'me'
127
128 return this.authHttp.delete(url)
129 .pipe(
130 map(this.restExtractor.extractDataBool),
131 catchError(err => this.restExtractor.handleError(err))
132 )
133 }
134
135 changeAvatar (avatarForm: FormData) {
136 const url = UserService.BASE_USERS_URL + 'me/avatar/pick'
137
138 return this.authHttp.post<{ avatar: ActorImage }>(url, avatarForm)
139 .pipe(catchError(err => this.restExtractor.handleError(err)))
140 }
141
142 deleteAvatar () {
143 const url = UserService.BASE_USERS_URL + 'me/avatar'
144
145 return this.authHttp.delete(url)
146 .pipe(
147 map(this.restExtractor.extractDataBool),
148 catchError(err => this.restExtractor.handleError(err))
149 )
150 }
151
152 signup (userCreate: UserRegister) {
153 return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate)
154 .pipe(
155 map(this.restExtractor.extractDataBool),
156 catchError(err => this.restExtractor.handleError(err))
157 )
158 }
159
160 getMyVideoQuotaUsed () {
161 const url = UserService.BASE_USERS_URL + 'me/video-quota-used'
162
163 return this.authHttp.get<UserVideoQuota>(url)
164 .pipe(catchError(err => this.restExtractor.handleError(err)))
165 }
166
167 askResetPassword (email: string) {
168 const url = UserService.BASE_USERS_URL + '/ask-reset-password'
169
170 return this.authHttp.post(url, { email })
171 .pipe(
172 map(this.restExtractor.extractDataBool),
173 catchError(err => this.restExtractor.handleError(err))
174 )
175 }
176
177 resetPassword (userId: number, verificationString: string, password: string) {
178 const url = `${UserService.BASE_USERS_URL}/${userId}/reset-password`
179 const body = {
180 verificationString,
181 password
182 }
183
184 return this.authHttp.post(url, body)
185 .pipe(
186 map(this.restExtractor.extractDataBool),
187 catchError(res => this.restExtractor.handleError(res))
188 )
189 }
190
191 verifyEmail (userId: number, verificationString: string, isPendingEmail: boolean) {
192 const url = `${UserService.BASE_USERS_URL}/${userId}/verify-email`
193 const body = {
194 verificationString,
195 isPendingEmail
196 }
197
198 return this.authHttp.post(url, body)
199 .pipe(
200 map(this.restExtractor.extractDataBool),
201 catchError(res => this.restExtractor.handleError(res))
202 )
203 }
204
205 askSendVerifyEmail (email: string) {
206 const url = UserService.BASE_USERS_URL + '/ask-send-verify-email'
207
208 return this.authHttp.post(url, { email })
209 .pipe(
210 map(this.restExtractor.extractDataBool),
211 catchError(err => this.restExtractor.handleError(err))
212 )
213 }
214
215 autocomplete (search: string): Observable<string[]> {
216 const url = UserService.BASE_USERS_URL + 'autocomplete'
217 const params = new HttpParams().append('search', search)
218
219 return this.authHttp
220 .get<string[]>(url, { params })
221 .pipe(catchError(res => this.restExtractor.handleError(res)))
222 }
223
224 getNewUsername (oldDisplayName: string, newDisplayName: string, currentUsername: string) {
225 // Don't update display name, the user seems to have changed it
226 if (this.displayNameToUsername(oldDisplayName) !== currentUsername) return currentUsername
227
228 return this.displayNameToUsername(newDisplayName)
229 }
230
231 displayNameToUsername (displayName: string) {
232 if (!displayName) return ''
233
234 return displayName
235 .toLowerCase()
236 .replace(/\s/g, '_')
237 .replace(/[^a-z0-9_.]/g, '')
238 }
239
240 /* ###### Admin methods ###### */
241
242 addUser (userCreate: UserCreate) {
243 return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
244 .pipe(
245 map(this.restExtractor.extractDataBool),
246 catchError(err => this.restExtractor.handleError(err))
247 )
248 }
249
250 updateUser (userId: number, userUpdate: UserUpdate) {
251 return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
252 .pipe(
253 map(this.restExtractor.extractDataBool),
254 catchError(err => this.restExtractor.handleError(err))
255 )
256 }
257
258 updateUsers (users: UserServerModel[], userUpdate: UserUpdate) {
259 return from(users)
260 .pipe(
261 concatMap(u => this.authHttp.put(UserService.BASE_USERS_URL + u.id, userUpdate)),
262 toArray(),
263 catchError(err => this.restExtractor.handleError(err))
264 )
265 }
266
267 getUserWithCache (userId: number) {
268 if (!this.userCache[userId]) {
269 this.userCache[userId] = this.getUser(userId).pipe(shareReplay())
270 }
271
272 return this.userCache[userId]
273 }
274
275 getUser (userId: number, withStats = false) {
276 const params = new HttpParams().append('withStats', withStats + '')
277 return this.authHttp.get<UserServerModel>(UserService.BASE_USERS_URL + userId, { params })
278 .pipe(catchError(err => this.restExtractor.handleError(err)))
279 }
280
281 getAnonymousUser () {
282 let videoLanguages: string[]
283
284 try {
285 const languagesString = this.localStorageService.getItem(UserLocalStorageKeys.VIDEO_LANGUAGES)
286 videoLanguages = languagesString && languagesString !== 'undefined'
287 ? JSON.parse(languagesString)
288 : null
289 } catch (err) {
290 videoLanguages = null
291 console.error('Cannot parse desired video languages from localStorage.', err)
292 }
293
294 return new User({
295 // local storage keys
296 nsfwPolicy: this.localStorageService.getItem(UserLocalStorageKeys.NSFW_POLICY),
297 webTorrentEnabled: this.localStorageService.getItem(UserLocalStorageKeys.WEBTORRENT_ENABLED) !== 'false',
298 theme: this.localStorageService.getItem(UserLocalStorageKeys.THEME) || 'instance-default',
299 videoLanguages,
300
301 autoPlayNextVideoPlaylist: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false',
302 autoPlayVideo: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO) === 'true',
303
304 // session storage keys
305 autoPlayNextVideo: this.sessionStorageService.getItem(UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
306 })
307 }
308
309 getUsers (parameters: {
310 pagination: RestPagination
311 sort: SortMeta
312 search?: string
313 }): Observable<ResultList<UserServerModel>> {
314 const { pagination, sort, search } = parameters
315
316 let params = new HttpParams()
317 params = this.restService.addRestGetParams(params, pagination, sort)
318
319 if (search) {
320 const filters = this.restService.parseQueryStringFilter(search, {
321 blocked: {
322 prefix: 'banned:',
323 isBoolean: true
324 }
325 })
326
327 params = this.restService.addObjectParams(params, filters)
328 }
329
330 return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params })
331 .pipe(
332 map(res => this.restExtractor.convertResultListDateToHuman(res)),
333 map(res => this.restExtractor.applyToResultListData(res, this.formatUser.bind(this))),
334 catchError(err => this.restExtractor.handleError(err))
335 )
336 }
337
338 removeUser (usersArg: UserServerModel | UserServerModel[]) {
339 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
340
341 return from(users)
342 .pipe(
343 concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
344 toArray(),
345 catchError(err => this.restExtractor.handleError(err))
346 )
347 }
348
349 banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) {
350 const body = reason ? { reason } : {}
351 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
352
353 return from(users)
354 .pipe(
355 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
356 toArray(),
357 catchError(err => this.restExtractor.handleError(err))
358 )
359 }
360
361 unbanUsers (usersArg: UserServerModel | UserServerModel[]) {
362 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
363
364 return from(users)
365 .pipe(
366 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
367 toArray(),
368 catchError(err => this.restExtractor.handleError(err))
369 )
370 }
371
372 getAnonymousOrLoggedUser () {
373 if (!this.authService.isLoggedIn()) {
374 return of(this.getAnonymousUser())
375 }
376
377 return this.authService.userInformationLoaded
378 .pipe(
379 first(),
380 map(() => this.authService.getUser())
381 )
382 }
383
384 private formatUser (user: UserServerModel) {
385 let videoQuota
386 if (user.videoQuota === -1) {
387 videoQuota = '∞'
388 } else {
389 videoQuota = getBytes(user.videoQuota, 0)
390 }
391
392 const videoQuotaUsed = getBytes(user.videoQuotaUsed, 0)
393
394 let videoQuotaDaily: string
395 let videoQuotaUsedDaily: string
396 if (user.videoQuotaDaily === -1) {
397 videoQuotaDaily = '∞'
398 videoQuotaUsedDaily = getBytes(0, 0) + ''
399 } else {
400 videoQuotaDaily = getBytes(user.videoQuotaDaily, 0) + ''
401 videoQuotaUsedDaily = getBytes(user.videoQuotaUsedDaily || 0, 0) + ''
402 }
403
404 const roleLabels: { [ id in UserRole ]: string } = {
405 [UserRole.USER]: $localize`User`,
406 [UserRole.ADMINISTRATOR]: $localize`Administrator`,
407 [UserRole.MODERATOR]: $localize`Moderator`
408 }
409
410 return Object.assign(user, {
411 roleLabel: roleLabels[user.role],
412 videoQuota,
413 videoQuotaUsed,
414 rawVideoQuota: user.videoQuota,
415 rawVideoQuotaUsed: user.videoQuotaUsed,
416 videoQuotaDaily,
417 videoQuotaUsedDaily,
418 rawVideoQuotaDaily: user.videoQuotaDaily,
419 rawVideoQuotaUsedDaily: user.videoQuotaUsedDaily
420 })
421 }
422 }