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