1 import { catchError, map } from 'rxjs/operators'
2 import { HttpClient, HttpParams } from '@angular/common/http'
3 import { Injectable } from '@angular/core'
4 import { BytesPipe } from 'ngx-pipes'
5 import { SortMeta } from 'primeng/components/common/sortmeta'
6 import { Observable } from 'rxjs'
7 import { ResultList, UserCreate, UserUpdate, User } from '../../../../../../shared'
8 import { environment } from '../../../../environments/environment'
9 import { RestExtractor, RestPagination, RestService } from '../../../shared'
10 import { I18n } from '@ngx-translate/i18n-polyfill'
13 export class UserService {
14 private static BASE_USERS_URL = environment.apiUrl + '/api/v1/users/'
15 private bytesPipe = new BytesPipe()
18 private authHttp: HttpClient,
19 private restService: RestService,
20 private restExtractor: RestExtractor,
24 addUser (userCreate: UserCreate) {
25 return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
27 map(this.restExtractor.extractDataBool),
28 catchError(err => this.restExtractor.handleError(err))
32 updateUser (userId: number, userUpdate: UserUpdate) {
33 return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
35 map(this.restExtractor.extractDataBool),
36 catchError(err => this.restExtractor.handleError(err))
40 getUser (userId: number) {
41 return this.authHttp.get<User>(UserService.BASE_USERS_URL + userId)
42 .pipe(catchError(err => this.restExtractor.handleError(err)))
45 getUsers (pagination: RestPagination, sort: SortMeta): Observable<ResultList<User>> {
46 let params = new HttpParams()
47 params = this.restService.addRestGetParams(params, pagination, sort)
49 return this.authHttp.get<ResultList<User>>(UserService.BASE_USERS_URL, { params })
51 map(res => this.restExtractor.convertResultListDateToHuman(res)),
52 map(res => this.restExtractor.applyToResultListData(res, this.formatUser.bind(this))),
53 catchError(err => this.restExtractor.handleError(err))
57 removeUser (user: User) {
58 return this.authHttp.delete(UserService.BASE_USERS_URL + user.id)
59 .pipe(catchError(err => this.restExtractor.handleError(err)))
62 banUser (user: User, reason?: string) {
63 const body = reason ? { reason } : {}
65 return this.authHttp.post(UserService.BASE_USERS_URL + user.id + '/block', body)
66 .pipe(catchError(err => this.restExtractor.handleError(err)))
69 unbanUser (user: User) {
70 return this.authHttp.post(UserService.BASE_USERS_URL + user.id + '/unblock', {})
71 .pipe(catchError(err => this.restExtractor.handleError(err)))
74 private formatUser (user: User) {
76 if (user.videoQuota === -1) {
77 videoQuota = this.i18n('Unlimited')
79 videoQuota = this.bytesPipe.transform(user.videoQuota, 0)
82 const videoQuotaUsed = this.bytesPipe.transform(user.videoQuotaUsed, 0)
84 return Object.assign(user, {