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