]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+search/search.component.ts
Remove useless async
[github/Chocobozzz/PeerTube.git] / client / src / app / +search / search.component.ts
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'
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 private subActivatedRoute: Subscription
48 private isInitialLoad = false // set to false to show the search filters on first arrival
49
50 private channelsPerPage = 2
51 private playlistsPerPage = 2
52 private videosPerPage = 10
53
54 private hasMoreResults = true
55 private isSearching = false
56
57 private lastSearchTarget: SearchTargetType
58
59 private serverConfig: HTMLServerConfig
60
61 constructor (
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
71 ) { }
72
73 ngOnInit () {
74 this.serverConfig = this.serverService.getHTMLConfig()
75
76 this.subActivatedRoute = this.route.queryParams
77 .subscribe({
78 next: queryParams => {
79 const querySearch = queryParams['search']
80 const searchTarget = queryParams['searchTarget']
81
82 // Search updated, reset filters
83 if (this.currentSearch !== querySearch || searchTarget !== this.advancedSearch.searchTarget) {
84 this.resetPagination()
85 this.advancedSearch.reset()
86
87 this.currentSearch = querySearch || undefined
88 this.updateTitle()
89 }
90
91 this.advancedSearch = new AdvancedSearch(queryParams)
92 if (!this.advancedSearch.searchTarget) {
93 this.advancedSearch.searchTarget = this.getDefaultSearchTarget()
94 }
95
96 this.error = this.checkFieldsAndGetError()
97
98 // Don't hide filters if we have some of them AND the user just came on the webpage, or we have an error
99 this.isSearchFilterCollapsed = !this.error && (this.isInitialLoad === false || !this.advancedSearch.containsValues())
100 this.isInitialLoad = false
101
102 this.search()
103 },
104
105 error: err => this.notifier.error(err.text)
106 })
107
108 this.userService.getAnonymousOrLoggedUser()
109 .subscribe(user => this.userMiniature = user)
110
111 this.hooks.runAction('action:search.init', 'search')
112 }
113
114 ngOnDestroy () {
115 if (this.subActivatedRoute) this.subActivatedRoute.unsubscribe()
116 }
117
118 isVideoChannel (d: VideoChannel | Video | VideoPlaylist): d is VideoChannel {
119 return d instanceof VideoChannel
120 }
121
122 isVideo (v: VideoChannel | Video | VideoPlaylist): v is Video {
123 return v instanceof Video
124 }
125
126 isPlaylist (v: VideoChannel | Video | VideoPlaylist): v is VideoPlaylist {
127 return v instanceof VideoPlaylist
128 }
129
130 isUserLoggedIn () {
131 return this.authService.isLoggedIn()
132 }
133
134 search () {
135 this.error = this.checkFieldsAndGetError()
136 if (this.error) return
137
138 this.isSearching = true
139
140 forkJoin([
141 this.getVideoChannelObs(),
142 this.getVideoPlaylistObs(),
143 this.getVideosObs()
144 ]).subscribe({
145 next: results => {
146 for (const result of results) {
147 this.results = this.results.concat(result.data)
148 }
149
150 this.pagination.totalItems = results.reduce((p, r) => p += r.total, 0)
151 this.lastSearchTarget = this.advancedSearch.searchTarget
152
153 this.hasMoreResults = this.results.length < this.pagination.totalItems
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 this.channelsPerPage = 2
251
252 this.results = []
253 }
254
255 private updateTitle () {
256 const suffix = this.currentSearch
257 ? ' ' + this.currentSearch
258 : ''
259
260 this.metaService.setTitle($localize`Search` + suffix)
261 }
262
263 private updateUrlFromAdvancedSearch () {
264 const search = this.currentSearch || undefined
265
266 this.router.navigate([], {
267 relativeTo: this.route,
268 queryParams: Object.assign({}, this.advancedSearch.toUrlObject(), { search })
269 })
270 }
271
272 private getVideosObs () {
273 const params = {
274 search: this.currentSearch,
275 componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.videosPerPage }),
276 advancedSearch: this.advancedSearch
277 }
278
279 return this.hooks.wrapObsFun(
280 this.searchService.searchVideos.bind(this.searchService),
281 params,
282 'search',
283 'filter:api.search.videos.list.params',
284 'filter:api.search.videos.list.result'
285 )
286 }
287
288 private getVideoChannelObs () {
289 const params = {
290 search: this.currentSearch,
291 componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.channelsPerPage }),
292 advancedSearch: this.advancedSearch
293 }
294
295 return this.hooks.wrapObsFun(
296 this.searchService.searchVideoChannels.bind(this.searchService),
297 params,
298 'search',
299 'filter:api.search.video-channels.list.params',
300 'filter:api.search.video-channels.list.result'
301 )
302 }
303
304 private getVideoPlaylistObs () {
305 const params = {
306 search: this.currentSearch,
307 componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.playlistsPerPage }),
308 advancedSearch: this.advancedSearch
309 }
310
311 return this.hooks.wrapObsFun(
312 this.searchService.searchVideoPlaylists.bind(this.searchService),
313 params,
314 'search',
315 'filter:api.search.video-playlists.list.params',
316 'filter:api.search.video-playlists.list.result'
317 )
318 }
319
320 private getDefaultSearchTarget (): SearchTargetType {
321 const searchIndexConfig = this.serverConfig.search.searchIndex
322
323 if (searchIndexConfig.enabled && (searchIndexConfig.isDefaultSearch || searchIndexConfig.disableLocalSearch)) {
324 return 'search-index'
325 }
326
327 return 'local'
328 }
329
330 private checkFieldsAndGetError () {
331 if (this.advancedSearch.host && !validateHost(this.advancedSearch.host)) {
332 return $localize`PeerTube instance host filter is invalid`
333 }
334
335 return undefined
336 }
337 }