Пример #1
0
        private async Task PlaySong(YoutubeExplode.Videos.Video input)
        {
            try
            {
                await audioClient.SetSpeakingAsync(true);

                var streamManifest = await youtube.Videos.Streams.GetManifestAsync(input.Id, Skip.Token);

                var streamInfo = streamManifest.GetAudioOnlyStreams().GetWithHighestBitrate();

                var stream = await youtube.Videos.Streams.GetAsync(streamInfo, Skip.Token);

                var memoryStream = new MemoryStream();
                await Cli.Wrap("ffmpeg")
                .WithArguments(" -hide_banner -loglevel panic -i pipe:0 -ac 2 -f s16le -ar 48000 pipe:1")
                .WithStandardInputPipe(PipeSource.FromStream(stream))
                .WithStandardOutputPipe(PipeTarget.ToStream(memoryStream))
                .ExecuteAsync(Skip.Token);

                using (var discord = audioClient.CreatePCMStream(AudioApplication.Music))
                {
                    try { await discord.WriteAsync(memoryStream.ToArray(), 0, (int)memoryStream.Length, Skip.Token); }
                    finally { await discord.FlushAsync(); }
                }
            }
            catch (Exception)
            {
            }
        }
Пример #2
0
        internal static async Task ExecuteInternal(Action <ArgumentsBuilder> configure, CancellationToken cancellationToken)
        {
            ThrowIfNull(ToolPath, nameof(SdkManager));

            var stdErrBuffer = new StringBuilder();
            await Cli.Wrap(ToolPath)
            .WithArguments(configure)
            .WithValidation(CommandResultValidation.None)
            .WithStandardErrorPipe(PipeTarget.ToStringBuilder(stdErrBuffer))
            .WithStandardOutputPipe(PipeTarget.ToDelegate(l => Logger.WriteLine(l, LogLevel.Detailed)))
            .WithStandardInputPipe(PipeSource.FromString("y"))
            .ExecuteAsync(cancellationToken);

            var stdErr = stdErrBuffer.ToString().Trim();

            if (!string.IsNullOrEmpty(stdErr))
            {
                if (stdErr.Split('\n').Select(x => x.Trim()).All(x => x.StartsWith("Warning:")))
                {
                    Logger.WriteWarning(stdErr);
                }
                else
                {
                    throw new Exception(stdErr);
                }
            }
        }
Пример #3
0
        public static async Task InstallEmulator(string emulatorName, int sdkVersion, CancellationToken cancellationToken)
        {
            var devices = await GetDevices(cancellationToken);

            var device = devices
                         .Where(x => Regex.IsMatch(x, @"^pixel_\d$"))
                         .OrderByDescending(x => x)
                         .FirstOrDefault();

            if (string.IsNullOrEmpty(device))
            {
                Logger.WriteError("Current Devices");
                foreach (var d in devices)
                {
                    Logger.WriteError($"  - {d}");
                }

                throw new Exception("No pixel device found.");
            }

            Logger.WriteLine($"Installing Emulator for SDK Version: {sdkVersion} with Device {device}", LogLevel.Normal);

            await ExecuteInternal(b =>
            {
                b.Add("create")
                .Add("avd")
                .Add("--name")
                .Add(emulatorName)
                .Add("--package")
                .Add($"system-images;android-{sdkVersion};google_apis_playstore;x86")
                .Add("--device")
                .Add(device)
                .Add("--force");
            }, cancellationToken, PipeSource.FromString("no")).ConfigureAwait(false);
        }
Пример #4
0
        private async void StartStream(YoutubeClient youtube, AudioClient audioClient, AudioOnlyStreamInfo streamInfo, IMessage?message)
        {
            Stream ytStream = await youtube.Videos.Streams.GetAsync(streamInfo);

            // Convert yt stream
            MemoryStream memoryStream = new MemoryStream();
            await Cli.Wrap("ffmpeg")
            .WithArguments(" -hide_banner -loglevel panic -i pipe:0 -ac 2 -f s16le -ar 48000 pipe:1")
            .WithStandardInputPipe(PipeSource.FromStream(ytStream))
            .WithStandardOutputPipe(PipeTarget.ToStream(memoryStream))
            .ExecuteAsync();

            // Clear stream before beginning
            if (audioClient.CurrentStream != null)
            {
                audioClient.CurrentStream.Dispose();
                audioClient.CurrentStream = null;
            }

            AudioOutStream discord = audioClient.Client.CreatePCMStream(AudioApplication.Mixed);

            audioClient.CurrentStream = discord;

            // Delete calling command
            if (message != null)
            {
                await message.DeleteAsync();
            }

            // Start playing music
            await this.WriteStreamToVoiceChannel(audioClient, discord, memoryStream);
        }
