public void ThenCanParseExcelDocumentationFormatWithLongFormSuccessfully()
        {
            var args = new[] {@"-documentation-format=excel"};

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            shouldContinue.ShouldBeTrue();
            configuration.DocumentationFormat.ShouldEqual(DocumentationFormat.Excel);
        }
        public void ThenCanParseExcelDocumentationFormatWithShortFormSuccessfully()
        {
            var args = new[] { @"-df=excel" };

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Check.That(shouldContinue).IsTrue();
            Check.That(configuration.DocumentationFormat).IsEqualTo(DocumentationFormat.Excel);
        }
        public void Then_can_parse_results_format_nunit_with_short_form_successfully()
        {
            var args = new string[] { @"-trfmt=nunit" };

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser();
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Assert.AreEqual(true, shouldContinue);
            Assert.AreEqual(TestResultsFormat.NUnit, configuration.TestResultsFormat);
        }
        public void ThenCanFilterOutNonExistingTestResultFiles()
        {
            var args = new[] { @"-link-results-file=c:\DoesNotExist.xml;" };

              var configuration = new Configuration();
              var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
              bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

              shouldContinue.ShouldBeTrue();
              configuration.HasTestResults.ShouldBeFalse();
              Assert.AreEqual(0, configuration.TestResultsFiles.Count());
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            //Basic parsing of arguments for now
            var parser = new CommandLineArgumentParser();
            parser.Parse(args);

            //Create a cloak manager
            var manager = new CloakManager();
            //Create a cloaking context
            var cloakContext = new CloakContext(parser.Settings);
            //Run the manager
            manager.Run(cloakContext);
        }
        public void ThenCanParseHelpRequestWithLongFormSuccessfully()
        {
            var args = new[] { @"--help" };

              var configuration = new Configuration();
              var writer = new StringWriter();
              var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
              bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, writer);

              StringAssert.Contains(expectedHelpString.ComparisonNormalize(),
                            writer.GetStringBuilder().ToString().ComparisonNormalize());
              shouldContinue.ShouldBeFalse();
        }
        public void Then_can_parse_long_form_arguments_successfully()
        {
            var args = new string[] { @"--feature-directory=c:\features", @"--output-directory=c:\features-output" };

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser();
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Assert.AreEqual(true, shouldContinue);
            Assert.AreEqual(@"c:\features", configuration.FeatureFolder.FullName);
            Assert.AreEqual(@"c:\features-output", configuration.OutputFolder.FullName);
            Assert.AreEqual(false, configuration.HasTestResults);
            Assert.AreEqual(null, configuration.TestResultsFile);
        }
    public void ThenCanParseHelpRequestWithLongFormSuccessfully()
    {
      var args = new[] { @"--help" };

      var configuration = new Configuration();
      var writer = new StringWriter();
      var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
      bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, writer);


      var actual = RetrieveString(writer);
      Check.That(actual).Contains(ExpectedHelpString.ComparisonNormalize());
      Check.That(shouldContinue).IsFalse();
    }
        public void Then_can_parse_help_request_with_short_form_successfully()
        {
            var args = new string[] { @"-h" };

            var configuration = new Configuration();
            var writer = new StringWriter();
            var commandLineArgumentParser = new CommandLineArgumentParser();
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, writer);

            StringAssert.Contains(expectedHelpString, writer.GetStringBuilder().ToString().Trim());
            Assert.AreEqual(false, shouldContinue);
            Assert.AreEqual(Path.GetFullPath(Directory.GetCurrentDirectory()), configuration.FeatureFolder.FullName);
            Assert.AreEqual(Path.GetFullPath(Environment.GetEnvironmentVariable("TEMP")), configuration.OutputFolder.FullName);
            Assert.AreEqual(false, configuration.HasTestFrameworkResults);
            Assert.AreEqual(null, configuration.LinkedTestFrameworkResultsFile);
        }
Esempio n. 10
0
        public void IntegerArrayWithNegativeValue()
        {
            var args = new[]
            {
                "--numberarray",
                "8",
                "-99",
                "7"
            };

            var result = CommandLineArgumentParser.Parse <NonAttributeOptions>(args);

            result.ParsedOptions.NumberArray.Length.Should().Be(3);
            result.ParsedOptions.NumberArray[0].Should().Be(8);
            result.ParsedOptions.NumberArray[1].Should().Be(-99);
            result.ParsedOptions.NumberArray[2].Should().Be(7);
            result.Result.Should().Be(OptionsResult.Success);
        }
        public void ThenCanParseHelpRequestWithLongFormSuccessfully()
        {
            var args = new[] {@"--help"};

            var configuration = new Configuration();
            var writer = new StringWriter();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, writer);


            StringAssert.Contains(expectedHelpString.ComparisonNormalize(),
                                  writer.GetStringBuilder().ToString().ComparisonNormalize());
            Assert.AreEqual(false, shouldContinue);
            Assert.AreEqual(Path.GetFullPath(Directory.GetCurrentDirectory()), configuration.FeatureFolder.FullName);
            Assert.AreEqual(Path.GetFullPath(Directory.GetCurrentDirectory()), configuration.OutputFolder.FullName);
            Assert.AreEqual(false, configuration.HasTestResults);
            Assert.AreEqual(null, configuration.TestResultsFile);
        }
Esempio n. 12
0
        public void TestUpdateOnly(string value, bool expected)
        {
            string[] args;
            if (value != "")
            {
                args    = new string[3];
                args[0] = "dummy";
                args[1] = "somepath";
                args[2] = value;
            }
            else
            {
                args    = new string[2];
                args[0] = "dummy";
                args[1] = "somepath";
            }

            Assert.Equal(expected, CommandLineArgumentParser.ParseArgs(args).Folders.First().UpdatedOnly);
        }
Esempio n. 13
0
        public void ThenCanParseHelpRequestWithLongFormSuccessfully()
        {
            var args = new[] { @"--help" };

            var  configuration             = new Configuration();
            var  writer                    = new StringWriter();
            var  commandLineArgumentParser = new CommandLineArgumentParser();
            bool shouldContinue            = commandLineArgumentParser.Parse(args, configuration, writer);


            StringAssert.Contains(expectedHelpString.ComparisonNormalize(),
                                  writer.GetStringBuilder().ToString().ComparisonNormalize());
            Assert.AreEqual(false, shouldContinue);
            Assert.AreEqual(Path.GetFullPath(Directory.GetCurrentDirectory()), configuration.FeatureFolder.FullName);
            Assert.AreEqual(Path.GetFullPath(Environment.GetEnvironmentVariable("TEMP")),
                            configuration.OutputFolder.FullName);
            Assert.AreEqual(false, configuration.HasTestResults);
            Assert.AreEqual(null, configuration.TestResultsFile);
        }
Esempio n. 14
0
        public void TestLogLevel(string value, EnumLogLevel expected)
        {
            string[] args;
            if (value != "")
            {
                args    = new string[3];
                args[0] = "dummy";
                args[1] = "somepath";
                args[2] = value;
            }
            else
            {
                args    = new string[2];
                args[0] = "dummy";
                args[1] = "somepath";
            }

            Assert.Equal(expected, CommandLineArgumentParser.ParseArgs(args).LogLevel);
        }
Esempio n. 15
0
        public void TestCreateRequestConfrm(string value, bool expected)
        {
            string[] args;
            if (value != "")
            {
                args    = new string[3];
                args[0] = "dummy";
                args[1] = "somepath";
                args[2] = value;
            }
            else
            {
                args    = new string[2];
                args[0] = "dummy";
                args[1] = "somepath";
            }

            Assert.Equal(expected, CommandLineArgumentParser.ParseArgs(args).RequestConfirm);
        }
Esempio n. 16
0
        public static void Main(string[] args)
        {
            try
            {
                Logger.Level = EnumLogLevel.Info;
                Logger.AddLogger(new ConsoleLogger());

                Commands theCommands = CommandLineArgumentParser.ParseArgs(args);
                if (theCommands.ShowHelp)
                {
                    Logger.Info(CommandLineArgumentParser.Help());
                }
                else
                {
                    Logger.Level = theCommands.LogLevel;
                    Logger.Info("Copy started.");
                    CommandHandler CommandHandler = new CommandHandler(theCommands);
                    Copier         Copier         = new Copier(theCommands, CommandHandler);
                    Copier.ProcessInfoEvent                   += ProcessInfo_ProcessInfoEvent;
                    CommandHandler.ProcessInfoEvent           += ProcessInfo_ProcessInfoEvent;
                    CommandHandler.ConfirmationRequestHandler += ConfirmationRequest;
                    Copier.Copy();
                    Logger.Info("Copy done.");
                    if (theCommands.PauseWhenDone)
                    {
                        Console.ReadKey();
                    }
                }
            }
            catch (System.IO.DirectoryNotFoundException ex)
            {
                Logger.Error(ex.Message);
            }
            catch (UnauthorizedAccessException ex)
            {
                Logger.Error(ex.Message);
            }
            catch (Exception ex)
            {
                Logger.Error("Failed with an unexpected exception.", ex);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Initializes static members of the<see cref="GlobalParameters" /> class.
        /// </summary>
        static GlobalParameters()
        {
            // Unique parameters that can be used alone
            string[] uniqueParameters =
            {
                "-gui",
                "-help"
            };
            CommandLineArgumentParser.DefineUniqueParameters(uniqueParameters);

            // Mandatory parameters of the application decoded from the command line.
            string[] requiredArguments =
            {
                "-rx",
                "-tx",
            };

            CommandLineArgumentParser.DefineRequiredParameters(requiredArguments);

            // Optional parameters
            string[] optionalArguments =
            {
                "-baud=9600",
                "-parity=none",
                "-stopbit=1",
                "-data=8",
                "-output=stdout",
                "-bytesPerLine=16"
            };
            CommandLineArgumentParser.DefineOptionalParameter(optionalArguments);

            // Supported switches
            string[] switches =
            {
                "-onlyHex",
                "-onlyAscii",
                "-time",
                "-collapsed",
                "-ycable"
            };
            CommandLineArgumentParser.DefineSwitches(switches);
        }
Esempio n. 18
0
        public List <SearchFilter> getSearchFilterList(string[] args)
        {
            List <SearchFilter>         filterList = new List <SearchFilter>();
            Dictionary <string, string> map        = new Dictionary <string, string>();

            arguments = CommandLineArgumentParser.Parse(args);
            if (arguments.Has("-SearchMail"))
            {
                map = getFilterMap("-SeaarchFilter");
                if (map["subject"] != null && !map["subject"].Equals(""))
                {
                    filterList.Add(Filters.filterBySubject(map["subject"]));
                }
                if (map["From"] != null && !map["From"].Equals(""))
                {
                    filterList.Add(Filters.filterBySubject(map["From"]));
                }
            }
            return(filterList);
        }
Esempio n. 19
0
        public void VerbSubclassReturned_CanSetBaseclassProperty()
        {
            var args = new[]
            {
                "verb",
                "--anoption",
                "optionvalue",
                "--anotheroption",
                "basic"
            };

            var parse   = CommandLineArgumentParser.Parse <StringOptions>(args);
            var options = parse.ParsedOptions;

            options.Should().BeOfType <VerbStringOptions>();
            var verbOptions = options as VerbStringOptions;

            verbOptions.AnotherOption.Should().Be("basic");
            parse.Result.Should().Be(OptionsResult.Success);
        }
Esempio n. 20
0
        public MailApplication(string [] args)
        {
            var argumetns = CommandLineArgumentParser.Parse(args);

            if (argumetns.Has("-GetMail"))
            {
                commandEnumration = CommandEnum.getmail;
            }
            else if (argumetns.Has("-SearchMail"))
            {
                commandEnumration = CommandEnum.searchmail;
            }
            else if (argumetns.Has("-Time"))
            {
                commandEnumration = CommandEnum.timeMail;
            }
            else
            {
                commandEnumration = CommandEnum.asistMail;
            }
        }
        public void ParseCommandLineArguments_Scenario_InvalidRegexPassed()
        {
            //Arrange
            string[] args         = new string[] { "-f", @"..\..\..\TestFiles\ISLogFile.log", "-r", "[" };
            string   outputPath   = "";
            string   regexPattern = "";
            string   file         = "";

            try
            {
                //Act
                CommandLineArgumentParser.ParseCommandLineArguments(args, out outputPath, out regexPattern, out file);
            }
            catch (Exception ex)
            {
                //Assert
                // RegexParseException thrown
                Assert.IsTrue(ex.Message == "Invalid pattern '[' at offset 1. Unterminated [] set.");
            }
            //Assert.ThrowsException<RegexParseException>(() => CommandLineArgumentParser.ParseCommandLineArguments(args, out outputPath, out regexPattern, out file), "Provided Regular Expression pattern can not be empty, it should contain two groups the first identifying the IP Address, and the second identifying the URL");
        }
        public void CanParseCommandLineArgumentsWithBothFilters()
        {
            parser = new CommandLineArgumentParser();

            string[] args = { "C:\\Logs.txt", "C:\\Logs.json", "-M", "pie", "-U", "bob" };

            var s = parser.ParseCommandLineArguments(args);

            Assert.AreEqual("C:\\Logs.txt", s.inputFilePath);
            Assert.AreEqual("C:\\Logs.json", s.outputFilePath);
            Assert.IsNotNull(s.commandLineArguments);
            Assert.IsTrue(s.commandLineArguments.Count == 2);

            Assert.AreEqual(CommandLineArgumentType.MessageFilter, s.commandLineArguments[0].ArgumentType);
            Assert.AreEqual(1, s.commandLineArguments[0].AdditionalParameters.Count);
            Assert.AreEqual("pie", s.commandLineArguments[0].AdditionalParameters[0]);

            Assert.AreEqual(CommandLineArgumentType.UserFilter, s.commandLineArguments[1].ArgumentType);
            Assert.AreEqual(1, s.commandLineArguments[1].AdditionalParameters.Count);
            Assert.AreEqual("bob", s.commandLineArguments[1].AdditionalParameters[0]);
        }
Esempio n. 23
0
        public async Task RunAsync(string[] args)
        {
            Logger.LogInformation("ROCKET CLI (https://aiwins.cn)");

            await CheckCliVersionAsync();

            var commandLineArgs = CommandLineArgumentParser.Parse(args);
            var commandType     = CommandSelector.Select(commandLineArgs);

            using (var scope = ServiceScopeFactory.CreateScope()) {
                var command = (IConsoleCommand)scope.ServiceProvider.GetRequiredService(commandType);

                try {
                    await command.ExecuteAsync(commandLineArgs);
                } catch (CliUsageException usageException) {
                    Logger.LogWarning(usageException.Message);
                } catch (Exception ex) {
                    Logger.LogException(ex);
                }
            }
        }
Esempio n. 24
0
    private async Task RunPromptAsync()
    {
        string GetPromptInput()
        {
            Console.WriteLine("Enter the command to execute or `exit` to exit the prompt model");
            Console.Write("> ");
            return(Console.ReadLine());
        }

        var promptInput = GetPromptInput();

        do
        {
            try
            {
                var commandLineArgs = CommandLineArgumentParser.Parse(promptInput.Split(" ").Where(x => !x.IsNullOrWhiteSpace()).ToArray());

                if (commandLineArgs.IsCommand("batch"))
                {
                    await RunBatchAsync(commandLineArgs);
                }
                else
                {
                    await RunInternalAsync(commandLineArgs);
                }
            }
            catch (CliUsageException usageException)
            {
                Logger.LogWarning(usageException.Message);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }

            promptInput = GetPromptInput();
        } while (promptInput?.ToLower() != "exit");
    }
Esempio n. 25
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("This app has to be run with proper arguments.");
                Console.ReadKey();
                return;
            }
            UpdaterStartupSettings settings     = CommandLineArgumentParser.GetSettings(args);
            UpdateInstructions     instructions = UpdateInstructionsReader.Read(settings.InstructionsFile);

            if (instructions != null)
            {
                Console.WriteLine($"Read update instructions from {settings.InstructionsFile}");

                var worker = new PackageUpdaterWorker();
                worker.TriggerUpdate(settings, instructions);
            }
            else
            {
                Console.WriteLine($"Failed to perform update based on instructions: {settings.InstructionsFile}");
            }
        }
