diff options
Diffstat (limited to 'client/src/app/core/users/user.service.ts')
-rw-r--r-- | client/src/app/core/users/user.service.ts | 375 |
1 files changed, 375 insertions, 0 deletions
diff --git a/client/src/app/core/users/user.service.ts b/client/src/app/core/users/user.service.ts new file mode 100644 index 000000000..ab395b1f9 --- /dev/null +++ b/client/src/app/core/users/user.service.ts | |||
@@ -0,0 +1,375 @@ | |||
1 | import { has } from 'lodash-es' | ||
2 | import { BytesPipe } from 'ngx-pipes' | ||
3 | import { SortMeta } from 'primeng/api' | ||
4 | import { from, Observable, of } from 'rxjs' | ||
5 | import { catchError, concatMap, filter, first, map, shareReplay, throttleTime, toArray } from 'rxjs/operators' | ||
6 | import { HttpClient, HttpParams } from '@angular/common/http' | ||
7 | import { Injectable } from '@angular/core' | ||
8 | import { AuthService } from '@app/core/auth' | ||
9 | import { I18n } from '@ngx-translate/i18n-polyfill' | ||
10 | import { | ||
11 | Avatar, | ||
12 | NSFWPolicyType, | ||
13 | ResultList, | ||
14 | User as UserServerModel, | ||
15 | UserCreate, | ||
16 | UserRegister, | ||
17 | UserRole, | ||
18 | UserUpdate, | ||
19 | UserUpdateMe, | ||
20 | UserVideoQuota | ||
21 | } from '@shared/models' | ||
22 | import { environment } from '../../../environments/environment' | ||
23 | import { RestExtractor, RestPagination, RestService } from '../rest' | ||
24 | import { LocalStorageService, SessionStorageService } from '../wrappers/storage.service' | ||
25 | import { User } from './user.model' | ||
26 | |||
27 | @Injectable() | ||
28 | export class UserService { | ||
29 | static BASE_USERS_URL = environment.apiUrl + '/api/v1/users/' | ||
30 | |||
31 | private bytesPipe = new BytesPipe() | ||
32 | |||
33 | private userCache: { [ id: number ]: Observable<UserServerModel> } = {} | ||
34 | |||
35 | constructor ( | ||
36 | private authHttp: HttpClient, | ||
37 | private authService: AuthService, | ||
38 | private restExtractor: RestExtractor, | ||
39 | private restService: RestService, | ||
40 | private localStorageService: LocalStorageService, | ||
41 | private sessionStorageService: SessionStorageService, | ||
42 | private i18n: I18n | ||
43 | ) { } | ||
44 | |||
45 | changePassword (currentPassword: string, newPassword: string) { | ||
46 | const url = UserService.BASE_USERS_URL + 'me' | ||
47 | const body: UserUpdateMe = { | ||
48 | currentPassword, | ||
49 | password: newPassword | ||
50 | } | ||
51 | |||
52 | return this.authHttp.put(url, body) | ||
53 | .pipe( | ||
54 | map(this.restExtractor.extractDataBool), | ||
55 | catchError(err => this.restExtractor.handleError(err)) | ||
56 | ) | ||
57 | } | ||
58 | |||
59 | changeEmail (password: string, newEmail: string) { | ||
60 | const url = UserService.BASE_USERS_URL + 'me' | ||
61 | const body: UserUpdateMe = { | ||
62 | currentPassword: password, | ||
63 | email: newEmail | ||
64 | } | ||
65 | |||
66 | return this.authHttp.put(url, body) | ||
67 | .pipe( | ||
68 | map(this.restExtractor.extractDataBool), | ||
69 | catchError(err => this.restExtractor.handleError(err)) | ||
70 | ) | ||
71 | } | ||
72 | |||
73 | updateMyProfile (profile: UserUpdateMe) { | ||
74 | const url = UserService.BASE_USERS_URL + 'me' | ||
75 | |||
76 | return this.authHttp.put(url, profile) | ||
77 | .pipe( | ||
78 | map(this.restExtractor.extractDataBool), | ||
79 | catchError(err => this.restExtractor.handleError(err)) | ||
80 | ) | ||
81 | } | ||
82 | |||
83 | updateMyAnonymousProfile (profile: UserUpdateMe) { | ||
84 | const supportedKeys = { | ||
85 | // local storage keys | ||
86 | nsfwPolicy: (val: NSFWPolicyType) => this.localStorageService.setItem(User.KEYS.NSFW_POLICY, val), | ||
87 | webTorrentEnabled: (val: boolean) => this.localStorageService.setItem(User.KEYS.WEBTORRENT_ENABLED, String(val)), | ||
88 | autoPlayVideo: (val: boolean) => this.localStorageService.setItem(User.KEYS.AUTO_PLAY_VIDEO, String(val)), | ||
89 | autoPlayNextVideoPlaylist: (val: boolean) => this.localStorageService.setItem(User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST, String(val)), | ||
90 | theme: (val: string) => this.localStorageService.setItem(User.KEYS.THEME, val), | ||
91 | videoLanguages: (val: string[]) => this.localStorageService.setItem(User.KEYS.VIDEO_LANGUAGES, JSON.stringify(val)), | ||
92 | |||
93 | // session storage keys | ||
94 | autoPlayNextVideo: (val: boolean) => | ||
95 | this.sessionStorageService.setItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO, String(val)) | ||
96 | } | ||
97 | |||
98 | for (const key of Object.keys(profile)) { | ||
99 | try { | ||
100 | if (has(supportedKeys, key)) supportedKeys[key](profile[key]) | ||
101 | } catch (err) { | ||
102 | console.error(`Cannot set item ${key} in localStorage. Likely due to a value impossible to stringify.`, err) | ||
103 | } | ||
104 | } | ||
105 | } | ||
106 | |||
107 | listenAnonymousUpdate () { | ||
108 | return this.localStorageService.watch([ | ||
109 | User.KEYS.NSFW_POLICY, | ||
110 | User.KEYS.WEBTORRENT_ENABLED, | ||
111 | User.KEYS.AUTO_PLAY_VIDEO, | ||
112 | User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST, | ||
113 | User.KEYS.THEME, | ||
114 | User.KEYS.VIDEO_LANGUAGES | ||
115 | ]).pipe( | ||
116 | throttleTime(200), | ||
117 | filter(() => this.authService.isLoggedIn() !== true), | ||
118 | map(() => this.getAnonymousUser()) | ||
119 | ) | ||
120 | } | ||
121 | |||
122 | deleteMe () { | ||
123 | const url = UserService.BASE_USERS_URL + 'me' | ||
124 | |||
125 | return this.authHttp.delete(url) | ||
126 | .pipe( | ||
127 | map(this.restExtractor.extractDataBool), | ||
128 | catchError(err => this.restExtractor.handleError(err)) | ||
129 | ) | ||
130 | } | ||
131 | |||
132 | changeAvatar (avatarForm: FormData) { | ||
133 | const url = UserService.BASE_USERS_URL + 'me/avatar/pick' | ||
134 | |||
135 | return this.authHttp.post<{ avatar: Avatar }>(url, avatarForm) | ||
136 | .pipe(catchError(err => this.restExtractor.handleError(err))) | ||
137 | } | ||
138 | |||
139 | signup (userCreate: UserRegister) { | ||
140 | return this.authHttp.post(UserService.BASE_USERS_URL + 'register', userCreate) | ||
141 | .pipe( | ||
142 | map(this.restExtractor.extractDataBool), | ||
143 | catchError(err => this.restExtractor.handleError(err)) | ||
144 | ) | ||
145 | } | ||
146 | |||
147 | getMyVideoQuotaUsed () { | ||
148 | const url = UserService.BASE_USERS_URL + 'me/video-quota-used' | ||
149 | |||
150 | return this.authHttp.get<UserVideoQuota>(url) | ||
151 | .pipe(catchError(err => this.restExtractor.handleError(err))) | ||
152 | } | ||
153 | |||
154 | askResetPassword (email: string) { | ||
155 | const url = UserService.BASE_USERS_URL + '/ask-reset-password' | ||
156 | |||
157 | return this.authHttp.post(url, { email }) | ||
158 | .pipe( | ||
159 | map(this.restExtractor.extractDataBool), | ||
160 | catchError(err => this.restExtractor.handleError(err)) | ||
161 | ) | ||
162 | } | ||
163 | |||
164 | resetPassword (userId: number, verificationString: string, password: string) { | ||
165 | const url = `${UserService.BASE_USERS_URL}/${userId}/reset-password` | ||
166 | const body = { | ||
167 | verificationString, | ||
168 | password | ||
169 | } | ||
170 | |||
171 | return this.authHttp.post(url, body) | ||
172 | .pipe( | ||
173 | map(this.restExtractor.extractDataBool), | ||
174 | catchError(res => this.restExtractor.handleError(res)) | ||
175 | ) | ||
176 | } | ||
177 | |||
178 | verifyEmail (userId: number, verificationString: string, isPendingEmail: boolean) { | ||
179 | const url = `${UserService.BASE_USERS_URL}/${userId}/verify-email` | ||
180 | const body = { | ||
181 | verificationString, | ||
182 | isPendingEmail | ||
183 | } | ||
184 | |||
185 | return this.authHttp.post(url, body) | ||
186 | .pipe( | ||
187 | map(this.restExtractor.extractDataBool), | ||
188 | catchError(res => this.restExtractor.handleError(res)) | ||
189 | ) | ||
190 | } | ||
191 | |||
192 | askSendVerifyEmail (email: string) { | ||
193 | const url = UserService.BASE_USERS_URL + '/ask-send-verify-email' | ||
194 | |||
195 | return this.authHttp.post(url, { email }) | ||
196 | .pipe( | ||
197 | map(this.restExtractor.extractDataBool), | ||
198 | catchError(err => this.restExtractor.handleError(err)) | ||
199 | ) | ||
200 | } | ||
201 | |||
202 | autocomplete (search: string): Observable<string[]> { | ||
203 | const url = UserService.BASE_USERS_URL + 'autocomplete' | ||
204 | const params = new HttpParams().append('search', search) | ||
205 | |||
206 | return this.authHttp | ||
207 | .get<string[]>(url, { params }) | ||
208 | .pipe(catchError(res => this.restExtractor.handleError(res))) | ||
209 | } | ||
210 | |||
211 | getNewUsername (oldDisplayName: string, newDisplayName: string, currentUsername: string) { | ||
212 | // Don't update display name, the user seems to have changed it | ||
213 | if (this.displayNameToUsername(oldDisplayName) !== currentUsername) return currentUsername | ||
214 | |||
215 | return this.displayNameToUsername(newDisplayName) | ||
216 | } | ||
217 | |||
218 | displayNameToUsername (displayName: string) { | ||
219 | if (!displayName) return '' | ||
220 | |||
221 | return displayName | ||
222 | .toLowerCase() | ||
223 | .replace(/\s/g, '_') | ||
224 | .replace(/[^a-z0-9_.]/g, '') | ||
225 | } | ||
226 | |||
227 | /* ###### Admin methods ###### */ | ||
228 | |||
229 | addUser (userCreate: UserCreate) { | ||
230 | return this.authHttp.post(UserService.BASE_USERS_URL, userCreate) | ||
231 | .pipe( | ||
232 | map(this.restExtractor.extractDataBool), | ||
233 | catchError(err => this.restExtractor.handleError(err)) | ||
234 | ) | ||
235 | } | ||
236 | |||
237 | updateUser (userId: number, userUpdate: UserUpdate) { | ||
238 | return this.authHttp.put(UserService.BASE_USERS_URL + userId, userUpdate) | ||
239 | .pipe( | ||
240 | map(this.restExtractor.extractDataBool), | ||
241 | catchError(err => this.restExtractor.handleError(err)) | ||
242 | ) | ||
243 | } | ||
244 | |||
245 | updateUsers (users: UserServerModel[], userUpdate: UserUpdate) { | ||
246 | return from(users) | ||
247 | .pipe( | ||
248 | concatMap(u => this.authHttp.put(UserService.BASE_USERS_URL + u.id, userUpdate)), | ||
249 | toArray(), | ||
250 | catchError(err => this.restExtractor.handleError(err)) | ||
251 | ) | ||
252 | } | ||
253 | |||
254 | getUserWithCache (userId: number) { | ||
255 | if (!this.userCache[userId]) { | ||
256 | this.userCache[ userId ] = this.getUser(userId).pipe(shareReplay()) | ||
257 | } | ||
258 | |||
259 | return this.userCache[userId] | ||
260 | } | ||
261 | |||
262 | getUser (userId: number, withStats = false) { | ||
263 | const params = new HttpParams().append('withStats', withStats + '') | ||
264 | return this.authHttp.get<UserServerModel>(UserService.BASE_USERS_URL + userId, { params }) | ||
265 | .pipe(catchError(err => this.restExtractor.handleError(err))) | ||
266 | } | ||
267 | |||
268 | getAnonymousUser () { | ||
269 | let videoLanguages: string[] | ||
270 | |||
271 | try { | ||
272 | videoLanguages = JSON.parse(this.localStorageService.getItem(User.KEYS.VIDEO_LANGUAGES)) | ||
273 | } catch (err) { | ||
274 | videoLanguages = null | ||
275 | console.error('Cannot parse desired video languages from localStorage.', err) | ||
276 | } | ||
277 | |||
278 | return new User({ | ||
279 | // local storage keys | ||
280 | nsfwPolicy: this.localStorageService.getItem(User.KEYS.NSFW_POLICY) as NSFWPolicyType, | ||
281 | webTorrentEnabled: this.localStorageService.getItem(User.KEYS.WEBTORRENT_ENABLED) !== 'false', | ||
282 | theme: this.localStorageService.getItem(User.KEYS.THEME) || 'instance-default', | ||
283 | videoLanguages, | ||
284 | |||
285 | autoPlayNextVideoPlaylist: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO_PLAYLIST) !== 'false', | ||
286 | autoPlayVideo: this.localStorageService.getItem(User.KEYS.AUTO_PLAY_VIDEO) === 'true', | ||
287 | |||
288 | // session storage keys | ||
289 | autoPlayNextVideo: this.sessionStorageService.getItem(User.KEYS.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true' | ||
290 | }) | ||
291 | } | ||
292 | |||
293 | getUsers (pagination: RestPagination, sort: SortMeta, search?: string): Observable<ResultList<UserServerModel>> { | ||
294 | let params = new HttpParams() | ||
295 | params = this.restService.addRestGetParams(params, pagination, sort) | ||
296 | |||
297 | if (search) params = params.append('search', search) | ||
298 | |||
299 | return this.authHttp.get<ResultList<UserServerModel>>(UserService.BASE_USERS_URL, { params }) | ||
300 | .pipe( | ||
301 | map(res => this.restExtractor.convertResultListDateToHuman(res)), | ||
302 | map(res => this.restExtractor.applyToResultListData(res, this.formatUser.bind(this))), | ||
303 | catchError(err => this.restExtractor.handleError(err)) | ||
304 | ) | ||
305 | } | ||
306 | |||
307 | removeUser (usersArg: UserServerModel | UserServerModel[]) { | ||
308 | const users = Array.isArray(usersArg) ? usersArg : [ usersArg ] | ||
309 | |||
310 | return from(users) | ||
311 | .pipe( | ||
312 | concatMap(u => this.authHttp.delete(UserService.BASE_USERS_URL + u.id)), | ||
313 | toArray(), | ||
314 | catchError(err => this.restExtractor.handleError(err)) | ||
315 | ) | ||
316 | } | ||
317 | |||
318 | banUsers (usersArg: UserServerModel | UserServerModel[], reason?: string) { | ||
319 | const body = reason ? { reason } : {} | ||
320 | const users = Array.isArray(usersArg) ? usersArg : [ usersArg ] | ||
321 | |||
322 | return from(users) | ||
323 | .pipe( | ||
324 | concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/block', body)), | ||
325 | toArray(), | ||
326 | catchError(err => this.restExtractor.handleError(err)) | ||
327 | ) | ||
328 | } | ||
329 | |||
330 | unbanUsers (usersArg: UserServerModel | UserServerModel[]) { | ||
331 | const users = Array.isArray(usersArg) ? usersArg : [ usersArg ] | ||
332 | |||
333 | return from(users) | ||
334 | .pipe( | ||
335 | concatMap(u => this.authHttp.post(UserService.BASE_USERS_URL + u.id + '/unblock', {})), | ||
336 | toArray(), | ||
337 | catchError(err => this.restExtractor.handleError(err)) | ||
338 | ) | ||
339 | } | ||
340 | |||
341 | getAnonymousOrLoggedUser () { | ||
342 | if (!this.authService.isLoggedIn()) { | ||
343 | return of(this.getAnonymousUser()) | ||
344 | } | ||
345 | |||
346 | return this.authService.userInformationLoaded | ||
347 | .pipe( | ||
348 | first(), | ||
349 | map(() => this.authService.getUser()) | ||
350 | ) | ||
351 | } | ||
352 | |||
353 | private formatUser (user: UserServerModel) { | ||
354 | let videoQuota | ||
355 | if (user.videoQuota === -1) { | ||
356 | videoQuota = this.i18n('Unlimited') | ||
357 | } else { | ||
358 | videoQuota = this.bytesPipe.transform(user.videoQuota, 0) | ||
359 | } | ||
360 | |||
361 | const videoQuotaUsed = this.bytesPipe.transform(user.videoQuotaUsed, 0) | ||
362 | |||
363 | const roleLabels: { [ id in UserRole ]: string } = { | ||
364 | [UserRole.USER]: this.i18n('User'), | ||
365 | [UserRole.ADMINISTRATOR]: this.i18n('Administrator'), | ||
366 | [UserRole.MODERATOR]: this.i18n('Moderator') | ||
367 | } | ||
368 | |||
369 | return Object.assign(user, { | ||
370 | roleLabel: roleLabels[user.role], | ||
371 | videoQuota, | ||
372 | videoQuotaUsed | ||
373 | }) | ||
374 | } | ||
375 | } | ||