Beispiel #1
0
            private async Task <byte[]> _GeneratePngBitmap(int pixelSize)
            {
                var _tempDirectoryPath = Path.Combine(Path.GetTempPath(), $"{typeof(LogoBuilder).FullName}_{Guid.NewGuid()}");

                try
                {
                    var _svgWithTextFilePath = Path.Combine(_tempDirectoryPath, $"{Guid.NewGuid()}.svg");
                    _CreateFileDirectoryIfMissing(_svgWithTextFilePath);
                    _SvgWithTextDocument.Save(_svgWithTextFilePath);

                    var _pngFilePath = Path.Combine(_tempDirectoryPath, $"{Guid.NewGuid()}.png");
                    await _RunInkscape(_svgWithTextFilePath, $@"--export-width {pixelSize} --export-height {pixelSize} --export-png ""{_pngFilePath}""").ConfigureAwait(false);

                    if (!string.IsNullOrEmpty(_LogoBuilder._PngOptExecutable))
                    {
                        using (var _pngOptCli = new Cli(_LogoBuilder._PngOptExecutable))
                        {
                            var _pngOptResult = await _pngOptCli.ExecuteAsync($"\"{_pngFilePath}\"").ConfigureAwait(false);

                            _pngOptResult.ThrowIfError();
                        }
                    }

                    return(File.ReadAllBytes(_pngFilePath));
                }
                finally
                {
                    if (Directory.Exists(_tempDirectoryPath))
                    {
                        Directory.Delete(_tempDirectoryPath, true);
                    }
                }
            }
Beispiel #2
0
        public async Task <string> Run(string imageName, Dictionary <string, string> environmentVariables = null, string command = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            StringBuilder result = new StringBuilder();
            StringBuilder error  = new StringBuilder();

            StringBuilder s = new StringBuilder();

            foreach (var key in environmentVariables.Keys)
            {
                s.Append($" -e {key}={environmentVariables[key]} ");
            }

            ExecutionInput input = new ExecutionInput($"run --rm {s.ToString()} {imageName} {command}");



            //input.StandardInput = s.ToString();


            var handler = new BufferHandler(stdOutLine => result.Append(stdOutLine), stdErrLine => error.Append(stdErrLine));

            //if (environmentVariables != null)
            //{
            //    input.EnvironmentVariables = environmentVariables;
            //}
            ExecutionOutput output = await _cliDocker.ExecuteAsync(input, cancellationToken, handler);

            if (output.ExitCode != 0)
            {
                throw new CliException("Could not run image", result.ToString(), error.ToString());
            }
            return(result.ToString());
        }
Beispiel #3
0
 public void ExecuteAsync_Sleep_CancelEarly_Test()
 {
     using (var cli = new Cli(_sleepBat))
         using (var cts = new CancellationTokenSource())
         {
             cts.Cancel();
             Assert.ThrowsAsync <TaskCanceledException>(() => cli.ExecuteAsync(cts.Token));
         }
 }
Beispiel #4
0
 public void ExecuteAsync_Sleep_CancelLate_Test()
 {
     using (var cli = new Cli(_sleepBat))
         using (var cts = new CancellationTokenSource())
         {
             cts.CancelAfter(TimeSpan.FromSeconds(1));
             Assert.ThrowsAsync <TaskCanceledException>(() => cli.ExecuteAsync(cts.Token));
         }
 }
Beispiel #5
0
        public async Task ExecuteAsync_NeverEnding_CancelEarly_Test()
        {
            var cli = new Cli(NeverEndingBat);

            var cts = new CancellationTokenSource();

            cts.Cancel();

            await Assert.ThrowsExceptionAsync <OperationCanceledException>(() => cli.ExecuteAsync(cts.Token));
        }
Beispiel #6
0
        public async Task ExecuteAsync_NeverEnding_CancelLate_Test()
        {
            var cli = new Cli(NeverEndingBat);

            var cts = new CancellationTokenSource();

            cts.CancelAfter(TimeSpan.FromSeconds(1));

            await Assert.ThrowsExceptionAsync <OperationCanceledException>(() => cli.ExecuteAsync(cts.Token));
        }