Esempio n. 26
0
        public string listAllFolder(string [] args, bool isHash)

        {
            string outputstring = "";

            arguments = CommandLineArgumentParser.Parse(args);
            if (isHash)
            {
                string url      = arguments.Get("-url").Next;
                string username = arguments.Get("-username").Next;
                string hash     = arguments.Get("-hash").Next;
                this.Mail = new Mail(url, username, hash, ExchangeVersion.Exchange2013);
            }
            else
            {
                string url      = arguments.Get("url").Next;
                string username = arguments.Get("-username").Next;
                string password = arguments.Get("-password").Next;
                this.Mail = new Mail(url, username, password);
            }
            outputstring += mail.listFolders();
            return(outputstring);
        }
Esempio n. 27
0
    public async Task RunAsync(string[] args)
    {
        Logger.LogInformation("ABP CLI (https://abp.io)");

        var commandLineArgs = CommandLineArgumentParser.Parse(args);

#if !DEBUG
        if (!commandLineArgs.Options.ContainsKey("skip-cli-version-check"))
        {
            await CheckCliVersionAsync();
        }
#endif
        try
        {
            if (commandLineArgs.IsCommand("prompt"))
            {
                await RunPromptAsync();
            }
            else if (commandLineArgs.IsCommand("batch"))
            {
                await RunBatchAsync(commandLineArgs);
            }
            else
            {
                await RunInternalAsync(commandLineArgs);
            }
        }
        catch (CliUsageException usageException)
        {
            Logger.LogWarning(usageException.Message);
        }
        catch (Exception ex)
        {
            Logger.LogException(ex);
        }
    }
Esempio n. 28
0
        /// <summary>
        /// The main entry point for the tool.
        /// </summary>
        static public void Run(string[] args)
        {
            try
            {
                object param = new StressTestToolParam();
                CommandLineArgumentParser.CommandLineParser(ref param, args);
                cParam = (StressTestToolParam)param;
                if (cParam.IsUsage)
                {
                    AssemblyUsage.PrintLogo(cParam.IsLogo);
                    AssemblyUsage.PrintUsage();
                    return;
                }

                if (!ApplyParameters(args))
                {
                    return;
                }
                //if (!ValidateParameters()) return;



                Console.WriteLine("cacheId = {0}, total-loop-count = {1}, test-case-iterations = {2}, testCaseIterationDelay = {3}, gets-per-iteration = {4}, updates-per-iteration = {5}, data-size = {6}, expiration = {7}, thread-count = {8}, reporting-interval = {9}.", cParam.CacheId, cParam.TotalLoopCount, cParam.TestCaseIterations, cParam.TestCaseIterationDelay, cParam.GetsPerIteration, cParam.UpdatesPerIteration, cParam.DataSize, cParam.Expiration, cParam.ThreadCount, cParam.ReportingInterval);
                Console.WriteLine("-------------------------------------------------------------------\n");
                Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;

                ThreadTest threadTest = new ThreadTest(cParam.CacheId, cParam.TotalLoopCount, cParam.TestCaseIterations, cParam.TestCaseIterationDelay, cParam.GetsPerIteration, cParam.UpdatesPerIteration, cParam.DataSize, cParam.Expiration, cParam.ThreadCount, cParam.ReportingInterval, cParam.IsLogo);
                threadTest.Test();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error: " + e.Message);
                Console.Error.WriteLine();
                Console.Error.WriteLine(e.ToString());
            }
        }
        public void ThenCanParseResultsFileAsSemicolonSeparatedListThatEndsWithASemicolon()
        {
            FileSystem.AddFile(@"c:\results1.xml", "<xml />");
            var args = new[] { @"-link-results-file=c:\results1.xml;" };

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Check.That(shouldContinue).IsTrue();
            Check.That(configuration.HasTestResults).IsTrue();
            Check.That(configuration.TestResultsFiles.Count()).IsEqualTo(1);
            Check.That(configuration.TestResultsFiles.First().FullName).IsEqualTo(@"c:\results1.xml");
        }
