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