1 import { has } from 'lodash-es'
2 import { BytesPipe } from 'ngx-pipes'
3 import { SortMeta } from 'primeng/api'
4 import { from, Observable, of } from 'rxjs'
5 import { catchError, concatMap, filter, first, map, shareReplay, throttleTime, toArray } from 'rxjs/operators'
6 import { HttpClient, HttpParams } from '@angular/common/http'
7 import { Injectable } from '@angular/core'
8 import { AuthService } from '@app/core/auth'
9 import { I18n } from '@ngx-translate/i18n-polyfill'
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) {
84 const supportedKeys = {
86 nsfwPolicy: (val: NSFWPolicyType) => this.localStorageService.setItem(User.KEYS.NSFW_POLICY, val),
87 webTorrentEnabled: (val: boolean) => this.localStorageService.setItem(User.KEYS.WEBTORRENT_ENABLED, String(val)),
88 autoPlayVideo: (val: boolean) => this.localStorageService.setItem(User.KEYS.AUTO_PLAY_VIDEO, String(val)),
89 autoPlayNextVideoPlaylist: (val: boolean) => this.localStorageService.setItem(User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST, String(val)),
90 theme: (val: string) => this.localStorageService.setItem(User.KEYS.THEME, val),
91 videoLanguages: (val: string[]) => this.localStorageService.setItem(User.KEYS.VIDEO_LANGUAGES, JSON.stringify(val)),
93 // session storage keys
94 autoPlayNextVideo: (val: boolean) =>
95 this.sessionStorageService.setItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO, String(val))
98 for (const key of Object.keys(profile)) {
100 if (has(supportedKeys, key)) supportedKeys[key](profile[key])
102 console.error(`Cannot set item ${key} in localStorage. Likely due to a value impossible to stringify.`, err)
107 listenAnonymousUpdate () {
108 return this.localStorageService.watch([
109 User.KEYS.NSFW_POLICY,
110 User.KEYS.WEBTORRENT_ENABLED,
111 User.KEYS.AUTO_PLAY_VIDEO,
112 User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST,
114 User.KEYS.VIDEO_LANGUAGES
117 filter(() => this.authService.isLoggedIn() !== true),
118 map(() => this.getAnonymousUser())
123 const url = UserService.BASE_USERS_URL + 'me'
125 return this.authHttp.delete(url)
127 map(this.restExtractor.extractDataBool),
128 catchError(err => this.restExtractor.handleError(err))
132 changeAvatar (avatarForm: FormData) {
133 const url = UserService.BASE_USERS_URL + 'me/avatar/pick'
135 return this.authHttp.post<{ avatar: Avatar }>(url, avatarForm)
136 .pipe(catchError(err => this.restExtractor.handleError(err)))
139 signup (userCreate: UserRegister) {
140 return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate)
142 map(this.restExtractor.extractDataBool),
143 catchError(err => this.restExtractor.handleError(err))
147 getMyVideoQuotaUsed () {
148 const url = UserService.BASE_USERS_URL + 'me/video-quota-used'
150 return this.authHttp.get<UserVideoQuota>(url)
151 .pipe(catchError(err => this.restExtractor.handleError(err)))
154 askResetPassword (email: string) {
155 const url = UserService.BASE_USERS_URL + '/ask-reset-password'
157 return this.authHttp.post(url, { email })
159 map(this.restExtractor.extractDataBool),
160 catchError(err => this.restExtractor.handleError(err))
164 resetPassword (userId: number, verificationString: string, password: string) {
165 const url = `${UserService.BASE_USERS_URL}/${userId}/reset-password`
171 return this.authHttp.post(url, body)
173 map(this.restExtractor.extractDataBool),
174 catchError(res => this.restExtractor.handleError(res))
178 verifyEmail (userId: number, verificationString: string, isPendingEmail: boolean) {
179 const url = `${UserService.BASE_USERS_URL}/${userId}/verify-email`
185 return this.authHttp.post(url, body)
187 map(this.restExtractor.extractDataBool),
188 catchError(res => this.restExtractor.handleError(res))
192 askSendVerifyEmail (email: string) {
193 const url = UserService.BASE_USERS_URL + '/ask-send-verify-email'
195 return this.authHttp.post(url, { email })
197 map(this.restExtractor.extractDataBool),
198 catchError(err => this.restExtractor.handleError(err))
202 autocomplete (search: string): Observable<string[]> {
203 const url = UserService.BASE_USERS_URL + 'autocomplete'
204 const params = new HttpParams().append('search', search)
207 .get<string[]>(url, { params })
208 .pipe(catchError(res => this.restExtractor.handleError(res)))
211 getNewUsername (oldDisplayName: string, newDisplayName: string, currentUsername: string) {
212 // Don't update display name, the user seems to have changed it
213 if (this.displayNameToUsername(oldDisplayName) !== currentUsername) return currentUsername
215 return this.displayNameToUsername(newDisplayName)
218 displayNameToUsername (displayName: string) {
219 if (!displayName) return ''
224 .replace(/[^a-z0-9_.]/g, '')
227 /* ###### Admin methods ###### */
229 addUser (userCreate: UserCreate) {
230 return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
232 map(this.restExtractor.extractDataBool),
233 catchError(err => this.restExtractor.handleError(err))
237 updateUser (userId: number, userUpdate: UserUpdate) {
238 return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
240 map(this.restExtractor.extractDataBool),
241 catchError(err => this.restExtractor.handleError(err))
245 updateUsers (users: UserServerModel[], userUpdate: UserUpdate) {
248 concatMap(u => this.authHttp.put(UserService.BASE_USERS_URL + u.id, userUpdate)),
250 catchError(err => this.restExtractor.handleError(err))
254 getUserWithCache (userId: number) {
255 if (!this.userCache[userId]) {
256 this.userCache[ userId ] = this.getUser(userId).pipe(shareReplay())
259 return this.userCache[userId]
262 getUser (userId: number, withStats = false) {
263 const params = new HttpParams().append('withStats', withStats + '')
264 return this.authHttp.get<UserServerModel>(UserService.BASE_USERS_URL + userId, { params })
265 .pipe(catchError(err => this.restExtractor.handleError(err)))
268 getAnonymousUser () {
269 let videoLanguages: string[]
272 videoLanguages = JSON.parse(this.localStorageService.getItem(User.KEYS.VIDEO_LANGUAGES))
274 videoLanguages = null
275 console.error('Cannot parse desired video languages from localStorage.', err)
279 // local storage keys
280 nsfwPolicy: this.localStorageService.getItem(User.KEYS.NSFW_POLICY) as NSFWPolicyType,
281 webTorrentEnabled: this.localStorageService.getItem(User.KEYS.WEBTORRENT_ENABLED) !== 'false',
282 theme: this.localStorageService.getItem(User.KEYS.THEME) || 'instance-default',
285 autoPlayNextVideoPlaylist: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false',
286 autoPlayVideo: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO) === 'true',
288 // session storage keys
289 autoPlayNextVideo: this.sessionStorageService.getItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
293 getUsers (parameters: {
294 pagination: RestPagination
297 }): Observable<ResultList<UserServerModel>> {
298 const { pagination, sort, search } = parameters
300 let params = new HttpParams()
301 params = this.restService.addRestGetParams(params, pagination, sort)
304 const filters = this.restService.parseQueryStringFilter(search, {
309 if (v === 'true') return v
310 if (v === 'false') return v
317 params = this.restService.addObjectParams(params, filters)
320 return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params })
322 map(res => this.restExtractor.convertResultListDateToHuman(res)),
323 map(res => this.restExtractor.applyToResultListData(res, this.formatUser.bind(this))),
324 catchError(err => this.restExtractor.handleError(err))
328 removeUser (usersArg: UserServerModel | UserServerModel[]) {
329 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
333 concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
335 catchError(err => this.restExtractor.handleError(err))
339 banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) {
340 const body = reason ? { reason } : {}
341 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
345 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
347 catchError(err => this.restExtractor.handleError(err))
351 unbanUsers (usersArg: UserServerModel | UserServerModel[]) {
352 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
356 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
358 catchError(err => this.restExtractor.handleError(err))
362 getAnonymousOrLoggedUser () {
363 if (!this.authService.isLoggedIn()) {
364 return of(this.getAnonymousUser())
367 return this.authService.userInformationLoaded
370 map(() => this.authService.getUser())
374 private formatUser (user: UserServerModel) {
376 if (user.videoQuota === -1) {
379 videoQuota = this.bytesPipe.transform(user.videoQuota, 0)
382 const videoQuotaUsed = this.bytesPipe.transform(user.videoQuotaUsed, 0)
385 let videoQuotaUsedDaily
386 if (user.videoQuotaDaily === -1) {
387 videoQuotaDaily = '∞'
388 videoQuotaUsedDaily = this.bytesPipe.transform(0, 0)
390 videoQuotaDaily = this.bytesPipe.transform(user.videoQuotaDaily, 0)
391 videoQuotaUsedDaily = this.bytesPipe.transform(user.videoQuotaUsedDaily || 0, 0)
394 const roleLabels: { [ id in UserRole ]: string } = {
395 [UserRole.USER]: this.i18n('User'),
396 [UserRole.ADMINISTRATOR]: this.i18n('Administrator'),
397 [UserRole.MODERATOR]: this.i18n('Moderator')
400 return Object.assign(user, {
401 roleLabel: roleLabels[user.role],
404 rawVideoQuota: user.videoQuota,
405 rawVideoQuotaUsed: user.videoQuotaUsed,
408 rawVideoQuotaDaily: user.videoQuotaDaily,
409 rawVideoQuotaUsedDaily: user.videoQuotaUsedDaily