]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/menu/menu.component.ts
896c824b8ac16fab1219819f7e3eaec867ef2647
[github/Chocobozzz/PeerTube.git] / client / src / app / menu / menu.component.ts
1 import { HotkeysService } from 'angular2-hotkeys'
2 import * as debug from 'debug'
3 import { forkJoin, Subscription } from 'rxjs'
4 import { first, switchMap } from 'rxjs/operators'
5 import { ViewportScroller } from '@angular/common'
6 import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'
7 import { Router } from '@angular/router'
8 import {
9 AuthService,
10 AuthStatus,
11 AuthUser,
12 HooksService,
13 MenuSection,
14 MenuService,
15 RedirectService,
16 ScreenService,
17 ServerService,
18 UserService
19 } from '@app/core'
20 import { scrollToTop } from '@app/helpers'
21 import { LanguageChooserComponent } from '@app/menu/language-chooser.component'
22 import { QuickSettingsModalComponent } from '@app/modal/quick-settings-modal.component'
23 import { PeertubeModalService } from '@app/shared/shared-main/peertube-modal/peertube-modal.service'
24 import { NgbDropdown } from '@ng-bootstrap/ng-bootstrap'
25 import { HTMLServerConfig, ServerConfig, UserRight, VideoConstant } from '@shared/models'
26
27 const debugLogger = debug('peertube:menu:MenuComponent')
28
29 @Component({
30 selector: 'my-menu',
31 templateUrl: './menu.component.html',
32 styleUrls: [ './menu.component.scss' ]
33 })
34 export class MenuComponent implements OnInit, OnDestroy {
35 @ViewChild('languageChooserModal', { static: true }) languageChooserModal: LanguageChooserComponent
36 @ViewChild('quickSettingsModal', { static: true }) quickSettingsModal: QuickSettingsModalComponent
37 @ViewChild('dropdown') dropdown: NgbDropdown
38
39 user: AuthUser
40 isLoggedIn: boolean
41
42 userHasAdminAccess = false
43 helpVisible = false
44
45 videoLanguages: string[] = []
46 nsfwPolicy: string
47
48 currentInterfaceLanguage: string
49
50 menuSections: MenuSection[] = []
51
52 private languages: VideoConstant<string>[] = []
53
54 private htmlServerConfig: HTMLServerConfig
55 private serverConfig: ServerConfig
56
57 private routesPerRight: { [role in UserRight]?: string } = {
58 [UserRight.MANAGE_USERS]: '/admin/users',
59 [UserRight.MANAGE_SERVER_FOLLOW]: '/admin/friends',
60 [UserRight.MANAGE_ABUSES]: '/admin/moderation/abuses',
61 [UserRight.MANAGE_VIDEO_BLACKLIST]: '/admin/moderation/video-blocks',
62 [UserRight.MANAGE_JOBS]: '/admin/jobs',
63 [UserRight.MANAGE_CONFIGURATION]: '/admin/config'
64 }
65
66 private languagesSub: Subscription
67 private modalSub: Subscription
68 private hotkeysSub: Subscription
69 private authSub: Subscription
70
71 constructor (
72 private viewportScroller: ViewportScroller,
73 private authService: AuthService,
74 private userService: UserService,
75 private serverService: ServerService,
76 private redirectService: RedirectService,
77 private hotkeysService: HotkeysService,
78 private screenService: ScreenService,
79 private menuService: MenuService,
80 private modalService: PeertubeModalService,
81 private router: Router,
82 private hooks: HooksService
83 ) { }
84
85 get isInMobileView () {
86 return this.screenService.isInMobileView()
87 }
88
89 get dropdownContainer () {
90 if (this.isInMobileView) return null
91
92 return 'body' as 'body'
93 }
94
95 get language () {
96 return this.languageChooserModal.getCurrentLanguage()
97 }
98
99 get requiresApproval () {
100 return this.serverConfig.signup.requiresApproval
101 }
102
103 ngOnInit () {
104 this.htmlServerConfig = this.serverService.getHTMLConfig()
105 this.currentInterfaceLanguage = this.languageChooserModal.getCurrentLanguage()
106
107 this.isLoggedIn = this.authService.isLoggedIn()
108 this.updateUserState()
109 this.buildMenuSections()
110
111 this.authSub = this.authService.loginChangedSource.subscribe(status => {
112 if (status === AuthStatus.LoggedIn) {
113 this.isLoggedIn = true
114 } else if (status === AuthStatus.LoggedOut) {
115 this.isLoggedIn = false
116 }
117
118 this.updateUserState()
119 this.buildMenuSections()
120 })
121
122 this.hotkeysSub = this.hotkeysService.cheatSheetToggle
123 .subscribe(isOpen => this.helpVisible = isOpen)
124
125 this.languagesSub = forkJoin([
126 this.serverService.getVideoLanguages(),
127 this.authService.userInformationLoaded.pipe(first())
128 ]).subscribe(([ languages ]) => {
129 this.languages = languages
130
131 this.buildUserLanguages()
132 })
133
134 this.serverService.getConfig()
135 .subscribe(config => this.serverConfig = config)
136
137 this.modalSub = this.modalService.openQuickSettingsSubject
138 .subscribe(() => this.openQuickSettings())
139 }
140
141 ngOnDestroy () {
142 if (this.modalSub) this.modalSub.unsubscribe()
143 if (this.languagesSub) this.languagesSub.unsubscribe()
144 if (this.hotkeysSub) this.hotkeysSub.unsubscribe()
145 if (this.authSub) this.authSub.unsubscribe()
146 }
147
148 isRegistrationAllowed () {
149 if (!this.serverConfig) return false
150
151 return this.serverConfig.signup.allowed &&
152 this.serverConfig.signup.allowedForCurrentIP
153 }
154
155 getFirstAdminRightAvailable () {
156 const user = this.authService.getUser()
157 if (!user) return undefined
158
159 const adminRights = [
160 UserRight.MANAGE_USERS,
161 UserRight.MANAGE_SERVER_FOLLOW,
162 UserRight.MANAGE_ABUSES,
163 UserRight.MANAGE_VIDEO_BLACKLIST,
164 UserRight.MANAGE_JOBS,
165 UserRight.MANAGE_CONFIGURATION
166 ]
167
168 for (const adminRight of adminRights) {
169 if (user.hasRight(adminRight)) {
170 return adminRight
171 }
172 }
173
174 return undefined
175 }
176
177 getFirstAdminRouteAvailable () {
178 const right = this.getFirstAdminRightAvailable()
179
180 return this.routesPerRight[right]
181 }
182
183 logout (event: Event) {
184 event.preventDefault()
185
186 this.authService.logout()
187 // Redirect to home page
188 this.redirectService.redirectToHomepage()
189 }
190
191 openLanguageChooser () {
192 this.languageChooserModal.show()
193 }
194
195 openHotkeysCheatSheet () {
196 this.hotkeysService.cheatSheetToggle.next(!this.helpVisible)
197 }
198
199 openQuickSettings () {
200 this.quickSettingsModal.show()
201 }
202
203 toggleUseP2P () {
204 if (!this.user) return
205 this.user.p2pEnabled = !this.user.p2pEnabled
206
207 this.userService.updateMyProfile({ p2pEnabled: this.user.p2pEnabled })
208 .subscribe(() => this.authService.refreshUserInformation())
209 }
210
211 langForLocale (localeId: string) {
212 if (localeId === '_unknown') return $localize`Unknown`
213
214 return this.languages.find(lang => lang.id === localeId).label
215 }
216
217 onActiveLinkScrollToAnchor (link: HTMLAnchorElement) {
218 const linkURL = link.getAttribute('href')
219 const linkHash = link.getAttribute('fragment')
220
221 // On same url without fragment restore top scroll position
222 if (!linkHash && this.router.url.includes(linkURL)) {
223 scrollToTop('smooth')
224 }
225
226 // On same url with fragment restore anchor scroll position
227 if (linkHash && this.router.url === linkURL) {
228 this.viewportScroller.scrollToAnchor(linkHash)
229 }
230
231 if (this.screenService.isInSmallView()) {
232 this.menuService.toggleMenu()
233 }
234 }
235
236 // Lock menu scroll when menu scroll to avoid fleeing / detached dropdown
237 onMenuScrollEvent () {
238 document.querySelector('menu').scrollTo(0, 0)
239 }
240
241 onDropdownOpenChange (opened: boolean) {
242 if (this.screenService.isInMobileView()) return
243
244 // Close dropdown when window scroll to avoid dropdown quick jump for re-position
245 const onWindowScroll = () => {
246 this.dropdown?.close()
247 window.removeEventListener('scroll', onWindowScroll)
248 }
249
250 if (opened) {
251 window.addEventListener('scroll', onWindowScroll)
252 document.querySelector('menu').scrollTo(0, 0) // Reset menu scroll to easy lock
253 document.querySelector('menu').addEventListener('scroll', this.onMenuScrollEvent)
254 } else {
255 document.querySelector('menu').removeEventListener('scroll', this.onMenuScrollEvent)
256 }
257 }
258
259 private async buildMenuSections () {
260 const menuSections = []
261
262 if (this.isLoggedIn) {
263 menuSections.push(
264 this.menuService.buildLibraryLinks(this.user?.canSeeVideosLink)
265 )
266 }
267
268 menuSections.push(
269 this.menuService.buildCommonLinks(this.htmlServerConfig)
270 )
271
272 this.menuSections = await this.hooks.wrapObject(menuSections, 'common', 'filter:left-menu.links.create.result')
273 }
274
275 private buildUserLanguages () {
276 if (!this.user) {
277 this.videoLanguages = []
278 return
279 }
280
281 if (!this.user.videoLanguages) {
282 this.videoLanguages = [ $localize`any language` ]
283 return
284 }
285
286 this.videoLanguages = this.user.videoLanguages
287 .map(locale => this.langForLocale(locale))
288 .map(value => value === undefined ? '?' : value)
289 }
290
291 private computeAdminAccess () {
292 const right = this.getFirstAdminRightAvailable()
293
294 this.userHasAdminAccess = right !== undefined
295 }
296
297 private computeVideosLink () {
298 if (!this.isLoggedIn) return
299
300 this.authService.userInformationLoaded
301 .pipe(
302 switchMap(() => this.user.computeCanSeeVideosLink(this.userService.getMyVideoQuotaUsed()))
303 ).subscribe(res => {
304 if (res === true) debugLogger('User can see videos link.')
305 else debugLogger('User cannot see videos link.')
306 })
307 }
308
309 private computeNSFWPolicy () {
310 if (!this.user) {
311 this.nsfwPolicy = null
312 return
313 }
314
315 switch (this.user.nsfwPolicy) {
316 case 'do_not_list':
317 this.nsfwPolicy = $localize`hide`
318 break
319
320 case 'blur':
321 this.nsfwPolicy = $localize`blur`
322 break
323
324 case 'display':
325 this.nsfwPolicy = $localize`display`
326 break
327 }
328 }
329
330 private updateUserState () {
331 this.user = this.isLoggedIn
332 ? this.authService.getUser()
333 : undefined
334
335 this.computeAdminAccess()
336 this.computeNSFWPolicy()
337 this.computeVideosLink()
338 }
339 }