import { combineLatest , Observable , of } from 'rxjs' ; import { catchError , flatMap , map , tap , timeout } from 'rxjs/operators' ; import { ID3MetadataService } from 'src/ts/download/metadata/id3-metadata-service' ; import { ITrackMetadata } from 'src/ts/download/metadata/track-metadata' ; import { TrackMetadataFactory } from 'src/ts/download/metadata/track-metadata-factory' ; import { ITrackDownloadInfo } from 'src/ts/download/track-download-info' ; import { IOptions } from 'src/ts/options/option' ; import { OptionsObservables } from 'src/ts/options/options-observables' ; import { logger } from 'src/ts/util/logger' ; import { XhrService } from 'src/ts/util/xhr-service' ; export const MetadataAdapter = { addMetadata$ ( downloadInfo ) { const fileExtension = downloadInfo . downloadOptions . filename . split ( '.' ) . pop ( ) ; const metadata$ = combineLatest ( of ( TrackMetadataFactory . create ( downloadInfo . trackInfo ) ) , OptionsObservables . getOptions$ ( ) ) . pipe ( flatMap ( withUpdatedCoverArtUrl$ ) ) ; switch ( fileExtension ) { case 'mp3' : return metadata$ . pipe ( flatMap ( ( metadata ) => ID3MetadataService . addID3V2Metadata$ ( metadata , downloadInfo ) ) , tap ( ( info ) => logger . debug ( 'Added mp3 metadata' , info ) ) ) ; default : return of ( downloadInfo ) ; } } , } ; function withUpdatedCoverArtUrl$ ( [ metadata , options ] ) { if ( ! options . addMetadata . addCoverArt ) { return of ( { ... metadata , cover_url : '' } ) ; } const origUrl = metadata . cover_url ; if ( ! origUrl ) { return of ( metadata ) ; } const highResUrl = getCoverArtUrlForResolution ( origUrl , 500 ) ; return XhrService . ping$ ( highResUrl ) . pipe ( timeout ( 10000 ) , map ( ( status ) => ( status === 200 ) ? highResUrl : origUrl ) , map ( ( url ) => ( { ... metadata , cover_url : url } ) ) , catchError ( ( ) => of ( metadata ) as Observable < ITrackMetadata > ) ) ; } function getCoverArtUrlForResolution ( url , resolution ) { return url . replace ( /^(.*)-large(\..*)$/ , `$1-t${ resolution }x${ resolution }$2` ) ; }