Add visitor settings, rework logged-in dropdown (#2514)
[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) {
238     return this.authHttp.get<UserServerModel>(UserService.BASE_USERS_URL + userId)
239                .pipe(catchError(err => this.restExtractor.handleError(err)))
240   }
241
242   getAnonymousUser () {
243     let videoLanguages
244     try {
245       videoLanguages = JSON.parse(this.localStorageService.getItem(User.KEYS.VIDEO_LANGUAGES))
246     } catch (err) {
247       videoLanguages = null
248       console.error('Cannot parse desired video languages from localStorage.', err)
249     }
250
251     return new User({
252       // local storage keys
253       nsfwPolicy: this.localStorageService.getItem(User.KEYS.NSFW_POLICY) as NSFWPolicyType,
254       webTorrentEnabled: this.localStorageService.getItem(User.KEYS.WEBTORRENT_ENABLED) !== 'false',
255       autoPlayVideo: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO) === 'true',
256       autoPlayNextVideoPlaylist: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST) === 'true',
257       theme: this.localStorageService.getItem(User.KEYS.THEME) || 'default',
258       videoLanguages,
259
260       // session storage keys
261       autoPlayNextVideo: this.sessionStorageService.getItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
262     })
263   }
264
265   getUsers (pagination: RestPagination, sort: SortMeta, search?: string): Observable<ResultList<UserServerModel>> {
266     let params = new HttpParams()
267     params = this.restService.addRestGetParams(params, pagination, sort)
268
269     if (search) params = params.append('search', search)
270
271     return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params })
272                .pipe(
273                  map(res => this.restExtractor.convertResultListDateToHuman(res)),
274                  map(res => this.restExtractor.applyToResultListData(res, this.formatUser.bind(this))),
275                  catchError(err => this.restExtractor.handleError(err))
276                )
277   }
278
279   removeUser (usersArg: UserServerModel | UserServerModel[]) {
280     const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
281
282     return from(users)
283       .pipe(
284         concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
285         toArray(),
286         catchError(err => this.restExtractor.handleError(err))
287       )
288   }
289
290   banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) {
291     const body = reason ? { reason } : {}
292     const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
293
294     return from(users)
295       .pipe(
296         concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
297         toArray(),
298         catchError(err => this.restExtractor.handleError(err))
299       )
300   }
301
302   unbanUsers (usersArg: UserServerModel | UserServerModel[]) {
303     const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
304
305     return from(users)
306       .pipe(
307         concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
308         toArray(),
309         catchError(err => this.restExtractor.handleError(err))
310       )
311   }
312
313   private formatUser (user: UserServerModel) {
314     let videoQuota
315     if (user.videoQuota === -1) {
316       videoQuota = this.i18n('Unlimited')
317     } else {
318       videoQuota = this.bytesPipe.transform(user.videoQuota, 0)
319     }
320
321     const videoQuotaUsed = this.bytesPipe.transform(user.videoQuotaUsed, 0)
322
323     const roleLabels: { [ id in UserRole ]: string } = {
324       [UserRole.USER]: this.i18n('User'),
325       [UserRole.ADMINISTRATOR]: this.i18n('Administrator'),
326       [UserRole.MODERATOR]: this.i18n('Moderator')
327     }
328
329     return Object.assign(user, {
330       roleLabel: roleLabels[user.role],
331       videoQuota,
332       videoQuotaUsed
333     })
334   }
335 }