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