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