Beispiel #7
0
        public void CancelAll_AfterExecuteAsync_Sleep_Test()
        {
            using (var cli = new Cli(_sleepBat))
            {
                // Kill after some time
                Task.Delay(TimeSpan.FromSeconds(1)).ContinueWith(_ => cli.CancelAll());

                // Execute
                Assert.ThrowsAsync <TaskCanceledException>(() => cli.ExecuteAsync());
            }
        }
Beispiel #8
0
        private static async Task <string> ExecuteDummyCliAsync(string args)
        {
            var output = await DummyCli.ExecuteAsync(args);

            if (output.HasError)
            {
                Assert.Fail($"Dummy reported an error:{Environment.NewLine}{output.StandardError}");
            }

            return(output.StandardOutput);
        }
Beispiel #9
0
        public async Task ExecuteAsync_EchoStdin_Empty_Test()
        {
            var cli = new Cli(EchoStdinBat);

            var output = await cli.ExecuteAsync();

            output.ThrowIfError();

            Assert.IsNotNull(output);
            Assert.AreEqual(14, output.ExitCode);
            Assert.AreEqual("ECHO is off.", output.StandardOutput.TrimEnd());
            Assert.AreEqual("", output.StandardError.TrimEnd());
        }
Beispiel #10
0
        public async Task ExecuteAsync_EchoArgs_Test()
        {
            var cli = new Cli(EchoArgsBat);

            var output = await cli.ExecuteAsync("Hello world");

            output.ThrowIfError();

            Assert.IsNotNull(output);
            Assert.AreEqual(14, output.ExitCode);
            Assert.AreEqual("Hello world", output.StandardOutput.TrimEnd());
            Assert.AreEqual("", output.StandardError.TrimEnd());
        }
Beispiel #11
0
        public static async void FormatFile(string goFilePath)
        {
            if (!File.Exists(goFilePath))
            {
                throw new ArgumentException("Argument projectPath does not exist");
            }

            using (var cli = new Cli(GoFormatterExec))
            {
                var output = await cli.ExecuteAsync($"-w {goFilePath}");

                output.ThrowIfError();
            }
        }
Beispiel #12
0
 async static Task ExecuteAsync(string command, State state)
 {
     try
     {
         await Cli.ExecuteAsync(new CommandRoot(state), command, new GlobalOptions());
     }
     catch (Exception ex)
     {
         var oldColor = Console.ForegroundColor;
         Console.ForegroundColor = ConsoleColor.Red;
         Console.WriteLine(ex.GetBaseException().Message);
         Console.ForegroundColor = oldColor;
     }
 }
Beispiel #13
0
 async static Task ExecuteAsync(string command)
 {
     try
     {
         await Cli.ExecuteAsync(typeof(Program).GetMethod(nameof(Run), BindingFlags.Static | BindingFlags.NonPublic), command);
     }
     catch (Exception ex)
     {
         var oldColor = Console.ForegroundColor;
         Console.ForegroundColor = ConsoleColor.Red;
         Console.WriteLine(ex.GetBaseException().Message);
         Console.ForegroundColor = oldColor;
     }
 }
Beispiel #14
0
        public async Task ExecuteAsync_ThrowError_Test()
        {
            var cli = new Cli(ThrowErrorBat);

            var output = await cli.ExecuteAsync();

            var ex = Assert.ThrowsException <StandardErrorException>(() => output.ThrowIfError());

            Assert.IsNotNull(output);
            Assert.AreEqual(14, output.ExitCode);
            Assert.AreEqual("", output.StandardOutput.TrimEnd());
            Assert.AreEqual("Hello world", output.StandardError.TrimEnd());
            Assert.AreEqual(output.StandardError, ex.StandardError);
        }
