1 import { forkJoin, of, Subscription } from 'rxjs'
2 import { LinkType } from 'src/types/link.type'
3 import { Component, OnDestroy, OnInit } from '@angular/core'
4 import { ActivatedRoute, Router } from '@angular/router'
5 import { AuthService, HooksService, MetaService, Notifier, ServerService, User, UserService } from '@app/core'
6 import { immutableAssign } from '@app/helpers'
7 import { validateHost } from '@app/shared/form-validators/host-validators'
8 import { Video, VideoChannel } from '@app/shared/shared-main'
9 import { AdvancedSearch, SearchService } from '@app/shared/shared-search'
10 import { MiniatureDisplayOptions } from '@app/shared/shared-video-miniature'
11 import { VideoPlaylist } from '@app/shared/shared-video-playlist'
12 import { HTMLServerConfig, SearchTargetType } from '@shared/models'
15 selector: 'my-search',
16 styleUrls: [ './search.component.scss' ],
17 templateUrl: './search.component.html'
19 export class SearchComponent implements OnInit, OnDestroy {
22 results: (Video | VideoChannel)[] = []
26 totalItems: null as number
28 advancedSearch: AdvancedSearch = new AdvancedSearch()
29 isSearchFilterCollapsed = true
32 videoDisplayOptions: MiniatureDisplayOptions = {
47 private subActivatedRoute: Subscription
48 private isInitialLoad = false // set to false to show the search filters on first arrival
50 private channelsPerPage = 2
51 private playlistsPerPage = 2
52 private videosPerPage = 10
54 private hasMoreResults = true
55 private isSearching = false
57 private lastSearchTarget: SearchTargetType
59 private serverConfig: HTMLServerConfig
62 private route: ActivatedRoute,
63 private router: Router,
64 private metaService: MetaService,
65 private notifier: Notifier,
66 private searchService: SearchService,
67 private authService: AuthService,
68 private userService: UserService,
69 private hooks: HooksService,
70 private serverService: ServerService
74 this.serverConfig = this.serverService.getHTMLConfig()
76 this.subActivatedRoute = this.route.queryParams.subscribe(
77 async queryParams => {
78 const querySearch = queryParams['search']
79 const searchTarget = queryParams['searchTarget']
81 // Search updated, reset filters
82 if (this.currentSearch !== querySearch || searchTarget !== this.advancedSearch.searchTarget) {
83 this.resetPagination()
84 this.advancedSearch.reset()
86 this.currentSearch = querySearch || undefined
90 this.advancedSearch = new AdvancedSearch(queryParams)
91 if (!this.advancedSearch.searchTarget) {
92 this.advancedSearch.searchTarget = this.getDefaultSearchTarget()
95 this.error = this.checkFieldsAndGetError()
97 // Don't hide filters if we have some of them AND the user just came on the webpage, or we have an error
98 this.isSearchFilterCollapsed = !this.error && (this.isInitialLoad === false || !this.advancedSearch.containsValues())
99 this.isInitialLoad = false
104 err => this.notifier.error(err.text)
107 this.userService.getAnonymousOrLoggedUser()
108 .subscribe(user => this.userMiniature = user)
110 this.hooks.runAction('action:search.init', 'search')
114 if (this.subActivatedRoute) this.subActivatedRoute.unsubscribe()
117 isVideoChannel (d: VideoChannel | Video | VideoPlaylist): d is VideoChannel {
118 return d instanceof VideoChannel
121 isVideo (v: VideoChannel | Video | VideoPlaylist): v is Video {
122 return v instanceof Video
125 isPlaylist (v: VideoChannel | Video | VideoPlaylist): v is VideoPlaylist {
126 return v instanceof VideoPlaylist
130 return this.authService.isLoggedIn()
134 this.error = this.checkFieldsAndGetError()
135 if (this.error) return
137 this.isSearching = true
140 this.getVideoChannelObs(),
141 this.getVideoPlaylistObs(),
143 ]).subscribe(results => {
144 for (const result of results) {
145 this.results = this.results.concat(result.data)
148 this.pagination.totalItems = results.reduce((p, r) => p += r.total, 0)
149 this.lastSearchTarget = this.advancedSearch.searchTarget
151 this.hasMoreResults = this.results.length < this.pagination.totalItems
155 if (this.advancedSearch.searchTarget !== 'search-index') {
156 this.notifier.error(err.message)
161 $localize`Search index is unavailable. Retrying with instance results instead.`,
162 $localize`Search error`
164 this.advancedSearch.searchTarget = 'local'
169 this.isSearching = false
175 if (!this.hasMoreResults || this.isSearching) return
177 this.pagination.currentPage += 1
182 this.resetPagination()
184 this.updateUrlFromAdvancedSearch()
188 return this.advancedSearch.size()
191 // Add VideoChannel/VideoPlaylist for typings, but the template already checks "video" argument is a video
192 removeVideoFromArray (video: Video | VideoChannel | VideoPlaylist) {
193 this.results = this.results.filter(r => !this.isVideo(r) || r.id !== video.id)
196 getLinkType (): LinkType {
197 if (this.advancedSearch.searchTarget === 'search-index') {
198 const remoteUriConfig = this.serverConfig.search.remoteUri
200 // Redirect on the external instance if not allowed to fetch remote data
201 if ((!this.isUserLoggedIn() && !remoteUriConfig.anonymous) || !remoteUriConfig.users) {
211 isExternalChannelUrl () {
212 return this.getLinkType() === 'external'
215 getExternalChannelUrl (channel: VideoChannel) {
216 // Same algorithm than videos
217 if (this.getLinkType() === 'external') {
221 // lazy-load or internal
225 getInternalChannelUrl (channel: VideoChannel) {
226 const linkType = this.getLinkType()
228 if (linkType === 'internal') {
229 return [ '/c', channel.nameWithHost ]
232 if (linkType === 'lazy-load') {
233 return [ '/search/lazy-load-channel', { url: channel.url } ]
241 return this.lastSearchTarget === 'search-index'
244 private resetPagination () {
245 this.pagination.currentPage = 1
246 this.pagination.totalItems = null
247 this.channelsPerPage = 2
252 private updateTitle () {
253 const suffix = this.currentSearch
254 ? ' ' + this.currentSearch
257 this.metaService.setTitle($localize`Search` + suffix)
260 private updateUrlFromAdvancedSearch () {
261 const search = this.currentSearch || undefined
263 this.router.navigate([], {
264 relativeTo: this.route,
265 queryParams: Object.assign({}, this.advancedSearch.toUrlObject(), { search })
269 private getVideosObs () {
271 search: this.currentSearch,
272 componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.videosPerPage }),
273 advancedSearch: this.advancedSearch
276 return this.hooks.wrapObsFun(
277 this.searchService.searchVideos.bind(this.searchService),
280 'filter:api.search.videos.list.params',
281 'filter:api.search.videos.list.result'
285 private getVideoChannelObs () {
286 if (!this.currentSearch) return of({ data: [], total: 0 })
289 search: this.currentSearch,
290 componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.channelsPerPage }),
291 advancedSearch: this.advancedSearch
294 return this.hooks.wrapObsFun(
295 this.searchService.searchVideoChannels.bind(this.searchService),
298 'filter:api.search.video-channels.list.params',
299 'filter:api.search.video-channels.list.result'
303 private getVideoPlaylistObs () {
304 if (!this.currentSearch) return of({ data: [], total: 0 })
307 search: this.currentSearch,
308 componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.playlistsPerPage }),
309 advancedSearch: this.advancedSearch
312 return this.hooks.wrapObsFun(
313 this.searchService.searchVideoPlaylists.bind(this.searchService),
316 'filter:api.search.video-playlists.list.params',
317 'filter:api.search.video-playlists.list.result'
321 private getDefaultSearchTarget (): SearchTargetType {
322 const searchIndexConfig = this.serverConfig.search.searchIndex
324 if (searchIndexConfig.enabled && (searchIndexConfig.isDefaultSearch || searchIndexConfig.disableLocalSearch)) {
325 return 'search-index'
331 private checkFieldsAndGetError () {
332 if (this.advancedSearch.host && !validateHost(this.advancedSearch.host)) {
333 return $localize`PeerTube instance host filter is invalid`