Пример #5
0
        public void ShouldExecuteTheCodeForThisNode()
        {
            var testSubject = new PipeSource <decimal, decimal>(_AddThree);

            testSubject.Call(4);
            _lastInputSeen.Should()
            .Be(4);
        }
Пример #6
0
        public void ShouldDisplayBindGraph()
        {
            var testSubject = new PipeSource <decimal, int>(_One);

            testSubject.AndThen(_Two).AndThen(new Collector <float>());
            testSubject.AndThen <string>(_Three);
            Approvals.Verify(testSubject);
        }
Пример #7
0
        public void CanGatherResultsEasily()
        {
            var testSubject = new PipeSource <decimal, decimal>(_AddThree);
            var results     = new Collector <decimal>();

            testSubject.AndThen(results);
            testSubject.Call(4);
            results.Results.Should()
            .BeEquivalentTo(7M);
        }
Пример #8
0
        public void SmokeTest()
        {
            var pipeline = new XmlPipeline();

            pipeline
            .Source(PipeSource.Files(new[] { Path.Combine(TestPath.InputTestFilesFolder, @"xml\test1.xml") }))
            .Pipe(new XsdValidateTransform(Path.Combine(TestPath.InputTestFilesFolder, @"xsd\schema1.xsd")))
            .Destination(PipeDestination.Folder(TestPath.OutputTestFilesFolder), s => s + "_out.xml")
            .Pump(false);
        }
Пример #9
0
        public void I_can_create_a_new_command_from_an_existing_one_by_specifying_different_stdin_pipe()
        {
            // Arrange
            var cmd = Cli.Wrap("foo").WithStandardInputPipe(PipeSource.Null);

            // Act
            var cmdOther = cmd.WithStandardInputPipe(PipeSource.FromString("new"));

            // Assert
            cmd.Should().BeEquivalentTo(cmdOther, o => o.Excluding(c => c.StandardInputPipe));
            cmd.StandardInputPipe.Should().NotBeSameAs(cmdOther.StandardInputPipe);
        }
Пример #10
0
        public void Stdin_pipe_can_be_set()
        {
            // Arrange
            var cmd = Cli.Wrap("foo").WithStandardInputPipe(PipeSource.Null);

            // Act
            var cmdOther = cmd.WithStandardInputPipe(PipeSource.FromString("new"));

            // Assert
            cmd.Should().BeEquivalentTo(cmdOther, o => o.Excluding(c => c.StandardInputPipe));
            cmd.StandardInputPipe.Should().NotBeSameAs(cmdOther.StandardInputPipe);
        }
Пример #11
0
        public void ShouldSendTheResultToAnyListeners()
        {
            var testSubject = new PipeSource <decimal, decimal>(_AddThree);

            using (var monitor = testSubject.Monitor())
            {
                testSubject.Call(4);
                var expectation = new[] { Result(7), Done() };
                monitor.OccurredEvents.Should()
                .BeEquivalentTo(expectation, options => options.WithStrictOrdering()
                                .ExcludingMissingMembers());
            }
        }
Пример #12
0
        public void ShouldAllowGeneratorFunctionsToPushSeveralArgumentsThenAutomaticallyFinishWhenTheyAreDone()
        {
            var testSubject = new PipeSource <decimal, decimal>(_AddOneTwoThree);

            using (var monitor = testSubject.Monitor())
            {
                testSubject.Call(4);
                var expectation = new[] { Result(5), Result(6), Result(7), Done() };
                monitor.OccurredEvents.Should()
                .BeEquivalentTo(expectation, options => options.WithStrictOrdering()
                                .ExcludingMissingMembers());
            }
        }
Пример #13
0
        public void should_create_pipe()
        {
            var pipe          = new FakePipe();
            var containerMock = new Mock <IContainer>();

            containerMock.Setup(x => x.GetInstance <FakePipe>()).Returns(pipe);

            var source = new PipeSource <FakePipe>(containerMock.Object);

            var pipes = source.GetPipes(typeof(FakeMessageHandler));

            pipes.Single().ShouldEqual(pipe);
        }
Пример #14
0
        public void ShouldConnectThroughMultipleLayers()
        {
            var head   = new PipeSource <decimal, decimal>(_AddThree);
            var middle = head.AndThen(_AddThree);

            using (var monitor = middle.Monitor())
            {
                head.Call(4);
                var expectation = new[] { Result(10), Done() };
                monitor.OccurredEvents.Should()
                .BeEquivalentTo(expectation, options => options.WithStrictOrdering()
                                .ExcludingMissingMembers());
            }
        }