Beispiel #15
0
        static async Task Run(string source, string output)
        {
            // Split volume
            var volumePathSplited = DevCore.IO.SplitVolumePath(source);

            Matcher matcher = new Matcher(StringComparison.InvariantCultureIgnoreCase);

            matcher.AddInclude(volumePathSplited.Item2);

            var results = MatcherExtensions.GetResultsInFullPath(matcher, volumePathSplited.Item1 + System.IO.Path.DirectorySeparatorChar);

            Console.WriteLine(string.Empty);
            Console.WriteLineFormatted($@"Volume: {volumePathSplited.Item1}", Color.Green);
            Console.WriteLineFormatted($@"Path: {volumePathSplited.Item2}", Color.Green);
            Console.WriteLineFormatted($@"{results.Count()} files found", Color.Green);
            results.ToList().ForEach(e => Console.WriteLine(e));

            Stopwatch sw = new Stopwatch();

            sw.Start();
            foreach (var item in results)
            {
                using (var cli = new Cli("ffmpeg"))
                {
                    var destiny = Path.ChangeExtension(item, output);
                    var args    = $@"-i ""{item}"" ""{destiny}""";

                    var handler = new BufferHandler(
                        stdOutLine => Console.WriteLine(stdOutLine),
                        stdErrLine => Console.WriteLine(stdErrLine));

                    Console.WriteLine(string.Empty);
                    Console.WriteFormatted($@"Executing: ", Color.Green);
                    Console.WriteLineFormatted($"ffmpeg {args}", Color.White);
                    Console.WriteLine(string.Empty);

                    await cli.ExecuteAsync(args, bufferHandler : handler);
                }
            }
            sw.Stop();

            if (results.Any())
            {
                Console.WriteLine(string.Empty);
                Console.Write($"The process has been executed in: ");
                Console.WriteFormatted($"{sw.Elapsed.TotalSeconds}", Color.Green);
                Console.WriteLine($" seconds.");
            }
        }
        private static async Task DownloadAndConvertVideoAsync(string id)
        {
            Console.WriteLine($"Working on video [{id}]...");

            // Get video info
            var video = await YoutubeClient.GetVideoAsync(id);

            var set = await YoutubeClient.GetVideoMediaStreamInfosAsync(id);

            var cleanTitle = video.Title.Replace(Path.GetInvalidFileNameChars(), '_');

            Console.WriteLine($"{video.Title}");

            // Get highest bitrate audio-only or highest quality mixed stream
            var streamInfo = GetBestAudioStreamInfo(set);

            // Download to temp file
            Console.WriteLine("Downloading...");
            Directory.CreateDirectory(TempDirectoryPath);
            var streamFileExt  = streamInfo.Container.GetFileExtension();
            var streamFilePath = Path.Combine(TempDirectoryPath, $"{Guid.NewGuid()}.{streamFileExt}");
            await YoutubeClient.DownloadMediaStreamAsync(streamInfo, streamFilePath);

            // Convert to mp3
            Console.WriteLine("Converting...");
            Directory.CreateDirectory(OutputDirectoryPath);
            var outputFilePath = Path.Combine(OutputDirectoryPath, $"{cleanTitle}.mp3");
            await FfmpegCli.ExecuteAsync($"-i \"{streamFilePath}\" -q:a 0 -map a \"{outputFilePath}\" -y");

            // Delete temp file
            Console.WriteLine("Deleting temp file...");
            File.Delete(streamFilePath);

            // Edit mp3 metadata
            Console.WriteLine("Writing metadata...");
            var idMatch = Regex.Match(video.Title, @"^(?<artist>.*?)-(?<title>.*?)$");
            var artist  = idMatch.Groups["artist"].Value.Trim();
            var title   = idMatch.Groups["title"].Value.Trim();

            using (var meta = TagLib.File.Create(outputFilePath))
            {
                meta.Tag.Performers = new[] { artist };
                meta.Tag.Title      = title;
                meta.Save();
            }

            Console.WriteLine($"Downloaded and converted video [{id}] to [{outputFilePath}]");
        }
Beispiel #17
0
        public async Task ExecuteAsync_EchoStdinToStdout_Empty_Test()
        {
            using (var cli = new Cli(_echoStdinToStdoutBat))
            {
                var output = await cli.ExecuteAsync();

                output.ThrowIfError();

                Assert.That(output, Is.Not.Null);
                Assert.That(output.ExitCode, Is.EqualTo(TestExitCode));
                Assert.That(output.StandardOutput.TrimEnd(), Is.EqualTo("ECHO is off."));
                Assert.That(output.StandardError.TrimEnd(), Is.Empty);
                Assert.That(output.StartTime, Is.LessThanOrEqualTo(output.ExitTime));
                Assert.That(output.RunTime, Is.EqualTo(output.ExitTime - output.StartTime));
            }
        }
