1 import * as debug from 'debug'
2 import { Observable, Subject, throwError } from 'rxjs'
3 import { first, 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
75 map(({ data }) => data),
76 map(data => data.find(finder))
78 .subscribe(result => {
80 obs.error(new Error($localize`Element ${param} not found`))
87 observableObject.notifier.next(param)
91 private getVideosInBulk (uuids: string[]) {
92 logger('Fetching videos %s.', uuids.join(', '))
94 return this.searchService.searchVideos({ uuids })
97 private getChannelsInBulk (handles: string[]) {
98 logger('Fetching channels %s.', handles.join(', '))
100 return this.searchService.searchVideoChannels({ handles })
103 private getPlaylistsInBulk (uuids: string[]) {
104 logger('Fetching playlists %s.', uuids.join(', '))
106 return this.searchService.searchVideoPlaylists({ uuids })
109 private buildBulkObservableObject <T extends number | string, R> (bulkGet: (params: T[]) => Observable<R>) {
110 const notifier = new Subject<T>()
115 result: buildBulkObservable({
119 notifierObservable: notifier.asObservable()