]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/search/search.component.ts
First implem global search
[github/Chocobozzz/PeerTube.git] / client / src / app / search / search.component.ts
1 import { forkJoin, of, Subscription } from 'rxjs'
2 import { Component, OnDestroy, OnInit } from '@angular/core'
3 import { ActivatedRoute, Router } from '@angular/router'
4 import { AuthService, Notifier, ServerService } from '@app/core'
5 import { HooksService } from '@app/core/plugins/hooks.service'
6 import { AdvancedSearch } from '@app/search/advanced-search.model'
7 import { SearchService } from '@app/search/search.service'
8 import { immutableAssign } from '@app/shared/misc/utils'
9 import { ComponentPagination } from '@app/shared/rest/component-pagination.model'
10 import { VideoChannel } from '@app/shared/video-channel/video-channel.model'
11 import { Video } from '@app/shared/video/video.model'
12 import { MetaService } from '@ngx-meta/core'
13 import { I18n } from '@ngx-translate/i18n-polyfill'
14 import { ServerConfig } from '@shared/models'
15 import { UserService } from '@app/shared'
16
17 @Component({
18 selector: 'my-search',
19 styleUrls: [ './search.component.scss' ],
20 templateUrl: './search.component.html'
21 })
22 export class SearchComponent implements OnInit, OnDestroy {
23 results: (Video | VideoChannel)[] = []
24
25 pagination: ComponentPagination = {
26 currentPage: 1,
27 itemsPerPage: 10, // Only for videos, use another variable for channels
28 totalItems: null
29 }
30 advancedSearch: AdvancedSearch = new AdvancedSearch()
31 isSearchFilterCollapsed = true
32 currentSearch: string
33
34 errorMessage: string
35 serverConfig: ServerConfig
36
37 private subActivatedRoute: Subscription
38 private isInitialLoad = false // set to false to show the search filters on first arrival
39 private firstSearch = true
40
41 private channelsPerPage = 2
42
43 constructor (
44 private i18n: I18n,
45 private route: ActivatedRoute,
46 private router: Router,
47 private metaService: MetaService,
48 private notifier: Notifier,
49 private searchService: SearchService,
50 private authService: AuthService,
51 private hooks: HooksService,
52 private serverService: ServerService
53 ) { }
54
55 get user () {
56 return this.authService.getUser()
57 }
58
59 ngOnInit () {
60 this.serverService.getConfig()
61 .subscribe(config => this.serverConfig = config)
62
63 this.subActivatedRoute = this.route.queryParams.subscribe(
64 async queryParams => {
65 const querySearch = queryParams['search']
66
67 // Search updated, reset filters
68 if (this.currentSearch !== querySearch) {
69 this.resetPagination()
70 this.advancedSearch.reset()
71
72 this.currentSearch = querySearch || undefined
73 this.updateTitle()
74 }
75
76 this.advancedSearch = new AdvancedSearch(queryParams)
77 if (!this.advancedSearch.searchTarget) {
78 this.advancedSearch.searchTarget = await this.serverService.getDefaultSearchTarget()
79 }
80
81 // Don't hide filters if we have some of them AND the user just came on the webpage
82 this.isSearchFilterCollapsed = this.isInitialLoad === false || !this.advancedSearch.containsValues()
83 this.isInitialLoad = false
84
85 this.search()
86 },
87
88 err => this.notifier.error(err.text)
89 )
90
91 this.hooks.runAction('action:search.init', 'search')
92 }
93
94 ngOnDestroy () {
95 if (this.subActivatedRoute) this.subActivatedRoute.unsubscribe()
96 }
97
98 isVideoChannel (d: VideoChannel | Video): d is VideoChannel {
99 return d instanceof VideoChannel
100 }
101
102 isVideo (v: VideoChannel | Video): v is Video {
103 return v instanceof Video
104 }
105
106 isUserLoggedIn () {
107 return this.authService.isLoggedIn()
108 }
109
110 search () {
111 forkJoin([
112 this.getVideosObs(),
113 this.getVideoChannelObs()
114 ]).subscribe(
115 ([videosResult, videoChannelsResult]) => {
116 this.results = this.results
117 .concat(videoChannelsResult.data)
118 .concat(videosResult.data)
119
120 this.pagination.totalItems = videosResult.total + videoChannelsResult.total
121
122 // Focus on channels if there are no enough videos
123 if (this.firstSearch === true && videosResult.data.length < this.pagination.itemsPerPage) {
124 this.resetPagination()
125 this.firstSearch = false
126
127 this.channelsPerPage = 10
128 this.search()
129 }
130
131 this.firstSearch = false
132 },
133
134 err => {
135 if (this.advancedSearch.searchTarget !== 'search-index') this.notifier.error(err.message)
136
137 this.notifier.error(
138 this.i18n('Search index is unavailable. Retrying with instance results instead.'),
139 this.i18n('Search error')
140 )
141 this.advancedSearch.searchTarget = 'local'
142 this.search()
143 }
144 )
145 }
146
147 onNearOfBottom () {
148 // Last page
149 if (this.pagination.totalItems <= (this.pagination.currentPage * this.pagination.itemsPerPage)) return
150
151 this.pagination.currentPage += 1
152 this.search()
153 }
154
155 onFiltered () {
156 this.resetPagination()
157
158 this.updateUrlFromAdvancedSearch()
159 }
160
161 numberOfFilters () {
162 return this.advancedSearch.size()
163 }
164
165 // Add VideoChannel for typings, but the template already checks "video" argument is a video
166 removeVideoFromArray (video: Video | VideoChannel) {
167 this.results = this.results.filter(r => !this.isVideo(r) || r.id !== video.id)
168 }
169
170 getChannelUrl (channel: VideoChannel) {
171 if (this.advancedSearch.searchTarget === 'search-index' && channel.url) {
172 const remoteUriConfig = this.serverConfig.search.remoteUri
173
174 // Redirect on the external instance if not allowed to fetch remote data
175 const externalRedirect = (!this.authService.isLoggedIn() && !remoteUriConfig.anonymous) || !remoteUriConfig.users
176 const fromPath = window.location.pathname + window.location.search
177
178 return [ '/search/lazy-load-channel', { url: channel.url, externalRedirect, fromPath } ]
179 }
180
181 return [ '/video-channels', channel.nameWithHost ]
182 }
183
184 hideActions () {
185 return this.advancedSearch.searchTarget === 'search-index'
186 }
187
188 private resetPagination () {
189 this.pagination.currentPage = 1
190 this.pagination.totalItems = null
191 this.channelsPerPage = 2
192
193 this.results = []
194 }
195
196 private updateTitle () {
197 const suffix = this.currentSearch ? ' ' + this.currentSearch : ''
198 this.metaService.setTitle(this.i18n('Search') + suffix)
199 }
200
201 private updateUrlFromAdvancedSearch () {
202 const search = this.currentSearch || undefined
203
204 this.router.navigate([], {
205 relativeTo: this.route,
206 queryParams: Object.assign({}, this.advancedSearch.toUrlObject(), { search })
207 })
208 }
209
210 private getVideosObs () {
211 const params = {
212 search: this.currentSearch,
213 componentPagination: this.pagination,
214 advancedSearch: this.advancedSearch
215 }
216
217 return this.hooks.wrapObsFun(
218 this.searchService.searchVideos.bind(this.searchService),
219 params,
220 'search',
221 'filter:api.search.videos.list.params',
222 'filter:api.search.videos.list.result'
223 )
224 }
225
226 private getVideoChannelObs () {
227 if (!this.currentSearch) return of({ data: [], total: 0 })
228
229 const params = {
230 search: this.currentSearch,
231 componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.channelsPerPage }),
232 searchTarget: this.advancedSearch.searchTarget
233 }
234
235 return this.hooks.wrapObsFun(
236 this.searchService.searchVideoChannels.bind(this.searchService),
237 params,
238 'search',
239 'filter:api.search.video-channels.list.params',
240 'filter:api.search.video-channels.list.result'
241 )
242 }
243 }