]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/users/user.service.ts
chore: add manifest in light build
[github/Chocobozzz/PeerTube.git] / client / src / app / core / users / user.service.ts
CommitLineData
5c20a455
C
1import { SortMeta } from 'primeng/api'
2import { from, Observable, of } from 'rxjs'
67ed6552 3import { catchError, concatMap, filter, first, map, shareReplay, throttleTime, toArray } from 'rxjs/operators'
74d63469 4import { HttpClient, HttpParams } from '@angular/common/http'
63c4db6d 5import { Injectable } from '@angular/core'
5c20a455 6import { AuthService } from '@app/core/auth'
b4c3c51d 7import { getBytes } from '@root-helpers/bytes'
a4ff3100 8import { UserLocalStorageKeys } from '@root-helpers/users'
67ed6552
C
9import {
10 Avatar,
11 NSFWPolicyType,
12 ResultList,
13 User as UserServerModel,
14 UserCreate,
15 UserRegister,
16 UserRole,
17 UserUpdate,
18 UserUpdateMe,
19 UserVideoQuota
20} from '@shared/models'
5c20a455 21import { environment } from '../../../environments/environment'
5c20a455 22import { RestExtractor, RestPagination, RestService } from '../rest'
67ed6552 23import { LocalStorageService, SessionStorageService } from '../wrappers/storage.service'
5c20a455 24import { User } from './user.model'
629d8d6f
C
25
26@Injectable()
e2a2d6c8 27export class UserService {
63c4db6d 28 static BASE_USERS_URL = environment.apiUrl + '/api/v1/users/'
629d8d6f 29
d3217560 30 private userCache: { [ id: number ]: Observable<UserServerModel> } = {}
218b0874 31
df98563e 32 constructor (
d592e0a9 33 private authHttp: HttpClient,
5c20a455 34 private authService: AuthService,
e724fa93
C
35 private restExtractor: RestExtractor,
36 private restService: RestService,
d3217560 37 private localStorageService: LocalStorageService,
66357162
C
38 private sessionStorageService: SessionStorageService
39 ) { }
629d8d6f 40
a890d1e0 41 changePassword (currentPassword: string, newPassword: string) {
8094a898
C
42 const url = UserService.BASE_USERS_URL + 'me'
43 const body: UserUpdateMe = {
a890d1e0 44 currentPassword,
629d8d6f 45 password: newPassword
df98563e 46 }
629d8d6f 47
de59c48f 48 return this.authHttp.put(url, body)
db400f44
C
49 .pipe(
50 map(this.restExtractor.extractDataBool),
e4f0e92e 51 catchError(err => this.restExtractor.handleError(err))
db400f44 52 )
629d8d6f 53 }
af5e743b 54
0ba5f5ba
C
55 changeEmail (password: string, newEmail: string) {
56 const url = UserService.BASE_USERS_URL + 'me'
57 const body: UserUpdateMe = {
58 currentPassword: password,
59 email: newEmail
60 }
61
62 return this.authHttp.put(url, body)
63 .pipe(
64 map(this.restExtractor.extractDataBool),
65 catchError(err => this.restExtractor.handleError(err))
66 )
67 }
68
ed56ad11 69 updateMyProfile (profile: UserUpdateMe) {
8094a898 70 const url = UserService.BASE_USERS_URL + 'me'
af5e743b 71
ed56ad11 72 return this.authHttp.put(url, profile)
db400f44
C
73 .pipe(
74 map(this.restExtractor.extractDataBool),
e4f0e92e 75 catchError(err => this.restExtractor.handleError(err))
db400f44 76 )
af5e743b 77 }
a184c71b 78
d3217560 79 updateMyAnonymousProfile (profile: UserUpdateMe) {
a4ff3100
C
80 try {
81 this.localStorageService.setItem(UserLocalStorageKeys.NSFW_POLICY, profile.nsfwPolicy)
82 this.localStorageService.setItem(UserLocalStorageKeys.WEBTORRENT_ENABLED, profile.webTorrentEnabled)
d3217560 83
a4ff3100
C
84 this.localStorageService.setItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO, profile.autoPlayNextVideo)
85 this.localStorageService.setItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST, profile.autoPlayNextVideoPlaylist)
d3217560 86
a4ff3100
C
87 this.localStorageService.setItem(UserLocalStorageKeys.THEME, profile.theme)
88 this.localStorageService.setItem(UserLocalStorageKeys.VIDEO_LANGUAGES, profile.videoLanguages)
89 } catch (err) {
90 console.error(`Cannot set item in localStorage. Likely due to a value impossible to stringify.`, err)
d3217560
RK
91 }
92 }
93
5c20a455
C
94 listenAnonymousUpdate () {
95 return this.localStorageService.watch([
a4ff3100
C
96 UserLocalStorageKeys.NSFW_POLICY,
97 UserLocalStorageKeys.WEBTORRENT_ENABLED,
98 UserLocalStorageKeys.AUTO_PLAY_VIDEO,
99 UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST,
100 UserLocalStorageKeys.THEME,
101 UserLocalStorageKeys.VIDEO_LANGUAGES
5c20a455
C
102 ]).pipe(
103 throttleTime(200),
104 filter(() => this.authService.isLoggedIn() !== true),
105 map(() => this.getAnonymousUser())
106 )
107 }
108
92b9d60c
C
109 deleteMe () {
110 const url = UserService.BASE_USERS_URL + 'me'
111
112 return this.authHttp.delete(url)
113 .pipe(
114 map(this.restExtractor.extractDataBool),
115 catchError(err => this.restExtractor.handleError(err))
116 )
117 }
118
c5911fd3
C
119 changeAvatar (avatarForm: FormData) {
120 const url = UserService.BASE_USERS_URL + 'me/avatar/pick'
121
5fcbd898 122 return this.authHttp.post<{ avatar: Avatar }>(url, avatarForm)
e4f0e92e 123 .pipe(catchError(err => this.restExtractor.handleError(err)))
c5911fd3
C
124 }
125
1d5342ab 126 signup (userCreate: UserRegister) {
d592e0a9 127 return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate)
db400f44
C
128 .pipe(
129 map(this.restExtractor.extractDataBool),
e4f0e92e 130 catchError(err => this.restExtractor.handleError(err))
db400f44 131 )
a184c71b 132 }
c5911fd3 133
ce5496d6 134 getMyVideoQuotaUsed () {
bf64ed41 135 const url = UserService.BASE_USERS_URL + 'me/video-quota-used'
c5911fd3 136
5fcbd898 137 return this.authHttp.get<UserVideoQuota>(url)
e4f0e92e 138 .pipe(catchError(err => this.restExtractor.handleError(err)))
c5911fd3 139 }
ecb4e35f
C
140
141 askResetPassword (email: string) {
142 const url = UserService.BASE_USERS_URL + '/ask-reset-password'
143
144 return this.authHttp.post(url, { email })
db400f44
C
145 .pipe(
146 map(this.restExtractor.extractDataBool),
e4f0e92e 147 catchError(err => this.restExtractor.handleError(err))
db400f44 148 )
ecb4e35f
C
149 }
150
151 resetPassword (userId: number, verificationString: string, password: string) {
152 const url = `${UserService.BASE_USERS_URL}/${userId}/reset-password`
153 const body = {
154 verificationString,
155 password
156 }
157
158 return this.authHttp.post(url, body)
db400f44
C
159 .pipe(
160 map(this.restExtractor.extractDataBool),
161 catchError(res => this.restExtractor.handleError(res))
162 )
ecb4e35f 163 }
d9eaee39 164
0ba5f5ba 165 verifyEmail (userId: number, verificationString: string, isPendingEmail: boolean) {
d9eaee39
JM
166 const url = `${UserService.BASE_USERS_URL}/${userId}/verify-email`
167 const body = {
0ba5f5ba
C
168 verificationString,
169 isPendingEmail
d9eaee39
JM
170 }
171
172 return this.authHttp.post(url, body)
173 .pipe(
174 map(this.restExtractor.extractDataBool),
175 catchError(res => this.restExtractor.handleError(res))
176 )
177 }
178
179 askSendVerifyEmail (email: string) {
180 const url = UserService.BASE_USERS_URL + '/ask-send-verify-email'
181
182 return this.authHttp.post(url, { email })
183 .pipe(
184 map(this.restExtractor.extractDataBool),
185 catchError(err => this.restExtractor.handleError(err))
186 )
187 }
74d63469
GR
188
189 autocomplete (search: string): Observable<string[]> {
190 const url = UserService.BASE_USERS_URL + 'autocomplete'
191 const params = new HttpParams().append('search', search)
192
193 return this.authHttp
194 .get<string[]>(url, { params })
195 .pipe(catchError(res => this.restExtractor.handleError(res)))
196 }
e724fa93 197
1f20622f
C
198 getNewUsername (oldDisplayName: string, newDisplayName: string, currentUsername: string) {
199 // Don't update display name, the user seems to have changed it
200 if (this.displayNameToUsername(oldDisplayName) !== currentUsername) return currentUsername
201
202 return this.displayNameToUsername(newDisplayName)
203 }
204
205 displayNameToUsername (displayName: string) {
206 if (!displayName) return ''
207
208 return displayName
209 .toLowerCase()
210 .replace(/\s/g, '_')
211 .replace(/[^a-z0-9_.]/g, '')
212 }
213
e724fa93
C
214 /* ###### Admin methods ###### */
215
216 addUser (userCreate: UserCreate) {
217 return this.authHttp.post(UserService.BASE_USERS_URL, userCreate)
218 .pipe(
219 map(this.restExtractor.extractDataBool),
220 catchError(err => this.restExtractor.handleError(err))
221 )
222 }
223
224 updateUser (userId: number, userUpdate: UserUpdate) {
225 return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate)
226 .pipe(
227 map(this.restExtractor.extractDataBool),
228 catchError(err => this.restExtractor.handleError(err))
229 )
230 }
231
d3217560 232 updateUsers (users: UserServerModel[], userUpdate: UserUpdate) {
fc2ec87a
JM
233 return from(users)
234 .pipe(
235 concatMap(u => this.authHttp.put(UserService.BASE_USERS_URL + u.id, userUpdate)),
236 toArray(),
237 catchError(err => this.restExtractor.handleError(err))
238 )
239 }
240
218b0874
C
241 getUserWithCache (userId: number) {
242 if (!this.userCache[userId]) {
243 this.userCache[ userId ] = this.getUser(userId).pipe(shareReplay())
244 }
245
246 return this.userCache[userId]
247 }
248
76314386
RK
249 getUser (userId: number, withStats = false) {
250 const params = new HttpParams().append('withStats', withStats + '')
251 return this.authHttp.get<UserServerModel>(UserService.BASE_USERS_URL + userId, { params })
e724fa93
C
252 .pipe(catchError(err => this.restExtractor.handleError(err)))
253 }
254
d3217560 255 getAnonymousUser () {
5c20a455 256 let videoLanguages: string[]
9870329f 257
d3217560 258 try {
a4ff3100 259 videoLanguages = JSON.parse(this.localStorageService.getItem(UserLocalStorageKeys.VIDEO_LANGUAGES))
d3217560
RK
260 } catch (err) {
261 videoLanguages = null
262 console.error('Cannot parse desired video languages from localStorage.', err)
263 }
264
265 return new User({
266 // local storage keys
a4ff3100
C
267 nsfwPolicy: this.localStorageService.getItem(UserLocalStorageKeys.NSFW_POLICY) as NSFWPolicyType,
268 webTorrentEnabled: this.localStorageService.getItem(UserLocalStorageKeys.WEBTORRENT_ENABLED) !== 'false',
269 theme: this.localStorageService.getItem(UserLocalStorageKeys.THEME) || 'instance-default',
d3217560
RK
270 videoLanguages,
271
a4ff3100
C
272 autoPlayNextVideoPlaylist: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false',
273 autoPlayVideo: this.localStorageService.getItem(UserLocalStorageKeys.AUTO_PLAY_VIDEO) === 'true',
9870329f 274
d3217560 275 // session storage keys
a4ff3100 276 autoPlayNextVideo: this.sessionStorageService.getItem(UserLocalStorageKeys.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
d3217560
RK
277 })
278 }
279
8491293b
RK
280 getUsers (parameters: {
281 pagination: RestPagination
282 sort: SortMeta
283 search?: string
284 }): Observable<ResultList<UserServerModel>> {
285 const { pagination, sort, search } = parameters
286
e724fa93
C
287 let params = new HttpParams()
288 params = this.restService.addRestGetParams(params, pagination, sort)
289
8491293b
RK
290 if (search) {
291 const filters = this.restService.parseQueryStringFilter(search, {
292 blocked: {
293 prefix: 'banned:',
294 isBoolean: true,
295 handler: v => {
296 if (v === 'true') return v
297 if (v === 'false') return v
298
299 return undefined
300 }
301 }
302 })
303
304 params = this.restService.addObjectParams(params, filters)
305 }
24b9417c 306
d3217560 307 return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params })
e724fa93
C
308 .pipe(
309 map(res => this.restExtractor.convertResultListDateToHuman(res)),
310 map(res => this.restExtractor.applyToResultListData(res, this.formatUser.bind(this))),
311 catchError(err => this.restExtractor.handleError(err))
312 )
313 }
314
d3217560 315 removeUser (usersArg: UserServerModel | UserServerModel[]) {
791645e6
C
316 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
317
318 return from(users)
319 .pipe(
320 concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)),
321 toArray(),
322 catchError(err => this.restExtractor.handleError(err))
323 )
e724fa93
C
324 }
325
d3217560 326 banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) {
e724fa93 327 const body = reason ? { reason } : {}
791645e6 328 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
e724fa93 329
791645e6
C
330 return from(users)
331 .pipe(
332 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)),
333 toArray(),
334 catchError(err => this.restExtractor.handleError(err))
335 )
e724fa93
C
336 }
337
d3217560 338 unbanUsers (usersArg: UserServerModel | UserServerModel[]) {
791645e6
C
339 const users = Array.isArray(usersArg) ? usersArg : [ usersArg ]
340
341 return from(users)
342 .pipe(
343 concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})),
344 toArray(),
345 catchError(err => this.restExtractor.handleError(err))
346 )
e724fa93
C
347 }
348
5c20a455
C
349 getAnonymousOrLoggedUser () {
350 if (!this.authService.isLoggedIn()) {
351 return of(this.getAnonymousUser())
352 }
353
354 return this.authService.userInformationLoaded
355 .pipe(
356 first(),
357 map(() => this.authService.getUser())
358 )
359 }
360
d3217560 361 private formatUser (user: UserServerModel) {
e724fa93
C
362 let videoQuota
363 if (user.videoQuota === -1) {
bc99dfe5 364 videoQuota = '∞'
e724fa93 365 } else {
b4c3c51d 366 videoQuota = getBytes(user.videoQuota, 0)
e724fa93
C
367 }
368
b4c3c51d 369 const videoQuotaUsed = getBytes(user.videoQuotaUsed, 0)
e724fa93 370
4f5d0459
RK
371 let videoQuotaDaily: string
372 let videoQuotaUsedDaily: string
bc99dfe5
RK
373 if (user.videoQuotaDaily === -1) {
374 videoQuotaDaily = '∞'
b4c3c51d 375 videoQuotaUsedDaily = getBytes(0, 0) + ''
bc99dfe5 376 } else {
b4c3c51d
C
377 videoQuotaDaily = getBytes(user.videoQuotaDaily, 0) + ''
378 videoQuotaUsedDaily = getBytes(user.videoQuotaUsedDaily || 0, 0) + ''
bc99dfe5
RK
379 }
380
e724fa93 381 const roleLabels: { [ id in UserRole ]: string } = {
66357162
C
382 [UserRole.USER]: $localize`User`,
383 [UserRole.ADMINISTRATOR]: $localize`Administrator`,
384 [UserRole.MODERATOR]: $localize`Moderator`
e724fa93
C
385 }
386
387 return Object.assign(user, {
388 roleLabel: roleLabels[user.role],
389 videoQuota,
bc99dfe5
RK
390 videoQuotaUsed,
391 rawVideoQuota: user.videoQuota,
392 rawVideoQuotaUsed: user.videoQuotaUsed,
393 videoQuotaDaily,
394 videoQuotaUsedDaily,
395 rawVideoQuotaDaily: user.videoQuotaDaily,
396 rawVideoQuotaUsedDaily: user.videoQuotaUsedDaily
e724fa93
C
397 })
398 }
629d8d6f 399}