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