]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+search/search.component.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / client / src / app / +search / search.component.ts
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'
13
14 @Component({
15 selector: 'my-search',
16 styleUrls: [ './search.component.scss' ],
17 templateUrl: './search.component.html'
18 })
19 export class SearchComponent implements OnInit, OnDestroy {
20 error: string
21
22 results: (Video | VideoChannel | VideoPlaylist)[] = []
23
24 pagination = {
25 currentPage: 1,
26 totalItems: null as number
27 }
28 advancedSearch: AdvancedSearch = new AdvancedSearch()
29 isSearchFilterCollapsed = true
30 currentSearch: string
31
32 videoDisplayOptions: MiniatureDisplayOptions = {
33 date: true,
34 views: true,
35 by: true,
36 avatar: false,
37 privacyLabel: false,
38 privacyText: false,
39 state: false,
40 blacklistInfo: false
41 }
42
43 errorMessage: string
44
45 userMiniature: User
46
47 onSearchDataSubject = new Subject<any>()
48
49 private subActivatedRoute: Subscription
50 private isInitialLoad = false // set to false to show the search filters on first arrival
51
52 private hasMoreResults = true
53 private isSearching = false
54
55 private lastSearchTarget: SearchTargetType
56
57 private serverConfig: HTMLServerConfig
58
59 constructor (
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
69 ) { }
70
71 ngOnInit () {
72 this.serverConfig = this.serverService.getHTMLConfig()
73
74 this.subActivatedRoute = this.route.queryParams
75 .subscribe({
76 next: queryParams => {
77 const querySearch = queryParams['search']
78 const searchTarget = queryParams['searchTarget']
79
80 // Search updated, reset filters
81 if (this.currentSearch !== querySearch || searchTarget !== this.advancedSearch.searchTarget) {
82 this.resetPagination()
83 this.advancedSearch.reset()
84
85 this.currentSearch = querySearch || undefined
86 this.updateTitle()
87 }
88
89 this.advancedSearch = new AdvancedSearch(queryParams)
90 if (!this.advancedSearch.searchTarget) {
91 this.advancedSearch.searchTarget = this.getDefaultSearchTarget()
92 }
93
94 this.error = this.checkFieldsAndGetError()
95
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
99
100 this.search()
101 },
102
103 error: err => this.notifier.error(err.message)
104 })
105
106 this.userService.getAnonymousOrLoggedUser()
107 .subscribe(user => this.userMiniature = user)
108
109 this.hooks.runAction('action:search.init', 'search')
110 }
111
112 ngOnDestroy () {
113 if (this.subActivatedRoute) this.subActivatedRoute.unsubscribe()
114 }
115
116 isVideoChannel (d: VideoChannel | Video | VideoPlaylist): d is VideoChannel {
117 return d instanceof VideoChannel
118 }
119
120 isVideo (v: VideoChannel | Video | VideoPlaylist): v is Video {
121 return v instanceof Video
122 }
123
124 isPlaylist (v: VideoChannel | Video | VideoPlaylist): v is VideoPlaylist {
125 return v instanceof VideoPlaylist
126 }
127
128 isUserLoggedIn () {
129 return this.authService.isLoggedIn()
130 }
131
132 search () {
133 this.error = this.checkFieldsAndGetError()
134 if (this.error) return
135
136 this.isSearching = true
137
138 forkJoin([
139 this.getVideoChannelObs(),
140 this.getVideoPlaylistObs(),
141 this.getVideosObs()
142 ]).subscribe({
143 next: results => {
144 for (const result of results) {
145 this.results = this.results.concat(result.data)
146 }
147
148 this.pagination.totalItems = results.reduce((p, r) => p += r.total, 0)
149 this.lastSearchTarget = this.advancedSearch.searchTarget
150
151 this.hasMoreResults = this.results.length < this.pagination.totalItems
152
153 this.onSearchDataSubject.next(results)
154 },
155
156 error: err => {
157 if (this.advancedSearch.searchTarget !== 'search-index') {
158 this.notifier.error(err.message)
159 return
160 }
161
162 this.notifier.error(
163 $localize`Search index is unavailable. Retrying with instance results instead.`,
164 $localize`Search error`
165 )
166 this.advancedSearch.searchTarget = 'local'
167 this.search()
168 },
169
170 complete: () => {
171 this.isSearching = false
172 }
173 })
174 }
175
176 onNearOfBottom () {
177 // Last page
178 if (!this.hasMoreResults || this.isSearching) return
179
180 this.pagination.currentPage += 1
181 this.search()
182 }
183
184 onFiltered () {
185 this.resetPagination()
186
187 this.updateUrlFromAdvancedSearch()
188 }
189
190 numberOfFilters () {
191 return this.advancedSearch.size()
192 }
193
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)
197 }
198
199 getLinkType (): LinkType {
200 if (this.advancedSearch.searchTarget === 'search-index') {
201 const remoteUriConfig = this.serverConfig.search.remoteUri
202
203 // Redirect on the external instance if not allowed to fetch remote data
204 if ((!this.isUserLoggedIn() && !remoteUriConfig.anonymous) || !remoteUriConfig.users) {
205 return 'external'
206 }
207
208 return 'lazy-load'
209 }
210
211 return 'internal'
212 }
213
214 isExternalChannelUrl () {
215 return this.getLinkType() === 'external'
216 }
217
218 getExternalChannelUrl (channel: VideoChannel) {
219 // Same algorithm than videos
220 if (this.getLinkType() === 'external') {
221 return channel.url
222 }
223
224 // lazy-load or internal
225 return undefined
226 }
227
228 getInternalChannelUrl (channel: VideoChannel) {
229 const linkType = this.getLinkType()
230
231 if (linkType === 'internal') {
232 return [ '/c', channel.nameWithHost ]
233 }
234
235 if (linkType === 'lazy-load') {
236 return [ '/search/lazy-load-channel', { url: channel.url } ]
237 }
238
239 // external
240 return undefined
241 }
242
243 hideActions () {
244 return this.lastSearchTarget === 'search-index'
245 }
246
247 private resetPagination () {
248 this.pagination.currentPage = 1
249 this.pagination.totalItems = null
250
251 this.results = []
252 }
253
254 private updateTitle () {
255 const title = this.currentSearch
256 ? $localize`Search ${this.currentSearch}`
257 : $localize`Search`
258
259 this.metaService.setTitle(title)
260 }
261
262 private updateUrlFromAdvancedSearch () {
263 const search = this.currentSearch || undefined
264
265 this.router.navigate([], {
266 relativeTo: this.route,
267 queryParams: Object.assign({}, this.advancedSearch.toUrlObject(), { search })
268 })
269 }
270
271 private getVideosObs () {
272 const params = {
273 search: this.currentSearch,
274 componentPagination: immutableAssign(this.pagination, { itemsPerPage: 10 }),
275 advancedSearch: this.advancedSearch
276 }
277
278 return this.hooks.wrapObsFun(
279 this.searchService.searchVideos.bind(this.searchService),
280 params,
281 'search',
282 'filter:api.search.videos.list.params',
283 'filter:api.search.videos.list.result'
284 )
285 }
286
287 private getVideoChannelObs () {
288 const params = {
289 search: this.currentSearch,
290 componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.buildChannelsPerPage() }),
291 advancedSearch: this.advancedSearch
292 }
293
294 return this.hooks.wrapObsFun(
295 this.searchService.searchVideoChannels.bind(this.searchService),
296 params,
297 'search',
298 'filter:api.search.video-channels.list.params',
299 'filter:api.search.video-channels.list.result'
300 )
301 }
302
303 private getVideoPlaylistObs () {
304 const params = {
305 search: this.currentSearch,
306 componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.buildPlaylistsPerPage() }),
307 advancedSearch: this.advancedSearch
308 }
309
310 return this.hooks.wrapObsFun(
311 this.searchService.searchVideoPlaylists.bind(this.searchService),
312 params,
313 'search',
314 'filter:api.search.video-playlists.list.params',
315 'filter:api.search.video-playlists.list.result'
316 )
317 }
318
319 private getDefaultSearchTarget (): SearchTargetType {
320 const searchIndexConfig = this.serverConfig.search.searchIndex
321
322 if (searchIndexConfig.enabled && (searchIndexConfig.isDefaultSearch || searchIndexConfig.disableLocalSearch)) {
323 return 'search-index'
324 }
325
326 return 'local'
327 }
328
329 private checkFieldsAndGetError () {
330 if (this.advancedSearch.host && !validateHost(this.advancedSearch.host)) {
331 return $localize`PeerTube instance host filter is invalid`
332 }
333
334 return undefined
335 }
336
337 private buildChannelsPerPage () {
338 if (this.advancedSearch.resultType === 'channels') return 10
339
340 return 2
341 }
342
343 private buildPlaylistsPerPage () {
344 if (this.advancedSearch.resultType === 'playlists') return 10
345
346 return 2
347 }
348 }