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 { I18n } from '@ngx-translate/i18n-polyfill'
9 import { UserLocalStorageKeys } from '@root-helpers/users'
14 User as UserServerModel,
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'
28 export class UserService {
29 static BASE_USERS_URL = environment.apiUrl + '/api/v1/users/'
31 private bytesPipe = new BytesPipe()
33 private userCache: { [ id: number ]: Observable<UserServerModel> } = {}
36 private authHttp: HttpClient,
37 private authService: AuthService,
38 private restExtractor: RestExtractor,
39 private restService: RestService,
40 private localStorageService: LocalStorageService,
41 private sessionStorageService: SessionStorageService,
45 changePassword (currentPassword: string, newPassword: string) {
46 const url = UserService.BASE_USERS_URL + 'me'
47 const body: UserUpdateMe = {
52 return this.authHttp.put(url, body)
54 map(this.restExtractor.extractDataBool),
55 catchError(err => this.restExtractor.handleError(err))
59 changeEmail (password: string, newEmail: string) {
60 const url = UserService.BASE_USERS_URL + 'me'
61 const body: UserUpdateMe = {
62 currentPassword: password,
66 return this.authHttp.put(url, body)
68 map(this.restExtractor.extractDataBool),
69 catchError(err => this.restExtractor.handleError(err))
73 updateMyProfile (profile: UserUpdateMe) {
74 const url = UserService.BASE_USERS_URL + 'me'
76 return this.authHttp.put(url, profile)
78 map(this.restExtractor.extractDataBool),
79 catchError(err => this.restExtractor.handleError(err))
83 updateMyAnonymousProfile (profile: UserUpdateMe) {
85 this.localStorageService.setItem(UserLocalStorageKeys.NSFW_POLICY, profile.nsfwPolicy)
86 this.localStorageService.setItem(UserLocalStorageKeys.WEBTORRENT_ENABLED, profile.webTorrentEnabled)
88 this.localStorageService.setItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO, profile.autoPlayNextVideo)
89 this.localStorageService.setItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST, profile.autoPlayNextVideoPlaylist)
91 this.localStorageService.setItem(UserLocalStorageKeys.THEME, profile.theme)
92 this.localStorageService.setItem(UserLocalStorageKeys.VIDEO_LANGUAGES, profile.videoLanguages)
94 console.error(`Cannot set item in localStorage. Likely due to a value impossible to stringify.`, err)
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
108 filter(() => this.authService.isLoggedIn() !== true),
109 map(() => this.getAnonymousUser())
114 const url = UserService.BASE_USERS_URL + 'me'
116 return this.authHttp.delete(url)
118 map(this.restExtractor.extractDataBool),
119 catchError(err => this.restExtractor.handleError(err))
123 changeAvatar (avatarForm: FormData) {
124 const url = UserService.BASE_USERS_URL + 'me/avatar/pick'
126 return this.authHttp.post<{ avatar: Avatar }>(url, avatarForm)
127 .pipe(catchError(err => this.restExtractor.handleError(err)))
130 signup (userCreate: UserRegister) {
131 return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate)
133 map(this.restExtractor.extractDataBool),
134 catchError(err => this.restExtractor.handleError(err))
138 getMyVideoQuotaUsed () {
139 const url = UserService.BASE_USERS_URL + 'me/video-quota-used'
141 return this.authHttp.get<UserVideoQuota>(url)
142 .pipe(catchError(err => this.restExtractor.handleError(err)))
145 askResetPassword (email: string) {
146 const url = UserService.BASE_USERS_URL + '/ask-reset-password'
148 return this.authHttp.post(url, { email })
150 map(this.restExtractor.extractDataBool),
151 catchError(err => this.restExtractor.handleError(err))
155 resetPassword (userId: number, verificationString: string, password: string) {
156 const url = `${UserService.BASE_USERS_URL}/${userId}/reset-password`
162 return this.authHttp.post(url, body)
164 map(this.restExtractor.extractDataBool),
165 catchError(res => this.restExtractor.handleError(res))
169 verifyEmail (userId: number, verificationString: string, isPendingEmail: boolean) {
170 const url = `${UserService.BASE_USERS_URL}/${userId}/verify-email`
176 return this.authHttp.post(url, body)
178 map(this.restExtractor.extractDataBool),
179 catchError(res => this.restExtractor.handleError(res))
183 askSendVerifyEmail (email: string) {
184 const url = UserService.BASE_USERS_URL + '/ask-send-verify-email'
186 return this.authHttp.post(url, { email })
188 map(this.restExtractor.extractDataBool),
189 catchError(err => this.restExtractor.handleError(err))
193 autocomplete (search: string): Observable<string[]> {
194 const url = UserService.BASE_USERS_URL + 'autocomplete'
195 const params = new HttpParams().append('search', search)
198 .get<string[]>(url, { params })
199 .pipe(catchError(res => this.restExtractor.handleError(res)))
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
206 return this.displayNameToUsername(newDisplayName)
209 displayNameToUsername (displayName: string) {
210 if (!displayName) return ''
215 .replace(/[^a-z0-9_.]/g, '')
218 /* ###### Admin methods ###### */
220 addUser (userCreate: UserCreate) {
221 return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
223 map(this.restExtractor.extractDataBool),
224 catchError(err => this.restExtractor.handleError(err))
228 updateUser (userId: number, userUpdate: UserUpdate) {
229 return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
231 map(this.restExtractor.extractDataBool),
232 catchError(err => this.restExtractor.handleError(err))
236 updateUsers (users: UserServerModel[], userUpdate: UserUpdate) {
239 concatMap(u => this.authHttp.put(UserService.BASE_USERS_URL + u.id, userUpdate)),
241 catchError(err => this.restExtractor.handleError(err))
245 getUserWithCache (userId: number) {
246 if (!this.userCache[userId]) {
247 this.userCache[ userId ] = this.getUser(userId).pipe(shareReplay())
250 return this.userCache[userId]
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)))
259 getAnonymousUser () {
260 let videoLanguages: string[]
263 videoLanguages = JSON.parse(this.localStorageService.getItem(UserLocalStorageKeys.VIDEO_LANGUAGES))
265 videoLanguages = null
266 console.error('Cannot parse desired video languages from localStorage.', err)
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',
276 autoPlayNextVideoPlaylist: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false',
277 autoPlayVideo: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO) === 'true',
279 // session storage keys
280 autoPlayNextVideo: this.sessionStorageService.getItem(UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
284 getUsers (parameters: {
285 pagination: RestPagination
288 }): Observable<ResultList<UserServerModel>> {
289 const { pagination, sort, search } = parameters
291 let params = new HttpParams()
292 params = this.restService.addRestGetParams(params, pagination, sort)
295 const filters = this.restService.parseQueryStringFilter(search, {
300 if (v === 'true') return v
301 if (v === 'false') return v
308 params = this.restService.addObjectParams(params, filters)
311 return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params })
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))
319 removeUser (usersArg: UserServerModel | UserServerModel[]) {
320 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
324 concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
326 catchError(err => this.restExtractor.handleError(err))
330 banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) {
331 const body = reason ? { reason } : {}
332 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
336 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
338 catchError(err => this.restExtractor.handleError(err))
342 unbanUsers (usersArg: UserServerModel | UserServerModel[]) {
343 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
347 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
349 catchError(err => this.restExtractor.handleError(err))
353 getAnonymousOrLoggedUser () {
354 if (!this.authService.isLoggedIn()) {
355 return of(this.getAnonymousUser())
358 return this.authService.userInformationLoaded
361 map(() => this.authService.getUser())
365 private formatUser (user: UserServerModel) {
367 if (user.videoQuota === -1) {
370 videoQuota = this.bytesPipe.transform(user.videoQuota, 0)
373 const videoQuotaUsed = this.bytesPipe.transform(user.videoQuotaUsed, 0)
375 let videoQuotaDaily: string
376 let videoQuotaUsedDaily: string
377 if (user.videoQuotaDaily === -1) {
378 videoQuotaDaily = '∞'
379 videoQuotaUsedDaily = this.bytesPipe.transform(0, 0) + ''
381 videoQuotaDaily = this.bytesPipe.transform(user.videoQuotaDaily, 0) + ''
382 videoQuotaUsedDaily = this.bytesPipe.transform(user.videoQuotaUsedDaily || 0, 0) + ''
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')
391 return Object.assign(user, {
392 roleLabel: roleLabels[user.role],
395 rawVideoQuota: user.videoQuota,
396 rawVideoQuotaUsed: user.videoQuotaUsed,
399 rawVideoQuotaDaily: user.videoQuotaDaily,
400 rawVideoQuotaUsedDaily: user.videoQuotaUsedDaily