Esempio n. 30
0
        static public void Run(string[] args)
        {
            try
            {
                object param = new RemoveCacheParam();
                CommandLineArgumentParser.CommandLineParser(ref param, args);
                cParam = (RemoveCacheParam)param;
                if (cParam.IsUsage)
                {
                    AssemblyUsage.PrintLogo(cParam.IsLogo);
                    AssemblyUsage.PrintUsage();
                    return;
                }

                if (!ValidateParameters())
                {
                    return;
                }

                if (cParam.Port != -1)
                {
                    NCache.Port = cParam.Port;
                }

                if (cParam.Port == -1)
                {
                    NCache.Port = NCache.UseTcp ? CacheConfigManager.NCacheTcpPort : CacheConfigManager.HttpPort;
                }

                if (cParam.Server != null || cParam.Server != string.Empty)
                {
                    NCache.ServerName = cParam.Server;
                }


                cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                Console.WriteLine("\nRemoving cache '{0}' on server {1}:{2}.", cParam.CacheId,
                                  cacheServer.GetBindIP(), NCache.Port);
                if (cacheServer != null)
                {
                    string getBindIp = string.Empty;
                    try
                    {
                        Alachisoft.NCache.Config.NewDom.CacheServerConfig serverConfig = cacheServer.GetNewConfiguration(cParam.CacheId);

                        if (serverConfig == null)
                        {
                            throw new Exception("Specified cache does not exist.");
                        }
                        if (serverConfig.CacheSettings.CacheType == "clustered-cache")
                        {
                            foreach (Address node in serverConfig.CacheDeployment.Servers.GetAllConfiguredNodes())
                            {
                                try
                                {
                                    NCache.ServerName = node.IpAddress.ToString();
                                    cacheServer       = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                                    cacheServer.UnregisterCache(cParam.CacheId, null, false);
                                    Console.WriteLine("Cache '{0}' successfully removed from server {1}:{2}.\n",
                                                      cParam.CacheId, NCache.ServerName, NCache.Port);
                                }
                                catch (Exception ex)
                                {
                                    Console.Error.WriteLine("Error: Failed to Rmove Cache '{0}' from server '{1}:{2}'. ",
                                                            cParam.CacheId, NCache.ServerName, NCache.Port);
                                    Console.Error.WriteLine("Error Detail: '{0}'. ", ex.Message);

                                    LogEvent(ex.Message);
                                }
                                finally
                                {
                                    cacheServer.Dispose();
                                }
                            }
                        }
                        else
                        {
                            try
                            {
                                getBindIp = cacheServer.GetBindIP();
                                cacheServer.UnregisterCache(cParam.CacheId, null, false);
                                Console.WriteLine("Cache '{0}' successfully removed from server {1}:{2}.\n",
                                                  cParam.CacheId, getBindIp, NCache.Port);
                            }
                            catch (Exception e)
                            {
                                throw e;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine("Error: Failed to Rmove Cache '{0}' from server '{1}:{2}'. ",
                                                cParam.CacheId, cacheServer.GetBindIP(), NCache.Port);
                        Console.Error.WriteLine(ex.Message);
                        LogEvent(ex.Message);
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error: {0}", e.Message);
                Console.Error.WriteLine();
                Console.Error.WriteLine(e.ToString());
            }
            finally
            {
                NCache.Dispose();
            }
        }
Esempio n. 31
0
        static void Main(string[] args)
        {
            ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;

            try
            {
                //判断操作系统
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    isWindows = false;
                }

                string CURRENT_PATH = Directory.GetCurrentDirectory();
                string fileName     = "";
                string exePath      = AppDomain.CurrentDomain.BaseDirectory;

                //goto HasFFmpeg;
                //寻找ffmpeg.exe
                if (!File.Exists("ffmpeg.exe"))
                {
                    try
                    {
                        string[] EnvironmentPath = null;

                        if (isWindows)
                        {
                            EnvironmentPath = Environment.GetEnvironmentVariable("Path").Split(';');
                        }
                        else
                        {
                            EnvironmentPath = Environment.GetEnvironmentVariable("PATH").Split(':');
                        }

                        foreach (var de in EnvironmentPath)
                        {
                            if (File.Exists(Path.Combine(de.Trim('\"').Trim(),
                                                         "ffmpeg" + (isWindows ? ".exe" : ""))))
                            {
                                goto HasFFmpeg;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        ;
                    }

                    if (isWindows)
                    {
                        Console.ForegroundColor = ConsoleColor.White; //设置前景色,即字体颜色
                        Console.BackgroundColor = ConsoleColor.Red;
                        Console.WriteLine("在PATH和程序路径下找不到 ffmpeg.exe");
                        Console.ResetColor(); //将控制台的前景色和背景色设为默认值
                        Console.WriteLine("请下载ffmpeg.exe并把他放到程序同目录.");
                        Console.WriteLine();
                        Console.WriteLine("x86 https://ffmpeg.zeranoe.com/builds/win32/static/");
                        Console.WriteLine("x64 https://ffmpeg.zeranoe.com/builds/win64/static/");
                        Console.WriteLine();
                        Console.WriteLine("按任意键退出.");
                        Console.ReadKey();
                        Environment.Exit(-1);
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.White; //设置前景色,即字体颜色
                        Console.BackgroundColor = ConsoleColor.Red;
                        Console.WriteLine("在PATH和程序路径下找不到 ffmpeg");
                        Console.ResetColor(); //将控制台的前景色和背景色设为默认值
                        Console.WriteLine("请自行安装ffmpeg.");
                        Console.WriteLine();
                        Console.WriteLine("按任意键退出.");
                        Environment.Exit(-1);
                    }
                }

HasFFmpeg:
                Global.WriteInit();
                Thread checkUpdate = new Thread(() =>
                {
                    //Global.CheckUpdate();
                });
                checkUpdate.IsBackground = true;
                checkUpdate.Start();

                int    maxThreads   = Environment.ProcessorCount;
                int    minThreads   = 16;
                int    retryCount   = 15;
                int    timeOut      = 10; //默认10秒
                string baseUrl      = "";
                string reqHeaders   = "";
                string keyFile      = "";
                string keyBase64    = "";
                string muxSetJson   = "MUXSETS.json";
                string workDir      = Path.Combine(CURRENT_PATH, "Downloads");
                bool   muxFastStart = false;
                bool   binaryMerge  = false;
                bool   delAfterDone = false;
                bool   parseOnly    = false;
                bool   noMerge      = false;

                /******************************************************/
                ServicePointManager.DefaultConnectionLimit = 1024;
                /******************************************************/

                if (File.Exists("headers.txt"))
                {
                    reqHeaders = File.ReadAllText("headers.txt");
                }

                //分析命令行参数
parseArgs:
                var arguments = CommandLineArgumentParser.Parse(args);
                if (args.Length == 1 && args[0] == "--help")
                {
                    Console.WriteLine(StaticText.HELP);
                    return;
                }

                if (arguments.Has("--enableDelAfterDone"))
                {
                    delAfterDone = true;
                }
                if (arguments.Has("--enableParseOnly"))
                {
                    parseOnly = true;
                }
                if (arguments.Has("--enableBinaryMerge"))
                {
                    binaryMerge = true;
                }
                if (arguments.Has("--disableDateInfo"))
                {
                    FFmpeg.WriteDate = false;
                }
                if (arguments.Has("--noMerge"))
                {
                    noMerge = true;
                }
                if (arguments.Has("--noProxy"))
                {
                    Global.NoProxy = true;
                }
                if (arguments.Has("--headers"))
                {
                    reqHeaders = arguments.Get("--headers").Next;
                }
                if (arguments.Has("--enableMuxFastStart"))
                {
                    muxFastStart = true;
                }
                if (arguments.Has("--disableIntegrityCheck"))
                {
                    DownloadManager.DisableIntegrityCheck = true;
                }
                if (arguments.Has("--enableAudioOnly"))
                {
                    Global.VIDEO_TYPE = "IGNORE";
                }
                if (arguments.Has("--muxSetJson"))
                {
                    muxSetJson = arguments.Get("--muxSetJson").Next;
                }
                if (arguments.Has("--workDir"))
                {
                    workDir = arguments.Get("--workDir").Next;
                    DownloadManager.HasSetDir = true;
                }
                if (arguments.Has("--saveName"))
                {
                    fileName = Global.GetValidFileName(arguments.Get("--saveName").Next);
                }
                if (arguments.Has("--useKeyFile"))
                {
                    if (File.Exists(arguments.Get("--useKeyFile").Next))
                    {
                        keyFile = arguments.Get("--useKeyFile").Next;
                    }
                }
                if (arguments.Has("--useKeyBase64"))
                {
                    keyBase64 = arguments.Get("--useKeyBase64").Next;
                }
                if (arguments.Has("--stopSpeed"))
                {
                    Global.STOP_SPEED = Convert.ToInt64(arguments.Get("--stopSpeed").Next);
                }
                if (arguments.Has("--maxSpeed"))
                {
                    Global.MAX_SPEED = Convert.ToInt64(arguments.Get("--maxSpeed").Next);
                }
                if (arguments.Has("--baseUrl"))
                {
                    baseUrl = arguments.Get("--baseUrl").Next;
                }
                if (arguments.Has("--maxThreads"))
                {
                    maxThreads = Convert.ToInt32(arguments.Get("--maxThreads").Next);
                }
                if (arguments.Has("--minThreads"))
                {
                    minThreads = Convert.ToInt32(arguments.Get("--minThreads").Next);
                }
                if (arguments.Has("--retryCount"))
                {
                    retryCount = Convert.ToInt32(arguments.Get("--retryCount").Next);
                }
                if (arguments.Has("--timeOut"))
                {
                    timeOut = Convert.ToInt32(arguments.Get("--timeOut").Next);
                }
                if (arguments.Has("--downloadRange"))
                {
                    string p = arguments.Get("--downloadRange").Next;

                    if (p.Contains(":"))
                    {
                        //时间码
                        Regex reg2 = new Regex(@"((\d+):(\d+):(\d+))?-((\d+):(\d+):(\d+))?");
                        if (reg2.IsMatch(p))
                        {
                            Parser.DurStart = reg2.Match(p).Groups[1].Value;
                            Parser.DurEnd   = reg2.Match(p).Groups[5].Value;
                            Parser.DelAd    = false;
                        }
                    }
                    else
                    {
                        //数字
                        Regex reg = new Regex(@"(\d*)-(\d*)");
                        if (reg.IsMatch(p))
                        {
                            if (!string.IsNullOrEmpty(reg.Match(p).Groups[1].Value))
                            {
                                Parser.RangeStart = Convert.ToInt32(reg.Match(p).Groups[1].Value);
                                Parser.DelAd      = false;
                            }
                            if (!string.IsNullOrEmpty(reg.Match(p).Groups[2].Value))
                            {
                                Parser.RangeEnd = Convert.ToInt32(reg.Match(p).Groups[2].Value);
                                Parser.DelAd    = false;
                            }
                        }
                    }
                }

                //如果只有URL,没有附加参数,则尝试解析配置文件
                if (args.Length == 1)
                {
                    if (File.Exists(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "N_m3u8DL-CLI.args.txt")))
                    {
                        args = Global.ParseArguments($"\"{args[0]}\"" + File.ReadAllText(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "N_m3u8DL-CLI.args.txt"))).ToArray();  //解析命令行
                        goto parseArgs;
                    }
                }

                //ReadLine字数上限
                Stream steam = Console.OpenStandardInput();
                Console.SetIn(new StreamReader(steam, Encoding.Default, false, 5000));
                int inputRetryCount = 20;
input:
                string testurl = "";


                //重试太多次,退出
                if (inputRetryCount == 0)
                {
                    Environment.Exit(-1);
                }

                if (args.Length > 0)
                {
                    testurl = args[0];
                }
                else
                {
                    Console.CursorVisible   = true;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("N_m3u8DL-CLI");
                    Console.ResetColor();
                    Console.Write(" > ");

                    if (isWindows)
                    {
                        args = Global.ParseArguments(Console.ReadLine()).ToArray();  //解析命令行
                    }
                    else
                    {
                        args = Global.SplitCommandLine(Console.ReadLine());  //解析命令行
                    }
                    Global.WriteInit();
                    Console.CursorVisible = false;
                    goto parseArgs;
                }

                if (fileName == "")
                {
                    fileName = Global.GetUrlFileName(testurl) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                }


                //优酷DRM设备更改

                /*if (testurl.Contains("playlist/m3u8"))
                 * {
                 *  string drm_type = Global.GetQueryString("drm_type", testurl);
                 *  string drm_device = Global.GetQueryString("drm_device", testurl);
                 *  if (drm_type != "1")
                 *  {
                 *      testurl = testurl.Replace("drm_type=" + drm_type, "drm_type=1");
                 *  }
                 *  if (drm_device != "11")
                 *  {
                 *      testurl = testurl.Replace("drm_device=" + drm_device, "drm_device=11");
                 *  }
                 * }*/
                string m3u8Content = string.Empty;
                bool   isVOD       = true;



                //开始解析

                Console.CursorVisible = false;
                LOGGER.PrintLine($"文件名称:{fileName}");
                LOGGER.PrintLine($"存储路径:{Path.GetDirectoryName(Path.Combine(workDir, fileName))}");

                Parser parser = new Parser();
                parser.DownName  = fileName;
                parser.DownDir   = Path.Combine(workDir, parser.DownName);
                parser.M3u8Url   = testurl;
                parser.KeyBase64 = keyBase64;
                parser.KeyFile   = keyFile;
                if (baseUrl != "")
                {
                    parser.BaseUrl = baseUrl;
                }
                parser.Headers = reqHeaders;
                LOGGER.LOGFILE = Path.Combine(exePath, "Logs", DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".log");
                LOGGER.InitLog();
                LOGGER.WriteLine("Start Parsing " + testurl);
                LOGGER.PrintLine("开始解析地址...", LOGGER.Warning);
                if (testurl.EndsWith(".json") && File.Exists(testurl))              //可直接跳过解析
                {
                    if (!Directory.Exists(Path.Combine(workDir, fileName)))         //若文件夹不存在则新建文件夹
                    {
                        Directory.CreateDirectory(Path.Combine(workDir, fileName)); //新建文件夹
                    }
                    File.Copy(testurl, Path.Combine(Path.Combine(workDir, fileName), "meta.json"));
                }
                else
                {
                    parser.Parse();  //开始解析
                }

                //仅解析模式
                if (parseOnly)
                {
                    LOGGER.PrintLine("解析m3u8成功, 程序退出");
                    Environment.Exit(0);
                }

                if (File.Exists(Path.Combine(Path.Combine(workDir, fileName), "meta.json")))
                {
                    JObject initJson = JObject.Parse(File.ReadAllText(Path.Combine(Path.Combine(workDir, fileName), "meta.json")));
                    isVOD = Convert.ToBoolean(initJson["m3u8Info"]["vod"].ToString());
                    //传给Watcher总时长
                    Watcher.TotalDuration = initJson["m3u8Info"]["totalDuration"].Value <double>();
                    LOGGER.PrintLine($"文件时长:{Global.FormatTime((int)Watcher.TotalDuration)}");
                    LOGGER.PrintLine("总分片:" + initJson["m3u8Info"]["originalCount"].Value <int>()
                                     + ", 已选择分片:" + initJson["m3u8Info"]["count"].Value <int>());
                }
                else
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(workDir, fileName));
                    directoryInfo.Delete(true);
                    LOGGER.PrintLine("地址无效", LOGGER.Error);
                    LOGGER.CursorIndex = 5;
                    inputRetryCount--;
                    goto input;
                }

                //点播
                if (isVOD == true)
                {
                    ServicePointManager.DefaultConnectionLimit = 10000;
                    DownloadManager md = new DownloadManager();
                    md.DownDir = parser.DownDir;
                    md.Headers = reqHeaders;
                    md.Threads = Environment.ProcessorCount;
                    if (md.Threads > maxThreads)
                    {
                        md.Threads = maxThreads;
                    }
                    if (md.Threads < minThreads)
                    {
                        md.Threads = minThreads;
                    }
                    if (File.Exists("minT.txt"))
                    {
                        int t = Convert.ToInt32(File.ReadAllText("minT.txt"));
                        if (md.Threads <= t)
                        {
                            md.Threads = t;
                        }
                    }
                    md.TimeOut      = timeOut * 1000;
                    md.NoMerge      = noMerge;
                    md.DownName     = fileName;
                    md.DelAfterDone = delAfterDone;
                    md.BinaryMerge  = binaryMerge;
                    md.MuxFormat    = "mp4";
                    md.RetryCount   = retryCount;
                    md.MuxSetJson   = muxSetJson;
                    md.MuxFastStart = muxFastStart;
                    md.DoDownload();
                }
                //直播
                if (isVOD == false)
                {
                    LOGGER.WriteLine("Living Stream Found");
                    LOGGER.WriteLine("Start Recording");
                    LOGGER.PrintLine("识别为直播流, 开始录制");
                    LOGGER.STOPLOG = true;  //停止记录日志
                                            //开辟文件流,且不关闭。(便于播放器不断读取文件)
                    string LivePath = Path.Combine(Directory.GetParent(parser.DownDir).FullName
                                                   , DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + fileName + ".ts");
                    FileStream outputStream = new FileStream(LivePath, FileMode.Append);

                    HLSLiveDownloader live = new HLSLiveDownloader();
                    live.DownDir    = parser.DownDir;
                    live.Headers    = reqHeaders;
                    live.LiveStream = outputStream;
                    live.LiveFile   = LivePath;
                    live.TimerStart();  //开始录制
                    Console.ReadKey();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public void ThenSetsLanguageToEnglishByDefault()
        {
            var args = new[] { "" };

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Check.That(configuration.Language).IsEqualTo("en");
        }
Esempio n. 33
0
        /// <summary>
        /// Sets the application level parameters to those specified at the command line.
        /// </summary>
        /// <param name="args">array of command line parameters</param>


        /// <summary>
        /// The main entry point for the tool.
        /// </summary>
        static public void Run(string[] args)
        {
            object param = new ListCachesParam();

            CommandLineArgumentParser.CommandLineParser(ref param, args);
            cParam = (ListCachesParam)param;
            AssemblyUsage.PrintLogo(cParam.IsLogo);



            if (cParam.IsUsage)
            {
                AssemblyUsage.PrintUsage();
                return;
            }

            if (!cParam.Detail && string.IsNullOrEmpty(cParam.Server) && args.Length != 0 && cParam.Port == -1 && cParam.IsUsage)
            {
                AssemblyUsage.PrintUsage();
                return;
            }


            if (cParam.Port != -1)
            {
                NCache.Port = cParam.Port;
            }
            if (cParam.Server != null && !cParam.Server.Equals(""))
            {
                NCache.ServerName = cParam.Server;
            }

            string getBindIp = string.Empty;



            try
            {
                ICacheServer m = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                getBindIp = m.GetBindIP();
                Console.WriteLine("Listing registered caches on server {0}:{1}\n", getBindIp, NCache.Port);

                if (m != null)
                {
                    Alachisoft.NCache.Common.Monitoring.ConfiguredCacheInfo[] caches = m.GetAllConfiguredCaches();
                    Alachisoft.NCache.Common.Monitoring.ConfiguredCacheInfo[] partitionedReplicaCaches = m.GetConfiguredPartitionedReplicaCaches();// PartitionedReplicaCaches;

                    if (caches.Length > 0 || partitionedReplicaCaches.Length > 0)
                    {
                        if (!cParam.Detail)
                        {
                            Console.WriteLine("{0,-25} {1,-35} {2,-15}", "Cache-Name", "Scheme", "Status");
                            Console.WriteLine("{0,-25} {1,-35} {2,-15}", "----------", "------", "------");
                        }

                        if (caches.Length > 0)
                        {
                            for (int i = 0; i < caches.Length; i++)
                            {
                                Alachisoft.NCache.Common.Monitoring.ConfiguredCacheInfo cacheInfo = caches[i];
                                if (!cParam.Detail)
                                {
                                    PrintCacheInfo(m.GetCacheStatistics2(cacheInfo.CacheId), cacheInfo.CacheId, cacheInfo.IsRunning);
                                }
                                else
                                {
                                    PrintDetailedCacheInfo(m.GetCacheStatistics2(cacheInfo.CacheId), null, cParam.PrintConf, cParam.XmlSyntax, cacheInfo.IsRunning, cacheInfo.CacheId, cacheInfo.CachePropString);
                                }
                            }
                        }

                        if (partitionedReplicaCaches.Length > 0)
                        {
                            IEnumerator ide = partitionedReplicaCaches.GetEnumerator();
                            while (ide.MoveNext())
                            {
                                Hashtable cacheTbl = ide.Current as Hashtable;
                                if (cacheTbl != null)
                                {
                                    IDictionaryEnumerator e = cacheTbl.GetEnumerator();
                                    while (e.MoveNext())
                                    {
                                        string partId = e.Key as string;
                                        Cache  cache  = (Cache)e.Value;
                                        if (!detailed)
                                        {
                                            PrintCacheInfo(cache, partId);
                                        }
                                        else
                                        {
                                            PrintDetailedCacheInfo(cache, partId, printConf, xmlSyntax);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("There are no registered caches on {0}", NCache.ServerName);
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error: {0}", e.Message);
                Console.Error.WriteLine();
                Console.Error.WriteLine(e.ToString());
            }
            finally
            {
                NCache.Dispose();
            }
        }
        public void ThenInputAndOutputDirectoryAreSetToTheCurrentDirectory()
        {
            var args = new[] { @"-v" };

            var configuration = new Configuration();
            var writer = new StringWriter();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            commandLineArgumentParser.Parse(args, configuration, writer);

            string currentDirectory = Assembly.GetExecutingAssembly().Location;

            Check.That(configuration.FeatureFolder.FullName).IsEqualTo(currentDirectory);
            Check.That(configuration.OutputFolder.FullName).IsEqualTo(currentDirectory);
        }
        public void ThenCanParseResultsFormatSpecrunWithShortFormSuccessfully()
        {
            var args = new[] { @"-trfmt=specrun" };

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Check.That(shouldContinue).IsTrue();
            Check.That(configuration.TestResultsFormat).IsEqualTo(TestResultsFormat.SpecRun);
        }
        public void ThenCanParseResultsFormatCucumberJsonWithShortFormSuccessfully()
        {
            var args = new[] { @"-trfmt=cucumberjson" };

              var configuration = new Configuration();
              var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
              bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

              shouldContinue.ShouldBeTrue();
              Assert.AreEqual(TestResultsFormat.CucumberJson, configuration.TestResultsFormat);
        }
Esempio n. 37
0
        /// <summary>
        /// The main entry point for the tool.
        /// </summary>
        static public void Run(string[] args)
        {
            try
            {
                object param = new AddNodeParam();
                CommandLineArgumentParser.CommandLineParser(ref param, args);
                cParam         = (AddNodeParam)param;
                cParam.CacheId = cParam.CacheId.ToLower();
                if (cParam.IsUsage)
                {
                    AssemblyUsage.PrintLogo(cParam.IsLogo);
                    AssemblyUsage.PrintUsage();
                    return;
                }

                if (!ValidateParameters())
                {
                    return;
                }
                if (cParam.Port != -1)
                {
                    NCache.Port = cParam.Port;
                }
                if (cParam.Port == -1)
                {
                    NCache.Port = NCache.UseTcp ? CacheConfigManager.NCacheTcpPort : CacheConfigManager.HttpPort;
                }


                try
                {
                    if (cParam.ExistingServer != null || cParam.ExistingServer != string.Empty)
                    {
                        NCache.ServerName = cParam.ExistingServer;
                    }
                    IPAddress address;
                    string    clusterIp;

                    ICacheServer m = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                    if (!IPAddress.TryParse(cParam.NewServer, out address))
                    {
                        clusterIp = m.GetClusterIP();
                        if (clusterIp != null && clusterIp != string.Empty)
                        {
                            cParam.NewServer = clusterIp;
                        }
                    }

                    NCache.ServerName = cParam.ExistingServer;
                    m = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));

                    if (!IPAddress.TryParse(cParam.ExistingServer, out address))
                    {
                        clusterIp = m.GetClusterIP();
                        if (clusterIp != null && clusterIp != string.Empty)
                        {
                            cParam.ExistingServer = clusterIp;
                        }
                    }
                    CacheStatusOnServerContainer isClustered = m.IsClusteredCache(cParam.CacheId.ToLower());
                    CacheStatusOnServer          result      = isClustered.cacheStatus;

                    if (result == CacheStatusOnServer.Unregistered)
                    {
                        throw new Exception("The requested cache is not registered on the source node.");
                    }
                    else if (result == CacheStatusOnServer.LocalCache)
                    {
                        throw new Exception("The AddNode Tool can be used with clustered caches only");
                    }

                    Console.WriteLine("Adding node '{0}' to cache '{1}'.", cParam.NewServer, cParam.CacheId);

                    NewCacheRegisterationInfo info = m.GetNewUpdatedCacheConfiguration(cParam.CacheId, _partId, cParam.NewServer, true);

                    //muds:
                    //first of all try to register the cache on the destination server.
                    try
                    {
                        NCache.ServerName = cParam.NewServer;
                        m = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));

                        if (!IPAddress.TryParse(cParam.NewServer, out address))
                        {
                            clusterIp = m.GetClusterIP();
                            if (clusterIp != null && clusterIp != string.Empty)
                            {
                                cParam.NewServer = clusterIp;
                            }
                        }

                        m.RegisterCache(cParam.CacheId, info.UpdatedCacheConfig, _partId, true, false);
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine("Failed to Create Cache on '{0}'. ", NCache.ServerName);
                        Console.Error.WriteLine("Error Detail: '{0}'. ", ex.Message);

                        LogEvent(ex.Message);
                        NCache.Dispose();
                        return;
                    }
                    finally
                    {
                        m.Dispose();
                    }
                    //muds:
                    // Now update the cache configurations on all the servers where the cache
                    //is registered.
                    foreach (string serverName in info.AffectedNodes)
                    {
                        if (info.AffectedPartitions.Count > 0)
                        {
                            foreach (string partId in info.AffectedPartitions)
                            {
                                try
                                {
                                    NCache.ServerName = serverName;
                                    if (!IPAddress.TryParse(NCache.ServerName, out address))
                                    {
                                        clusterIp = m.GetClusterIP();
                                        if (clusterIp != null && clusterIp != string.Empty)
                                        {
                                            NCache.ServerName = clusterIp;
                                        }
                                    }
                                    reregister = true;
                                    m          = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));

                                    m.RegisterCache(cParam.CacheId, info.UpdatedCacheConfig, _partId, true, false);
                                }
                                catch (Exception ex)
                                {
                                    Console.Error.WriteLine("Failed to Create Cache on '{0}'. ", NCache.ServerName);
                                    Console.Error.WriteLine("Error Detail: '{0}'. ", ex.Message);

                                    LogEvent(ex.Message);
                                }
                                finally
                                {
                                    m.Dispose();
                                }
                            }
                        }
                        else
                        {
                            try
                            {
                                NCache.ServerName = serverName;
                                if (!IPAddress.TryParse(NCache.ServerName, out address))
                                {
                                    clusterIp = m.GetClusterIP();
                                    if (clusterIp != null && clusterIp != string.Empty)
                                    {
                                        NCache.ServerName = clusterIp;
                                    }
                                }
                                reregister = true;
                                m          = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));

                                m.RegisterCache(cParam.CacheId, info.UpdatedCacheConfig, _partId, true, false);
                            }
                            catch (Exception ex)
                            {
                                Console.Error.WriteLine("Failed to Create Cache on '{0}'. ", NCache.ServerName);
                                Console.Error.WriteLine("Error Detail: '{0}'. ", ex.Message);

                                LogEvent(ex.Message);
                                NCache.Dispose();
                                return;
                            }
                            finally
                            {
                                m.Dispose();
                            }
                        }
                    }
                    List <string> serversToUpdate = new List <string>();
                    foreach (Config.NewDom.ServerNode node in info.UpdatedCacheConfig.CacheDeployment.Servers.ServerNodeList)
                    {
                        serversToUpdate.Add(node.IP);
                    }
                    Management.Management.Util.ManagementWorkFlow.UpdateServerMappingConfig(serversToUpdate.ToArray());
                    //Add in client.ncconf
                    Dictionary <string, Dictionary <int, Management.ClientConfiguration.Dom.CacheServer> > serversPriorityList = new Dictionary <string, Dictionary <int, Alachisoft.NCache.Management.ClientConfiguration.Dom.CacheServer> >();
                    ToolServerOperations.ClientConfigUtil _clientConfigUtil = new ToolServerOperations.ClientConfigUtil();
                    try
                    {
                        ArrayList clusterNodes = info.UpdatedCacheConfig.CacheDeployment.Servers.NodesList;

                        foreach (Alachisoft.NCache.Config.NewDom.ServerNode nodei in clusterNodes)
                        {
                            serversPriorityList.Add(nodei.IP, _clientConfigUtil.GetPrioritizedServerListForClient(nodei.IP, cParam.CacheId, clusterNodes));
                        }

                        Alachisoft.NCache.Config.NewDom.ServerNode nodeForClientList = new Config.NewDom.ServerNode();   //Hack: priority list requires a serverIP and client Ip cant be used hence!!
                        foreach (Alachisoft.NCache.Config.NewDom.ServerNode node in clusterNodes)
                        {
                            NCache.ServerName = node.IP;
                            ICacheServer _cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                            Management.ClientConfiguration.CacheServerList _cacheServerList = new Management.ClientConfiguration.CacheServerList(serversPriorityList[node.IP]);
                            _cacheServer.UpdateClientServersList(cParam.CacheId, _cacheServerList, RtContextValue.NCACHE.ToString());
                            nodeForClientList = node;
                        }


                        List <Alachisoft.NCache.Config.Dom.ClientNode> clientNodeList = info.UpdatedCacheConfig.CacheDeployment.ClientNodes.NodesList;
                        foreach (Alachisoft.NCache.Config.Dom.ClientNode node in clientNodeList)
                        {
                            NCache.ServerName = node.Name;
                            ICacheServer _cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                            Management.ClientConfiguration.CacheServerList _cacheServerList = new Management.ClientConfiguration.CacheServerList(serversPriorityList[nodeForClientList.IP]);
                            _cacheServer.UpdateClientServersList(cParam.CacheId, _cacheServerList, RtContextValue.NCACHE.ToString());
                        }
                    }
                    catch (Exception e)
                    {
                    }

                    Console.WriteLine("'{0}' successfully added to cache '{1}'.\n", cParam.NewServer,
                                      cParam.CacheId);
                }

                catch (ConfigurationException e)
                {
                    Console.Error.WriteLine("Failed to add '{0}' to '{1}'. Error: {2} ", NCache.ServerName.ToLower(), cParam.CacheId, e.Message);
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("Failed to add '{0}' to '{1}'. Error: {2} ", NCache.ServerName.ToLower(), cParam.CacheId, e.Message);
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error : {0}", e.Message);
            }
            finally
            {
                NCache.Dispose();
            }
        }
        public void ThenCanParseVersionRequestShortFormSuccessfully()
        {
            var args = new[] {@"-v"};

            var configuration = new Configuration();
            var writer = new StringWriter();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, writer);

            StringAssert.IsMatch(expectedVersionString.ComparisonNormalize(),
                                 writer.GetStringBuilder().ToString().ComparisonNormalize());
            Assert.AreEqual(false, shouldContinue);
            Assert.AreEqual(Path.GetFullPath(Directory.GetCurrentDirectory()), configuration.FeatureFolder.FullName);
            Assert.AreEqual(Path.GetFullPath(Environment.GetEnvironmentVariable("TEMP")),
                            configuration.OutputFolder.FullName);
            Assert.AreEqual(false, configuration.HasTestResults);
            Assert.AreEqual(null, configuration.TestResultsFile);
        }
        public void ThenCanParseResultsFormatSpecrunWithLongFormSuccessfully()
        {
            var args = new[] { @"-test-results-format=specrun" };

              var configuration = new Configuration();
              var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
              bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

              shouldContinue.ShouldBeTrue();
              Assert.AreEqual(TestResultsFormat.SpecRun, configuration.TestResultsFormat);
        }
        public void ThenCanParseVersionRequestShortFormSuccessfully()
        {
            var args = new[] { @"-v" };

              var configuration = new Configuration();
              var writer = new StringWriter();
              var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
              bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, writer);

              StringAssert.IsMatch(expectedVersionString.ComparisonNormalize(),
                           writer.GetStringBuilder().ToString().ComparisonNormalize());
              shouldContinue.ShouldBeFalse();
        }
        public void ThenCanParseResultsFormatXunitWithShortFormSuccessfully()
        {
            var args = new[] {@"-trfmt=xunit"};

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Assert.AreEqual(true, shouldContinue);
            Assert.AreEqual(TestResultsFormat.xUnit, configuration.TestResultsFormat);
        }
        public void ThenInputAndOutputDirectoryAreSetToTheCurrentDirectory()
        {
            var args = new[] { @"-v" };

              var configuration = new Configuration();
              var writer = new StringWriter();
              var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
              commandLineArgumentParser.Parse(args, configuration, writer);

              Assert.AreEqual(CurrentDirectory, configuration.FeatureFolder.FullName);
              Assert.AreEqual(CurrentDirectory, configuration.OutputFolder.FullName);
        }
        public void ThenCanParseResultsFileWithShortFormSuccessfully()
        {
            FileSystem.AddFile(@"c:\results.xml", "<xml />");
            var args = new[] { @"-lr=c:\results.xml" };

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Check.That(shouldContinue).IsTrue();
            Check.That(configuration.HasTestResults).IsTrue();
            Check.That(configuration.TestResultsFile.FullName).IsEqualTo(@"c:\results.xml");
        }
Esempio n. 44
0
        public void IntegrationTest_Scenario_ProvidedExampleFile()
        {
            string file         = "";
            string outputFile   = "";
            string regexPattern = "";

            string[] args = { "-f", @"..\..\..\TestFiles\ProvidedExample.log", "-o", @"..\..\..\OutputFiles" };
            try
            {
                // Only run if the -h --help flags are not passed as arguments
                if (CommandLineArgumentParser.ParseCommandLineArguments(args, out outputFile, out regexPattern, out file))
                {
                    // Assert that Command Line arguments are parsed as expected
                    Assert.AreEqual(@"..\..\..\OutputFiles", outputFile);
                    Assert.AreEqual(@"(^(?:[0-9]{1,3}\.){3}[0-9]{1,3})(?:.+)(?:""{1}(?:GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE){1}\s{1}(.+)\s{1}(?:HTTP/1.1|HTTP/1.0|HTTP/2|HTTP/3){1}""{1})(?:.+$)", regexPattern);
                    Assert.AreEqual(@"..\..\..\TestFiles\ProvidedExample.log", file);
                    ProcessedLogs pLogs = new ProcessedLogs();
                    // Process the log files
                    ProcessLogFile logger = new ProcessLogFile(file, regexPattern, pLogs);
                    logger.ReadFromFileAndStore();
                    // Assert - pLogs was populated as expected
                    Assert.AreEqual(23, logger.successful);
                    Assert.AreEqual(0, logger.failed);
                    Assert.AreEqual(11, pLogs.GetIpAddresses().Count);
                    Assert.AreEqual(22, pLogs.GetUrls().Count);

                    // Sort the processed logs
                    SortProcessedLogs sort = new SortProcessedLogs(pLogs);
                    sort.BeginSort(thenBy: true);
                    Assert.IsTrue(sort.sortedIPList.ToArray()[0].Key == "168.41.191.40" && sort.sortedIPList.ToArray()[0].Value == 4);
                    Assert.IsTrue(sort.sortedIPList.ToArray()[1].Key == "72.44.32.10" && sort.sortedIPList.ToArray()[1].Value == 3);
                    Assert.IsTrue(sort.sortedIPList.ToArray()[2].Key == "50.112.00.11" && sort.sortedIPList.ToArray()[2].Value == 3);
                    Assert.IsTrue(sort.sortedUrlList.ToArray()[0].Key == "/docs/manage-websites/" && sort.sortedUrlList.ToArray()[0].Value == 2);
                    Assert.IsTrue(sort.sortedUrlList.ToArray()[1].Key == "http://example.net/faq/" && sort.sortedUrlList.ToArray()[1].Value == 1);
                    Assert.IsTrue(sort.sortedUrlList.ToArray()[2].Key == "http://example.net/blog/category/meta/" && sort.sortedUrlList.ToArray()[2].Value == 1);

                    string fileName = "ProvidedExampleOutputFile.txt";
                    if (!string.IsNullOrEmpty(outputFile))
                    {
                        OutputResults.PrintToFile(sort.sortedIPList, sort.sortedUrlList, outputFile, fileName: fileName, append: false);
                    }

                    string fullPath = outputFile + @"\" + fileName;
                    Assert.IsTrue(File.Exists(fullPath));
                    using (var sr = new StreamReader(fullPath))
                    {
                        string output = sr.ReadToEnd();
                        Assert.IsTrue(output.Contains(string.Format("Number of unique IP Addresses:{0}", 11)));
                        Assert.IsTrue(output.Contains(string.Format("Most Active IP Addresses:{0} - HITS:{1}", "168.41.191.40", "4")));
                        Assert.IsTrue(output.Contains(string.Format("Most Active IP Addresses:{0} - HITS:{1}", "72.44.32.10", "3")));
                        Assert.IsTrue(output.Contains(string.Format("Most Active IP Addresses:{0} - HITS:{1}", "50.112.00.11", "3")));
                        Assert.IsTrue(output.Contains(string.Format("Most visited URLS:{0} - Occurences:{1}", "/docs/manage-websites/", "2")));
                        Assert.IsTrue(output.Contains(string.Format("Most visited URLS:{0} - Occurences:{1}", "http://example.net/faq/", "1")));
                        Assert.IsTrue(output.Contains(string.Format("Most visited URLS:{0} - Occurences:{1}", "http://example.net/blog/category/meta/", "1")));
                    }
                }
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        public void ThenCanParseShortFormArgumentsSuccessfully()
        {
            var args = new[] { @"-f=c:\features", @"-o=c:\features-output" };

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Check.That(shouldContinue).IsTrue();
            Check.That(configuration.FeatureFolder.FullName).IsEqualTo(@"c:\features");
            Check.That(configuration.OutputFolder.FullName).IsEqualTo(@"c:\features-output");
        }
Esempio n. 46
0
        public void IntegrationTest_Scenario_AdditionalExampleFile()
        {
            string file         = "";
            string outputFile   = "";
            string regexPattern = "";

            string[] args = { "-f", @"..\..\..\TestFiles\ISLogFile.log", "-o", @"..\..\..\OutputFiles" };
            try
            {
                // Only run if the -h --help flags are not passed as arguments
                if (CommandLineArgumentParser.ParseCommandLineArguments(args, out outputFile, out regexPattern, out file))
                {
                    // Assert that Command Line arguments are parsed as expected
                    Assert.AreEqual(@"..\..\..\OutputFiles", outputFile);
                    Assert.AreEqual(@"(^(?:[0-9]{1,3}\.){3}[0-9]{1,3})(?:.+)(?:""{1}(?:GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE){1}\s{1}(.+)\s{1}(?:HTTP/1.1|HTTP/1.0|HTTP/2|HTTP/3){1}""{1})(?:.+$)", regexPattern);
                    Assert.AreEqual(@"..\..\..\TestFiles\ISLogFile.log", file);
                    ProcessedLogs pLogs = new ProcessedLogs();
                    // Process the log files
                    ProcessLogFile logger = new ProcessLogFile(file, regexPattern, pLogs);
                    logger.ReadFromFileAndStore();
                    // Assert - pLogs was populated as expected
                    Assert.AreEqual(10000, logger.successful);
                    Assert.AreEqual(0, logger.failed);
                    Assert.AreEqual(1753, pLogs.GetIpAddresses().Count);
                    Assert.AreEqual(1498, pLogs.GetUrls().Count);

                    // Sort the processed logs
                    SortProcessedLogs sort = new SortProcessedLogs(pLogs);
                    sort.BeginSort(thenBy: true);
                    Assert.IsTrue(sort.sortedIPList.ToArray()[0].Key == "66.249.73.135" && sort.sortedIPList.ToArray()[0].Value == 482);
                    Assert.IsTrue(sort.sortedIPList.ToArray()[1].Key == "46.105.14.53" && sort.sortedIPList.ToArray()[1].Value == 364);
                    Assert.IsTrue(sort.sortedIPList.ToArray()[2].Key == "130.237.218.86" && sort.sortedIPList.ToArray()[2].Value == 357);
                    Assert.IsTrue(sort.sortedUrlList.ToArray()[0].Key == "/favicon.ico" && sort.sortedUrlList.ToArray()[0].Value == 807);
                    Assert.IsTrue(sort.sortedUrlList.ToArray()[1].Key == "/style2.css" && sort.sortedUrlList.ToArray()[1].Value == 546);
                    Assert.IsTrue(sort.sortedUrlList.ToArray()[2].Key == "/reset.css" && sort.sortedUrlList.ToArray()[2].Value == 538);

                    string fileName = "AdditionalExampleOutputFile.txt";
                    if (!string.IsNullOrEmpty(outputFile))
                    {
                        OutputResults.PrintToFile(sort.sortedIPList, sort.sortedUrlList, outputFile, fileName: fileName, append: false);
                    }

                    string fullPath = outputFile + @"\" + fileName;
                    Assert.IsTrue(File.Exists(fullPath));
                    using (var sr = new StreamReader(fullPath))
                    {
                        string output = sr.ReadToEnd();
                        Assert.IsTrue(output.Contains(string.Format("Number of unique IP Addresses:{0}", 1753)));
                        Assert.IsTrue(output.Contains(string.Format("Most Active IP Addresses:{0} - HITS:{1}", "66.249.73.135", "482")));
                        Assert.IsTrue(output.Contains(string.Format("Most Active IP Addresses:{0} - HITS:{1}", "46.105.14.53", "364")));
                        Assert.IsTrue(output.Contains(string.Format("Most Active IP Addresses:{0} - HITS:{1}", "130.237.218.86", "357")));
                        Assert.IsTrue(output.Contains(string.Format("Most visited URLS:{0} - Occurences:{1}", "/favicon.ico", "807")));
                        Assert.IsTrue(output.Contains(string.Format("Most visited URLS:{0} - Occurences:{1}", "/style2.css", "546")));
                        Assert.IsTrue(output.Contains(string.Format("Most visited URLS:{0} - Occurences:{1}", "/reset.css", "538")));
                    }
                }
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        public void ThenCanParseResultsFormatCucumberJsonWithLongFormSuccessfully()
        {
            var args = new[] { @"-test-results-format=cucumberjson" };

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Check.That(shouldContinue).IsTrue();
            Check.That(configuration.TestResultsFormat).IsEqualTo(TestResultsFormat.CucumberJson);
        }
        public void ThenCanParseResultsFileWithShortFormSuccessfully()
        {
            var args = new[] { @"-lr=c:\results.xml" };

              var configuration = new Configuration();
              var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
              bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

              shouldContinue.ShouldBeTrue();
              configuration.HasTestResults.ShouldBeTrue();
              Assert.AreEqual(@"c:\results.xml", configuration.TestResultsFile.FullName);
        }
        public void ThenCanFilterOutNonExistingTestResultFiles()
        {
            var args = new[] { @"-link-results-file=c:\DoesNotExist.xml;" };

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Check.That(shouldContinue).IsTrue();
            Check.That(configuration.HasTestResults).IsFalse();
            Check.That(configuration.TestResultsFiles).IsEmpty();
        }
Esempio n. 50
0
        static void Main(string[] args)
        {
            SetConsoleCtrlHandler(cancelHandler, true);
            ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;

            try
            {
                //goto httplitsen;
                //当前程序路径(末尾有\)
                string CURRENT_PATH = Directory.GetCurrentDirectory();
                string fileName     = "";

                //寻找ffmpeg.exe
                if (!File.Exists("ffmpeg.exe"))
                {
                    try
                    {
                        string[] EnvironmentPath = Environment.GetEnvironmentVariable("Path").Split(';');
                        foreach (var de in EnvironmentPath)
                        {
                            if (File.Exists(Path.Combine(de.Trim('\"').Trim(), "ffmpeg.exe")))
                            {
                                goto HasFFmpeg;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        ;
                    }

                    Console.BackgroundColor = ConsoleColor.Red;   //设置背景色
                    Console.ForegroundColor = ConsoleColor.White; //设置前景色,即字体颜色
                    Console.WriteLine("在PATH和程序路径下找不到 ffmpeg.exe");
                    Console.ResetColor();                         //将控制台的前景色和背景色设为默认值
                    Console.WriteLine("请下载ffmpeg.exe并把他放到程序同目录.");
                    Console.WriteLine();
                    Console.WriteLine("x86 https://ffmpeg.zeranoe.com/builds/win32/static/");
                    Console.WriteLine("x64 https://ffmpeg.zeranoe.com/builds/win64/static/");
                    Console.WriteLine();
                    Console.WriteLine("按任意键退出.");
                    Console.ReadKey();
                    Environment.Exit(-1);
                }

HasFFmpeg:
                Global.WriteInit();
                Thread checkUpdate = new Thread(() =>
                {
                    Global.CheckUpdate();
                });
                checkUpdate.IsBackground = true;
                checkUpdate.Start();

                int    maxThreads   = Environment.ProcessorCount;
                int    minThreads   = 16;
                int    retryCount   = 15;
                int    timeOut      = 10; //默认10秒
                string baseUrl      = "";
                string reqHeaders   = "";
                string keyFile      = "";
                string keyBase64    = "";
                string muxSetJson   = "MUXSETS.json";
                string workDir      = CURRENT_PATH + "\\Downloads";
                bool   muxFastStart = false;
                bool   delAfterDone = false;
                bool   parseOnly    = false;
                bool   noMerge      = false;

                /******************************************************/
                ServicePointManager.DefaultConnectionLimit = 1024;
                ServicePointManager.SecurityProtocol       = SecurityProtocolType.Ssl3
                                                             | SecurityProtocolType.Tls
                                                             | (SecurityProtocolType)0x300  //Tls11
                                                             | (SecurityProtocolType)0xC00; //Tls12
                /******************************************************/

                if (File.Exists(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "headers.txt")))
                {
                    reqHeaders = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "headers.txt"));
                }

                //分析命令行参数
parseArgs:
                var arguments = CommandLineArgumentParser.Parse(args);
                if (args.Length == 1 && args[0] == "--help")
                {
                    Console.WriteLine(@"N_m3u8DL-CLI.exe <URL|File|JSON> [OPTIONS]  

    --workDir    Directory      设定程序工作目录
    --saveName   Filename       设定存储文件名(不包括后缀)
    --baseUrl    BaseUrl        设定Baseurl
    --headers    headers        设定请求头,格式 key:value 使用|分割不同的key&value
    --maxThreads Thread         设定程序的最大线程数(默认为32)
    --minThreads Thread         设定程序的最小线程数(默认为16)
    --retryCount Count          设定程序的重试次数(默认为15)
    --timeOut    Sec            设定程序网络请求的超时时间(单位为秒,默认为10秒)
    --muxSetJson File           使用外部json文件定义混流选项
    --useKeyFile File           使用外部16字节文件定义AES-128解密KEY
    --useKeyBase64 Base64String 使用Base64字符串定义AES-128解密KEY
    --downloadRange Range       仅下载视频的一部分分片或长度
    --liveRecDur HH:MM:SS       直播录制时,达到此长度自动退出软件
    --stopSpeed  Number         当速度低于此值时,重试(单位为KB/s)
    --maxSpeed   Number         设置下载速度上限(单位为KB/s)
    --enableYouKuAes            使用优酷AES-128解密方案
    --enableDelAfterDone        开启下载后删除临时文件夹的功能
    --enableMuxFastStart        开启混流mp4的FastStart特性
    --enableBinaryMerge         开启二进制合并分片
    --enableParseOnly           开启仅解析模式(程序只进行到meta.json)
    --enableAudioOnly           合并时仅封装音频轨道
    --disableDateInfo           关闭混流中的日期写入
    --noMerge                   禁用自动合并
    --noProxy                   不自动使用系统代理
    --disableIntegrityCheck     不检测分片数量是否完整");
                    return;
                }
                if (arguments.Has("--enableDelAfterDone"))
                {
                    delAfterDone = true;
                }
                if (arguments.Has("--enableParseOnly"))
                {
                    parseOnly = true;
                }
                if (arguments.Has("--enableBinaryMerge"))
                {
                    DownloadManager.BinaryMerge = true;
                }
                if (arguments.Has("--disableDateInfo"))
                {
                    FFmpeg.WriteDate = false;
                }
                if (arguments.Has("--noMerge"))
                {
                    noMerge = true;
                }
                if (arguments.Has("--noProxy"))
                {
                    Global.NoProxy = true;
                }
                if (arguments.Has("--headers"))
                {
                    reqHeaders = arguments.Get("--headers").Next;
                }
                if (arguments.Has("--enableMuxFastStart"))
                {
                    muxFastStart = true;
                }
                if (arguments.Has("--enableYouKuAes"))
                {
                    Downloader.YouKuAES = true;
                }
                if (arguments.Has("--disableIntegrityCheck"))
                {
                    DownloadManager.DisableIntegrityCheck = true;
                }
                if (arguments.Has("--enableAudioOnly"))
                {
                    Global.VIDEO_TYPE = "IGNORE";
                }
                if (arguments.Has("--muxSetJson"))
                {
                    muxSetJson = arguments.Get("--muxSetJson").Next;
                }
                if (arguments.Has("--workDir"))
                {
                    workDir = arguments.Get("--workDir").Next;
                    DownloadManager.HasSetDir = true;
                }
                if (arguments.Has("--saveName"))
                {
                    fileName = Global.GetValidFileName(arguments.Get("--saveName").Next);
                }
                if (arguments.Has("--useKeyFile"))
                {
                    if (File.Exists(arguments.Get("--useKeyFile").Next))
                    {
                        keyFile = arguments.Get("--useKeyFile").Next;
                    }
                }
                if (arguments.Has("--useKeyBase64"))
                {
                    keyBase64 = arguments.Get("--useKeyBase64").Next;
                }
                if (arguments.Has("--stopSpeed"))
                {
                    Global.STOP_SPEED = Convert.ToInt64(arguments.Get("--stopSpeed").Next);
                }
                if (arguments.Has("--maxSpeed"))
                {
                    Global.MAX_SPEED = Convert.ToInt64(arguments.Get("--maxSpeed").Next);
                }
                if (arguments.Has("--baseUrl"))
                {
                    baseUrl = arguments.Get("--baseUrl").Next;
                }
                if (arguments.Has("--maxThreads"))
                {
                    maxThreads = Convert.ToInt32(arguments.Get("--maxThreads").Next);
                }
                if (arguments.Has("--minThreads"))
                {
                    minThreads = Convert.ToInt32(arguments.Get("--minThreads").Next);
                }
                if (arguments.Has("--retryCount"))
                {
                    retryCount = Convert.ToInt32(arguments.Get("--retryCount").Next);
                }
                if (arguments.Has("--timeOut"))
                {
                    timeOut = Convert.ToInt32(arguments.Get("--timeOut").Next);
                }
                if (arguments.Has("--liveRecDur"))
                {
                    //时间码
                    Regex reg2 = new Regex(@"(\d+):(\d+):(\d+)");
                    var   t    = arguments.Get("--liveRecDur").Next;
                    if (reg2.IsMatch(t))
                    {
                        int HH = Convert.ToInt32(reg2.Match(t).Groups[1].Value);
                        int MM = Convert.ToInt32(reg2.Match(t).Groups[2].Value);
                        int SS = Convert.ToInt32(reg2.Match(t).Groups[3].Value);
                        HLSLiveDownloader.REC_DUR_LIMIT = SS + MM * 60 + HH * 60 * 60;
                    }
                }
                if (arguments.Has("--downloadRange"))
                {
                    string p = arguments.Get("--downloadRange").Next;

                    if (p.Contains(":"))
                    {
                        //时间码
                        Regex reg2 = new Regex(@"((\d+):(\d+):(\d+))?-((\d+):(\d+):(\d+))?");
                        if (reg2.IsMatch(p))
                        {
                            Parser.DurStart = reg2.Match(p).Groups[1].Value;
                            Parser.DurEnd   = reg2.Match(p).Groups[5].Value;
                            Parser.DelAd    = false;
                        }
                    }
                    else
                    {
                        //数字
                        Regex reg = new Regex(@"(\d*)-(\d*)");
                        if (reg.IsMatch(p))
                        {
                            if (!string.IsNullOrEmpty(reg.Match(p).Groups[1].Value))
                            {
                                Parser.RangeStart = Convert.ToInt32(reg.Match(p).Groups[1].Value);
                                Parser.DelAd      = false;
                            }
                            if (!string.IsNullOrEmpty(reg.Match(p).Groups[2].Value))
                            {
                                Parser.RangeEnd = Convert.ToInt32(reg.Match(p).Groups[2].Value);
                                Parser.DelAd    = false;
                            }
                        }
                    }
                }

                //如果只有URL,没有附加参数,则尝试解析配置文件
                if (args.Length == 1)
                {
                    if (File.Exists(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "N_m3u8DL-CLI.args.txt")))
                    {
                        args = Global.ParseArguments($"\"{args[0]}\"" + File.ReadAllText(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "N_m3u8DL-CLI.args.txt"))).ToArray();  //解析命令行
                        goto parseArgs;
                    }
                }

                //ReadLine字数上限
                Stream steam = Console.OpenStandardInput();
                Console.SetIn(new StreamReader(steam, Encoding.Default, false, 5000));
                int inputRetryCount = 20;
input:
                string testurl = "";


                //重试太多次,退出
                if (inputRetryCount == 0)
                {
                    Environment.Exit(-1);
                }

                if (args.Length > 0)
                {
                    testurl = args[0];
                }
                else
                {
                    Console.CursorVisible   = true;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("N_m3u8DL-CLI");
                    Console.ResetColor();
                    Console.Write(" > ");

                    args = Global.ParseArguments(Console.ReadLine()).ToArray();  //解析命令行
                    Global.WriteInit();
                    Console.CursorVisible = false;
                    goto parseArgs;
                }

                if (fileName == "")
                {
                    fileName = Global.GetUrlFileName(testurl) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                }


                if (testurl.Contains("twitcasting") && testurl.Contains("/fmp4/"))
                {
                    DownloadManager.BinaryMerge = true;
                }

                //优酷DRM设备更改

                /*if (testurl.Contains("playlist/m3u8"))
                 * {
                 *  string drm_type = Global.GetQueryString("drm_type", testurl);
                 *  string drm_device = Global.GetQueryString("drm_device", testurl);
                 *  if (drm_type != "1")
                 *  {
                 *      testurl = testurl.Replace("drm_type=" + drm_type, "drm_type=1");
                 *  }
                 *  if (drm_device != "11")
                 *  {
                 *      testurl = testurl.Replace("drm_device=" + drm_device, "drm_device=11");
                 *  }
                 * }*/
                string m3u8Content = string.Empty;
                bool   isVOD       = true;


                //开始解析

                Console.CursorVisible = false;
                LOGGER.PrintLine($"文件名称:{fileName}");
                LOGGER.PrintLine($"存储路径:{Path.GetDirectoryName(Path.Combine(workDir, fileName))}");

                Parser parser = new Parser();
                parser.DownName  = fileName;
                parser.DownDir   = Path.Combine(workDir, parser.DownName);
                parser.M3u8Url   = testurl;
                parser.KeyBase64 = keyBase64;
                parser.KeyFile   = keyFile;
                if (baseUrl != "")
                {
                    parser.BaseUrl = baseUrl;
                }
                parser.Headers = reqHeaders;
                string exePath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
                LOGGER.LOGFILE = Path.Combine(exePath, "Logs", DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".log");
                LOGGER.InitLog();
                LOGGER.WriteLine("Start Parsing " + testurl);
                LOGGER.PrintLine("开始解析地址...", LOGGER.Warning);
                if (testurl.EndsWith(".json") && File.Exists(testurl))              //可直接跳过解析
                {
                    if (!Directory.Exists(Path.Combine(workDir, fileName)))         //若文件夹不存在则新建文件夹
                    {
                        Directory.CreateDirectory(Path.Combine(workDir, fileName)); //新建文件夹
                    }
                    File.Copy(testurl, Path.Combine(Path.Combine(workDir, fileName), "meta.json"), true);
                }
                else
                {
                    parser.Parse();  //开始解析
                }

                //仅解析模式
                if (parseOnly)
                {
                    LOGGER.PrintLine("解析m3u8成功, 程序退出");
                    Environment.Exit(0);
                }

                if (File.Exists(Path.Combine(Path.Combine(workDir, fileName), "meta.json")))
                {
                    JObject initJson = JObject.Parse(File.ReadAllText(Path.Combine(Path.Combine(workDir, fileName), "meta.json")));
                    isVOD = Convert.ToBoolean(initJson["m3u8Info"]["vod"].ToString());
                    //传给Watcher总时长
                    Watcher.TotalDuration = initJson["m3u8Info"]["totalDuration"].Value <double>();
                    LOGGER.PrintLine($"文件时长:{Global.FormatTime((int)Watcher.TotalDuration)}");
                    LOGGER.PrintLine("总分片:" + initJson["m3u8Info"]["originalCount"].Value <int>()
                                     + ", 已选择分片:" + initJson["m3u8Info"]["count"].Value <int>());
                }
                else
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(workDir, fileName));
                    directoryInfo.Delete(true);
                    LOGGER.PrintLine("地址无效", LOGGER.Error);
                    LOGGER.CursorIndex = 5;
                    inputRetryCount--;
                    goto input;
                }

                //点播
                if (isVOD == true)
                {
                    ServicePointManager.DefaultConnectionLimit = 10000;
                    DownloadManager md = new DownloadManager();
                    md.DownDir = parser.DownDir;
                    md.Headers = reqHeaders;
                    md.Threads = Environment.ProcessorCount;
                    if (md.Threads > maxThreads)
                    {
                        md.Threads = maxThreads;
                    }
                    if (md.Threads < minThreads)
                    {
                        md.Threads = minThreads;
                    }
                    if (File.Exists("minT.txt"))
                    {
                        int t = Convert.ToInt32(File.ReadAllText("minT.txt"));
                        if (md.Threads <= t)
                        {
                            md.Threads = t;
                        }
                    }
                    md.TimeOut      = timeOut * 1000;
                    md.NoMerge      = noMerge;
                    md.DownName     = fileName;
                    md.DelAfterDone = delAfterDone;
                    md.MuxFormat    = "mp4";
                    md.RetryCount   = retryCount;
                    md.MuxSetJson   = muxSetJson;
                    md.MuxFastStart = muxFastStart;
                    md.DoDownload();
                }
                //直播
                if (isVOD == false)
                {
                    LOGGER.WriteLine("Living Stream Found");
                    LOGGER.WriteLine("Start Recording");
                    LOGGER.PrintLine("识别为直播流, 开始录制");
                    //LOGGER.STOPLOG = true;  //停止记录日志
                    //开辟文件流,且不关闭。(便于播放器不断读取文件)
                    string LivePath = Path.Combine(Directory.GetParent(parser.DownDir).FullName
                                                   , DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + fileName + ".ts");
                    FileStream outputStream = new FileStream(LivePath, FileMode.Append);

                    HLSLiveDownloader live = new HLSLiveDownloader();
                    live.DownDir    = parser.DownDir;
                    live.Headers    = reqHeaders;
                    live.LiveStream = outputStream;
                    live.LiveFile   = LivePath;
                    live.TimerStart();  //开始录制
                    Console.ReadKey();
                }

                //监听测试

                /*httplitsen:
                 * HTTPListener.StartListening();*/
                LOGGER.WriteLineError("Download Failed");
                LOGGER.PrintLine("下载失败, 程序退出", LOGGER.Error);
                Console.CursorVisible = true;
                Environment.Exit(-1);
                //Console.Write("按任意键继续..."); Console.ReadKey(); return;
            }
            catch (Exception ex)
            {
                Console.CursorVisible = true;
                LOGGER.PrintLine(ex.Message, LOGGER.Error);
            }
        }
        public void ThenCanParseResultsFileAsSemicolonSeparatedListThatStartsWithASemicolon()
        {
            var args = new[] { @"-link-results-file=;c:\results1.xml" };

              var configuration = new Configuration();
              var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
              bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

              shouldContinue.ShouldBeTrue();
              configuration.HasTestResults.ShouldBeTrue();
              Assert.AreEqual(1, configuration.TestResultsFiles.Length);
              Assert.AreEqual(@"c:\results1.xml", configuration.TestResultsFiles[0].FullName);
        }
Esempio n. 52
0
        /// <summary>
        /// The main entry point for the tool.
        /// </summary>
        static public void Run(string[] args)
        {
            try
            {
                object param = new AddClientNodeParam();
                CommandLineArgumentParser.CommandLineParser(ref param, args);
                cParam = (AddClientNodeParam)param;
                if (cParam.IsUsage)
                {
                    AssemblyUsage.PrintLogo(cParam.IsLogo);
                    AssemblyUsage.PrintUsage();
                    return;
                }

                if (!ValidateParameters())
                {
                    return;
                }
                bool multipleServers = false;
                if (cParam.Server != null || cParam.Server != string.Empty)
                {
                    _serverList = cParam.Server.Split(',');
                    if (_serverList.Length > 1 || (_serverList[0].Contains(":")))
                    {
                        multipleServers = true;
                    }
                }
tryNextServer:
                if (multipleServers)
                {
                    string[] serverAddress = _serverList[index].Split(':');
                    if (serverAddress.Length == 2)
                    {
                        if (!IsValidIP(serverAddress[0]))
                        {
                            Console.Error.WriteLine("Error: Invalid Server IP.");
                            return;
                        }
                        NCache.ServerName = serverAddress[0];
                        try
                        {
                            NCache.Port = Convert.ToInt32(serverAddress[1]);
                        }
                        catch (Exception)
                        {
                            throw new Exception("Invalid Port :" + serverAddress[1] + " specified for server : " + serverAddress[0] + ".");
                        }
                    }
                    else
                    if (serverAddress.Length == 1)
                    {
                        if (!IsValidIP(serverAddress[0]))
                        {
                            Console.Error.WriteLine("Error: Invalid Server IP.");
                            return;
                        }
                        NCache.ServerName = serverAddress[0];
                        NCache.Port       = cParam.Port;
                        if (cParam.Port == -1)
                        {
                            NCache.Port = NCache.UseTcp ? CacheConfigManager.NCacheTcpPort : CacheConfigManager.HttpPort;
                        }
                    }
                    else
                    {
                        throw new Exception("Invalid server Address specified, kindly specify as [IPAdress] or [IPAdress]:[Port].");
                    }
                }
                else
                {
                    if (cParam.Port != -1)
                    {
                        NCache.Port = cParam.Port;
                    }
                    if (cParam.Server != null || cParam.Server != string.Empty)
                    {
                        NCache.ServerName = cParam.Server;
                    }
                    if (cParam.Port == -1)
                    {
                        NCache.Port = NCache.UseTcp ? CacheConfigManager.NCacheTcpPort : CacheConfigManager.HttpPort;
                    }
                }


                try
                {
                    _server     = NCache.ServerName;
                    cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));
                }
                catch (Exception ex)
                {
                    if (multipleServers)
                    {
                        if (index < _serverList.Length - 1)
                        {
                            Console.Error.WriteLine("Failed to connect to server : " + NCache.ServerName + ":" + NCache.Port + " \nTrying next server.");
                            index++;
                            goto tryNextServer;
                        }
                    }
                    throw ex;
                }
                config = cacheServer.GetNewConfiguration(cParam.CacheId);
                //for getting server mappings
                if (cParam.AcquireServerMapping)
                {
                    Alachisoft.NCache.Management.MappingConfiguration.Dom.MappingConfiguration mapping = cacheServer.GetServerMappingForClient();
                    if (mapping != null)
                    {
                        _clientIPMapping = mapping.ClientIPMapping;
                        foreach (Mapping mappingServer in mapping.ManagementIPMapping.MappingServers)
                        {
                            if (mappingServer != null)
                            {
                                _managementIPMapping.Add(mappingServer.PrivateIP, mappingServer);
                            }
                        }
                    }
                }
                if (config == null)
                {
                    Console.Error.WriteLine("Error : The cache'{0}' does not exist on server {1}:{2} .", cParam.CacheId, NCache.ServerName, NCache.Port);
                    return;
                }
                if (config.CacheSettings.CacheType == "clustered-cache")
                {
                    Console.WriteLine("Adding client node '{0}' to cache '{1}' on server {2}:{3}.",
                                      cParam.ClientNode, cParam.CacheId, NCache.ServerName, NCache.Port);
                    foreach (Address node in config.CacheDeployment.Servers.GetAllConfiguredNodes())
                    {
                        currentServerNodes.Add(node.IpAddress.ToString());
                    }
                }
                else
                {
                    Console.Error.WriteLine("Error: Client nodes cannot be added to local caches");
                    return;
                }
                if (config.CacheDeployment.ClientNodes != null)
                {
                    foreach (ClientNode clientNode in config.CacheDeployment.ClientNodes.NodesList)
                    {
                        if (cParam.ClientNode.Equals(clientNode.Name))
                        {
                            Console.Error.WriteLine("Error: " + clientNode.Name + " already part of \"" + cParam.CacheId + "\"");
                            return;
                        }
                        currentClientNodes.Add(clientNode.Name);
                    }
                }

                UpdateConfigs();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Error: {0}", ex.Message);
            }
        }
        public void ParseArguments(string[] args)
        {
            string[] arguments = args.Skip(1).ToArray();

            if (arguments.Length < 1)
            {
                return;
            }

            string joined = string.Join(" ", arguments);

            log.DebugFormat("Command line arguments:{0}", string.Join(" ", arguments));

            try
            {
                if (arguments.Length == 1)
                {
                    if (arguments[0].Trim() == "-help" || arguments[0].Trim() == "-h")
                    {
                        PrintUsage();
                    }
                    else if (File.Exists(arguments[0]))
                    {
                        // Special case for dragging a file on top of the program icon or starting with a workspace.
                        if (Path.GetExtension(arguments[0]).ToLower() == ".xml")
                        {
                            Workspace workspace = new Workspace();
                            bool      loaded    = workspace.Load(arguments[0]);
                            if (loaded)
                            {
                                foreach (IScreenDescription screen in workspace.Screens)
                                {
                                    LaunchSettingsManager.AddScreenDescription(screen);
                                }
                            }
                        }
                        else
                        {
                            // Assume video and try to load it in a single screen.
                            ScreenDescriptionPlayback sdp = new ScreenDescriptionPlayback();
                            sdp.FullPath = arguments[0];
                            sdp.Autoplay = true;
                            sdp.Stretch  = true;
                            LaunchSettingsManager.AddScreenDescription(sdp);
                        }
                    }
                }
                else
                {
                    CommandLineArgumentParser.ParseArguments(arguments);

                    string name         = CommandLineArgumentParser.GetParamValue("-name");
                    bool   hideExplorer = CommandLineArgumentParser.IsSwitchOn("-hideExplorer");
                    string workspace    = CommandLineArgumentParser.GetParamValue("-workspace");
                    string video        = CommandLineArgumentParser.GetParamValue("-video");
                    string speed        = CommandLineArgumentParser.GetParamValue("-speed");
                    bool   stretch      = CommandLineArgumentParser.IsSwitchOn("-stretch");

                    // General program state.
                    if (!string.IsNullOrEmpty(name))
                    {
                        LaunchSettingsManager.Name = name;
                    }

                    LaunchSettingsManager.ShowExplorer = !hideExplorer;

                    // Workspace.
                    if (!string.IsNullOrEmpty(workspace))
                    {
                        Workspace w      = new Workspace();
                        bool      loaded = w.Load(workspace);
                        if (loaded)
                        {
                            foreach (IScreenDescription screen in w.Screens)
                            {
                                LaunchSettingsManager.AddScreenDescription(screen);
                            }
                        }
                    }
                    else if (!string.IsNullOrEmpty(video))
                    {
                        // Manual description.
                        ScreenDescriptionPlayback sdp = new ScreenDescriptionPlayback();
                        sdp.FullPath = video;

                        double speedValue;
                        bool   parsed = double.TryParse(speed, NumberStyles.Any, CultureInfo.InvariantCulture, out speedValue);
                        if (parsed)
                        {
                            speedValue = Math.Max(1, Math.Min(200, speedValue));
                        }
                        else
                        {
                            speedValue = 100;
                        }

                        sdp.SpeedPercentage = speedValue;
                        sdp.Stretch         = stretch;

                        LaunchSettingsManager.AddScreenDescription(sdp);
                    }
                }
            }
            catch (CommandLineArgumentException e)
            {
                log.Error("Command line arguments couldn't be parsed.");
                log.Error(e.Message);
                PrintUsage();
            }
        }
