import * as debug from 'debug' import { Observable, Subject } from 'rxjs' import { filter, first, map } from 'rxjs/operators' import { Injectable } from '@angular/core' import { buildBulkObservable } from '@app/helpers' import { ResultList } from '@shared/models/common' import { Video, VideoChannel } from '../shared-main' import { VideoPlaylist } from '../shared-video-playlist' import { SearchService } from './search.service' const logger = debug('peertube:search:FindInBulkService') type BulkObservables

= { notifier: Subject

result: Observable<{ params: P[], response: R }> } @Injectable() export class FindInBulkService { private getVideoInBulk: BulkObservables> private getChannelInBulk: BulkObservables> private getPlaylistInBulk: BulkObservables> constructor ( private searchService: SearchService ) { this.getVideoInBulk = this.buildBulkObservableObject(this.getVideosInBulk.bind(this)) this.getChannelInBulk = this.buildBulkObservableObject(this.getChannelsInBulk.bind(this)) this.getPlaylistInBulk = this.buildBulkObservableObject(this.getPlaylistsInBulk.bind(this)) } getVideo (uuid: string): Observable

(options: { observableObject: BulkObservables> param: P finder: (d: R) => boolean }) { const { observableObject, param, finder } = options return new Observable(obs => { observableObject.result .pipe( filter(result => result.params.includes(param)), first(), map(result => result.response.data), map(data => data.find(finder)) ) .subscribe(result => { if (!result) { obs.error(new Error($localize`Element ${param} not found`)) } else { obs.next(result) obs.complete() } }) observableObject.notifier.next(param) }) } private getVideosInBulk (uuids: string[]) { logger('Fetching videos %s.', uuids.join(', ')) return this.searchService.searchVideos({ uuids }) } private getChannelsInBulk (handles: string[]) { logger('Fetching channels %s.', handles.join(', ')) return this.searchService.searchVideoChannels({ handles }) } private getPlaylistsInBulk (uuids: string[]) { logger('Fetching playlists %s.', uuids.join(', ')) return this.searchService.searchVideoPlaylists({ uuids }) } private buildBulkObservableObject

(bulkGet: (params: P[]) => Observable) { const notifier = new Subject

() return { notifier, result: buildBulkObservable({ time: 500, bulkGet, notifierObservable: notifier.asObservable() }) } } }