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'
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 userCache: { [ id: number ]: Observable<UserServerModel> } = {}
33 private authHttp: HttpClient,
34 private authService: AuthService,
35 private restExtractor: RestExtractor,
36 private restService: RestService,
37 private localStorageService: LocalStorageService,
38 private sessionStorageService: SessionStorageService
41 changePassword (currentPassword: string, newPassword: string) {
42 const url = UserService.BASE_USERS_URL + 'me'
43 const body: UserUpdateMe = {
48 return this.authHttp.put(url, body)
50 map(this.restExtractor.extractDataBool),
51 catchError(err => this.restExtractor.handleError(err))
55 changeEmail (password: string, newEmail: string) {
56 const url = UserService.BASE_USERS_URL + 'me'
57 const body: UserUpdateMe = {
58 currentPassword: password,
62 return this.authHttp.put(url, body)
64 map(this.restExtractor.extractDataBool),
65 catchError(err => this.restExtractor.handleError(err))
69 updateMyProfile (profile: UserUpdateMe) {
70 const url = UserService.BASE_USERS_URL + 'me'
72 return this.authHttp.put(url, profile)
74 map(this.restExtractor.extractDataBool),
75 catchError(err => this.restExtractor.handleError(err))
79 updateMyAnonymousProfile (profile: UserUpdateMe) {
81 this.localStorageService.setItem(UserLocalStorageKeys.NSFW_POLICY, profile.nsfwPolicy)
82 this.localStorageService.setItem(UserLocalStorageKeys.WEBTORRENT_ENABLED, profile.webTorrentEnabled)
84 this.localStorageService.setItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO, profile.autoPlayNextVideo)
85 this.localStorageService.setItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST, profile.autoPlayNextVideoPlaylist)
87 this.localStorageService.setItem(UserLocalStorageKeys.THEME, profile.theme)
88 this.localStorageService.setItem(UserLocalStorageKeys.VIDEO_LANGUAGES, profile.videoLanguages)
90 console.error(`Cannot set item in localStorage. Likely due to a value impossible to stringify.`, err)
94 listenAnonymousUpdate () {
95 return this.localStorageService.watch([
96 UserLocalStorageKeys.NSFW_POLICY,
97 UserLocalStorageKeys.WEBTORRENT_ENABLED,
98 UserLocalStorageKeys.AUTO_PLAY_VIDEO,
99 UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST,
100 UserLocalStorageKeys.THEME,
101 UserLocalStorageKeys.VIDEO_LANGUAGES
104 filter(() => this.authService.isLoggedIn() !== true),
105 map(() => this.getAnonymousUser())
110 const url = UserService.BASE_USERS_URL + 'me'
112 return this.authHttp.delete(url)
114 map(this.restExtractor.extractDataBool),
115 catchError(err => this.restExtractor.handleError(err))
119 changeAvatar (avatarForm: FormData) {
120 const url = UserService.BASE_USERS_URL + 'me/avatar/pick'
122 return this.authHttp.post<{ avatar: Avatar }>(url, avatarForm)
123 .pipe(catchError(err => this.restExtractor.handleError(err)))
126 signup (userCreate: UserRegister) {
127 return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate)
129 map(this.restExtractor.extractDataBool),
130 catchError(err => this.restExtractor.handleError(err))
134 getMyVideoQuotaUsed () {
135 const url = UserService.BASE_USERS_URL + 'me/video-quota-used'
137 return this.authHttp.get<UserVideoQuota>(url)
138 .pipe(catchError(err => this.restExtractor.handleError(err)))
141 askResetPassword (email: string) {
142 const url = UserService.BASE_USERS_URL + '/ask-reset-password'
144 return this.authHttp.post(url, { email })
146 map(this.restExtractor.extractDataBool),
147 catchError(err => this.restExtractor.handleError(err))
151 resetPassword (userId: number, verificationString: string, password: string) {
152 const url = `${UserService.BASE_USERS_URL}/${userId}/reset-password`
158 return this.authHttp.post(url, body)
160 map(this.restExtractor.extractDataBool),
161 catchError(res => this.restExtractor.handleError(res))
165 verifyEmail (userId: number, verificationString: string, isPendingEmail: boolean) {
166 const url = `${UserService.BASE_USERS_URL}/${userId}/verify-email`
172 return this.authHttp.post(url, body)
174 map(this.restExtractor.extractDataBool),
175 catchError(res => this.restExtractor.handleError(res))
179 askSendVerifyEmail (email: string) {
180 const url = UserService.BASE_USERS_URL + '/ask-send-verify-email'
182 return this.authHttp.post(url, { email })
184 map(this.restExtractor.extractDataBool),
185 catchError(err => this.restExtractor.handleError(err))
189 autocomplete (search: string): Observable<string[]> {
190 const url = UserService.BASE_USERS_URL + 'autocomplete'
191 const params = new HttpParams().append('search', search)
194 .get<string[]>(url, { params })
195 .pipe(catchError(res => this.restExtractor.handleError(res)))
198 getNewUsername (oldDisplayName: string, newDisplayName: string, currentUsername: string) {
199 // Don't update display name, the user seems to have changed it
200 if (this.displayNameToUsername(oldDisplayName) !== currentUsername) return currentUsername
202 return this.displayNameToUsername(newDisplayName)
205 displayNameToUsername (displayName: string) {
206 if (!displayName) return ''
211 .replace(/[^a-z0-9_.]/g, '')
214 /* ###### Admin methods ###### */
216 addUser (userCreate: UserCreate) {
217 return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
219 map(this.restExtractor.extractDataBool),
220 catchError(err => this.restExtractor.handleError(err))
224 updateUser (userId: number, userUpdate: UserUpdate) {
225 return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
227 map(this.restExtractor.extractDataBool),
228 catchError(err => this.restExtractor.handleError(err))
232 updateUsers (users: UserServerModel[], userUpdate: UserUpdate) {
235 concatMap(u => this.authHttp.put(UserService.BASE_USERS_URL + u.id, userUpdate)),
237 catchError(err => this.restExtractor.handleError(err))
241 getUserWithCache (userId: number) {
242 if (!this.userCache[userId]) {
243 this.userCache[ userId ] = this.getUser(userId).pipe(shareReplay())
246 return this.userCache[userId]
249 getUser (userId: number, withStats = false) {
250 const params = new HttpParams().append('withStats', withStats + '')
251 return this.authHttp.get<UserServerModel>(UserService.BASE_USERS_URL + userId, { params })
252 .pipe(catchError(err => this.restExtractor.handleError(err)))
255 getAnonymousUser () {
256 let videoLanguages: string[]
259 videoLanguages = JSON.parse(this.localStorageService.getItem(UserLocalStorageKeys.VIDEO_LANGUAGES))
261 videoLanguages = null
262 console.error('Cannot parse desired video languages from localStorage.', err)
266 // local storage keys
267 nsfwPolicy: this.localStorageService.getItem(UserLocalStorageKeys.NSFW_POLICY) as NSFWPolicyType,
268 webTorrentEnabled: this.localStorageService.getItem(UserLocalStorageKeys.WEBTORRENT_ENABLED) !== 'false',
269 theme: this.localStorageService.getItem(UserLocalStorageKeys.THEME) || 'instance-default',
272 autoPlayNextVideoPlaylist: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false',
273 autoPlayVideo: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO) === 'true',
275 // session storage keys
276 autoPlayNextVideo: this.sessionStorageService.getItem(UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
280 getUsers (parameters: {
281 pagination: RestPagination
284 }): Observable<ResultList<UserServerModel>> {
285 const { pagination, sort, search } = parameters
287 let params = new HttpParams()
288 params = this.restService.addRestGetParams(params, pagination, sort)
291 const filters = this.restService.parseQueryStringFilter(search, {
296 if (v === 'true') return v
297 if (v === 'false') return v
304 params = this.restService.addObjectParams(params, filters)
307 return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params })
309 map(res => this.restExtractor.convertResultListDateToHuman(res)),
310 map(res => this.restExtractor.applyToResultListData(res, this.formatUser.bind(this))),
311 catchError(err => this.restExtractor.handleError(err))
315 removeUser (usersArg: UserServerModel | UserServerModel[]) {
316 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
320 concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
322 catchError(err => this.restExtractor.handleError(err))
326 banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) {
327 const body = reason ? { reason } : {}
328 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
332 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
334 catchError(err => this.restExtractor.handleError(err))
338 unbanUsers (usersArg: UserServerModel | UserServerModel[]) {
339 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
343 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
345 catchError(err => this.restExtractor.handleError(err))
349 getAnonymousOrLoggedUser () {
350 if (!this.authService.isLoggedIn()) {
351 return of(this.getAnonymousUser())
354 return this.authService.userInformationLoaded
357 map(() => this.authService.getUser())
361 private formatUser (user: UserServerModel) {
363 if (user.videoQuota === -1) {
366 videoQuota = getBytes(user.videoQuota, 0)
369 const videoQuotaUsed = getBytes(user.videoQuotaUsed, 0)
371 let videoQuotaDaily: string
372 let videoQuotaUsedDaily: string
373 if (user.videoQuotaDaily === -1) {
374 videoQuotaDaily = '∞'
375 videoQuotaUsedDaily = getBytes(0, 0) + ''
377 videoQuotaDaily = getBytes(user.videoQuotaDaily, 0) + ''
378 videoQuotaUsedDaily = getBytes(user.videoQuotaUsedDaily || 0, 0) + ''
381 const roleLabels: { [ id in UserRole ]: string } = {
382 [UserRole.USER]: $localize`User`,
383 [UserRole.ADMINISTRATOR]: $localize`Administrator`,
384 [UserRole.MODERATOR]: $localize`Moderator`
387 return Object.assign(user, {
388 roleLabel: roleLabels[user.role],
391 rawVideoQuota: user.videoQuota,
392 rawVideoQuotaUsed: user.videoQuotaUsed,
395 rawVideoQuotaDaily: user.videoQuotaDaily,
396 rawVideoQuotaUsedDaily: user.videoQuotaUsedDaily