|
- import { EventEmitter } from 'events';
- import { spawnSync } from 'child_process';
- import { readFileSync, unlinkSync } from 'fs';
- import { CreateBaseClipperParams, FILE_TYPES, VideoClipEventEmitter } from '../../common';
- import { getFileExtension, constructDefaultDownloadArgs } from './utilities';
-
- export interface CreateYouTubeClipperParams extends CreateBaseClipperParams {
- downloaderExecutablePath?: string;
- }
-
- export class YouTubeVideoClipEventEmitter extends EventEmitter implements VideoClipEventEmitter {
- constructor(private readonly params: CreateYouTubeClipperParams) {
- super();
- }
-
- process() {
- if (!this.params.downloaderExecutablePath) {
- this.emit('error', new Error('Downloader not found.'));
- this.emit('end');
- return;
- }
-
- const fileExtension = getFileExtension(
- this.params.downloaderExecutablePath,
- this.params.url,
- );
- const cacheFilename = `output.${fileExtension}`; // todo label this on the cache
- const downloadArgs = constructDefaultDownloadArgs(
- cacheFilename,
- this.params.url,
- this.params.start,
- this.params.end,
- );
-
- this.emit('process', {
- type: 'download',
- phase: 'start',
- command: `${this.params.downloaderExecutablePath} ${downloadArgs.join(' ')}`,
- });
- const downloaderProcess = spawnSync(
- this.params.downloaderExecutablePath,
- downloadArgs,
- );
- if (downloaderProcess.error) {
- this.emit('error', downloaderProcess.error);
- this.emit('end');
- return;
- }
- this.emit('process', {
- type: 'download',
- phase: 'success',
- });
-
- const output = readFileSync(cacheFilename);
- unlinkSync(cacheFilename);
- this.emit('success', {
- contentType: FILE_TYPES[fileExtension],
- content: output,
- });
- this.emit('end');
- }
- }
|