1 import { forkJoin, Subject, 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 onSearchDataSubject = new Subject<any>()
49 private subActivatedRoute: Subscription
50 private isInitialLoad = false // set to false to show the search filters on first arrival
52 private hasMoreResults = true
53 private isSearching = false
55 private lastSearchTarget: SearchTargetType
57 private serverConfig: HTMLServerConfig
60 private route: ActivatedRoute,
61 private router: Router,
62 private metaService: MetaService,
63 private notifier: Notifier,
64 private searchService: SearchService,
65 private authService: AuthService,
66 private userService: UserService,
67 private hooks: HooksService,
68 private serverService: ServerService
72 this.serverConfig = this.serverService.getHTMLConfig()
74 this.subActivatedRoute = this.route.queryParams
76 next: queryParams => {
77 const querySearch = queryParams['search']
78 const searchTarget = queryParams['searchTarget']
80 // Search updated, reset filters
81 if (this.currentSearch !== querySearch || searchTarget !== this.advancedSearch.searchTarget) {
82 this.resetPagination()
83 this.advancedSearch.reset()
85 this.currentSearch = querySearch || undefined
89 this.advancedSearch = new AdvancedSearch(queryParams)
90 if (!this.advancedSearch.searchTarget) {
91 this.advancedSearch.searchTarget = this.getDefaultSearchTarget()
94 this.error = this.checkFieldsAndGetError()
96 // Don't hide filters if we have some of them AND the user just came on the webpage, or we have an error
97 this.isSearchFilterCollapsed = !this.error && (this.isInitialLoad === false || !this.advancedSearch.containsValues())
98 this.isInitialLoad = false
103 error: err => this.notifier.error(err.message)
106 this.userService.getAnonymousOrLoggedUser()
107 .subscribe(user => this.userMiniature = user)
109 this.hooks.runAction('action:search.init', 'search')
113 if (this.subActivatedRoute) this.subActivatedRoute.unsubscribe()
116 isVideoChannel (d: VideoChannel | Video | VideoPlaylist): d is VideoChannel {
117 return d instanceof VideoChannel
120 isVideo (v: VideoChannel | Video | VideoPlaylist): v is Video {
121 return v instanceof Video
124 isPlaylist (v: VideoChannel | Video | VideoPlaylist): v is VideoPlaylist {
125 return v instanceof VideoPlaylist
129 return this.authService.isLoggedIn()
133 this.error = this.checkFieldsAndGetError()
134 if (this.error) return
136 this.isSearching = true
139 this.getVideoChannelObs(),
140 this.getVideoPlaylistObs(),
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
153 this.onSearchDataSubject.next(results)
157 if (this.advancedSearch.searchTarget !== 'search-index') {
158 this.notifier.error(err.message)
163 $localize`Search index is unavailable. Retrying with instance results instead.`,
164 $localize`Search error`
166 this.advancedSearch.searchTarget = 'local'
171 this.isSearching = false
178 if (!this.hasMoreResults || this.isSearching) return
180 this.pagination.currentPage += 1
185 this.resetPagination()
187 this.updateUrlFromAdvancedSearch()
191 return this.advancedSearch.size()
194 // Add VideoChannel/VideoPlaylist for typings, but the template already checks "video" argument is a video
195 removeVideoFromArray (video: Video | VideoChannel | VideoPlaylist) {
196 this.results = this.results.filter(r => !this.isVideo(r) || r.id !== video.id)
199 getLinkType (): LinkType {
200 if (this.advancedSearch.searchTarget === 'search-index') {
201 const remoteUriConfig = this.serverConfig.search.remoteUri
203 // Redirect on the external instance if not allowed to fetch remote data
204 if ((!this.isUserLoggedIn() && !remoteUriConfig.anonymous) || !remoteUriConfig.users) {
214 isExternalChannelUrl () {
215 return this.getLinkType() === 'external'
218 getExternalChannelUrl (channel: VideoChannel) {
219 // Same algorithm than videos
220 if (this.getLinkType() === 'external') {
224 // lazy-load or internal
228 getInternalChannelUrl (channel: VideoChannel) {
229 const linkType = this.getLinkType()
231 if (linkType === 'internal') {
232 return [ '/c', channel.nameWithHost ]
235 if (linkType === 'lazy-load') {
236 return [ '/search/lazy-load-channel', { url: channel.url } ]
244 return this.lastSearchTarget === 'search-index'
247 private resetPagination () {
248 this.pagination.currentPage = 1
249 this.pagination.totalItems = null
254 private updateTitle () {
255 const title = this.currentSearch
256 ? $localize`Search ${this.currentSearch}`
259 this.metaService.setTitle(title)
262 private updateUrlFromAdvancedSearch () {
263 const search = this.currentSearch || undefined
265 this.router.navigate([], {
266 relativeTo: this.route,
267 queryParams: Object.assign({}, this.advancedSearch.toUrlObject(), { search })
271 private getVideosObs () {
273 search: this.currentSearch,
274 componentPagination: immutableAssign(this.pagination, { itemsPerPage: 10 }),
275 advancedSearch: this.advancedSearch
278 return this.hooks.wrapObsFun(
279 this.searchService.searchVideos.bind(this.searchService),
282 'filter:api.search.videos.list.params',
283 'filter:api.search.videos.list.result'
287 private getVideoChannelObs () {
289 search: this.currentSearch,
290 componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.buildChannelsPerPage() }),
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 () {
305 search: this.currentSearch,
306 componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.buildPlaylistsPerPage() }),
307 advancedSearch: this.advancedSearch
310 return this.hooks.wrapObsFun(
311 this.searchService.searchVideoPlaylists.bind(this.searchService),
314 'filter:api.search.video-playlists.list.params',
315 'filter:api.search.video-playlists.list.result'
319 private getDefaultSearchTarget (): SearchTargetType {
320 const searchIndexConfig = this.serverConfig.search.searchIndex
322 if (searchIndexConfig.enabled && (searchIndexConfig.isDefaultSearch || searchIndexConfig.disableLocalSearch)) {
323 return 'search-index'
329 private checkFieldsAndGetError () {
330 if (this.advancedSearch.host && !validateHost(this.advancedSearch.host)) {
331 return $localize`PeerTube instance host filter is invalid`
337 private buildChannelsPerPage () {
338 if (this.advancedSearch.resultType === 'channels') return 10
343 private buildPlaylistsPerPage () {
344 if (this.advancedSearch.resultType === 'playlists') return 10