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