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