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