]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/users/user.service.ts
Agnostic actor image storage
[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 handler: v => {
325 if (v === 'true') return v
326 if (v === 'false') return v
327
328 return undefined
329 }
330 }
331 })
332
333 params = this.restService.addObjectParams(params, filters)
334 }
335
336 return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params })
337 .pipe(
338 map(res => this.restExtractor.convertResultListDateToHuman(res)),
339 map(res => this.restExtractor.applyToResultListData(res, this.formatUser.bind(this))),
340 catchError(err => this.restExtractor.handleError(err))
341 )
342 }
343
344 removeUser (usersArg: UserServerModel | UserServerModel[]) {
345 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
346
347 return from(users)
348 .pipe(
349 concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
350 toArray(),
351 catchError(err => this.restExtractor.handleError(err))
352 )
353 }
354
355 banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) {
356 const body = reason ? { reason } : {}
357 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
358
359 return from(users)
360 .pipe(
361 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
362 toArray(),
363 catchError(err => this.restExtractor.handleError(err))
364 )
365 }
366
367 unbanUsers (usersArg: UserServerModel | UserServerModel[]) {
368 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
369
370 return from(users)
371 .pipe(
372 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
373 toArray(),
374 catchError(err => this.restExtractor.handleError(err))
375 )
376 }
377
378 getAnonymousOrLoggedUser () {
379 if (!this.authService.isLoggedIn()) {
380 return of(this.getAnonymousUser())
381 }
382
383 return this.authService.userInformationLoaded
384 .pipe(
385 first(),
386 map(() => this.authService.getUser())
387 )
388 }
389
390 private formatUser (user: UserServerModel) {
391 let videoQuota
392 if (user.videoQuota === -1) {
393 videoQuota = '∞'
394 } else {
395 videoQuota = getBytes(user.videoQuota, 0)
396 }
397
398 const videoQuotaUsed = getBytes(user.videoQuotaUsed, 0)
399
400 let videoQuotaDaily: string
401 let videoQuotaUsedDaily: string
402 if (user.videoQuotaDaily === -1) {
403 videoQuotaDaily = '∞'
404 videoQuotaUsedDaily = getBytes(0, 0) + ''
405 } else {
406 videoQuotaDaily = getBytes(user.videoQuotaDaily, 0) + ''
407 videoQuotaUsedDaily = getBytes(user.videoQuotaUsedDaily || 0, 0) + ''
408 }
409
410 const roleLabels: { [ id in UserRole ]: string } = {
411 [UserRole.USER]: $localize`User`,
412 [UserRole.ADMINISTRATOR]: $localize`Administrator`,
413 [UserRole.MODERATOR]: $localize`Moderator`
414 }
415
416 return Object.assign(user, {
417 roleLabel: roleLabels[user.role],
418 videoQuota,
419 videoQuotaUsed,
420 rawVideoQuota: user.videoQuota,
421 rawVideoQuotaUsed: user.videoQuotaUsed,
422 videoQuotaDaily,
423 videoQuotaUsedDaily,
424 rawVideoQuotaDaily: user.videoQuotaDaily,
425 rawVideoQuotaUsedDaily: user.videoQuotaUsedDaily
426 })
427 }
428 }