Beispiel #18
0
        public async Task ExecuteAsync_EchoEnvVar_Test()
        {
            var cli = new Cli(EchoEnvVarBat);

            var input = new ExecutionInput();

            input.EnvironmentVariables.Add("TEST_ENV_VAR", "Hello world");

            var output = await cli.ExecuteAsync(input);

            output.ThrowIfError();

            Assert.IsNotNull(output);
            Assert.AreEqual(14, output.ExitCode);
            Assert.AreEqual("Hello world", output.StandardOutput.TrimEnd());
            Assert.AreEqual("", output.StandardError.TrimEnd());
        }
Beispiel #19
0
        public async Task ExecuteAsync_EchoArgsToStderr_Test()
        {
            using (var cli = new Cli(_echoArgsToStderrBat))
            {
                var output = await cli.ExecuteAsync(TestString);

                var ex = Assert.Throws <StandardErrorException>(() => output.ThrowIfError());

                Assert.That(output, Is.Not.Null);
                Assert.That(output.ExitCode, Is.EqualTo(TestExitCode));
                Assert.That(output.StandardOutput.TrimEnd(), Is.Empty);
                Assert.That(output.StandardError.TrimEnd(), Is.EqualTo(TestString));
                Assert.That(output.StandardError, Is.EqualTo(ex.StandardError));
                Assert.That(output.StartTime, Is.LessThanOrEqualTo(output.ExitTime));
                Assert.That(output.RunTime, Is.EqualTo(output.ExitTime - output.StartTime));
            }
        }
Beispiel #20
0
        private async void btnUpload_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.textBoxFirmwareFile.Text) || string.IsNullOrWhiteSpace(this.comPortCombo.Text))
            {
                labelStatus.ForeColor = Color.Orange;
                UpdateStatusLabel();
                return;
            }

            labelStatus.ForeColor = Color.Yellow;
            UpdateStatusLabel("Uploading...");
            SetEnabled(false);

            using (var cli = new Cli("Avrdude/avrdude.exe"))
            {
                // Execute
                var output = await cli.ExecuteAsync($"-CAvrdude/avrdude.conf -v -patmega328p -carduino -P{this.comPortCombo.Text} -b57600 -D -Uflash:w:\"{this.textBoxFirmwareFile.Text}\":i ");

                // Extract output
                var code      = output.ExitCode;
                var stdOut    = output.StandardOutput;
                var stdErr    = output.StandardError;
                var startTime = output.StartTime;
                var exitTime  = output.ExitTime;
                var runTime   = output.RunTime;
                //output.ThrowIfError();

                this.btnOutput.Visible = true;

                if (output.ExitCode != 0)
                {
                    _output = output.StandardError;
                    SetEnabled(true);
                    labelStatus.ForeColor = Color.Red;
                    UpdateStatusLabel("Upload failed - click on Output for details");
                }
                else
                {
                    _output = output.HasError ? output.StandardError : output.StandardOutput;
                    SetEnabled(true);
                    labelStatus.ForeColor = Color.Green;
                    UpdateStatusLabel("Upload successful!");
                }
            }
        }
Beispiel #21
0
        public static async Task <string> GetGoEnvironmentPath()
        {
            using (var cli = new Cli("go.exe"))
            {
                var output = await cli.ExecuteAsync("env");

                output.ThrowIfError();
                var fullGoPath = output.StandardOutput.Split("\r\n").FirstOrDefault(l => l.StartsWith("set GOPATH="));
                var errMsg     = $"Go path not found in {nameof(GetGoEnvironmentPath)}";
                var match      = Regex.Match(fullGoPath ?? throw new Exception(errMsg), @"(?<=set GOPATH=).*", RegexOptions.ECMAScript);
                if (!match.Success)
                {
                    throw new Exception(errMsg);
                }
                var goPath = match.Groups.First();
                return(goPath.Value);
            }
        }
