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 { 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'
27 export class UserService {
28 static BASE_USERS_URL = environment.apiUrl + '/api/v1/users/'
30 private userCache: { [ id: number ]: Observable<UserServerModel> } = {}
32 private signupInThisSession = false
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
44 hasSignupInThisSession () {
45 return this.signupInThisSession
48 changePassword (currentPassword: string, newPassword: string) {
49 const url = UserService.BASE_USERS_URL + 'me'
50 const body: UserUpdateMe = {
55 return this.authHttp.put(url, body)
57 map(this.restExtractor.extractDataBool),
58 catchError(err => this.restExtractor.handleError(err))
62 changeEmail (password: string, newEmail: string) {
63 const url = UserService.BASE_USERS_URL + 'me'
64 const body: UserUpdateMe = {
65 currentPassword: password,
69 return this.authHttp.put(url, body)
71 map(this.restExtractor.extractDataBool),
72 catchError(err => this.restExtractor.handleError(err))
76 updateMyProfile (profile: UserUpdateMe) {
77 const url = UserService.BASE_USERS_URL + 'me'
79 return this.authHttp.put(url, profile)
81 map(this.restExtractor.extractDataBool),
82 catchError(err => this.restExtractor.handleError(err))
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
96 const obj = Object.keys(localStorageKeys)
97 .filter(key => key in profile)
98 .map(key => ([ localStorageKeys[key], profile[key] ]))
100 for (const [ key, value ] of obj) {
102 if (value === undefined) {
103 this.localStorageService.removeItem(key)
107 const localStorageValue = typeof value === 'string'
109 : JSON.stringify(value)
111 this.localStorageService.setItem(key, localStorageValue)
113 console.error(`Cannot set ${key}->${value} in localStorage. Likely due to a value impossible to stringify.`, err)
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
128 filter(() => this.authService.isLoggedIn() !== true),
129 map(() => this.getAnonymousUser())
134 const url = UserService.BASE_USERS_URL + 'me'
136 return this.authHttp.delete(url)
138 map(this.restExtractor.extractDataBool),
139 catchError(err => this.restExtractor.handleError(err))
143 changeAvatar (avatarForm: FormData) {
144 const url = UserService.BASE_USERS_URL + 'me/avatar/pick'
146 return this.authHttp.post<{ avatar: ActorImage }>(url, avatarForm)
147 .pipe(catchError(err => this.restExtractor.handleError(err)))
151 const url = UserService.BASE_USERS_URL + 'me/avatar'
153 return this.authHttp.delete(url)
155 map(this.restExtractor.extractDataBool),
156 catchError(err => this.restExtractor.handleError(err))
160 signup (userCreate: UserRegister) {
161 return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate)
163 map(this.restExtractor.extractDataBool),
164 tap(() => this.signupInThisSession = true),
165 catchError(err => this.restExtractor.handleError(err))
169 getMyVideoQuotaUsed () {
170 const url = UserService.BASE_USERS_URL + 'me/video-quota-used'
172 return this.authHttp.get<UserVideoQuota>(url)
173 .pipe(catchError(err => this.restExtractor.handleError(err)))
176 askResetPassword (email: string) {
177 const url = UserService.BASE_USERS_URL + '/ask-reset-password'
179 return this.authHttp.post(url, { email })
181 map(this.restExtractor.extractDataBool),
182 catchError(err => this.restExtractor.handleError(err))
186 resetPassword (userId: number, verificationString: string, password: string) {
187 const url = `${UserService.BASE_USERS_URL}/${userId}/reset-password`
193 return this.authHttp.post(url, body)
195 map(this.restExtractor.extractDataBool),
196 catchError(res => this.restExtractor.handleError(res))
200 verifyEmail (userId: number, verificationString: string, isPendingEmail: boolean) {
201 const url = `${UserService.BASE_USERS_URL}/${userId}/verify-email`
207 return this.authHttp.post(url, body)
209 map(this.restExtractor.extractDataBool),
210 catchError(res => this.restExtractor.handleError(res))
214 askSendVerifyEmail (email: string) {
215 const url = UserService.BASE_USERS_URL + '/ask-send-verify-email'
217 return this.authHttp.post(url, { email })
219 map(this.restExtractor.extractDataBool),
220 catchError(err => this.restExtractor.handleError(err))
224 autocomplete (search: string): Observable<string[]> {
225 const url = UserService.BASE_USERS_URL + 'autocomplete'
226 const params = new HttpParams().append('search', search)
229 .get<string[]>(url, { params })
230 .pipe(catchError(res => this.restExtractor.handleError(res)))
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
237 return this.displayNameToUsername(newDisplayName)
240 displayNameToUsername (displayName: string) {
241 if (!displayName) return ''
246 .replace(/[^a-z0-9_.]/g, '')
249 /* ###### Admin methods ###### */
251 addUser (userCreate: UserCreate) {
252 return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
254 map(this.restExtractor.extractDataBool),
255 catchError(err => this.restExtractor.handleError(err))
259 updateUser (userId: number, userUpdate: UserUpdate) {
260 return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
262 map(this.restExtractor.extractDataBool),
263 catchError(err => this.restExtractor.handleError(err))
267 updateUsers (users: UserServerModel[], userUpdate: UserUpdate) {
270 concatMap(u => this.authHttp.put(UserService.BASE_USERS_URL + u.id, userUpdate)),
272 catchError(err => this.restExtractor.handleError(err))
276 getUserWithCache (userId: number) {
277 if (!this.userCache[userId]) {
278 this.userCache[userId] = this.getUser(userId).pipe(shareReplay())
281 return this.userCache[userId]
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)))
290 getAnonymousUser () {
291 let videoLanguages: string[]
294 const languagesString = this.localStorageService.getItem(UserLocalStorageKeys.VIDEO_LANGUAGES)
295 videoLanguages = languagesString && languagesString !== 'undefined'
296 ? JSON.parse(languagesString)
299 videoLanguages = null
300 console.error('Cannot parse desired video languages from localStorage.', err)
303 const defaultNSFWPolicy = this.server.getHTMLConfig().instance.defaultNSFWPolicy
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',
312 autoPlayNextVideoPlaylist: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false',
313 autoPlayVideo: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO) === 'true',
315 // session storage keys
316 autoPlayNextVideo: this.sessionStorageService.getItem(UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
320 getUsers (parameters: {
321 pagination: RestPagination
324 }): Observable<ResultList<UserServerModel>> {
325 const { pagination, sort, search } = parameters
327 let params = new HttpParams()
328 params = this.restService.addRestGetParams(params, pagination, sort)
331 const filters = this.restService.parseQueryStringFilter(search, {
338 params = this.restService.addObjectParams(params, filters)
341 return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params })
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))
349 removeUser (usersArg: UserServerModel | UserServerModel[]) {
350 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
354 concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
356 catchError(err => this.restExtractor.handleError(err))
360 banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) {
361 const body = reason ? { reason } : {}
362 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
366 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
368 catchError(err => this.restExtractor.handleError(err))
372 unbanUsers (usersArg: UserServerModel | UserServerModel[]) {
373 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
377 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
379 catchError(err => this.restExtractor.handleError(err))
383 getAnonymousOrLoggedUser () {
384 if (!this.authService.isLoggedIn()) {
385 return of(this.getAnonymousUser())
388 return this.authService.userInformationLoaded
391 map(() => this.authService.getUser())
395 private formatUser (user: UserServerModel) {
397 if (user.videoQuota === -1) {
400 videoQuota = getBytes(user.videoQuota, 0)
403 const videoQuotaUsed = getBytes(user.videoQuotaUsed, 0)
405 let videoQuotaDaily: string
406 let videoQuotaUsedDaily: string
407 if (user.videoQuotaDaily === -1) {
408 videoQuotaDaily = '∞'
409 videoQuotaUsedDaily = getBytes(0, 0) + ''
411 videoQuotaDaily = getBytes(user.videoQuotaDaily, 0) + ''
412 videoQuotaUsedDaily = getBytes(user.videoQuotaUsedDaily || 0, 0) + ''
415 const roleLabels: { [ id in UserRole ]: string } = {
416 [UserRole.USER]: $localize`User`,
417 [UserRole.ADMINISTRATOR]: $localize`Administrator`,
418 [UserRole.MODERATOR]: $localize`Moderator`
421 return Object.assign(user, {
422 roleLabel: roleLabels[user.role],
425 rawVideoQuota: user.videoQuota,
426 rawVideoQuotaUsed: user.videoQuotaUsed,
429 rawVideoQuotaDaily: user.videoQuotaDaily,
430 rawVideoQuotaUsedDaily: user.videoQuotaUsedDaily