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'
13 User as UserServerModel,
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'
27 export class UserService {
28 static BASE_USERS_URL = environment.apiUrl + '/api/v1/users/'
30 private bytesPipe = new BytesPipe()
32 private userCache: { [ id: number ]: Observable<UserServerModel> } = {}
35 private authHttp: HttpClient,
36 private authService: AuthService,
37 private restExtractor: RestExtractor,
38 private restService: RestService,
39 private localStorageService: LocalStorageService,
40 private sessionStorageService: SessionStorageService
43 changePassword (currentPassword: string, newPassword: string) {
44 const url = UserService.BASE_USERS_URL + 'me'
45 const body: UserUpdateMe = {
50 return this.authHttp.put(url, body)
52 map(this.restExtractor.extractDataBool),
53 catchError(err => this.restExtractor.handleError(err))
57 changeEmail (password: string, newEmail: string) {
58 const url = UserService.BASE_USERS_URL + 'me'
59 const body: UserUpdateMe = {
60 currentPassword: password,
64 return this.authHttp.put(url, body)
66 map(this.restExtractor.extractDataBool),
67 catchError(err => this.restExtractor.handleError(err))
71 updateMyProfile (profile: UserUpdateMe) {
72 const url = UserService.BASE_USERS_URL + 'me'
74 return this.authHttp.put(url, profile)
76 map(this.restExtractor.extractDataBool),
77 catchError(err => this.restExtractor.handleError(err))
81 updateMyAnonymousProfile (profile: UserUpdateMe) {
83 this.localStorageService.setItem(UserLocalStorageKeys.NSFW_POLICY, profile.nsfwPolicy)
84 this.localStorageService.setItem(UserLocalStorageKeys.WEBTORRENT_ENABLED, profile.webTorrentEnabled)
86 this.localStorageService.setItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO, profile.autoPlayNextVideo)
87 this.localStorageService.setItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST, profile.autoPlayNextVideoPlaylist)
89 this.localStorageService.setItem(UserLocalStorageKeys.THEME, profile.theme)
90 this.localStorageService.setItem(UserLocalStorageKeys.VIDEO_LANGUAGES, profile.videoLanguages)
92 console.error(`Cannot set item in localStorage. Likely due to a value impossible to stringify.`, err)
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
106 filter(() => this.authService.isLoggedIn() !== true),
107 map(() => this.getAnonymousUser())
112 const url = UserService.BASE_USERS_URL + 'me'
114 return this.authHttp.delete(url)
116 map(this.restExtractor.extractDataBool),
117 catchError(err => this.restExtractor.handleError(err))
121 changeAvatar (avatarForm: FormData) {
122 const url = UserService.BASE_USERS_URL + 'me/avatar/pick'
124 return this.authHttp.post<{ avatar: Avatar }>(url, avatarForm)
125 .pipe(catchError(err => this.restExtractor.handleError(err)))
128 signup (userCreate: UserRegister) {
129 return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate)
131 map(this.restExtractor.extractDataBool),
132 catchError(err => this.restExtractor.handleError(err))
136 getMyVideoQuotaUsed () {
137 const url = UserService.BASE_USERS_URL + 'me/video-quota-used'
139 return this.authHttp.get<UserVideoQuota>(url)
140 .pipe(catchError(err => this.restExtractor.handleError(err)))
143 askResetPassword (email: string) {
144 const url = UserService.BASE_USERS_URL + '/ask-reset-password'
146 return this.authHttp.post(url, { email })
148 map(this.restExtractor.extractDataBool),
149 catchError(err => this.restExtractor.handleError(err))
153 resetPassword (userId: number, verificationString: string, password: string) {
154 const url = `${UserService.BASE_USERS_URL}/${userId}/reset-password`
160 return this.authHttp.post(url, body)
162 map(this.restExtractor.extractDataBool),
163 catchError(res => this.restExtractor.handleError(res))
167 verifyEmail (userId: number, verificationString: string, isPendingEmail: boolean) {
168 const url = `${UserService.BASE_USERS_URL}/${userId}/verify-email`
174 return this.authHttp.post(url, body)
176 map(this.restExtractor.extractDataBool),
177 catchError(res => this.restExtractor.handleError(res))
181 askSendVerifyEmail (email: string) {
182 const url = UserService.BASE_USERS_URL + '/ask-send-verify-email'
184 return this.authHttp.post(url, { email })
186 map(this.restExtractor.extractDataBool),
187 catchError(err => this.restExtractor.handleError(err))
191 autocomplete (search: string): Observable<string[]> {
192 const url = UserService.BASE_USERS_URL + 'autocomplete'
193 const params = new HttpParams().append('search', search)
196 .get<string[]>(url, { params })
197 .pipe(catchError(res => this.restExtractor.handleError(res)))
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
204 return this.displayNameToUsername(newDisplayName)
207 displayNameToUsername (displayName: string) {
208 if (!displayName) return ''
213 .replace(/[^a-z0-9_.]/g, '')
216 /* ###### Admin methods ###### */
218 addUser (userCreate: UserCreate) {
219 return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
221 map(this.restExtractor.extractDataBool),
222 catchError(err => this.restExtractor.handleError(err))
226 updateUser (userId: number, userUpdate: UserUpdate) {
227 return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
229 map(this.restExtractor.extractDataBool),
230 catchError(err => this.restExtractor.handleError(err))
234 updateUsers (users: UserServerModel[], userUpdate: UserUpdate) {
237 concatMap(u => this.authHttp.put(UserService.BASE_USERS_URL + u.id, userUpdate)),
239 catchError(err => this.restExtractor.handleError(err))
243 getUserWithCache (userId: number) {
244 if (!this.userCache[userId]) {
245 this.userCache[ userId ] = this.getUser(userId).pipe(shareReplay())
248 return this.userCache[userId]
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)))
257 getAnonymousUser () {
258 let videoLanguages: string[]
261 videoLanguages = JSON.parse(this.localStorageService.getItem(UserLocalStorageKeys.VIDEO_LANGUAGES))
263 videoLanguages = null
264 console.error('Cannot parse desired video languages from localStorage.', err)
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',
274 autoPlayNextVideoPlaylist: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false',
275 autoPlayVideo: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO) === 'true',
277 // session storage keys
278 autoPlayNextVideo: this.sessionStorageService.getItem(UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
282 getUsers (parameters: {
283 pagination: RestPagination
286 }): Observable<ResultList<UserServerModel>> {
287 const { pagination, sort, search } = parameters
289 let params = new HttpParams()
290 params = this.restService.addRestGetParams(params, pagination, sort)
293 const filters = this.restService.parseQueryStringFilter(search, {
298 if (v === 'true') return v
299 if (v === 'false') return v
306 params = this.restService.addObjectParams(params, filters)
309 return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params })
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))
317 removeUser (usersArg: UserServerModel | UserServerModel[]) {
318 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
322 concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
324 catchError(err => this.restExtractor.handleError(err))
328 banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) {
329 const body = reason ? { reason } : {}
330 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
334 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
336 catchError(err => this.restExtractor.handleError(err))
340 unbanUsers (usersArg: UserServerModel | UserServerModel[]) {
341 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
345 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
347 catchError(err => this.restExtractor.handleError(err))
351 getAnonymousOrLoggedUser () {
352 if (!this.authService.isLoggedIn()) {
353 return of(this.getAnonymousUser())
356 return this.authService.userInformationLoaded
359 map(() => this.authService.getUser())
363 private formatUser (user: UserServerModel) {
365 if (user.videoQuota === -1) {
368 videoQuota = this.bytesPipe.transform(user.videoQuota, 0)
371 const videoQuotaUsed = this.bytesPipe.transform(user.videoQuotaUsed, 0)
373 let videoQuotaDaily: string
374 let videoQuotaUsedDaily: string
375 if (user.videoQuotaDaily === -1) {
376 videoQuotaDaily = '∞'
377 videoQuotaUsedDaily = this.bytesPipe.transform(0, 0) + ''
379 videoQuotaDaily = this.bytesPipe.transform(user.videoQuotaDaily, 0) + ''
380 videoQuotaUsedDaily = this.bytesPipe.transform(user.videoQuotaUsedDaily || 0, 0) + ''
383 const roleLabels: { [ id in UserRole ]: string } = {
384 [UserRole.USER]: $localize`User`,
385 [UserRole.ADMINISTRATOR]: $localize`Administrator`,
386 [UserRole.MODERATOR]: $localize`Moderator`
389 return Object.assign(user, {
390 roleLabel: roleLabels[user.role],
393 rawVideoQuota: user.videoQuota,
394 rawVideoQuotaUsed: user.videoQuotaUsed,
397 rawVideoQuotaDaily: user.videoQuotaDaily,
398 rawVideoQuotaUsedDaily: user.videoQuotaUsedDaily