Пример #15
0
        public void GatheringResultsRethrowsExceptions()
        {
            var testSubject = new PipeSource <decimal, decimal>(_ThowException);
            var results     = new Collector <decimal>();

            testSubject.AndThen(results);
            testSubject.Call(4);
            results.Invoking(all =>
            {
                var r = all.Results;
            })
            .Should()
            .Throw <AggregateException>()
            .WithInnerException <ArgumentException>()
            .WithMessage("The right one.");
        }
Пример #16
0
        private static async Task ExecuteInternal(Action <ArgumentsBuilder> configure, CancellationToken cancellationToken)
        {
            ThrowIfNull(ToolPath, nameof(SdkManager));

            var stdErrBuffer = new StringBuilder();
            await Cli.Wrap(ToolPath)
            .WithArguments(configure)
            .WithStandardErrorPipe(PipeTarget.ToStringBuilder(stdErrBuffer))
            .WithStandardOutputPipe(PipeTarget.ToDelegate(l => Logger.WriteLine(l, LogLevel.Detailed)))
            .WithStandardInputPipe(PipeSource.FromString("y"))
            .ExecuteAsync(cancellationToken);

            var stdErr = stdErrBuffer.ToString().Trim();

            if (!string.IsNullOrEmpty(stdErr))
            {
                throw new Exception(stdErr);
            }
        }
Пример #17
0
        public static async Task InstallEmulator(int sdkVersion, CancellationToken cancellationToken)
        {
            var devices = await GetDevices(cancellationToken);

            var device = devices
                         .Where(x => Regex.IsMatch(x, @"^pixel_\d$"))
                         .OrderByDescending(x => x)
                         .FirstOrDefault();

            Logger.WriteLine($"Installing Emulator for SDK Version: {sdkVersion} with Device {device}", LogLevel.Normal);

            await ExecuteInternal(b =>
            {
                b.Add("create")
                .Add("avd")
                .Add($"-n {DefaultUITestEmulatorName}")
                .Add($@"-k ""system-images;android-{sdkVersion};google_apis_playstore;x86""")
                .Add($"--device {device}")
                .Add("--force");
            }, cancellationToken, PipeSource.FromString("no")).ConfigureAwait(false);
        }
Пример #18
0
        public static PipeSource <string, CharacterFile> CreatePipeline(out Collector <CharacterFile> characterTrap, out Collector <ConfigFile> configTrap,
                                                                        out PipeMiddle <CharacterFile, ConfigFile> configFileNode, out Collector <CardData> partialCardsTrap, out Collector <CardData> localCardsTrap)
        {
            var orchestration = new PipeSource <string, CharacterFile>(CharacterFile.From);

            characterTrap = new Collector <CharacterFile>();
            orchestration.AndThen(characterTrap);

            configFileNode = orchestration.AndThen(ConfigFile.Matching);
            configTrap     = new Collector <ConfigFile>();
            configFileNode.AndThen(configTrap);

            partialCardsTrap = new Collector <CardData>();
            var partialCardFinder =
                orchestration.AndThen(PipelineAdapter.Scatter <CharacterFile, CardData>(CharacterFile.GetTheCards));

            partialCardFinder.AndThen(partialCardsTrap);

            localCardsTrap = new Collector <CardData>();
            var localCardFinder = configFileNode.AndThen(PipelineAdapter.Scatter <ConfigFile, CardData>(ConfigFile.GetTheCards));

            localCardFinder.AndThen(localCardsTrap);
            return(orchestration);
        }