Esempio n. 54
0
        static public void Run(string[] args)
        {
            try
            {
                object param = new RemoveClientNodeParam();
                CommandLineArgumentParser.CommandLineParser(ref param, args);
                cParam = (RemoveClientNodeParam)param;
                if (cParam.IsUsage)
                {
                    AssemblyUsage.PrintLogo(cParam.IsLogo);
                    AssemblyUsage.PrintUsage();
                    return;
                }

                if (!ValidateParameters())
                {
                    return;
                }

                if (cParam.Port != -1)
                {
                    NCache.Port = cParam.Port;
                }

                if (cParam.Port == -1)
                {
                    NCache.Port = NCache.UseTcp ? CacheConfigManager.NCacheTcpPort : CacheConfigManager.HttpPort;
                }


                if (cParam.Server != null || cParam.Server != string.Empty)
                {
                    NCache.ServerName = cParam.Server;
                }

                cacheServer = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30));

                config = cacheServer.GetNewConfiguration(cParam.CacheId);
                string getClusterIp = cacheServer.GetClusterIP();
                if (config == null)
                {
                    Console.Error.WriteLine("Error: The cache doesnot exist.");
                    return;
                }
                if (config.CacheSettings.CacheType == "clustered-cache")
                {
                    Console.WriteLine("Removing client node '{0}' from cache '{1}' on server '{2}:{3}'.",
                                      cParam.ClientNode, cParam.CacheId, getClusterIp, NCache.Port);
                    foreach (Address node in config.CacheDeployment.Servers.GetAllConfiguredNodes())
                    {
                        currentServerNodes.Add(node.IpAddress.ToString());
                    }
                }
                else
                {
                    Console.Error.WriteLine("Error: Client nodes cannot be added to local caches");
                    return;
                }

                if (UpdateConfigs())
                {
                    Console.WriteLine("Client node '{0}' successfully removed from cache '{1}' on server {2}:{3}.",
                                      cParam.ClientNode, cParam.CacheId, getClusterIp, NCache.Port);
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Error: {0}", ex.Message);
            }
            finally
            {
                if (cacheServer != null)
                {
                    cacheServer.Dispose();
                }
            }
        }
        public void ThenCanParseShortFormArgumentsSuccessfully()
        {
            var args = new[] {@"-f=c:\features", @"-o=c:\features-output"};

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Assert.AreEqual(true, shouldContinue);
            Assert.AreEqual(@"c:\features", configuration.FeatureFolder.FullName);
            Assert.AreEqual(@"c:\features-output", configuration.OutputFolder.FullName);
            Assert.AreEqual(false, configuration.HasTestResults);
            Assert.AreEqual(null, configuration.TestResultsFile);
        }
        public void Then_can_parse_results_file_with_short_form_successfully()
        {
            var args = new string[] { @"-lr=c:\results.xml" };

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser();
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Assert.AreEqual(true, shouldContinue);
            Assert.AreEqual(Path.GetFullPath(Directory.GetCurrentDirectory()), configuration.FeatureFolder.FullName);
            Assert.AreEqual(Path.GetFullPath(Environment.GetEnvironmentVariable("TEMP")), configuration.OutputFolder.FullName);
            Assert.AreEqual(true, configuration.HasTestFrameworkResults);
            Assert.AreEqual(@"c:\results.xml", configuration.LinkedTestFrameworkResultsFile.FullName);
        }
