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