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'
12 User as UserServerModel,
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'
26 export class UserService {
27 static BASE_USERS_URL = environment.apiUrl + '/api/v1/users/'
29 private userCache: { [ id: number ]: Observable<UserServerModel> } = {}
31 private signupInThisSession = false
34 private authHttp: HttpClient,
35 private authService: AuthService,
36 private restExtractor: RestExtractor,
37 private restService: RestService,
38 private localStorageService: LocalStorageService,
39 private sessionStorageService: SessionStorageService
42 hasSignupInThisSession () {
43 return this.signupInThisSession
46 changePassword (currentPassword: string, newPassword: string) {
47 const url = UserService.BASE_USERS_URL + 'me'
48 const body: UserUpdateMe = {
53 return this.authHttp.put(url, body)
55 map(this.restExtractor.extractDataBool),
56 catchError(err => this.restExtractor.handleError(err))
60 changeEmail (password: string, newEmail: string) {
61 const url = UserService.BASE_USERS_URL + 'me'
62 const body: UserUpdateMe = {
63 currentPassword: password,
67 return this.authHttp.put(url, body)
69 map(this.restExtractor.extractDataBool),
70 catchError(err => this.restExtractor.handleError(err))
74 updateMyProfile (profile: UserUpdateMe) {
75 const url = UserService.BASE_USERS_URL + 'me'
77 return this.authHttp.put(url, profile)
79 map(this.restExtractor.extractDataBool),
80 catchError(err => this.restExtractor.handleError(err))
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
94 const obj = Object.keys(localStorageKeys)
95 .filter(key => key in profile)
96 .map(key => ([ localStorageKeys[key], profile[key] ]))
98 for (const [ key, value ] of obj) {
100 if (value === undefined) {
101 this.localStorageService.removeItem(key)
105 const localStorageValue = typeof value === 'string'
107 : JSON.stringify(value)
109 this.localStorageService.setItem(key, localStorageValue)
111 console.error(`Cannot set ${key}->${value} in localStorage. Likely due to a value impossible to stringify.`, err)
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
126 filter(() => this.authService.isLoggedIn() !== true),
127 map(() => this.getAnonymousUser())
132 const url = UserService.BASE_USERS_URL + 'me'
134 return this.authHttp.delete(url)
136 map(this.restExtractor.extractDataBool),
137 catchError(err => this.restExtractor.handleError(err))
141 changeAvatar (avatarForm: FormData) {
142 const url = UserService.BASE_USERS_URL + 'me/avatar/pick'
144 return this.authHttp.post<{ avatar: ActorImage }>(url, avatarForm)
145 .pipe(catchError(err => this.restExtractor.handleError(err)))
149 const url = UserService.BASE_USERS_URL + 'me/avatar'
151 return this.authHttp.delete(url)
153 map(this.restExtractor.extractDataBool),
154 catchError(err => this.restExtractor.handleError(err))
158 signup (userCreate: UserRegister) {
159 return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate)
161 map(this.restExtractor.extractDataBool),
162 tap(() => this.signupInThisSession = true),
163 catchError(err => this.restExtractor.handleError(err))
167 getMyVideoQuotaUsed () {
168 const url = UserService.BASE_USERS_URL + 'me/video-quota-used'
170 return this.authHttp.get<UserVideoQuota>(url)
171 .pipe(catchError(err => this.restExtractor.handleError(err)))
174 askResetPassword (email: string) {
175 const url = UserService.BASE_USERS_URL + '/ask-reset-password'
177 return this.authHttp.post(url, { email })
179 map(this.restExtractor.extractDataBool),
180 catchError(err => this.restExtractor.handleError(err))
184 resetPassword (userId: number, verificationString: string, password: string) {
185 const url = `${UserService.BASE_USERS_URL}/${userId}/reset-password`
191 return this.authHttp.post(url, body)
193 map(this.restExtractor.extractDataBool),
194 catchError(res => this.restExtractor.handleError(res))
198 verifyEmail (userId: number, verificationString: string, isPendingEmail: boolean) {
199 const url = `${UserService.BASE_USERS_URL}/${userId}/verify-email`
205 return this.authHttp.post(url, body)
207 map(this.restExtractor.extractDataBool),
208 catchError(res => this.restExtractor.handleError(res))
212 askSendVerifyEmail (email: string) {
213 const url = UserService.BASE_USERS_URL + '/ask-send-verify-email'
215 return this.authHttp.post(url, { email })
217 map(this.restExtractor.extractDataBool),
218 catchError(err => this.restExtractor.handleError(err))
222 autocomplete (search: string): Observable<string[]> {
223 const url = UserService.BASE_USERS_URL + 'autocomplete'
224 const params = new HttpParams().append('search', search)
227 .get<string[]>(url, { params })
228 .pipe(catchError(res => this.restExtractor.handleError(res)))
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
235 return this.displayNameToUsername(newDisplayName)
238 displayNameToUsername (displayName: string) {
239 if (!displayName) return ''
244 .replace(/[^a-z0-9_.]/g, '')
247 /* ###### Admin methods ###### */
249 addUser (userCreate: UserCreate) {
250 return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
252 map(this.restExtractor.extractDataBool),
253 catchError(err => this.restExtractor.handleError(err))
257 updateUser (userId: number, userUpdate: UserUpdate) {
258 return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
260 map(this.restExtractor.extractDataBool),
261 catchError(err => this.restExtractor.handleError(err))
265 updateUsers (users: UserServerModel[], userUpdate: UserUpdate) {
268 concatMap(u => this.authHttp.put(UserService.BASE_USERS_URL + u.id, userUpdate)),
270 catchError(err => this.restExtractor.handleError(err))
274 getUserWithCache (userId: number) {
275 if (!this.userCache[userId]) {
276 this.userCache[userId] = this.getUser(userId).pipe(shareReplay())
279 return this.userCache[userId]
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)))
288 getAnonymousUser () {
289 let videoLanguages: string[]
292 const languagesString = this.localStorageService.getItem(UserLocalStorageKeys.VIDEO_LANGUAGES)
293 videoLanguages = languagesString && languagesString !== 'undefined'
294 ? JSON.parse(languagesString)
297 videoLanguages = null
298 console.error('Cannot parse desired video languages from localStorage.', err)
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',
308 autoPlayNextVideoPlaylist: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false',
309 autoPlayVideo: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO) === 'true',
311 // session storage keys
312 autoPlayNextVideo: this.sessionStorageService.getItem(UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
316 getUsers (parameters: {
317 pagination: RestPagination
320 }): Observable<ResultList<UserServerModel>> {
321 const { pagination, sort, search } = parameters
323 let params = new HttpParams()
324 params = this.restService.addRestGetParams(params, pagination, sort)
327 const filters = this.restService.parseQueryStringFilter(search, {
334 params = this.restService.addObjectParams(params, filters)
337 return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params })
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))
345 removeUser (usersArg: UserServerModel | UserServerModel[]) {
346 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
350 concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
352 catchError(err => this.restExtractor.handleError(err))
356 banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) {
357 const body = reason ? { reason } : {}
358 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
362 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
364 catchError(err => this.restExtractor.handleError(err))
368 unbanUsers (usersArg: UserServerModel | UserServerModel[]) {
369 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
373 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
375 catchError(err => this.restExtractor.handleError(err))
379 getAnonymousOrLoggedUser () {
380 if (!this.authService.isLoggedIn()) {
381 return of(this.getAnonymousUser())
384 return this.authService.userInformationLoaded
387 map(() => this.authService.getUser())
391 private formatUser (user: UserServerModel) {
393 if (user.videoQuota === -1) {
396 videoQuota = getBytes(user.videoQuota, 0)
399 const videoQuotaUsed = getBytes(user.videoQuotaUsed, 0)
401 let videoQuotaDaily: string
402 let videoQuotaUsedDaily: string
403 if (user.videoQuotaDaily === -1) {
404 videoQuotaDaily = '∞'
405 videoQuotaUsedDaily = getBytes(0, 0) + ''
407 videoQuotaDaily = getBytes(user.videoQuotaDaily, 0) + ''
408 videoQuotaUsedDaily = getBytes(user.videoQuotaUsedDaily || 0, 0) + ''
411 const roleLabels: { [ id in UserRole ]: string } = {
412 [UserRole.USER]: $localize`User`,
413 [UserRole.ADMINISTRATOR]: $localize`Administrator`,
414 [UserRole.MODERATOR]: $localize`Moderator`
417 return Object.assign(user, {
418 roleLabel: roleLabels[user.role],
421 rawVideoQuota: user.videoQuota,
422 rawVideoQuotaUsed: user.videoQuotaUsed,
425 rawVideoQuotaDaily: user.videoQuotaDaily,
426 rawVideoQuotaUsedDaily: user.videoQuotaUsedDaily