Fix default anonymous theme
[oweals/peertube.git] / client / src / app / shared / users / user.service.ts
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'
17
18 @Injectable()
19 export class UserService {
20   static BASE_USERS_URL = environment.apiUrl + '/api/v1/users/'
21
22   private bytesPipe = new BytesPipe()
23
24   private userCache: { [ id: number ]: Observable<UserServerModel> } = {}
25
26   constructor (
27     private authHttp: HttpClient,
28     private restExtractor: RestExtractor,
29     private restService: RestService,
30     private localStorageService: LocalStorageService,
31     private sessionStorageService: SessionStorageService,
32     private i18n: I18n
33   ) { }
34
35   changePassword (currentPassword: string, newPassword: string) {
36     const url = UserService.BASE_USERS_URL + 'me'
37     const body: UserUpdateMe = {
38       currentPassword,
39       password: newPassword
40     }
41
42     return this.authHttp.put(url, body)
43                .pipe(
44                  map(this.restExtractor.extractDataBool),
45                  catchError(err => this.restExtractor.handleError(err))
46                )
47   }
48
49   changeEmail (password: string, newEmail: string) {
50     const url = UserService.BASE_USERS_URL + 'me'
51     const body: UserUpdateMe = {
52       currentPassword: password,
53       email: newEmail
54     }
55
56     return this.authHttp.put(url, body)
57                .pipe(
58                  map(this.restExtractor.extractDataBool),
59                  catchError(err => this.restExtractor.handleError(err))
60                )
61   }
62
63   updateMyProfile (profile: UserUpdateMe) {
64     const url = UserService.BASE_USERS_URL + 'me'
65
66     return this.authHttp.put(url, profile)
67                .pipe(
68                  map(this.restExtractor.extractDataBool),
69                  catchError(err => this.restExtractor.handleError(err))
70                )
71   }
72
73   updateMyAnonymousProfile (profile: UserUpdateMe) {
74     const supportedKeys = {
75       // local storage keys
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)),
82
83       // session storage keys
84       autoPlayNextVideo: (val: boolean) =>
85         this.sessionStorageService.setItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO, String(val))
86     }
87
88     for (const key of Object.keys(profile)) {
89       try {
90         if (has(supportedKeys, key)) supportedKeys[key](profile[key])
91       } catch (err) {
92         console.error(`Cannot set item ${key} in localStorage. Likely due to a value impossible to stringify.`, err)
93       }
94     }
95   }
96
97   deleteMe () {
98     const url = UserService.BASE_USERS_URL + 'me'
99
100     return this.authHttp.delete(url)
101                .pipe(
102                  map(this.restExtractor.extractDataBool),
103                  catchError(err => this.restExtractor.handleError(err))
104                )
105   }
106
107   changeAvatar (avatarForm: FormData) {
108     const url = UserService.BASE_USERS_URL + 'me/avatar/pick'
109
110     return this.authHttp.post<{ avatar: Avatar }>(url, avatarForm)
111                .pipe(catchError(err => this.restExtractor.handleError(err)))
112   }
113
114   signup (userCreate: UserRegister) {
115     return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate)
116                .pipe(
117                  map(this.restExtractor.extractDataBool),
118                  catchError(err => this.restExtractor.handleError(err))
119                )
120   }
121
122   getMyVideoQuotaUsed () {
123     const url = UserService.BASE_USERS_URL + 'me/video-quota-used'
124
125     return this.authHttp.get<UserVideoQuota>(url)
126                .pipe(catchError(err => this.restExtractor.handleError(err)))
127   }
128
129   askResetPassword (email: string) {
130     const url = UserService.BASE_USERS_URL + '/ask-reset-password'
131
132     return this.authHttp.post(url, { email })
133                .pipe(
134                  map(this.restExtractor.extractDataBool),
135                  catchError(err => this.restExtractor.handleError(err))
136                )
137   }
138
139   resetPassword (userId: number, verificationString: string, password: string) {
140     const url = `${UserService.BASE_USERS_URL}/${userId}/reset-password`
141     const body = {
142       verificationString,
143       password
144     }
145
146     return this.authHttp.post(url, body)
147                .pipe(
148                  map(this.restExtractor.extractDataBool),
149                  catchError(res => this.restExtractor.handleError(res))
150                )
151   }
152
153   verifyEmail (userId: number, verificationString: string, isPendingEmail: boolean) {
154     const url = `${UserService.BASE_USERS_URL}/${userId}/verify-email`
155     const body = {
156       verificationString,
157       isPendingEmail
158     }
159
160     return this.authHttp.post(url, body)
161                .pipe(
162                  map(this.restExtractor.extractDataBool),
163                  catchError(res => this.restExtractor.handleError(res))
164                )
165   }
166
167   askSendVerifyEmail (email: string) {
168     const url = UserService.BASE_USERS_URL + '/ask-send-verify-email'
169
170     return this.authHttp.post(url, { email })
171                .pipe(
172                  map(this.restExtractor.extractDataBool),
173                  catchError(err => this.restExtractor.handleError(err))
174                )
175   }
176
177   autocomplete (search: string): Observable<string[]> {
178     const url = UserService.BASE_USERS_URL + 'autocomplete'
179     const params = new HttpParams().append('search', search)
180
181     return this.authHttp
182       .get<string[]>(url, { params })
183       .pipe(catchError(res => this.restExtractor.handleError(res)))
184   }
185
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
189
190     return this.displayNameToUsername(newDisplayName)
191   }
192
193   displayNameToUsername (displayName: string) {
194     if (!displayName) return ''
195
196     return displayName
197       .toLowerCase()
198       .replace(/\s/g, '_')
199       .replace(/[^a-z0-9_.]/g, '')
200   }
201
202   /* ###### Admin methods ###### */
203
204   addUser (userCreate: UserCreate) {
205     return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
206                .pipe(
207                  map(this.restExtractor.extractDataBool),
208                  catchError(err => this.restExtractor.handleError(err))
209                )
210   }
211
212   updateUser (userId: number, userUpdate: UserUpdate) {
213     return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
214                .pipe(
215                  map(this.restExtractor.extractDataBool),
216                  catchError(err => this.restExtractor.handleError(err))
217                )
218   }
219
220   updateUsers (users: UserServerModel[], userUpdate: UserUpdate) {
221     return from(users)
222       .pipe(
223         concatMap(u => this.authHttp.put(UserService.BASE_USERS_URL + u.id, userUpdate)),
224         toArray(),
225         catchError(err => this.restExtractor.handleError(err))
226       )
227   }
228
229   getUserWithCache (userId: number) {
230     if (!this.userCache[userId]) {
231       this.userCache[ userId ] = this.getUser(userId).pipe(shareReplay())
232     }
233
234     return this.userCache[userId]
235   }
236
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)))
241   }
242
243   getAnonymousUser () {
244     let videoLanguages
245
246     try {
247       videoLanguages = JSON.parse(this.localStorageService.getItem(User.KEYS.VIDEO_LANGUAGES))
248     } catch (err) {
249       videoLanguages = null
250       console.error('Cannot parse desired video languages from localStorage.', err)
251     }
252
253     return new User({
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',
258       videoLanguages,
259
260       autoPlayNextVideoPlaylist: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false',
261       autoPlayVideo: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO) === 'true',
262
263       // session storage keys
264       autoPlayNextVideo: this.sessionStorageService.getItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
265     })
266   }
267
268   getUsers (pagination: RestPagination, sort: SortMeta, search?: string): Observable<ResultList<UserServerModel>> {
269     let params = new HttpParams()
270     params = this.restService.addRestGetParams(params, pagination, sort)
271
272     if (search) params = params.append('search', search)
273
274     return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params })
275                .pipe(
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))
279                )
280   }
281
282   removeUser (usersArg: UserServerModel | UserServerModel[]) {
283     const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
284
285     return from(users)
286       .pipe(
287         concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
288         toArray(),
289         catchError(err => this.restExtractor.handleError(err))
290       )
291   }
292
293   banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) {
294     const body = reason ? { reason } : {}
295     const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
296
297     return from(users)
298       .pipe(
299         concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
300         toArray(),
301         catchError(err => this.restExtractor.handleError(err))
302       )
303   }
304
305   unbanUsers (usersArg: UserServerModel | UserServerModel[]) {
306     const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
307
308     return from(users)
309       .pipe(
310         concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
311         toArray(),
312         catchError(err => this.restExtractor.handleError(err))
313       )
314   }
315
316   private formatUser (user: UserServerModel) {
317     let videoQuota
318     if (user.videoQuota === -1) {
319       videoQuota = this.i18n('Unlimited')
320     } else {
321       videoQuota = this.bytesPipe.transform(user.videoQuota, 0)
322     }
323
324     const videoQuotaUsed = this.bytesPipe.transform(user.videoQuotaUsed, 0)
325
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')
330     }
331
332     return Object.assign(user, {
333       roleLabel: roleLabels[user.role],
334       videoQuota,
335       videoQuotaUsed
336     })
337   }
338 }