Beispiel #22
0
        public async Task ExecuteAsync_EchoEnvVarToStdout_Test()
        {
            using (var cli = new Cli(_echoEnvVarToStdoutBat))
            {
                var input = new ExecutionInput();
                input.EnvironmentVariables.Add(TestEnvVar, TestString);

                var output = await cli.ExecuteAsync(input);

                output.ThrowIfError();

                Assert.That(output, Is.Not.Null);
                Assert.That(output.ExitCode, Is.EqualTo(TestExitCode));
                Assert.That(output.StandardOutput.TrimEnd(), Is.EqualTo(TestString));
                Assert.That(output.StandardError.TrimEnd(), Is.Empty);
                Assert.That(output.StartTime, Is.LessThanOrEqualTo(output.ExitTime));
                Assert.That(output.RunTime, Is.EqualTo(output.ExitTime - output.StartTime));
            }
        }
Beispiel #23
0
        private static async Task DownloadVideoAsync(string id)
        {
            Console.WriteLine($"Working on video [{id}]...");

            // Get video info
            var video = await YoutubeClient.GetVideoAsync(id);

            var cleanTitle = video.Title.Replace(Path.GetInvalidFileNameChars(), '_');

            Console.WriteLine($"{video.Title}");

            // Get best streams
            var streamInfoSet = await YoutubeClient.GetVideoMediaStreamInfosAsync(id);

            var videoStreamInfo = streamInfoSet.Video.WithHighestVideoQuality();
            var audioStreamInfo = streamInfoSet.Audio.WithHighestBitrate();

            // Download streams
            Console.WriteLine("Downloading...");
            Directory.CreateDirectory(TempDirectoryPath);
            var videoStreamFileExt  = videoStreamInfo.Container.GetFileExtension();
            var videoStreamFilePath = Path.Combine(TempDirectoryPath, $"VID-{Guid.NewGuid()}.{videoStreamFileExt}");
            await YoutubeClient.DownloadMediaStreamAsync(videoStreamInfo, videoStreamFilePath);

            var audioStreamFileExt  = audioStreamInfo.Container.GetFileExtension();
            var audioStreamFilePath = Path.Combine(TempDirectoryPath, $"AUD-{Guid.NewGuid()}.{audioStreamFileExt}");
            await YoutubeClient.DownloadMediaStreamAsync(audioStreamInfo, audioStreamFilePath);

            // Mux streams
            Console.WriteLine("Combining...");
            Directory.CreateDirectory(OutputDirectoryPath);
            var outputFilePath = Path.Combine(OutputDirectoryPath, $"{cleanTitle}.mp4");
            await FfmpegCli.ExecuteAsync($"-i \"{videoStreamFilePath}\" -i \"{audioStreamFilePath}\" -shortest \"{outputFilePath}\" -y");

            // Delete temp files
            Console.WriteLine("Deleting temp files...");
            File.Delete(videoStreamFilePath);
            File.Delete(audioStreamFilePath);

            Console.WriteLine($"Downloaded video [{id}] to [{outputFilePath}]");
        }
Beispiel #24
0
        public static async Task Build(string projectPath)
        {
            if (!Directory.Exists(projectPath))
            {
                throw new ArgumentException("Argument projectPath does not exist");
            }

            using (var cli = new Cli(GoExec, projectPath))
            {
                var status = await cli.ExecuteAsync("build");

                if (status.HasError)
                {
                    Console.WriteLine("Go build error occurred:", status.StandardError);
                }
                else
                {
                    Console.WriteLine($"Build completed at {projectPath}");
                }
            }
        }