Пример #19
0
        public async Task SendYTAudioAsync(IGuild guild, IMessageChannel channel, IVoiceChannel target, string path, double volume = 1.0)
        {
            volume *= 0.25;


            CurrentAudioInformation client;

            if (CurrentAudioClients.TryGetValue(guild.Id, out client))
            {
                await CheckAudioClient(guild, target, client.client);

                string youtubeID = GetYouTubeVideoIdFromUrl(path);

                if (youtubeID == null)
                {
                    await channel.SendMessageAsync("That is not a valid youtube link!");

                    return;
                }

                if (!string.IsNullOrEmpty(client.playing))
                {
                    client.queue.Enqueue(path);
                    await channel.SendMessageAsync($"Added {path} to the queue.");

                    return;
                }

                client.playing = path;

                await _log.LogAsync(new LogMessage(LogSeverity.Info, "Audio", $"Starting playback of {path} in {guild.Name}"));

                if (client.currentStream == null)
                {
                    client.currentStream = client.client.CreatePCMStream(AudioApplication.Mixed, 98304, 200);
                }

                var youtube = new YoutubeClient();

                var streamManifest = await youtube.Videos.Streams.GetManifestAsync(youtubeID);

                var streamInfo = streamManifest.GetAudioOnlyStreams().GetWithHighestBitrate();

                var memoryStream = new MemoryStream();
                var video        = await youtube.Videos.Streams.GetAsync(streamInfo);

                await Cli.Wrap("ffmpeg")
                .WithArguments($"-hide_banner -loglevel panic -i pipe:0 -filter:a \"volume = {volume}\" -ac 2 -f s16le -ar 48000 pipe:1")
                .WithStandardInputPipe(PipeSource.FromStream(video))
                .WithStandardOutputPipe(PipeTarget.ToStream(memoryStream))
                .ExecuteAsync();

                try {
                    client.cancelTokenSource = new CancellationTokenSource();
                    await client.currentStream.WriteAsync(memoryStream.ToArray(), 0, (int)memoryStream.Length, client.cancelTokenSource.Token);
                } catch (OperationCanceledException e) {
                    await channel.SendMessageAsync($"Stopped http://youtu.be/{youtubeID}");
                } finally {
                    await _log.LogAsync(new LogMessage(LogSeverity.Verbose, "Audio", $"Finished playing {path}."));
                    await CheckQueue(guild, channel, target);
                }
            }
            else
            {
                await JoinAudio(guild, target);
                await SendYTAudioAsync(guild, channel, target, path, volume);
            }
        }
Пример #20
0
        private static async Task <string> ExecuteInternal(Action <ArgumentsBuilder> configure, CancellationToken cancellationToken, PipeSource stdInput = null)
        {
            var toolPath = ToolPath;

            ThrowIfNull(toolPath, nameof(AvdManager));
            var builder = new ArgumentsBuilder();

            configure(builder);
            var args = builder.Build();

            Logger.WriteLine($"{toolPath} {args}", LogLevel.Normal);
            var stdErrBuffer = new StringBuilder();
            var stdOutBuffer = new StringBuilder();
            var stdOut       = PipeTarget.Merge(PipeTarget.ToStringBuilder(stdOutBuffer),
                                                PipeTarget.ToDelegate(l => Logger.WriteLine(l, LogLevel.Verbose)));

            var cmd = Cli.Wrap(toolPath)
                      .WithArguments(args)
                      .WithStandardErrorPipe(PipeTarget.ToStringBuilder(stdErrBuffer))
                      .WithStandardOutputPipe(stdOut);

            if (stdInput != null)
            {
                cmd = cmd.WithStandardInputPipe(stdInput);
            }

            await cmd.ExecuteAsync(cancellationToken);

            var stdErr = stdErrBuffer.ToString().Trim();

            if (!string.IsNullOrEmpty(stdErr))
            {
                throw new Exception(stdErr);
            }

            return(stdOutBuffer.ToString().Trim());
        }
Пример #21
0
        private static async Task <string> ExecuteInternal(Action <ArgumentsBuilder> configure, CancellationToken cancellationToken, PipeSource stdInput = null)
        {
            var toolPath = ToolPath;

            ThrowIfNull(toolPath, nameof(AvdManager));
            var builder = new ArgumentsBuilder();

            configure(builder);
            var args = builder.Build();

            Logger.WriteLine($"{toolPath} {args}", LogLevel.Normal);
            var errorBuffer  = new List <string>();
            var stdOutBuffer = new StringBuilder();
            var stdOut       = PipeTarget.Merge(PipeTarget.ToStringBuilder(stdOutBuffer),
                                                PipeTarget.ToDelegate(l => Logger.WriteLine(l, LogLevel.Verbose)));

            var stdErr = PipeTarget.ToDelegate(l =>
            {
                if (string.IsNullOrEmpty(l))
                {
                    return;
                }
                else if (l.Contains("Warning: "))
                {
                    Logger.WriteWarning(l);
                }
                else
                {
                    errorBuffer.Add(l);
                }
            });

            var cmd = Cli.Wrap(toolPath)
                      .WithArguments(args)
                      .WithValidation(CommandResultValidation.None)
                      .WithStandardErrorPipe(stdErr)
                      .WithStandardOutputPipe(stdOut);

            if (stdInput != null)
            {
                cmd = cmd.WithStandardInputPipe(stdInput);
            }

            await cmd.ExecuteAsync(cancellationToken);

            if (errorBuffer.Any())
            {
                throw new Exception(string.Join(Environment.NewLine, errorBuffer));
            }

            return(stdOutBuffer.ToString().Trim());
        }