{"size": 1776, "ext": "js", "max_stars_repo_path": "src/lib/extended-info-providers/ffmpeg-image-provider.js", "max_stars_repo_name": "inkubux/MediaSpeed", "max_stars_repo_stars_event_min_datetime": "2018-02-06T19:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T12:51:03.000Z", "max_issues_repo_path": "src/lib/extended-info-providers/ffmpeg-image-provider.js", "max_issues_repo_name": "inkubux/MediaSpeed", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/extended-info-providers/ffmpeg-image-provider.js", "max_forks_repo_name": "inkubux/MediaSpeed", "max_forks_repo_forks_event_min_datetime": "2018-01-16T01:57:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-28T00:05:07.000Z"}
{"max_stars_count": 10, "max_issues_count": null, "max_forks_count": 3, "avg_line_length": 33.5094339623, "max_line_length": 104, "alphanum_fraction": 0.5703828829}
import EventsEnum from '../events-enum';

export default class FFMpegImageProvider {
    constructor(eventEmitter, ffmpegApi, movieService, episodeService, imageDestinationFolder, logger) {
        this.eventEmitter = eventEmitter;
        this.ffmpegApi = ffmpegApi;
        this.movieService = movieService;
        this.episodeService = episodeService;
        this.imageDestinationFolder = imageDestinationFolder;

        this.logger = logger;

        this.eventEmitter.on(EventsEnum.EPISODE_CREATED, async (episode, season, show) => {
            await this.execute(episode);
        });

        this.eventEmitter.on(EventsEnum.MOVIE_CREATED, async movie => {
            await this.execute(movie);
        });
    }

    async execute(media) {
        this.logger.debug('Creating ffmpeg image from media ' + media.filePath);
        const localScreenshot = await this.executeffMpeg(media);

        if (media.type === 'movie') {
            await this.movieService.update(media.uid, { local_screenshot: localScreenshot });
        }

        if (media.type === 'episode') {
            await this.episodeService.update(media.uid, { local_screenshot: localScreenshot });
        }

        return media;
    }

    async executeffMpeg(media) {
        return new Promise((resolve, reject) => {
            this.ffmpegApi(media.filePath)
                .screenshots({
                    timestamps: ['50%'],
                    filename: media.uid + '_screenshot.jpg',
                    folder: this.imageDestinationFolder,
                    size: '640x?'
                })
                .on('end', () => {
                    resolve(media.uid + '_screenshot.jpg');
                })
                .on('error', e => reject(e.message));
        });
    }
}