Esempio n. 57
0
        static void Main(string[] args)
        {
            SetConsoleCtrlHandler(cancelHandler, true);
            ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
            string loc     = "zh-CN";
            string currLoc = Thread.CurrentThread.CurrentUICulture.Name;

            if (currLoc == "zh-TW" || currLoc == "zh-HK" || currLoc == "zh-MO")
            {
                loc = "zh-TW";
            }
            else if (loc == "zh-CN" || loc == "zh-SG")
            {
                loc = "zh-CN";
            }
            else
            {
                loc = "en-US";
            }
            //设置语言
            CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(loc);
            Thread.CurrentThread.CurrentUICulture   = CultureInfo.GetCultureInfo(loc);

            try
            {
                //goto httplitsen;
                //当前程序路径(末尾有\)
                string CURRENT_PATH = Directory.GetCurrentDirectory();
                string fileName     = "";

                //寻找ffmpeg.exe
                if (!File.Exists("ffmpeg.exe") && !File.Exists(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "ffmpeg.exe")))
                {
                    try
                    {
                        string[] EnvironmentPath = Environment.GetEnvironmentVariable("Path").Split(';');
                        foreach (var de in EnvironmentPath)
                        {
                            if (File.Exists(Path.Combine(de.Trim('\"').Trim(), "ffmpeg.exe")))
                            {
                                goto HasFFmpeg;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        ;
                    }

                    Console.BackgroundColor = ConsoleColor.Red;   //设置背景色
                    Console.ForegroundColor = ConsoleColor.White; //设置前景色,即字体颜色
                    Console.WriteLine(strings.ffmpegLost);
                    Console.ResetColor();                         //将控制台的前景色和背景色设为默认值
                    Console.WriteLine(strings.ffmpegTip);
                    Console.WriteLine();
                    Console.WriteLine("x86 https://ffmpeg.zeranoe.com/builds/win32/static/");
                    Console.WriteLine("x64 https://ffmpeg.zeranoe.com/builds/win64/static/");
                    Console.WriteLine();
                    Console.WriteLine(strings.pressAnyKeyExit);
                    Console.ReadKey();
                    Environment.Exit(-1);
                }

HasFFmpeg:
                Global.WriteInit();
                if (!File.Exists(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "NO_UPDATE")))
                {
                    Thread checkUpdate = new Thread(() =>
                    {
                        Global.CheckUpdate();
                    });
                    checkUpdate.IsBackground = true;
                    checkUpdate.Start();
                }

                int    maxThreads   = Environment.ProcessorCount;
                int    minThreads   = 16;
                int    retryCount   = 15;
                int    timeOut      = 10; //默认10秒
                string baseUrl      = "";
                string reqHeaders   = "";
                string keyFile      = "";
                string keyBase64    = "";
                string keyIV        = "";
                string muxSetJson   = "MUXSETS.json";
                string workDir      = CURRENT_PATH + "\\Downloads";
                bool   muxFastStart = false;
                bool   delAfterDone = false;
                bool   parseOnly    = false;
                bool   noMerge      = false;

                /******************************************************/
                ServicePointManager.DefaultConnectionLimit = 1024;
                ServicePointManager.SecurityProtocol       = SecurityProtocolType.Ssl3
                                                             | SecurityProtocolType.Tls
                                                             | (SecurityProtocolType)0x300  //Tls11
                                                             | (SecurityProtocolType)0xC00; //Tls12
                /******************************************************/

                if (File.Exists(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "headers.txt")))
                {
                    reqHeaders = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "headers.txt"));
                }

                //分析命令行参数
