aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/+search/search.component.ts
blob: 31394a1d14cb366dcd88b86cfe292e7be35cdff6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import { forkJoin, Subject, Subscription } from 'rxjs'
import { LinkType } from 'src/types/link.type'
import { Component, OnDestroy, OnInit } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { AuthService, HooksService, MetaService, Notifier, ServerService, User, UserService } from '@app/core'
import { immutableAssign } from '@app/helpers'
import { validateHost } from '@app/shared/form-validators/host-validators'
import { Video, VideoChannel } from '@app/shared/shared-main'
import { AdvancedSearch, SearchService } from '@app/shared/shared-search'
import { MiniatureDisplayOptions } from '@app/shared/shared-video-miniature'
import { VideoPlaylist } from '@app/shared/shared-video-playlist'
import { HTMLServerConfig, SearchTargetType } from '@shared/models'

@Component({
  selector: 'my-search',
  styleUrls: [ './search.component.scss' ],
  templateUrl: './search.component.html'
})
export class SearchComponent implements OnInit, OnDestroy {
  error: string

  results: (Video | VideoChannel | VideoPlaylist)[] = []

  pagination = {
    currentPage: 1,
    totalItems: null as number
  }
  advancedSearch: AdvancedSearch = new AdvancedSearch()
  isSearchFilterCollapsed = true
  currentSearch: string

  videoDisplayOptions: MiniatureDisplayOptions = {
    date: true,
    views: true,
    by: true,
    avatar: false,
    privacyLabel: false,
    privacyText: false,
    state: false,
    blacklistInfo: false
  }

  errorMessage: string

  userMiniature: User

  onSearchDataSubject = new Subject<any>()

  private subActivatedRoute: Subscription
  private isInitialLoad = false // set to false to show the search filters on first arrival

  private hasMoreResults = true
  private isSearching = false

  private lastSearchTarget: SearchTargetType

  private serverConfig: HTMLServerConfig

  constructor (
    private route: ActivatedRoute,
    private router: Router,
    private metaService: MetaService,
    private notifier: Notifier,
    private searchService: SearchService,
    private authService: AuthService,
    private userService: UserService,
    private hooks: HooksService,
    private serverService: ServerService
  ) { }

  ngOnInit () {
    this.serverConfig = this.serverService.getHTMLConfig()

    this.subActivatedRoute = this.route.queryParams
      .subscribe({
        next: queryParams => {
          const querySearch = queryParams['search']
          const searchTarget = queryParams['searchTarget']

          // Search updated, reset filters
          if (this.currentSearch !== querySearch || searchTarget !== this.advancedSearch.searchTarget) {
            this.resetPagination()
            this.advancedSearch.reset()

            this.currentSearch = querySearch || undefined
            this.updateTitle()
          }

          this.advancedSearch = new AdvancedSearch(queryParams)
          if (!this.advancedSearch.searchTarget) {
            this.advancedSearch.searchTarget = this.getDefaultSearchTarget()
          }

          this.error = this.checkFieldsAndGetError()

          // Don't hide filters if we have some of them AND the user just came on the webpage, or we have an error
          this.isSearchFilterCollapsed = !this.error && (this.isInitialLoad === false || !this.advancedSearch.containsValues())
          this.isInitialLoad = false

          this.search()
        },

        error: err => this.notifier.error(err.message)
      })

    this.userService.getAnonymousOrLoggedUser()
      .subscribe(user => this.userMiniature = user)

    this.hooks.runAction('action:search.init', 'search')
  }

  ngOnDestroy () {
    if (this.subActivatedRoute) this.subActivatedRoute.unsubscribe()
  }

  isVideoChannel (d: VideoChannel | Video | VideoPlaylist): d is VideoChannel {
    return d instanceof VideoChannel
  }

  isVideo (v: VideoChannel | Video | VideoPlaylist): v is Video {
    return v instanceof Video
  }

  isPlaylist (v: VideoChannel | Video | VideoPlaylist): v is VideoPlaylist {
    return v instanceof VideoPlaylist
  }

  isUserLoggedIn () {
    return this.authService.isLoggedIn()
  }

  search () {
    this.error = this.checkFieldsAndGetError()
    if (this.error) return

    this.isSearching = true

    forkJoin([
      this.getVideoChannelObs(),
      this.getVideoPlaylistObs(),
      this.getVideosObs()
    ]).subscribe({
      next: results => {
        for (const result of results) {
          this.results = this.results.concat(result.data)
        }

        this.pagination.totalItems = results.reduce((p, r) => p += r.total, 0)
        this.lastSearchTarget = this.advancedSearch.searchTarget

        this.hasMoreResults = this.results.length < this.pagination.totalItems

        this.onSearchDataSubject.next(results)
      },

      error: err => {
        if (this.advancedSearch.searchTarget !== 'search-index') {
          this.notifier.error(err.message)
          return
        }

        this.notifier.error(
          $localize`Search index is unavailable. Retrying with instance results instead.`,
          $localize`Search error`
        )
        this.advancedSearch.searchTarget = 'local'
        this.search()
      },

      complete: () => {
        this.isSearching = false
      }
    })
  }