Beispiel #25
0
        private async Task WaitForContainerToDie()
        {
            ExecutionInput          input = new ExecutionInput($@"events --filter com.docker.compose.project={_projectName} --filter event=die");
            CancellationTokenSource monitorTokenSource = new CancellationTokenSource();
            var linkedTokens = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token, monitorTokenSource.Token);

            var handler = new BufferHandler(
                stdOutLine => monitorTokenSource.Cancel(), // We received the info we were waiting for
                stdErrLine => monitorTokenSource.Cancel());

            try
            {
                await _cliDocker.ExecuteAsync(input, linkedTokens.Token, handler);
            }
            catch (OperationCanceledException e)
            {
                // Only throw the cancelltion exception if the global token was cancelled
                if (_cancellationTokenSource.IsCancellationRequested)
                {
                    throw;
                }
            }
        }
        /// <inheritdoc />
        public override async Task <ExportInformation> ExportCaptureAsync(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
        {
            var exportInformation = new ExportInformation(Designation, Description);

            var fullPath = captureDetails.Filename ?? surface.SaveNamedTmpFile(CoreConfiguration, _externalCommandConfiguration);

            using (var cli = new Cli(_externalCommandDefinition.Command))
            {
                var arguments = string.Format(_externalCommandDefinition.Arguments, fullPath);
                // Execute
                var output = await cli.ExecuteAsync(arguments).ConfigureAwait(true);

                if (_externalCommandDefinition.CommandBehavior.HasFlag(CommandBehaviors.ParseOutputForUris))
                {
                    var uriMatches = UriRegexp.Matches(output.StandardOutput);
                    if (uriMatches.Count > 0)
                    {
                        exportInformation.Uri = uriMatches[0].Groups[1].Value;

                        using (var clipboardAccessToken = ClipboardNative.Access())
                        {
                            clipboardAccessToken.ClearContents();
                            clipboardAccessToken.SetAsUrl(exportInformation.Uri);
                        }
                    }
                }

                if (_externalCommandDefinition.CommandBehavior.HasFlag(CommandBehaviors.DeleteOnExit))
                {
                    File.Delete(fullPath);
                }
            }

            ProcessExport(exportInformation, surface);
            return(exportInformation);
        }
Beispiel #27
0
        public async Task ExecuteAsync_EchoSpam_BufferHandler_Test()
        {
            using (var cli = new Cli(_echoSpamBat))
            {
                // Collect stdout/stderr from handler separately
                var stdOutBuffer = new StringBuilder();
                var stdErrBuffer = new StringBuilder();
                var handler      = new BufferHandler(
                    stdOutLine => stdOutBuffer.AppendLine(stdOutLine),
                    stdErrLine => stdErrBuffer.AppendLine(stdErrLine));

                var output = await cli.ExecuteAsync(bufferHandler : handler);

                var ex = Assert.Throws <StandardErrorException>(() => output.ThrowIfError());

                Assert.That(output, Is.Not.Null);
                Assert.That(output.ExitCode, Is.EqualTo(TestExitCode));
                Assert.That(output.StandardOutput, Is.EqualTo(stdOutBuffer.ToString()));
                Assert.That(output.StandardError, Is.EqualTo(stdErrBuffer.ToString()));
                Assert.That(output.StandardError, Is.EqualTo(ex.StandardError));
                Assert.That(output.StartTime, Is.LessThanOrEqualTo(output.ExitTime));
                Assert.That(output.RunTime, Is.EqualTo(output.ExitTime - output.StartTime));
            }
        }
Beispiel #28
0
        private async Task descargarVideoHDAsync(string id)
        {
            numVideoProgress++;
            // Get video info
            try
            {
                updateProgressBar(11, "Video #" + numVideoProgress + " - Recogiendo información del video...");
                var video = await YoutubeClient.GetVideoAsync(id);

                updateProgressBar(13, "Video #" + numVideoProgress + " - ...información de video recogida.");
                updateProgressBar(13, "Video #" + numVideoProgress + " - Renombrando...");
                var cleanTitle = video.Title.Replace(Path.GetInvalidFileNameChars(), '_');
                updateProgressBar(15, "Video #" + numVideoProgress + " - ... video renombrado.");

                // Get best streams
                var streamInfoSet = await YoutubeClient.GetVideoMediaStreamInfosAsync(id);

                updateProgressBar(17, "Video #" + numVideoProgress + " - Buscando mejor stream...");
                var videoStreamInfo = streamInfoSet.Video.WithHighestVideoQuality();
                updateProgressBar(19, "Video #" + numVideoProgress + " - Buscando la mayor calidad...");
                var audioStreamInfo = streamInfoSet.Audio.WithHighestBitrate();
                updateProgressBar(21, "Video #" + numVideoProgress + " - Buscando el mejor sonido...");

                // Download streams
                updateProgressBar(22, "Video #" + numVideoProgress + " - Creando directorio temporal...");
                Directory.CreateDirectory(TempDirectoryPath);
                updateProgressBar(23, "Video #" + numVideoProgress + " - Extrayendo extensión de archivos...");
                var videoStreamFileExt = videoStreamInfo.Container.GetFileExtension();
                updateProgressBar(24, "Video #" + numVideoProgress + " - Creando rutas de archivos...");
                var videoStreamFilePath = Path.Combine(TempDirectoryPath, $"VID-{Guid.NewGuid()}.{videoStreamFileExt}");
                updateProgressBar(25, "Video #" + numVideoProgress + " - Descargando el video...");
                await YoutubeClient.DownloadMediaStreamAsync(videoStreamInfo, videoStreamFilePath);

                updateProgressBar(36, "Video #" + numVideoProgress + " - ... video descargado.");
                var audioStreamFileExt  = audioStreamInfo.Container.GetFileExtension();
                var audioStreamFilePath = Path.Combine(TempDirectoryPath, $"AUD-{Guid.NewGuid()}.{audioStreamFileExt}");
                updateProgressBar(39, "Video #" + numVideoProgress + " - Descargando el sonido...");
                await YoutubeClient.DownloadMediaStreamAsync(audioStreamInfo, audioStreamFilePath);

                updateProgressBar(49, "Video #" + numVideoProgress + " - ...sonido descargado.");

                // Mux streams
                updateProgressBar(50, "Video #" + numVideoProgress + " - Creando directorio de salida...");
                Directory.CreateDirectory(OutputDirectoryPath);
                var outputFilePath = Path.Combine(OutputDirectoryPath, $"{cleanTitle}.mp4");
                updateProgressBar(60, "Video #" + numVideoProgress + " - Combinando video y audio...");
                await FfmpegCli.ExecuteAsync($"-i \"{videoStreamFilePath}\" -i \"{audioStreamFilePath}\" -shortest \"{outputFilePath}\" -y");

                updateProgressBar(98, "Video #" + numVideoProgress + " - ... video y audio combinados con éxito.");

                // Delete temp files
                updateProgressBar(99, "Video #" + numVideoProgress + " - Eliminando archivos temporales...");
                File.Delete(videoStreamFilePath);
                File.Delete(audioStreamFilePath);
                updateProgressBar(100, "Video #" + numVideoProgress + " - ... proceso finalizado.");
            } catch (VideoUnavailableException ex)
            {
                Console.WriteLine("Excepción capturada: " + ex.Message);
                Console.WriteLine("Video NO DISPONIBLE: https://www.youtube.com/watch?v=" + id);
                failedDownloads.Add(id);
            }
        }
Beispiel #29
0
        public async Task <string> DownloadVideo(string videoId)
        {
            this.logger.LogTrace($"Working on video [{videoId}]...");

            // Get video info
            var video = await this.youtube.GetVideoAsync(videoId);

            var cleanTitle = video.Title.Replace(Path.GetInvalidFileNameChars(), '_');

            this.logger.LogTrace($"{video.Title}");

            // Get best streams
            var streamInfoSet = await this.youtube.GetVideoMediaStreamInfosAsync(videoId);

            var videoStreamInfo = streamInfoSet.Video.WithHighestVideoQuality();
            var audioStreamInfo = streamInfoSet.Audio.WithHighestBitrate();

            // Download streams
            this.logger.LogTrace("Downloading...");
            Directory.CreateDirectory(tempFolder);
            var videoStreamFileExt  = videoStreamInfo.Container.GetFileExtension();
            var videoStreamFilePath = Path.Combine(tempFolder, $"VID-{Guid.NewGuid()}.{videoStreamFileExt}");

            using (var progress = new ProgressBar())
                await this.youtube.DownloadMediaStreamAsync(videoStreamInfo, videoStreamFilePath, progress);
            var audioStreamFileExt  = audioStreamInfo.Container.GetFileExtension();
            var audioStreamFilePath = Path.Combine(tempFolder, $"AUD-{Guid.NewGuid()}.{audioStreamFileExt}");

            using (var progress = new ProgressBar())
                await this.youtube.DownloadMediaStreamAsync(audioStreamInfo, audioStreamFilePath, progress);

            Directory.CreateDirectory(outputFolder);
            var outputFilePath = Path.Combine(outputFolder, $"{cleanTitle}.mp4");

            using (var stream = File.OpenRead(videoStreamFilePath))
            {
                if (stream.Length > 30 * 1024 * 1024)
                {
                    // Delete temp files
                    this.logger.LogTrace("Deleting temp files...");
                    stream.Close();
                    File.Move(videoStreamFilePath, outputFilePath);
                    File.Delete(audioStreamFilePath);
                    this.logger.LogTrace($"Downloaded video [{videoId}] to [{outputFilePath}]");
                    return(outputFilePath);
                }
            }

            // Mux streams
            this.logger.LogTrace("Combining...");
            this.converterCli.SetArguments($"-i \"{videoStreamFilePath}\" -i \"{audioStreamFilePath}\" -shortest \"{outputFilePath}\" -y");
            try
            {
                await converterCli.ExecuteAsync();
            }
            catch (Exception)
            {
                // ignored
            }
            finally
            {
                // Delete temp files
                this.logger.LogTrace("Deleting temp files...");
                File.Delete(videoStreamFilePath);
                File.Delete(audioStreamFilePath);
            }

            this.logger.LogTrace($"Downloaded video [{videoId}] to [{outputFilePath}]");
            return(outputFilePath);
        }
Beispiel #30
0
        public async Task Download(Song s = null, List <Song> songs = null)
        {
            string             path       = String.Empty;
            string             album      = s == null ? songs[0].Album : s.Album;
            string             artist     = s == null ? songs[0].Artist : s.Artist;
            string             id         = s == null ? songs[0].ID : s.ID;
            string             name       = s == null ? songs[0].Video.Title : s.Video.Title;
            string             cleanTitle = Path.GetInvalidFileNameChars().Aggregate(name, (current, c) => current.Replace(c.ToString(), String.Empty));
            MediaStreamInfoSet set        = await client.GetVideoMediaStreamInfosAsync(id);

            MediaStreamInfo streamInfo = set.Audio.WithHighestBitrate();

            // download to temp file
            Directory.CreateDirectory(TempDirectoryPath);
            string streamFileExt  = streamInfo.Container.GetFileExtension();
            string streamFilePath = Path.Combine(TempDirectoryPath, $"{Guid.NewGuid()}.{streamFileExt}");
            await client.DownloadMediaStreamAsync(streamInfo, streamFilePath);

            // create directories
            if (String.IsNullOrEmpty(artist))
            {
                path = GetPath(Settings.MusicPath, "Unknown Artist");
                if (String.IsNullOrEmpty(album))
                {
                    path = GetPath(path, "Unknown Album");
                }
            }
            else
            {
                path = GetPath(Settings.MusicPath, artist);
                if (!String.IsNullOrEmpty(album))
                {
                    path = GetPath(path, album);
                }
            }

            string mp3Path = String.Format(@"{0}\{1}.mp3", path, cleanTitle);

            // convert to mp3
            try
            {
                FfmpegCli.SetArguments($"-i \"{streamFilePath}\" -q:a 0 -map a \"{mp3Path}\" -y");
                await FfmpegCli.ExecuteAsync();
            }
            catch (Exception e)
            {
            }

            // delete temp file
            File.Delete(streamFilePath);

            // save/split mp3
            using (TagLib.File meta = TagLib.File.Create(mp3Path))
            {
                if (s != null)
                {
                    s.Path = mp3Path;
                    SaveMp3(meta, s);
                }
                else
                {
                    meta.Tag.Album = songs[0].Album;
                    meta.Save();
                    Split(songs, path, mp3Path);
                }
            }
        }