]>
Commit | Line | Data |
---|---|---|
5c20a455 C |
1 | import { SortMeta } from 'primeng/api' |
2 | import { from, Observable, of } from 'rxjs' | |
67ed6552 | 3 | import { catchError, concatMap, filter, first, map, shareReplay, 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 | |
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 | 37 | private sessionStorageService: SessionStorageService |
9df52d66 | 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]) { | |
9df52d66 | 269 | this.userCache[userId] = this.getUser(userId).pipe(shareReplay()) |
218b0874 C |
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:', | |
1a7d0887 | 323 | isBoolean: true |
8491293b RK |
324 | } |
325 | }) | |
326 | ||
327 | params = this.restService.addObjectParams(params, filters) | |
328 | } | |
24b9417c | 329 | |
d3217560 | 330 | return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params }) |
e724fa93 C |
331 | .pipe( |
332 | map(res => this.restExtractor.convertResultListDateToHuman(res)), | |
333 | map(res => this.restExtractor.applyToResultListData(res, this.formatUser.bind(this))), | |
334 | catchError(err => this.restExtractor.handleError(err)) | |
335 | ) | |
336 | } | |
337 | ||
d3217560 | 338 | removeUser (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.delete(UserService.BASE_USERS_URL + u.id)), | |
344 | toArray(), | |
345 | catchError(err => this.restExtractor.handleError(err)) | |
346 | ) | |
e724fa93 C |
347 | } |
348 | ||
d3217560 | 349 | banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) { |
e724fa93 | 350 | const body = reason ? { reason } : {} |
791645e6 | 351 | const users = Array.isArray(usersArg) ? usersArg : [ usersArg ] |
e724fa93 | 352 | |
791645e6 C |
353 | return from(users) |
354 | .pipe( | |
355 | concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)), | |
356 | toArray(), | |
357 | catchError(err => this.restExtractor.handleError(err)) | |
358 | ) | |
e724fa93 C |
359 | } |
360 | ||
d3217560 | 361 | unbanUsers (usersArg: UserServerModel | UserServerModel[]) { |
791645e6 C |
362 | const users = Array.isArray(usersArg) ? usersArg : [ usersArg ] |
363 | ||
364 | return from(users) | |
365 | .pipe( | |
366 | concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})), | |
367 | toArray(), | |
368 | catchError(err => this.restExtractor.handleError(err)) | |
369 | ) | |
e724fa93 C |
370 | } |
371 | ||
5c20a455 C |
372 | getAnonymousOrLoggedUser () { |
373 | if (!this.authService.isLoggedIn()) { | |
374 | return of(this.getAnonymousUser()) | |
375 | } | |
376 | ||
377 | return this.authService.userInformationLoaded | |
378 | .pipe( | |
379 | first(), | |
380 | map(() => this.authService.getUser()) | |
381 | ) | |
382 | } | |
383 | ||
d3217560 | 384 | private formatUser (user: UserServerModel) { |
e724fa93 C |
385 | let videoQuota |
386 | if (user.videoQuota === -1) { | |
bc99dfe5 | 387 | videoQuota = '∞' |
e724fa93 | 388 | } else { |
b4c3c51d | 389 | videoQuota = getBytes(user.videoQuota, 0) |
e724fa93 C |
390 | } |
391 | ||
b4c3c51d | 392 | const videoQuotaUsed = getBytes(user.videoQuotaUsed, 0) |
e724fa93 | 393 | |
4f5d0459 RK |
394 | let videoQuotaDaily: string |
395 | let videoQuotaUsedDaily: string | |
bc99dfe5 RK |
396 | if (user.videoQuotaDaily === -1) { |
397 | videoQuotaDaily = '∞' | |
b4c3c51d | 398 | videoQuotaUsedDaily = getBytes(0, 0) + '' |
bc99dfe5 | 399 | } else { |
b4c3c51d C |
400 | videoQuotaDaily = getBytes(user.videoQuotaDaily, 0) + '' |
401 | videoQuotaUsedDaily = getBytes(user.videoQuotaUsedDaily || 0, 0) + '' | |
bc99dfe5 RK |
402 | } |
403 | ||
e724fa93 | 404 | const roleLabels: { [ id in UserRole ]: string } = { |
66357162 C |
405 | [UserRole.USER]: $localize`User`, |
406 | [UserRole.ADMINISTRATOR]: $localize`Administrator`, | |
407 | [UserRole.MODERATOR]: $localize`Moderator` | |
e724fa93 C |
408 | } |
409 | ||
410 | return Object.assign(user, { | |
411 | roleLabel: roleLabels[user.role], | |
412 | videoQuota, | |
bc99dfe5 RK |
413 | videoQuotaUsed, |
414 | rawVideoQuota: user.videoQuota, | |
415 | rawVideoQuotaUsed: user.videoQuotaUsed, | |
416 | videoQuotaDaily, | |
417 | videoQuotaUsedDaily, | |
418 | rawVideoQuotaDaily: user.videoQuotaDaily, | |
419 | rawVideoQuotaUsedDaily: user.videoQuotaUsedDaily | |
e724fa93 C |
420 | }) |
421 | } | |
629d8d6f | 422 | } |