1 import { forkJoin, 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 | VideoPlaylist)[] = []
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 hasMoreResults = true
51 private isSearching = false
53 private lastSearchTarget: SearchTargetType
55 private serverConfig: HTMLServerConfig
58 private route: ActivatedRoute,
59 private router: Router,
60 private metaService: MetaService,
61 private notifier: Notifier,
62 private searchService: SearchService,
63 private authService: AuthService,
64 private userService: UserService,
65 private hooks: HooksService,
66 private serverService: ServerService
70 this.serverConfig = this.serverService.getHTMLConfig()
72 this.subActivatedRoute = this.route.queryParams
74 next: queryParams => {
75 const querySearch = queryParams['search']
76 const searchTarget = queryParams['searchTarget']
78 // Search updated, reset filters
79 if (this.currentSearch !== querySearch || searchTarget !== this.advancedSearch.searchTarget) {
80 this.resetPagination()
81 this.advancedSearch.reset()
83 this.currentSearch = querySearch || undefined
87 this.advancedSearch = new AdvancedSearch(queryParams)
88 if (!this.advancedSearch.searchTarget) {
89 this.advancedSearch.searchTarget = this.getDefaultSearchTarget()
92 this.error = this.checkFieldsAndGetError()
94 // Don't hide filters if we have some of them AND the user just came on the webpage, or we have an error
95 this.isSearchFilterCollapsed = !this.error && (this.isInitialLoad === false || !this.advancedSearch.containsValues())
96 this.isInitialLoad = false
101 error: err => this.notifier.error(err.text)
104 this.userService.getAnonymousOrLoggedUser()
105 .subscribe(user => this.userMiniature = user)
107 this.hooks.runAction('action:search.init', 'search')
111 if (this.subActivatedRoute) this.subActivatedRoute.unsubscribe()
114 isVideoChannel (d: VideoChannel | Video | VideoPlaylist): d is VideoChannel {
115 return d instanceof VideoChannel
118 isVideo (v: VideoChannel | Video | VideoPlaylist): v is Video {
119 return v instanceof Video
122 isPlaylist (v: VideoChannel | Video | VideoPlaylist): v is VideoPlaylist {
123 return v instanceof VideoPlaylist
127 return this.authService.isLoggedIn()
131 this.error = this.checkFieldsAndGetError()
132 if (this.error) return
134 this.isSearching = true
137 this.getVideoChannelObs(),
138 this.getVideoPlaylistObs(),
142 for (const result of results) {
143 this.results = this.results.concat(result.data)
146 this.pagination.totalItems = results.reduce((p, r) => p += r.total, 0)
147 this.lastSearchTarget = this.advancedSearch.searchTarget
149 this.hasMoreResults = this.results.length < this.pagination.totalItems
153 if (this.advancedSearch.searchTarget !== 'search-index') {
154 this.notifier.error(err.message)
159 $localize`Search index is unavailable. Retrying with instance results instead.`,
160 $localize`Search error`
162 this.advancedSearch.searchTarget = 'local'
167 this.isSearching = false
174 if (!this.hasMoreResults || this.isSearching) return
176 this.pagination.currentPage += 1
181 this.resetPagination()
183 this.updateUrlFromAdvancedSearch()
187 return this.advancedSearch.size()
190 // Add VideoChannel/VideoPlaylist for typings, but the template already checks "video" argument is a video
191 removeVideoFromArray (video: Video | VideoChannel | VideoPlaylist) {
192 this.results = this.results.filter(r => !this.isVideo(r) || r.id !== video.id)
195 getLinkType (): LinkType {
196 if (this.advancedSearch.searchTarget === 'search-index') {
197 const remoteUriConfig = this.serverConfig.search.remoteUri
199 // Redirect on the external instance if not allowed to fetch remote data
200 if ((!this.isUserLoggedIn() && !remoteUriConfig.anonymous) || !remoteUriConfig.users) {
210 isExternalChannelUrl () {
211 return this.getLinkType() === 'external'
214 getExternalChannelUrl (channel: VideoChannel) {
215 // Same algorithm than videos
216 if (this.getLinkType() === 'external') {
220 // lazy-load or internal
224 getInternalChannelUrl (channel: VideoChannel) {
225 const linkType = this.getLinkType()
227 if (linkType === 'internal') {
228 return [ '/c', channel.nameWithHost ]
231 if (linkType === 'lazy-load') {
232 return [ '/search/lazy-load-channel', { url: channel.url } ]
240 return this.lastSearchTarget === 'search-index'
243 private resetPagination () {
244 this.pagination.currentPage = 1
245 this.pagination.totalItems = null
250 private updateTitle () {
251 const title = this.currentSearch
252 ? $localize`Search ${this.currentSearch}`
255 this.metaService.setTitle(title)
258 private updateUrlFromAdvancedSearch () {
259 const search = this.currentSearch || undefined
261 this.router.navigate([], {
262 relativeTo: this.route,
263 queryParams: Object.assign({}, this.advancedSearch.toUrlObject(), { search })
267 private getVideosObs () {
269 search: this.currentSearch,
270 componentPagination: immutableAssign(this.pagination, { itemsPerPage: 10 }),
271 advancedSearch: this.advancedSearch
274 return this.hooks.wrapObsFun(
275 this.searchService.searchVideos.bind(this.searchService),
278 'filter:api.search.videos.list.params',
279 'filter:api.search.videos.list.result'
283 private getVideoChannelObs () {
285 search: this.currentSearch,
286 componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.buildChannelsPerPage() }),
287 advancedSearch: this.advancedSearch
290 return this.hooks.wrapObsFun(
291 this.searchService.searchVideoChannels.bind(this.searchService),
294 'filter:api.search.video-channels.list.params',
295 'filter:api.search.video-channels.list.result'
299 private getVideoPlaylistObs () {
301 search: this.currentSearch,
302 componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.buildPlaylistsPerPage() }),
303 advancedSearch: this.advancedSearch
306 return this.hooks.wrapObsFun(
307 this.searchService.searchVideoPlaylists.bind(this.searchService),
310 'filter:api.search.video-playlists.list.params',
311 'filter:api.search.video-playlists.list.result'
315 private getDefaultSearchTarget (): SearchTargetType {
316 const searchIndexConfig = this.serverConfig.search.searchIndex
318 if (searchIndexConfig.enabled && (searchIndexConfig.isDefaultSearch || searchIndexConfig.disableLocalSearch)) {
319 return 'search-index'
325 private checkFieldsAndGetError () {
326 if (this.advancedSearch.host && !validateHost(this.advancedSearch.host)) {
327 return $localize`PeerTube instance host filter is invalid`
333 private buildChannelsPerPage () {
334 if (this.advancedSearch.resultType === 'channels') return 10
339 private buildPlaylistsPerPage () {
340 if (this.advancedSearch.resultType === 'playlists') return 10