parseArgs:
                var arguments = CommandLineArgumentParser.Parse(args);
                if (args.Length == 1 && args[0] == "--help")
                {
                    Console.WriteLine(strings.helpInfo);
                    return;
                }
                if (arguments.Has("--enableDelAfterDone"))
                {
                    delAfterDone = true;
                }
                if (arguments.Has("--enableParseOnly"))
                {
                    parseOnly = true;
                }
                if (arguments.Has("--enableBinaryMerge"))
                {
                    DownloadManager.BinaryMerge = true;
                }
                if (arguments.Has("--disableDateInfo"))
                {
                    FFmpeg.WriteDate = false;
                }
                if (arguments.Has("--noMerge"))
                {
                    noMerge = true;
                }
                if (arguments.Has("--noProxy"))
                {
                    Global.NoProxy = true;
                }
                if (arguments.Has("--headers"))
                {
                    reqHeaders = arguments.Get("--headers").Next;
                }
                if (arguments.Has("--enableMuxFastStart"))
                {
                    muxFastStart = true;
                }
                if (arguments.Has("--disableIntegrityCheck"))
                {
                    DownloadManager.DisableIntegrityCheck = true;
                }
                if (arguments.Has("--enableAudioOnly"))
                {
                    Global.VIDEO_TYPE = "IGNORE";
                }
                if (arguments.Has("--muxSetJson"))
                {
                    muxSetJson = arguments.Get("--muxSetJson").Next;
                }
                if (arguments.Has("--workDir"))
                {
                    workDir = arguments.Get("--workDir").Next;
                    DownloadManager.HasSetDir = true;
                }
                if (arguments.Has("--saveName"))
                {
                    fileName = Global.GetValidFileName(arguments.Get("--saveName").Next);
                }
                if (arguments.Has("--useKeyFile"))
                {
                    if (File.Exists(arguments.Get("--useKeyFile").Next))
                    {
                        keyFile = arguments.Get("--useKeyFile").Next;
                    }
                }
                if (arguments.Has("--useKeyBase64"))
                {
                    keyBase64 = arguments.Get("--useKeyBase64").Next;
                }
                if (arguments.Has("--useKeyIV"))
                {
                    keyIV = arguments.Get("--useKeyIV").Next;
                }
                if (arguments.Has("--stopSpeed"))
                {
                    Global.STOP_SPEED = Convert.ToInt64(arguments.Get("--stopSpeed").Next);
                }
                if (arguments.Has("--maxSpeed"))
                {
                    Global.MAX_SPEED = Convert.ToInt64(arguments.Get("--maxSpeed").Next);
                }
                if (arguments.Has("--baseUrl"))
                {
                    baseUrl = arguments.Get("--baseUrl").Next;
                }
                if (arguments.Has("--maxThreads"))
                {
                    maxThreads = Convert.ToInt32(arguments.Get("--maxThreads").Next);
                }
                if (arguments.Has("--minThreads"))
                {
                    minThreads = Convert.ToInt32(arguments.Get("--minThreads").Next);
                }
                if (arguments.Has("--retryCount"))
                {
                    retryCount = Convert.ToInt32(arguments.Get("--retryCount").Next);
                }
                if (arguments.Has("--timeOut"))
                {
                    timeOut = Convert.ToInt32(arguments.Get("--timeOut").Next);
                }
                if (arguments.Has("--liveRecDur"))
                {
                    //时间码
                    Regex reg2 = new Regex(@"(\d+):(\d+):(\d+)");
                    var   t    = arguments.Get("--liveRecDur").Next;
                    if (reg2.IsMatch(t))
                    {
                        int HH = Convert.ToInt32(reg2.Match(t).Groups[1].Value);
                        int MM = Convert.ToInt32(reg2.Match(t).Groups[2].Value);
                        int SS = Convert.ToInt32(reg2.Match(t).Groups[3].Value);
                        HLSLiveDownloader.REC_DUR_LIMIT = SS + MM * 60 + HH * 60 * 60;
                    }
                }
                if (arguments.Has("--downloadRange"))
                {
                    string p = arguments.Get("--downloadRange").Next;

                    if (p.Contains(":"))
                    {
                        //时间码
                        Regex reg2 = new Regex(@"((\d+):(\d+):(\d+))?-((\d+):(\d+):(\d+))?");
                        if (reg2.IsMatch(p))
                        {
                            Parser.DurStart = reg2.Match(p).Groups[1].Value;
                            Parser.DurEnd   = reg2.Match(p).Groups[5].Value;
                            Parser.DelAd    = false;
                        }
                    }
                    else
                    {
                        //数字
                        Regex reg = new Regex(@"(\d*)-(\d*)");
                        if (reg.IsMatch(p))
                        {
                            if (!string.IsNullOrEmpty(reg.Match(p).Groups[1].Value))
                            {
                                Parser.RangeStart = Convert.ToInt32(reg.Match(p).Groups[1].Value);
                                Parser.DelAd      = false;
                            }
                            if (!string.IsNullOrEmpty(reg.Match(p).Groups[2].Value))
                            {
                                Parser.RangeEnd = Convert.ToInt32(reg.Match(p).Groups[2].Value);
                                Parser.DelAd    = false;
                            }
                        }
                    }
                }

                //如果只有URL,没有附加参数,则尝试解析配置文件
                if (args.Length == 1 || (args.Length == 3 && args[1].ToLower() == "--savename"))
                {
                    if (File.Exists(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "N_m3u8DL-CLI.args.txt")))
                    {
                        if (args.Length == 3)
                        {
                            args = Global.ParseArguments($"\"{args[0]}\" {args[1]} {args[2]} " + File.ReadAllText(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "N_m3u8DL-CLI.args.txt"))).ToArray();  //解析命令行
                        }
                        else
                        {
                            args = Global.ParseArguments($"\"{args[0]}\" " + File.ReadAllText(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), "N_m3u8DL-CLI.args.txt"))).ToArray();  //解析命令行
                        }
                        goto parseArgs;
                    }
                }

                //ReadLine字数上限
                Stream steam = Console.OpenStandardInput();
                Console.SetIn(new StreamReader(steam, Encoding.Default, false, 5000));
                int inputRetryCount = 20;
