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