ca4a32cbc7732ca5fe1107472445d2891a26b60a
[oweals/peertube.git] / client / src / app / header / header.component.ts
1 import { filter, first, map, tap } from 'rxjs/operators'
2 import { Component, OnInit } from '@angular/core'
3 import { ActivatedRoute, NavigationEnd, Params, Router } from '@angular/router'
4 import { getParameterByName } from '../shared/misc/utils'
5 import { AuthService } from '@app/core'
6 import { of } from 'rxjs'
7 import { I18n } from '@ngx-translate/i18n-polyfill'
8
9 @Component({
10   selector: 'my-header',
11   templateUrl: './header.component.html',
12   styleUrls: [ './header.component.scss' ]
13 })
14
15 export class HeaderComponent implements OnInit {
16   searchValue = ''
17   ariaLabelTextForSearch = ''
18
19   constructor (
20     private router: Router,
21     private route: ActivatedRoute,
22     private auth: AuthService,
23     private i18n: I18n
24   ) {}
25
26   ngOnInit () {
27     this.ariaLabelTextForSearch = this.i18n('Search videos, channels')
28
29     this.router.events
30         .pipe(
31           filter(e => e instanceof NavigationEnd),
32           map(() => getParameterByName('search', window.location.href))
33         )
34         .subscribe(searchQuery => this.searchValue = searchQuery || '')
35   }
36
37   doSearch () {
38     const queryParams: Params = {}
39
40     if (window.location.pathname === '/search' && this.route.snapshot.queryParams) {
41       Object.assign(queryParams, this.route.snapshot.queryParams)
42     }
43
44     Object.assign(queryParams, { search: this.searchValue })
45
46     const o = this.auth.isLoggedIn()
47       ? this.loadUserLanguagesIfNeeded(queryParams)
48       : of(true)
49
50     o.subscribe(() => this.router.navigate([ '/search' ], { queryParams }))
51   }
52
53   private loadUserLanguagesIfNeeded (queryParams: any) {
54     if (queryParams && queryParams.languageOneOf) return of(queryParams)
55
56     return this.auth.userInformationLoaded
57                .pipe(
58                  first(),
59                  tap(() => Object.assign(queryParams, { languageOneOf: this.auth.getUser().videoLanguages }))
60                )
61   }
62 }