input:
                string testurl = "";


                //重试太多次,退出
                if (inputRetryCount == 0)
                {
                    Environment.Exit(-1);
                }

                if (args.Length > 0)
                {
                    testurl = args[0];
                }
                else
                {
                    Console.CursorVisible   = true;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write("N_m3u8DL-CLI");
                    Console.ResetColor();
                    Console.Write(" > ");

                    args = Global.ParseArguments(Console.ReadLine()).ToArray();  //解析命令行
                    Global.WriteInit();
                    Console.CursorVisible = false;
                    goto parseArgs;
                }

                if (fileName == "")
                {
                    fileName = Global.GetUrlFileName(testurl) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                }


                if (testurl.Contains("twitcasting") && testurl.Contains("/fmp4/"))
                {
                    DownloadManager.BinaryMerge = true;
                }

                //优酷DRM设备更改

                /*if (testurl.Contains("playlist/m3u8"))
                 * {
                 *  string drm_type = Global.GetQueryString("drm_type", testurl);
                 *  string drm_device = Global.GetQueryString("drm_device", testurl);
                 *  if (drm_type != "1")
                 *  {
                 *      testurl = testurl.Replace("drm_type=" + drm_type, "drm_type=1");
                 *  }
                 *  if (drm_device != "11")
                 *  {
                 *      testurl = testurl.Replace("drm_device=" + drm_device, "drm_device=11");
                 *  }
                 * }*/
                string m3u8Content = string.Empty;
                bool   isVOD       = true;


                //开始解析

                Console.CursorVisible = false;
                LOGGER.PrintLine($"{strings.fileName}{fileName}");
                LOGGER.PrintLine($"{strings.savePath}{Path.GetDirectoryName(Path.Combine(workDir, fileName))}");

                Parser parser = new Parser();
                parser.DownName  = fileName;
                parser.DownDir   = Path.Combine(workDir, parser.DownName);
                parser.M3u8Url   = testurl;
                parser.KeyBase64 = keyBase64;
                parser.KeyIV     = keyIV;
                parser.KeyFile   = keyFile;
                if (baseUrl != "")
                {
                    parser.BaseUrl = baseUrl;
                }
                parser.Headers = reqHeaders;
                string exePath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
                LOGGER.LOGFILE = Path.Combine(exePath, "Logs", DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".log");
                LOGGER.InitLog();
                LOGGER.WriteLine(strings.startParsing + testurl);
                LOGGER.PrintLine(strings.startParsing, LOGGER.Warning);
                if (testurl.EndsWith(".json") && File.Exists(testurl))              //可直接跳过解析
                {
                    if (!Directory.Exists(Path.Combine(workDir, fileName)))         //若文件夹不存在则新建文件夹
                    {
                        Directory.CreateDirectory(Path.Combine(workDir, fileName)); //新建文件夹
                    }
                    File.Copy(testurl, Path.Combine(Path.Combine(workDir, fileName), "meta.json"), true);
                }
                else
                {
                    parser.Parse();  //开始解析
                }

                //仅解析模式
                if (parseOnly)
                {
                    LOGGER.PrintLine(strings.parseExit);
                    Environment.Exit(0);
                }

                if (File.Exists(Path.Combine(Path.Combine(workDir, fileName), "meta.json")))
                {
                    JObject initJson = JObject.Parse(File.ReadAllText(Path.Combine(Path.Combine(workDir, fileName), "meta.json")));
                    isVOD = Convert.ToBoolean(initJson["m3u8Info"]["vod"].ToString());
                    //传给Watcher总时长
                    Watcher.TotalDuration = initJson["m3u8Info"]["totalDuration"].Value <double>();
                    LOGGER.PrintLine($"{strings.fileDuration}{Global.FormatTime((int)Watcher.TotalDuration)}");
                    LOGGER.PrintLine(strings.segCount + initJson["m3u8Info"]["originalCount"].Value <int>()
                                     + $", {strings.selectedCount}" + initJson["m3u8Info"]["count"].Value <int>());
                }
                else
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(workDir, fileName));
                    directoryInfo.Delete(true);
                    LOGGER.PrintLine(strings.InvalidUri, LOGGER.Error);
                    LOGGER.CursorIndex = 5;
                    inputRetryCount--;
                    goto input;
                }

                //点播
                if (isVOD == true)
                {
                    ServicePointManager.DefaultConnectionLimit = 10000;
                    DownloadManager md = new DownloadManager();
                    md.DownDir = parser.DownDir;
                    md.Headers = reqHeaders;
                    md.Threads = Environment.ProcessorCount;
                    if (md.Threads > maxThreads)
                    {
                        md.Threads = maxThreads;
                    }
                    if (md.Threads < minThreads)
                    {
                        md.Threads = minThreads;
                    }
                    if (File.Exists("minT.txt"))
                    {
                        int t = Convert.ToInt32(File.ReadAllText("minT.txt"));
                        if (md.Threads <= t)
                        {
                            md.Threads = t;
                        }
                    }
                    md.TimeOut      = timeOut * 1000;
                    md.NoMerge      = noMerge;
                    md.DownName     = fileName;
                    md.DelAfterDone = delAfterDone;
                    md.MuxFormat    = "mp4";
                    md.RetryCount   = retryCount;
                    md.MuxSetJson   = muxSetJson;
                    md.MuxFastStart = muxFastStart;
                    md.DoDownload();
                }
                //直播
                if (isVOD == false)
                {
                    LOGGER.WriteLine(strings.liveStreamFoundAndRecoding);
                    LOGGER.PrintLine(strings.liveStreamFoundAndRecoding);
                    //LOGGER.STOPLOG = true;  //停止记录日志
                    //开辟文件流,且不关闭。(便于播放器不断读取文件)
                    string LivePath = Path.Combine(Directory.GetParent(parser.DownDir).FullName
                                                   , DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + fileName + ".ts");
                    FileStream outputStream = new FileStream(LivePath, FileMode.Append);

                    HLSLiveDownloader live = new HLSLiveDownloader();
                    live.DownDir    = parser.DownDir;
                    live.Headers    = reqHeaders;
                    live.LiveStream = outputStream;
                    live.LiveFile   = LivePath;
                    live.TimerStart();  //开始录制
                    Console.ReadKey();
                }

                //监听测试

                /*httplitsen:
                 * HTTPListener.StartListening();*/
                LOGGER.WriteLineError(strings.downloadFailed);
                LOGGER.PrintLine(strings.downloadFailed, LOGGER.Error);
                Console.CursorVisible = true;
                Thread.Sleep(3000);
                Environment.Exit(-1);
                //Console.Write("按任意键继续..."); Console.ReadKey(); return;
            }
            catch (Exception ex)
            {
                Console.CursorVisible = true;
                LOGGER.PrintLine(ex.Message, LOGGER.Error);
            }
        }
        public void ThenCanParseResultsFileWithShortFormSuccessfully()
        {
            var args = new[] {@"-lr=c:\results.xml"};

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Assert.AreEqual(true, shouldContinue);
            Assert.AreEqual(Path.GetFullPath(Directory.GetCurrentDirectory()), configuration.FeatureFolder.FullName);
            Assert.AreEqual(Path.GetFullPath(Environment.GetEnvironmentVariable("TEMP")),
                            configuration.OutputFolder.FullName);
            Assert.AreEqual(true, configuration.HasTestResults);
            Assert.AreEqual(@"c:\results.xml", configuration.TestResultsFile.FullName);
        }
Esempio n. 59
0
        public void InitializeCommandLinePrameters(string[] args)
        {
            object parameters = this;

            CommandLineArgumentParser.CommandLineParser(ref parameters, args);
        }
        public void ThenCanParseResultsFormatMstestWithLongFormSuccessfully()
        {
            var args = new[] {@"-test-results-format=mstest"};

            var configuration = new Configuration();
            var commandLineArgumentParser = new CommandLineArgumentParser(FileSystem);
            bool shouldContinue = commandLineArgumentParser.Parse(args, configuration, TextWriter.Null);

            Assert.AreEqual(true, shouldContinue);
            Assert.AreEqual(TestResultsFormat.MsTest, configuration.TestResultsFormat);
        }