  onNearOfBottom () {
    // Last page
    if (!this.hasMoreResults || this.isSearching) return

    this.pagination.currentPage += 1
    this.search()
  }

  onFiltered () {
    this.resetPagination()

    this.updateUrlFromAdvancedSearch()
  }

  numberOfFilters () {
    return this.advancedSearch.size()
  }

  // Add VideoChannel/VideoPlaylist for typings, but the template already checks "video" argument is a video
  removeVideoFromArray (video: Video | VideoChannel | VideoPlaylist) {
    this.results = this.results.filter(r => !this.isVideo(r) || r.id !== video.id)
  }

  getLinkType (): LinkType {
    if (this.advancedSearch.searchTarget === 'search-index') {
      const remoteUriConfig = this.serverConfig.search.remoteUri

      // Redirect on the external instance if not allowed to fetch remote data
      if ((!this.isUserLoggedIn() && !remoteUriConfig.anonymous) || !remoteUriConfig.users) {
        return 'external'
      }

      return 'lazy-load'
    }

    return 'internal'
  }

  isExternalChannelUrl () {
    return this.getLinkType() === 'external'
  }

  getExternalChannelUrl (channel: VideoChannel) {
    // Same algorithm than videos
    if (this.getLinkType() === 'external') {
      return channel.url
    }

    // lazy-load or internal
    return undefined
  }

  getInternalChannelUrl (channel: VideoChannel) {
    const linkType = this.getLinkType()

    if (linkType === 'internal') {
      return [ '/c', channel.nameWithHost ]
    }

    if (linkType === 'lazy-load') {
      return [ '/search/lazy-load-channel', { url: channel.url } ]
    }

    // external
    return undefined
  }

  hideActions () {
    return this.lastSearchTarget === 'search-index'
  }

  private resetPagination () {
    this.pagination.currentPage = 1
    this.pagination.totalItems = null

    this.results = []
  }

  private updateTitle () {
    const title = this.currentSearch
      ? $localize`Search ${this.currentSearch}`
      : $localize`Search`

    this.metaService.setTitle(title)
  }

  private updateUrlFromAdvancedSearch () {
    const search = this.currentSearch || undefined

    this.router.navigate([], {
      relativeTo: this.route,
      queryParams: Object.assign({}, this.advancedSearch.toUrlObject(), { search })
    })
  }

  private getVideosObs () {
    const params = {
      search: this.currentSearch,
      componentPagination: immutableAssign(this.pagination, { itemsPerPage: 10 }),
      advancedSearch: this.advancedSearch
    }

    return this.hooks.wrapObsFun(
      this.searchService.searchVideos.bind(this.searchService),
      params,
      'search',
      'filter:api.search.videos.list.params',
      'filter:api.search.videos.list.result'
    )
  }

  private getVideoChannelObs () {
    const params = {
      search: this.currentSearch,
      componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.buildChannelsPerPage() }),
      advancedSearch: this.advancedSearch
    }

    return this.hooks.wrapObsFun(
      this.searchService.searchVideoChannels.bind(this.searchService),
      params,
      'search',
      'filter:api.search.video-channels.list.params',
      'filter:api.search.video-channels.list.result'
    )
  }

  private getVideoPlaylistObs () {
    const params = {
      search: this.currentSearch,
      componentPagination: immutableAssign(this.pagination, { itemsPerPage: this.buildPlaylistsPerPage() }),
      advancedSearch: this.advancedSearch
    }

    return this.hooks.wrapObsFun(
      this.searchService.searchVideoPlaylists.bind(this.searchService),
      params,
      'search',
      'filter:api.search.video-playlists.list.params',
      'filter:api.search.video-playlists.list.result'
    )
  }

  private getDefaultSearchTarget (): SearchTargetType {
    const searchIndexConfig = this.serverConfig.search.searchIndex

    if (searchIndexConfig.enabled && (searchIndexConfig.isDefaultSearch || searchIndexConfig.disableLocalSearch)) {
      return 'search-index'
    }

    return 'local'
  }

  private checkFieldsAndGetError () {
    if (this.advancedSearch.host && !validateHost(this.advancedSearch.host)) {
      return $localize`PeerTube instance host filter is invalid`
    }

    return undefined
  }

  private buildChannelsPerPage () {
    if (this.advancedSearch.resultType === 'channels') return 10

    return 2
  }

  private buildPlaylistsPerPage () {
    if (this.advancedSearch.resultType === 'playlists') return 10

    return 2
  }
}