1 import { from, Observable } from 'rxjs'
2 import { catchError, concatMap, map, shareReplay, toArray } from 'rxjs/operators'
3 import { HttpClient, HttpParams } from '@angular/common/http'
4 import { Injectable } from '@angular/core'
5 import { ResultList, User as UserServerModel, UserCreate, UserRole, UserUpdate, UserUpdateMe, UserVideoQuota } from '../../../../../shared'
6 import { environment } from '../../../environments/environment'
7 import { RestExtractor, RestPagination, RestService } from '../rest'
8 import { Avatar } from '../../../../../shared/models/avatars/avatar.model'
9 import { SortMeta } from 'primeng/api'
10 import { BytesPipe } from 'ngx-pipes'
11 import { I18n } from '@ngx-translate/i18n-polyfill'
12 import { UserRegister } from '@shared/models/users/user-register.model'
13 import { User } from './user.model'
14 import { NSFWPolicyType } from '@shared/models/videos/nsfw-policy.type'
15 import { has } from 'lodash-es'
16 import { LocalStorageService, SessionStorageService } from '../misc/storage.service'
19 export class UserService {
20 static BASE_USERS_URL = environment.apiUrl + '/api/v1/users/'
22 private bytesPipe = new BytesPipe()
24 private userCache: { [ id: number ]: Observable<UserServerModel> } = {}
27 private authHttp: HttpClient,
28 private restExtractor: RestExtractor,
29 private restService: RestService,
30 private localStorageService: LocalStorageService,
31 private sessionStorageService: SessionStorageService,
35 changePassword (currentPassword: string, newPassword: string) {
36 const url = UserService.BASE_USERS_URL + 'me'
37 const body: UserUpdateMe = {
42 return this.authHttp.put(url, body)
44 map(this.restExtractor.extractDataBool),
45 catchError(err => this.restExtractor.handleError(err))
49 changeEmail (password: string, newEmail: string) {
50 const url = UserService.BASE_USERS_URL + 'me'
51 const body: UserUpdateMe = {
52 currentPassword: password,
56 return this.authHttp.put(url, body)
58 map(this.restExtractor.extractDataBool),
59 catchError(err => this.restExtractor.handleError(err))
63 updateMyProfile (profile: UserUpdateMe) {
64 const url = UserService.BASE_USERS_URL + 'me'
66 return this.authHttp.put(url, profile)
68 map(this.restExtractor.extractDataBool),
69 catchError(err => this.restExtractor.handleError(err))
73 updateMyAnonymousProfile (profile: UserUpdateMe) {
74 const supportedKeys = {
76 nsfwPolicy: (val: NSFWPolicyType) => this.localStorageService.setItem(User.KEYS.NSFW_POLICY, val),
77 webTorrentEnabled: (val: boolean) => this.localStorageService.setItem(User.KEYS.WEBTORRENT_ENABLED, String(val)),
78 autoPlayVideo: (val: boolean) => this.localStorageService.setItem(User.KEYS.AUTO_PLAY_VIDEO, String(val)),
79 autoPlayNextVideoPlaylist: (val: boolean) => this.localStorageService.setItem(User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST, String(val)),
80 theme: (val: string) => this.localStorageService.setItem(User.KEYS.THEME, val),
81 videoLanguages: (val: string[]) => this.localStorageService.setItem(User.KEYS.VIDEO_LANGUAGES, JSON.stringify(val)),
83 // session storage keys
84 autoPlayNextVideo: (val: boolean) =>
85 this.sessionStorageService.setItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO, String(val))
88 for (const key of Object.keys(profile)) {
90 if (has(supportedKeys, key)) supportedKeys[key](profile[key])
92 console.error(`Cannot set item ${key} in localStorage. Likely due to a value impossible to stringify.`, err)
98 const url = UserService.BASE_USERS_URL + 'me'
100 return this.authHttp.delete(url)
102 map(this.restExtractor.extractDataBool),
103 catchError(err => this.restExtractor.handleError(err))
107 changeAvatar (avatarForm: FormData) {
108 const url = UserService.BASE_USERS_URL + 'me/avatar/pick'
110 return this.authHttp.post<{ avatar: Avatar }>(url, avatarForm)
111 .pipe(catchError(err => this.restExtractor.handleError(err)))
114 signup (userCreate: UserRegister) {
115 return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate)
117 map(this.restExtractor.extractDataBool),
118 catchError(err => this.restExtractor.handleError(err))
122 getMyVideoQuotaUsed () {
123 const url = UserService.BASE_USERS_URL + 'me/video-quota-used'
125 return this.authHttp.get<UserVideoQuota>(url)
126 .pipe(catchError(err => this.restExtractor.handleError(err)))
129 askResetPassword (email: string) {
130 const url = UserService.BASE_USERS_URL + '/ask-reset-password'
132 return this.authHttp.post(url, { email })
134 map(this.restExtractor.extractDataBool),
135 catchError(err => this.restExtractor.handleError(err))
139 resetPassword (userId: number, verificationString: string, password: string) {
140 const url = `${UserService.BASE_USERS_URL}/${userId}/reset-password`
146 return this.authHttp.post(url, body)
148 map(this.restExtractor.extractDataBool),
149 catchError(res => this.restExtractor.handleError(res))
153 verifyEmail (userId: number, verificationString: string, isPendingEmail: boolean) {
154 const url = `${UserService.BASE_USERS_URL}/${userId}/verify-email`
160 return this.authHttp.post(url, body)
162 map(this.restExtractor.extractDataBool),
163 catchError(res => this.restExtractor.handleError(res))
167 askSendVerifyEmail (email: string) {
168 const url = UserService.BASE_USERS_URL + '/ask-send-verify-email'
170 return this.authHttp.post(url, { email })
172 map(this.restExtractor.extractDataBool),
173 catchError(err => this.restExtractor.handleError(err))
177 autocomplete (search: string): Observable<string[]> {
178 const url = UserService.BASE_USERS_URL + 'autocomplete'
179 const params = new HttpParams().append('search', search)
182 .get<string[]>(url, { params })
183 .pipe(catchError(res => this.restExtractor.handleError(res)))
186 getNewUsername (oldDisplayName: string, newDisplayName: string, currentUsername: string) {
187 // Don't update display name, the user seems to have changed it
188 if (this.displayNameToUsername(oldDisplayName) !== currentUsername) return currentUsername
190 return this.displayNameToUsername(newDisplayName)
193 displayNameToUsername (displayName: string) {
194 if (!displayName) return ''
199 .replace(/[^a-z0-9_.]/g, '')
202 /* ###### Admin methods ###### */
204 addUser (userCreate: UserCreate) {
205 return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
207 map(this.restExtractor.extractDataBool),
208 catchError(err => this.restExtractor.handleError(err))
212 updateUser (userId: number, userUpdate: UserUpdate) {
213 return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
215 map(this.restExtractor.extractDataBool),
216 catchError(err => this.restExtractor.handleError(err))
220 updateUsers (users: UserServerModel[], userUpdate: UserUpdate) {
223 concatMap(u => this.authHttp.put(UserService.BASE_USERS_URL + u.id, userUpdate)),
225 catchError(err => this.restExtractor.handleError(err))
229 getUserWithCache (userId: number) {
230 if (!this.userCache[userId]) {
231 this.userCache[ userId ] = this.getUser(userId).pipe(shareReplay())
234 return this.userCache[userId]
237 getUser (userId: number, withStats = false) {
238 const params = new HttpParams().append('withStats', withStats + '')
239 return this.authHttp.get<UserServerModel>(UserService.BASE_USERS_URL + userId, { params })
240 .pipe(catchError(err => this.restExtractor.handleError(err)))
243 getAnonymousUser () {
247 videoLanguages = JSON.parse(this.localStorageService.getItem(User.KEYS.VIDEO_LANGUAGES))
249 videoLanguages = null
250 console.error('Cannot parse desired video languages from localStorage.', err)
254 // local storage keys
255 nsfwPolicy: this.localStorageService.getItem(User.KEYS.NSFW_POLICY) as NSFWPolicyType,
256 webTorrentEnabled: this.localStorageService.getItem(User.KEYS.WEBTORRENT_ENABLED) !== 'false',
257 theme: this.localStorageService.getItem(User.KEYS.THEME) || 'instance-default',
260 autoPlayNextVideoPlaylist: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false',
261 autoPlayVideo: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO) === 'true',
263 // session storage keys
264 autoPlayNextVideo: this.sessionStorageService.getItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
268 getUsers (pagination: RestPagination, sort: SortMeta, search?: string): Observable<ResultList<UserServerModel>> {
269 let params = new HttpParams()
270 params = this.restService.addRestGetParams(params, pagination, sort)
272 if (search) params = params.append('search', search)
274 return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params })
276 map(res => this.restExtractor.convertResultListDateToHuman(res)),
277 map(res => this.restExtractor.applyToResultListData(res, this.formatUser.bind(this))),
278 catchError(err => this.restExtractor.handleError(err))
282 removeUser (usersArg: UserServerModel | UserServerModel[]) {
283 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
287 concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
289 catchError(err => this.restExtractor.handleError(err))
293 banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) {
294 const body = reason ? { reason } : {}
295 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
299 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
301 catchError(err => this.restExtractor.handleError(err))
305 unbanUsers (usersArg: UserServerModel | UserServerModel[]) {
306 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
310 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
312 catchError(err => this.restExtractor.handleError(err))
316 private formatUser (user: UserServerModel) {
318 if (user.videoQuota === -1) {
319 videoQuota = this.i18n('Unlimited')
321 videoQuota = this.bytesPipe.transform(user.videoQuota, 0)
324 const videoQuotaUsed = this.bytesPipe.transform(user.videoQuotaUsed, 0)
326 const roleLabels: { [ id in UserRole ]: string } = {
327 [UserRole.USER]: this.i18n('User'),
328 [UserRole.ADMINISTRATOR]: this.i18n('Administrator'),
329 [UserRole.MODERATOR]: this.i18n('Moderator')
332 return Object.assign(user, {
333 roleLabel: roleLabels[user.role],