1 import * as debug from 'debug'
2 import { Observable, Subject } from 'rxjs'
3 import { map } from 'rxjs/operators'
4 import { Injectable, NgZone } from '@angular/core'
5 import { buildBulkObservable } from '@app/helpers'
6 import { ResultList } from '@shared/models/common'
7 import { Video, VideoChannel } from '../shared-main'
8 import { VideoPlaylist } from '../shared-video-playlist'
9 import { SearchService } from './search.service'
11 const logger = debug('peertube:search:FindInBulkService')
13 type BulkObservables <P extends number | string, R> = {
19 export class FindInBulkService {
21 private getVideoInBulk: BulkObservables<string, ResultList<Video>>
22 private getChannelInBulk: BulkObservables<string, ResultList<VideoChannel>>
23 private getPlaylistInBulk: BulkObservables<string, ResultList<VideoPlaylist>>
26 private searchService: SearchService,
27 private ngZone: NgZone
29 this.getVideoInBulk = this.buildBulkObservableObject(this.getVideosInBulk.bind(this))
30 this.getChannelInBulk = this.buildBulkObservableObject(this.getChannelsInBulk.bind(this))
31 this.getPlaylistInBulk = this.buildBulkObservableObject(this.getPlaylistsInBulk.bind(this))
34 getVideo (uuid: string): Observable<Video> {
35 logger('Schedule video fetch for uuid %s.', uuid)
38 observableObject: this.getVideoInBulk,
39 finder: v => v.uuid === uuid,
44 getChannel (handle: string): Observable<VideoChannel> {
45 logger('Schedule channel fetch for handle %s.', handle)
48 observableObject: this.getChannelInBulk,
49 finder: c => c.nameWithHost === handle || c.nameWithHostForced === handle,
54 getPlaylist (uuid: string): Observable<VideoPlaylist> {
55 logger('Schedule playlist fetch for uuid %s.', uuid)
58 observableObject: this.getPlaylistInBulk,
59 finder: p => p.uuid === uuid,
64 private getData <P extends number | string, R> (options: {
65 observableObject: BulkObservables<P, ResultList<R>>
67 finder: (d: R) => boolean
69 const { observableObject, param, finder } = options
71 return new Observable<R>(obs => {
72 observableObject.result
74 map(({ data }) => data),
75 map(data => data.find(finder))
77 .subscribe(result => {
82 observableObject.notifier.next(param)
86 private getVideosInBulk (uuids: string[]) {
87 logger('Fetching videos %s.', uuids.join(', '))
89 return this.searchService.searchVideos({ uuids })
92 private getChannelsInBulk (handles: string[]) {
93 logger('Fetching channels %s.', handles.join(', '))
95 return this.searchService.searchVideoChannels({ handles })
98 private getPlaylistsInBulk (uuids: string[]) {
99 logger('Fetching playlists %s.', uuids.join(', '))
101 return this.searchService.searchVideoPlaylists({ uuids })
104 private buildBulkObservableObject <T extends number | string, R> (bulkGet: (params: T[]) => Observable<R>) {
105 const notifier = new Subject<T>()
110 result: buildBulkObservable({
114 notifierObservable: notifier.asObservable()