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 { 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> } = {}
32 private authHttp: HttpClient,
33 private authService: AuthService,
34 private restExtractor: RestExtractor,
35 private restService: RestService,
36 private localStorageService: LocalStorageService,
37 private sessionStorageService: SessionStorageService
40 changePassword (currentPassword: string, newPassword: string) {
41 const url = UserService.BASE_USERS_URL + 'me'
42 const body: UserUpdateMe = {
47 return this.authHttp.put(url, body)
49 map(this.restExtractor.extractDataBool),
50 catchError(err => this.restExtractor.handleError(err))
54 changeEmail (password: string, newEmail: string) {
55 const url = UserService.BASE_USERS_URL + 'me'
56 const body: UserUpdateMe = {
57 currentPassword: password,
61 return this.authHttp.put(url, body)
63 map(this.restExtractor.extractDataBool),
64 catchError(err => this.restExtractor.handleError(err))
68 updateMyProfile (profile: UserUpdateMe) {
69 const url = UserService.BASE_USERS_URL + 'me'
71 return this.authHttp.put(url, profile)
73 map(this.restExtractor.extractDataBool),
74 catchError(err => this.restExtractor.handleError(err))
78 updateMyAnonymousProfile (profile: UserUpdateMe) {
79 const localStorageKeys: { [ id in keyof UserUpdateMe ]: string } = {
80 nsfwPolicy: UserLocalStorageKeys.NSFW_POLICY,
81 webTorrentEnabled: UserLocalStorageKeys.WEBTORRENT_ENABLED,
82 autoPlayNextVideo: UserLocalStorageKeys.AUTO_PLAY_VIDEO,
83 autoPlayNextVideoPlaylist: UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST,
84 theme: UserLocalStorageKeys.THEME,
85 videoLanguages: UserLocalStorageKeys.VIDEO_LANGUAGES
88 const obj = Object.keys(localStorageKeys)
89 .filter(key => key in profile)
90 .map(key => ([ localStorageKeys[key], profile[key] ]))
92 for (const [ key, value ] of obj) {
94 if (value === undefined) {
95 this.localStorageService.removeItem(key)
99 const localStorageValue = typeof value === 'string'
101 : JSON.stringify(value)
103 this.localStorageService.setItem(key, localStorageValue)
105 console.error(`Cannot set ${key}->${value} in localStorage. Likely due to a value impossible to stringify.`, err)
110 listenAnonymousUpdate () {
111 return this.localStorageService.watch([
112 UserLocalStorageKeys.NSFW_POLICY,
113 UserLocalStorageKeys.WEBTORRENT_ENABLED,
114 UserLocalStorageKeys.AUTO_PLAY_VIDEO,
115 UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST,
116 UserLocalStorageKeys.THEME,
117 UserLocalStorageKeys.VIDEO_LANGUAGES
120 filter(() => this.authService.isLoggedIn() !== true),
121 map(() => this.getAnonymousUser())
126 const url = UserService.BASE_USERS_URL + 'me'
128 return this.authHttp.delete(url)
130 map(this.restExtractor.extractDataBool),
131 catchError(err => this.restExtractor.handleError(err))
135 changeAvatar (avatarForm: FormData) {
136 const url = UserService.BASE_USERS_URL + 'me/avatar/pick'
138 return this.authHttp.post<{ avatar: ActorImage }>(url, avatarForm)
139 .pipe(catchError(err => this.restExtractor.handleError(err)))
143 const url = UserService.BASE_USERS_URL + 'me/avatar'
145 return this.authHttp.delete(url)
147 map(this.restExtractor.extractDataBool),
148 catchError(err => this.restExtractor.handleError(err))
152 signup (userCreate: UserRegister) {
153 return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate)
155 map(this.restExtractor.extractDataBool),
156 catchError(err => this.restExtractor.handleError(err))
160 getMyVideoQuotaUsed () {
161 const url = UserService.BASE_USERS_URL + 'me/video-quota-used'
163 return this.authHttp.get<UserVideoQuota>(url)
164 .pipe(catchError(err => this.restExtractor.handleError(err)))
167 askResetPassword (email: string) {
168 const url = UserService.BASE_USERS_URL + '/ask-reset-password'
170 return this.authHttp.post(url, { email })
172 map(this.restExtractor.extractDataBool),
173 catchError(err => this.restExtractor.handleError(err))
177 resetPassword (userId: number, verificationString: string, password: string) {
178 const url = `${UserService.BASE_USERS_URL}/${userId}/reset-password`
184 return this.authHttp.post(url, body)
186 map(this.restExtractor.extractDataBool),
187 catchError(res => this.restExtractor.handleError(res))
191 verifyEmail (userId: number, verificationString: string, isPendingEmail: boolean) {
192 const url = `${UserService.BASE_USERS_URL}/${userId}/verify-email`
198 return this.authHttp.post(url, body)
200 map(this.restExtractor.extractDataBool),
201 catchError(res => this.restExtractor.handleError(res))
205 askSendVerifyEmail (email: string) {
206 const url = UserService.BASE_USERS_URL + '/ask-send-verify-email'
208 return this.authHttp.post(url, { email })
210 map(this.restExtractor.extractDataBool),
211 catchError(err => this.restExtractor.handleError(err))
215 autocomplete (search: string): Observable<string[]> {
216 const url = UserService.BASE_USERS_URL + 'autocomplete'
217 const params = new HttpParams().append('search', search)
220 .get<string[]>(url, { params })
221 .pipe(catchError(res => this.restExtractor.handleError(res)))
224 getNewUsername (oldDisplayName: string, newDisplayName: string, currentUsername: string) {
225 // Don't update display name, the user seems to have changed it
226 if (this.displayNameToUsername(oldDisplayName) !== currentUsername) return currentUsername
228 return this.displayNameToUsername(newDisplayName)
231 displayNameToUsername (displayName: string) {
232 if (!displayName) return ''
237 .replace(/[^a-z0-9_.]/g, '')
240 /* ###### Admin methods ###### */
242 addUser (userCreate: UserCreate) {
243 return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
245 map(this.restExtractor.extractDataBool),
246 catchError(err => this.restExtractor.handleError(err))
250 updateUser (userId: number, userUpdate: UserUpdate) {
251 return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
253 map(this.restExtractor.extractDataBool),
254 catchError(err => this.restExtractor.handleError(err))
258 updateUsers (users: UserServerModel[], userUpdate: UserUpdate) {
261 concatMap(u => this.authHttp.put(UserService.BASE_USERS_URL + u.id, userUpdate)),
263 catchError(err => this.restExtractor.handleError(err))
267 getUserWithCache (userId: number) {
268 if (!this.userCache[userId]) {
269 this.userCache[userId] = this.getUser(userId).pipe(shareReplay())
272 return this.userCache[userId]
275 getUser (userId: number, withStats = false) {
276 const params = new HttpParams().append('withStats', withStats + '')
277 return this.authHttp.get<UserServerModel>(UserService.BASE_USERS_URL + userId, { params })
278 .pipe(catchError(err => this.restExtractor.handleError(err)))
281 getAnonymousUser () {
282 let videoLanguages: string[]
285 const languagesString = this.localStorageService.getItem(UserLocalStorageKeys.VIDEO_LANGUAGES)
286 videoLanguages = languagesString && languagesString !== 'undefined'
287 ? JSON.parse(languagesString)
290 videoLanguages = null
291 console.error('Cannot parse desired video languages from localStorage.', err)
295 // local storage keys
296 nsfwPolicy: this.localStorageService.getItem(UserLocalStorageKeys.NSFW_POLICY),
297 webTorrentEnabled: this.localStorageService.getItem(UserLocalStorageKeys.WEBTORRENT_ENABLED) !== 'false',
298 theme: this.localStorageService.getItem(UserLocalStorageKeys.THEME) || 'instance-default',
301 autoPlayNextVideoPlaylist: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false',
302 autoPlayVideo: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO) === 'true',
304 // session storage keys
305 autoPlayNextVideo: this.sessionStorageService.getItem(UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
309 getUsers (parameters: {
310 pagination: RestPagination
313 }): Observable<ResultList<UserServerModel>> {
314 const { pagination, sort, search } = parameters
316 let params = new HttpParams()
317 params = this.restService.addRestGetParams(params, pagination, sort)
320 const filters = this.restService.parseQueryStringFilter(search, {
327 params = this.restService.addObjectParams(params, filters)
330 return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params })
332 map(res => this.restExtractor.convertResultListDateToHuman(res)),
333 map(res => this.restExtractor.applyToResultListData(res, this.formatUser.bind(this))),
334 catchError(err => this.restExtractor.handleError(err))
338 removeUser (usersArg: UserServerModel | UserServerModel[]) {
339 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
343 concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
345 catchError(err => this.restExtractor.handleError(err))
349 banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) {
350 const body = reason ? { reason } : {}
351 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
355 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
357 catchError(err => this.restExtractor.handleError(err))
361 unbanUsers (usersArg: UserServerModel | UserServerModel[]) {
362 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
366 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
368 catchError(err => this.restExtractor.handleError(err))
372 getAnonymousOrLoggedUser () {
373 if (!this.authService.isLoggedIn()) {
374 return of(this.getAnonymousUser())
377 return this.authService.userInformationLoaded
380 map(() => this.authService.getUser())
384 private formatUser (user: UserServerModel) {
386 if (user.videoQuota === -1) {
389 videoQuota = getBytes(user.videoQuota, 0)
392 const videoQuotaUsed = getBytes(user.videoQuotaUsed, 0)
394 let videoQuotaDaily: string
395 let videoQuotaUsedDaily: string
396 if (user.videoQuotaDaily === -1) {
397 videoQuotaDaily = '∞'
398 videoQuotaUsedDaily = getBytes(0, 0) + ''
400 videoQuotaDaily = getBytes(user.videoQuotaDaily, 0) + ''
401 videoQuotaUsedDaily = getBytes(user.videoQuotaUsedDaily || 0, 0) + ''
404 const roleLabels: { [ id in UserRole ]: string } = {
405 [UserRole.USER]: $localize`User`,
406 [UserRole.ADMINISTRATOR]: $localize`Administrator`,
407 [UserRole.MODERATOR]: $localize`Moderator`
410 return Object.assign(user, {
411 roleLabel: roleLabels[user.role],
414 rawVideoQuota: user.videoQuota,
415 rawVideoQuotaUsed: user.videoQuotaUsed,
418 rawVideoQuotaDaily: user.videoQuotaDaily,
419 rawVideoQuotaUsedDaily: user.videoQuotaUsedDaily