Exemplo n.º 1
0
 public ComHelp(CommandHandler handler) : base(handler)
 {
   id = "help";
   config.Level = 0;
   config.ListenTo = CommandConfig.ListenChannelPmBattle;
   description = "lists all commands available specifically to you";
 }
Exemplo n.º 2
0
        public void RunCommand(CommandHandler sender, List<string> args)
        {
            string cmdname = args.FirstOrDefault();

            if (cmdname == null)
            {
                foreach (ITradeCommand cmd in sender.Commands)
                {
                    VersatileIO.WriteComplex("&f  {0}: &7{1}".Fmt(cmd.RegistryName, cmd.Description));
                }
            }
            else
            {
                ITradeCommand cmd = sender.FindCommand(cmdname);
                if (cmd == null)
                {
                    VersatileIO.WriteLine("No command found by name of " + cmdname, ConsoleColor.Red);
                    return;
                }

                bool hasAliases = cmd.Aliases.Length > 1;
                string aliases = cmd.Aliases.ToReadableString((s) => "'" + s + "'", includeBraces: false);
                VersatileIO.WriteComplex("&fCommand '{0}': &7{1}".Fmt(cmd.RegistryName, cmd.Description));
                VersatileIO.WriteComplex("&f  Syntax: &7" + cmd.Syntax);
                if (hasAliases)
                {
                    VersatileIO.WriteComplex("&f  Aliases: &7" + aliases);
                }
            }
        }
Exemplo n.º 3
0
        public void RunCommand(CommandHandler sender, List<string> args)
        {
            RetrievalType? type = null;

            if (args.HasItems())
            {
                if (args[0].EqualsIgnoreCase("schema"))
                {
                    type = RetrievalType.Schema;
                }
                else if (args[0].EqualsIgnoreCase("prices"))
                {
                    type = RetrievalType.PriceData;
                }
                else if (args[0].EqualsIgnoreCase("market"))
                {
                    type = RetrievalType.MarketData;
                }
                else if (args[0].EqualsIgnoreCase("backpack"))
                {
                    type = RetrievalType.BackpackContents;
                }
            }

            Refresh(type);
        }
Exemplo n.º 4
0
 public ComBalance(CommandHandler handler) : base(handler)
 {
   id = "balance";
   description = "assigns people to <allycount> rank balanced alliances, e.g. !balance - makes 2 random but balanced alliances";
   paramDescription = "<allycount>";
   config.Throttling = 5;
 }
Exemplo n.º 5
0
 public QueryRoutes(CommandHandler commandHandler, QueryFacade queryFacade) : base()
 {
     Get["/GetShortlist", true] = async (parameters, _) =>
      {
          return Response.AsJson(await queryFacade.GetShortListAsync());
      };
 }
Exemplo n.º 6
0
        public void RunCommand(CommandHandler sender, List<string> args)
        {
            DealsFilters filters = new DealsFilters();

            string steamid = Settings.Instance.HomeSteamID64;

            foreach (string s in args)
            {
                if (!s.StartsWith("/"))
                {
                    steamid = s;
                    continue;
                }

                filters.HandleArg(s);
            }

            List<ItemSale> sales = DealFinder.FindDeals(steamid, filters);
            if (sales == null)
            {
                // already logged
                return;
            }

            sales.Sort((a, b) => a.Profit.TotalRefined.CompareTo(b.Profit.TotalRefined));

            VersatileIO.WriteLine();
            VersatileIO.Info("{0} deals found:", sales.Count);

            foreach (ItemSale s in sales)
            {
                VersatileIO.WriteComplex("  " + s.ToComplexString());
            }
        }
Exemplo n.º 7
0
        public void RunCommand(CommandHandler sender, List<string> args)
        {
            VersatileIO.Write("Custom Steam Tools Library ", ConsoleColor.Green);
            VersatileIO.WriteLine(AsmVersion, ConsoleColor.Yellow);
            VersatileIO.WriteLine(AsmDescription);
            VersatileIO.WriteLine(AsmCopyright, ConsoleColor.Gray);

            VersatileIO.WriteLine("License: GPL v3 (link below)");
            VersatileIO.WriteLine("  https://github.com/einsteinsci/custom-steam-tools/blob/master/LICENSE.txt", ConsoleColor.Gray);
            VersatileIO.WriteLine();

            VersatileIO.WriteLine("Special Thanks:", ConsoleColor.Green);
            VersatileIO.WriteLine();

            VersatileIO.WriteLine("JSON.NET for all the JSON parsing");
            VersatileIO.WriteLine("  Project: http://www.newtonsoft.com/json", ConsoleColor.Gray);
            VersatileIO.WriteLine("  License: https://github.com/JamesNK/Newtonsoft.Json/blob/master/LICENSE.md", ConsoleColor.Gray);

            VersatileIO.WriteLine("The HTML Agility Pack for all the data scraping");
            VersatileIO.WriteLine("  Project: https://htmlagilitypack.codeplex.com/", ConsoleColor.Gray);
            VersatileIO.WriteLine("  License: https://htmlagilitypack.codeplex.com/license", ConsoleColor.Gray);

            VersatileIO.WriteLine("Backpack.tf for tons of trading data");
            VersatileIO.WriteLine("  URL: https://backpack.tf/", ConsoleColor.Gray);

            VersatileIO.WriteLine("And of course, Valve for TF2");
            VersatileIO.WriteLine("  URL: http://www.teamfortress.com/", ConsoleColor.Gray);
        }
Exemplo n.º 8
0
        public StatsService(ShardedDiscordClient  client, CommandHandler cmdHandler)
        {

            this.client = client;

            Reset();
            this.client.MessageReceived += _ => Task.FromResult(MessageCounter++);
            cmdHandler.CommandExecuted += (_, e) => CommandsRan++;

            this.client.Disconnected += _ => Reset();

            this.carbonitexTimer = new Timer(async (state) =>
            {
            if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.CarbonKey))
                return;
                try
                {
                    using (var http = new HttpClient())
                    {
                        using (var content = new FormUrlEncodedContent(
                            new Dictionary<string, string> {
                                { "servercount", this.client.GetGuilds().Count.ToString() },
                                { "key", NadekoBot.Credentials.CarbonKey }}))
                        {
                            content.Headers.Clear();
                            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                            var res = await http.PostAsync("https://www.carbonitex.net/discord/data/botdata.php", content).ConfigureAwait(false);
                        }
                    };
                }
                catch { }
            }, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));
        }
        /// <summary>
        /// Istanzia un nuovo oggetto.
        /// </summary>
        public MainViewModel()
        {
            m_Updater = new UiThreadUpdater();

            m_TaskData = string.Empty;
            m_SearchNodeUri = string.Empty;

            m_ProcessingServicesList = new ObservableCollection<String>();
            m_SelectedProcessingServiceIndex = -1;

            m_TaskResult = string.Empty;
            m_ReportText = string.Empty;

            m_IsBusy = false;

            m_SearchCommand = new CommandHandler<Object>(
                (s) => { ExecuteSearch(); },   // ICommand.Execute
                (s) => { return CanExecuteSearch(); }   // ICommand.CanExecute
            );

            m_ProcessCommand = new CommandHandler<Object>(
                (s) => { ExecuteProcess(); },   // ICommand.Execute
                (s) => { return CanExecuteProcess(); }   // ICommand.CanExecute
            );

            m_ClearCommand = new CommandHandler<Object>(
                (s) => { ExecuteClear(); },   // ICommand.Execute
                (s) => { return CanExecuteClear(); }   // ICommand.CanExecute
            );

            m_TasksCounter = 0;
        }
Exemplo n.º 10
0
 public CommandInformation(int argumentCount, CommandHandler handler, string argumentDescription, string description)
 {
     ArgumentCount = argumentCount;
     Handler = handler;
     ArgumentDescription = argumentDescription;
     Description = description;
 }
Exemplo n.º 11
0
 public void RegisterHandler(CommandHandler commandHandler)
 {
   foreach(var commandType in commandHandler.GetHandledCommands())
   {
     _handlers.Add(commandType, commandHandler);
   }
 }
Exemplo n.º 12
0
 public CommandInfo(string command, CommandHandler.Command function, byte gmlevel, string[] param)
 {
     Command = command;
     Function = function;
     GmLevel = gmlevel;
     Parameters = param;
 }
Exemplo n.º 13
0
 public ComRandom(CommandHandler handler) : base(handler)
 {
   id = "random";
   description = "assigns people to <allycount> random alliances, e.g. !random - makes 2 random alliances";
   paramDescription = "<allycount>";
   config.Throttling = 5;
 }
Exemplo n.º 14
0
 internal void AddCommand( string command, CommandHandler handler, bool isConsoleSafe ) {
     if( isConsoleSafe ) {
         consoleSafeHandlers.Add( command, handler );
     } else {
         handlers.Add( command, handler );
     }
 }
Exemplo n.º 15
0
        public async Task RunAsync(params string[] args)
        {
            _log = LogManager.GetCurrentClassLogger();

            _log.Info("Starting NadekoBot v" + StatsService.BotVersion);

            //create client
            Client = new ShardedDiscordClient(new DiscordSocketConfig
            {
                AudioMode = Discord.Audio.AudioMode.Outgoing,
                MessageCacheSize = 10,
                LogLevel = LogSeverity.Warning,
                TotalShards = Credentials.TotalShards,
                ConnectionTimeout = int.MaxValue
            });

            //initialize Services
            CommandService = new CommandService();
            Localizer = new Localization();
            Google = new GoogleApiService();
            CommandHandler = new CommandHandler(Client, CommandService);
            Stats = new StatsService(Client, CommandHandler);

            //setup DI
            var depMap = new DependencyMap();
            depMap.Add<ILocalization>(Localizer);
            depMap.Add<ShardedDiscordClient>(Client);
            depMap.Add<CommandService>(CommandService);
            depMap.Add<IGoogleApiService>(Google);


            //setup typereaders
            CommandService.AddTypeReader<PermissionAction>(new PermissionActionTypeReader());
            CommandService.AddTypeReader<Command>(new CommandTypeReader());
            CommandService.AddTypeReader<Module>(new ModuleTypeReader());
            CommandService.AddTypeReader<IGuild>(new GuildTypeReader());

            //connect
            await Client.LoginAsync(TokenType.Bot, Credentials.Token).ConfigureAwait(false);
            await Client.ConnectAsync().ConfigureAwait(false);
            await Client.DownloadAllUsersAsync().ConfigureAwait(false);

            _log.Info("Connected");

            //load commands and prefixes
            using (var uow = DbHandler.UnitOfWork())
            {
                ModulePrefixes = new ConcurrentDictionary<string, string>(uow.BotConfig.GetOrCreate().ModulePrefixes.ToDictionary(m => m.ModuleName, m => m.Prefix));
            }
            // start handling messages received in commandhandler
            await CommandHandler.StartHandling().ConfigureAwait(false);

            await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly, depMap).ConfigureAwait(false);
#if !GLOBAL_NADEKO
            await CommandService.Load(new Music(Localizer, CommandService, Client, Google)).ConfigureAwait(false);
#endif
            Ready = true;
            Console.WriteLine(await Stats.Print().ConfigureAwait(false));
        }
Exemplo n.º 16
0
 // reader thread only
 public void RegisterConsumer(Type commandtype, CommandHandler handler)
 {
     if (!consumersbycommand.ContainsKey(commandtype))
     {
         consumersbycommand.Add(commandtype, new List<CommandHandler>());
     }
     consumersbycommand[commandtype].Add(handler);
 }
Exemplo n.º 17
0
		public CommandInfo (string command, PositionTypes min_position, CommandHandler pointer, int min_level, SubCommands subcmd)
		{
			Command = command;
			MinimumPosition = min_position;
			CommandPointer = pointer;
			MinimumLevel = min_level;
			SubCommand = subcmd;
		}
Exemplo n.º 18
0
 public LoginViewModel(ILoginView view, CompositionContainer shellContainer, IEventAggregator eventAggregator)
 {
     this.View = view;
     this.View.ViewModel = this;
     this.ShellContainer = shellContainer;
     this.EventAggregator = eventAggregator;
     LoginCommand = new CommandHandler<object, object>(OnLogin);
 }
Exemplo n.º 19
0
 /// <summary>
 /// </summary>
 public void AddHandler(string command, CommandHandler pfunc)
 {
     // AddCommandHandler("/user", pfunc);
     lock (this._commands)
     {
         this._commands.Add(command, pfunc);
     }
 }
Exemplo n.º 20
0
 public Command(object id, string name, CommandHandler handler, params object[] parameters)
     : this(id, name, handler)
 {
     if (null != parameters && parameters.Length > 0) {
         this.Parameters = parameters;
         this.ParameterDescriptions = new string[parameters.Length];
     }
 }
Exemplo n.º 21
0
    public ComRing(CommandHandler handler) : base(handler)
    {
      id = "ring";
      description = "rings all unready or specific player(s)";
      config.ListenTo = CommandConfig.ListenGameBattle;

      allowEmptyArgs = true;
      canTargetMultiple = true;
    }
Exemplo n.º 22
0
 public ComId(CommandHandler handler) : base(handler)
 {
   id = "id";
   description = "changes player id";
   config.Level = 2;
   playernameStartIndex = 1;
   allowEmptyArgs = false;
   canTargetMultiple = false;
 }
Exemplo n.º 23
0
 public ComKick(CommandHandler handler) : base(handler)
 {
   id = "kick";
   description = "kicks a player from game/battle room";
   config.ListenTo = CommandConfig.ListenPmGameBattle;
   config.Level = 3;
   allowEmptyArgs = false;
   canTargetMultiple = false;
 }
Exemplo n.º 24
0
 /// <summary>
 /// Creates a new command.
 /// </summary>
 /// <param name="command">The name of the command.</param>
 /// <param name="handler">The method for the command event.</param>
 /// <param name="addToLog">True to add the command to the log, otherwise false.</param>
 /// <param name="addToHistory">True to add the command to the input history, otherwise false.</param>
 /// <param name="manual">The manual of the command, one line per index.</param>
 public Command(string command, CommandHandler handler, bool addToLog, bool addToHistory,
     string[] manual)
 {
     Name = command;
     Handler = handler;
     AddToLog = addToLog;
     AddToHistory = addToHistory;
     Manual = manual;
 }
Exemplo n.º 25
0
 public LoginViewModel(ILoginView view)
 {
     View = view;
     View.ViewModel = this;
     ViewDispatcher = ((ILoginView)View).ViewDispatcher;
     LoginCommand = new CommandHandler<object, object>(LoginCommandAction);
     CloseCommand = new CommandHandler<object, object>(CloseCommandExecute);
     //DbHandler.Instance.SaveUserData(new User { Username = "******", Password = "******", Fullname = "Administrator", Address = "Dhaka", UserId = 1 });
 }
Exemplo n.º 26
0
 public ShellViewModel(IShellView view, CompositionContainer compositionContainer, IEventAggregator eventAggregator, Lazy<IShellService> shellService)
 {
     View = view;
     View.ViewModel = this;
     ShellContainer = compositionContainer;
     EventAggregator = eventAggregator;
     ShellService = shellService;
     LogoutCommand = new CommandHandler<object, object>(LogoutCommandAction);
     _tabCollection = new Lazy<OptimizedObservableCollection<IViewModel>>();
 }
Exemplo n.º 27
0
 public MainViewModel(IMainView view, CompositionContainer compositionContainer)
 {
     View = view;
     View.ViewModel = this;
     ShellContainer = compositionContainer;
     ViewDispatcher = ((IMainView)View).ViewDispatcher;
     CloseCommand = new CommandHandler<object, object>(CloseCommandAction);
     HardwareView = HardwareViewModel.View as UserControl;
     BranchView = BranchViewModel.View as UserControl;
 }
Exemplo n.º 28
0
        public static void Main()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            var userInterface = new UserInterface();
            var commandHandler = new CommandHandler();
            var engine = new Engine(commandHandler, userInterface);

            engine.Run();
        }
Exemplo n.º 29
0
        public void RunCommand(CommandHandler sender, List<string> args)
        {
            if (args.Count == 0)
            {
                VersatileIO.Error("Usage: " + Syntax);
                return;
            }

            string query = string.Join(" ", args);
            Item item = CmdInfo.SearchItem(query);
            PriceCheckResults results = GetPriceCheckResults(item);

            if (results == null)
            {
                return;
            }

            if (!results.HasResults)
            {
                VersatileIO.Error("  No price data found for item " + item.Name);
                return;
            }

            if (results.HasCrates)
            {
                VersatileIO.Info("Crates by series:");
            }
            foreach (CheckedPrice c in results.Uniques)
            {
                VersatileIO.WriteLine("  " + c, c.Quality.GetColor());
            }

            foreach (CheckedPrice c in results.Others)
            {
                VersatileIO.WriteLine("  " + c, c.Quality.GetColor());
            }

            if (results.HasUnusuals)
            {
                string code = VersatileIO.GetSelection("  Enter a code or continue: ", true,
                    "U", "Get unusual prices.");
                if (code != null && code.Trim().EqualsIgnoreCase("u"))
                {
                    VersatileIO.Info("{0} effects priced:", results.Unusuals.Count);
                    Price total = Price.Zero;
                    foreach (CheckedPrice u in results.Unusuals)
                    {
                        VersatileIO.WriteLine("  " + u.GetUnusualEffectString(), ConsoleColor.DarkMagenta);
                        total += u.Pricing.Pricing.Mid;
                    }
                    Price avg = total / results.Unusuals.Count;
                    VersatileIO.Info("Average Unusual Price: " + avg);
                }
            }
        }
Exemplo n.º 30
0
 public MainViewModel(IMainView view, CompositionContainer compositionContainer)
 {
     View = view;
     View.ViewModel = this;
     ShellContainer = compositionContainer;
     CloseCommand = new CommandHandler<object, object>(CloseCommandAction);
     ItemsCommand = new CommandHandler<object, object>(ItemsCommandAction);
     StockInCommand = new CommandHandler<object, object>(StockInCommandAction);
     StockOutCommand = new CommandHandler<object, object>(StockOutCommandAction);
     ProductReturnCommand = new CommandHandler<object, object>(ProductReturnCommandAction);
 }
Exemplo n.º 31
0
        static bool HandleBanListIPCommand(StringArguments args, CommandHandler handler)
        {
            PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.DEL_EXPIRED_IP_BANS);

            DB.Login.Execute(stmt);

            string filterStr = args.NextString();
            string filter    = !string.IsNullOrEmpty(filterStr) ? filterStr : "";

            SQLResult result;

            if (string.IsNullOrEmpty(filter))
            {
                stmt   = DB.Login.GetPreparedStatement(LoginStatements.SEL_IP_BANNED_ALL);
                result = DB.Login.Query(stmt);
            }
            else
            {
                stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_IP_BANNED_BY_IP);
                stmt.AddValue(0, filter);
                result = DB.Login.Query(stmt);
            }

            if (result.IsEmpty())
            {
                handler.SendSysMessage(CypherStrings.BanlistNoip);
                return(true);
            }

            handler.SendSysMessage(CypherStrings.BanlistMatchingip);
            // Chat short output
            if (handler.GetSession())
            {
                do
                {
                    handler.SendSysMessage("{0}", result.Read <string>(0));
                }while (result.NextRow());
            }
            // Console wide output
            else
            {
                handler.SendSysMessage(CypherStrings.BanlistIps);
                handler.SendSysMessage(" ===============================================================================");
                handler.SendSysMessage(CypherStrings.BanlistIpsHeader);
                do
                {
                    handler.SendSysMessage("-------------------------------------------------------------------------------");

                    long     timeBan   = result.Read <uint>(1);
                    DateTime tmBan     = Time.UnixTimeToDateTime(timeBan);
                    string   bannedby  = result.Read <string>(3).Substring(0, 15);
                    string   banreason = result.Read <string>(4).Substring(0, 15);

                    if (result.Read <uint>(1) == result.Read <uint>(2))
                    {
                        handler.SendSysMessage("|{0}|{1:D2}-{2:D2}-{3:D2} {4:D2}:{5:D2}|   permanent  |{6}|{7}|",
                                               result.Read <string>(0), tmBan.Year % 100, tmBan.Month + 1, tmBan.Day, tmBan.Hour, tmBan.Minute,
                                               bannedby, banreason);
                    }
                    else
                    {
                        long     timeUnban = result.Read <uint>(2);
                        DateTime tmUnban;
                        tmUnban = Time.UnixTimeToDateTime(timeUnban);
                        handler.SendSysMessage("|{0}|{1:D2}-{2:D2}-{3:D2} {4:D2}:{5:D2}|{6:D2}-{7:D2}-{8:D2} {9:D2}:{10:D2}|{11}|{12}|",
                                               result.Read <string>(0), tmBan.Year % 100, tmBan.Month + 1, tmBan.Day, tmBan.Hour, tmBan.Minute,
                                               tmUnban.Year % 100, tmUnban.Month + 1, tmUnban.Day, tmUnban.Hour, tmUnban.Minute,
                                               bannedby, banreason);
                    }
                }while (result.NextRow());

                handler.SendSysMessage(" ===============================================================================");
            }

            return(true);
        }
Exemplo n.º 32
0
        static bool HandleBanCharacterCommand(StringArguments args, CommandHandler handler)
        {
            if (args.Empty())
            {
                return(false);
            }

            string name = args.NextString();

            if (string.IsNullOrEmpty(name))
            {
                return(false);
            }

            string durationStr = args.NextString();

            if (string.IsNullOrEmpty(durationStr))
            {
                return(false);
            }

            uint duration = uint.Parse(durationStr);

            string reasonStr = args.NextString("");

            if (string.IsNullOrEmpty(reasonStr))
            {
                return(false);
            }

            if (!ObjectManager.NormalizePlayerName(ref name))
            {
                handler.SendSysMessage(CypherStrings.PlayerNotFound);
                return(false);
            }

            string author = handler.GetSession() != null?handler.GetSession().GetPlayerName() : "Server";

            switch (Global.WorldMgr.BanCharacter(name, durationStr, reasonStr, author))
            {
            case BanReturn.Success:
            {
                if (duration > 0)
                {
                    if (WorldConfig.GetBoolValue(WorldCfg.ShowBanInWorld))
                    {
                        Global.WorldMgr.SendWorldText(CypherStrings.BanCharacterYoubannedmessageWorld, author, name, Time.secsToTimeString(Time.TimeStringToSecs(durationStr), true), reasonStr);
                    }
                    else
                    {
                        handler.SendSysMessage(CypherStrings.BanYoubanned, name, Time.secsToTimeString(Time.TimeStringToSecs(durationStr), true), reasonStr);
                    }
                }
                else
                {
                    if (WorldConfig.GetBoolValue(WorldCfg.ShowBanInWorld))
                    {
                        Global.WorldMgr.SendWorldText(CypherStrings.BanCharacterYoupermbannedmessageWorld, author, name, reasonStr);
                    }
                    else
                    {
                        handler.SendSysMessage(CypherStrings.BanYoupermbanned, name, reasonStr);
                    }
                }
                break;
            }

            case BanReturn.Notfound:
            {
                handler.SendSysMessage(CypherStrings.BanNotfound, "character", name);

                return(false);
            }

            default:
                break;
            }

            return(true);
        }
Exemplo n.º 33
0
        static bool HandleBanListCharacterCommand(StringArguments args, CommandHandler handler)
        {
            if (args.Empty())
            {
                return(false);
            }

            string filter = args.NextString();

            if (string.IsNullOrEmpty(filter))
            {
                return(false);
            }

            PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_GUID_BY_NAME_FILTER);

            stmt.AddValue(0, filter);
            SQLResult result = DB.Characters.Query(stmt);

            if (result.IsEmpty())
            {
                handler.SendSysMessage(CypherStrings.BanlistNocharacter);
                return(true);
            }

            handler.SendSysMessage(CypherStrings.BanlistMatchingcharacter);

            // Chat short output
            if (handler.GetSession())
            {
                do
                {
                    PreparedStatement stmt2 = DB.Characters.GetPreparedStatement(CharStatements.SEL_BANNED_NAME);
                    stmt2.AddValue(0, result.Read <ulong>(0));
                    SQLResult banResult = DB.Characters.Query(stmt2);
                    if (!banResult.IsEmpty())
                    {
                        handler.SendSysMessage(banResult.Read <string>(0));
                    }
                }while (result.NextRow());
            }
            // Console wide output
            else
            {
                handler.SendSysMessage(CypherStrings.BanlistCharacters);
                handler.SendSysMessage(" =============================================================================== ");
                handler.SendSysMessage(CypherStrings.BanlistCharactersHeader);
                do
                {
                    handler.SendSysMessage("-------------------------------------------------------------------------------");

                    string char_name = result.Read <string>(1);

                    PreparedStatement stmt2 = DB.Characters.GetPreparedStatement(CharStatements.SEL_BANINFO_LIST);
                    stmt2.AddValue(0, result.Read <ulong>(0));
                    SQLResult banInfo = DB.Characters.Query(stmt2);
                    if (!banInfo.IsEmpty())
                    {
                        do
                        {
                            long     timeBan   = banInfo.Read <uint>(0);
                            DateTime tmBan     = Time.UnixTimeToDateTime(timeBan);
                            string   bannedby  = banInfo.Read <string>(2).Substring(0, 15);
                            string   banreason = banInfo.Read <string>(3).Substring(0, 15);

                            if (banInfo.Read <uint>(0) == banInfo.Read <uint>(1))
                            {
                                handler.SendSysMessage("|{0}|{1:D2}-{2:D2}-{3:D2} {4:D2}:{5:D2}|   permanent  |{6}|{7}|",
                                                       char_name, tmBan.Year % 100, tmBan.Month + 1, tmBan.Day, tmBan.Hour, tmBan.Minute,
                                                       bannedby, banreason);
                            }
                            else
                            {
                                long     timeUnban = banInfo.Read <uint>(1);
                                DateTime tmUnban   = Time.UnixTimeToDateTime(timeUnban);
                                handler.SendSysMessage("|{0}|{1:D2}-{2:D2}-{3:D2} {4:D2}:{5:D2}|{6:D2}-{7:D2}-{8:D2} {9:D2}:{10:D2}|{11}|{12}|",
                                                       char_name, tmBan.Year % 100, tmBan.Month + 1, tmBan.Day, tmBan.Hour, tmBan.Minute,
                                                       tmUnban.Year % 100, tmUnban.Month + 1, tmUnban.Day, tmUnban.Hour, tmUnban.Minute,
                                                       bannedby, banreason);
                            }
                        }while (banInfo.NextRow());
                    }
                }while (result.NextRow());
                handler.SendSysMessage(" =============================================================================== ");
            }

            return(true);
        }
Exemplo n.º 34
0
        public static int Main(params string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 2048;
            ServicePointManager.ServerCertificateValidationCallback = delegate
            {
                return(true);
            };

            var rootCommand = new RootCommand
            {
                new Argument <string>(
                    "url",
                    description: "视频地址 或 av|bv|BV|ep|ss"),
                new Option <bool>(
                    new string[] { "--use-tv-api", "-tv" },
                    "使用TV端解析模式"),
                new Option <bool>(
                    new string[] { "--only-hevc", "-hevc" },
                    "下载hevc编码"),
                new Option <bool>(
                    new string[] { "--only-show-info", "-info" },
                    "仅解析不下载"),
                new Option <bool>(
                    new string[] { "--hide-streams", "-hs" },
                    "不要显示所有可用音视频流"),
                new Option <bool>(
                    new string[] { "--interactive", "-ia" },
                    "交互式选择清晰度"),
                new Option <bool>(
                    new string[] { "--multi-thread", "-mt" },
                    "使用多线程下载"),
                new Option <string>(
                    new string[] { "--select-page", "-p" },
                    "选择指定分p或分p范围"),
                new Option <string>(
                    new string[] { "--cookie", "-c" },
                    "设置字符串cookie用以下载网页接口的会员内容"),
                new Option <string>(
                    new string[] { "--access-token", "-a" },
                    "设置access_token用以下载TV接口的会员内容")
            };

            Command loginCommand = new Command(
                "login",
                "通过APP扫描二维码以登录您的WEB账号");

            rootCommand.AddCommand(loginCommand);
            Command loginTVCommand = new Command(
                "logintv",
                "通过APP扫描二维码以登录您的TV账号");

            rootCommand.AddCommand(loginTVCommand);
            rootCommand.Description = "BBDown是一个免费且便捷高效的哔哩哔哩下载/解析软件.";
            rootCommand.TreatUnmatchedTokensAsErrors = true;

            //WEB登录
            loginCommand.Handler = CommandHandler.Create(delegate
            {
                try
                {
                    Log("获取登录地址...");
                    string loginUrl = "https://passport.bilibili.com/qrcode/getLoginUrl";
                    string url      = JObject.Parse(GetWebSource(loginUrl))["data"]["url"].ToString();
                    string oauthKey = GetQueryString("oauthKey", url);
                    //Log(oauthKey);
                    //Log(url);
                    bool flag = false;
                    Log("生成二维码...");
                    QRCodeGenerator qrGenerator = new QRCodeGenerator();
                    QRCodeData qrCodeData       = qrGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.Q);
                    QRCode qrCode      = new QRCode(qrCodeData);
                    Bitmap qrCodeImage = qrCode.GetGraphic(7);
                    qrCodeImage.Save("qrcode.png", System.Drawing.Imaging.ImageFormat.Png);
                    Log("生成二维码成功:qrcode.png, 请打开并扫描");
                    while (true)
                    {
                        Thread.Sleep(1000);
                        string w    = GetLoginStatus(oauthKey);
                        string data = JObject.Parse(w)["data"].ToString();
                        if (data == "-2")
                        {
                            LogColor("二维码已过期, 请重新执行登录指令.");
                            break;
                        }
                        else if (data == "-4") //等待扫码
                        {
                            continue;
                        }
                        else if (data == "-5") //等待确认
                        {
                            if (!flag)
                            {
                                Log("扫码成功, 请确认...");
                                flag = !flag;
                            }
                        }
                        else
                        {
                            string cc = JObject.Parse(w)["data"]["url"].ToString();
                            Log("登录成功: SESSDATA=" + GetQueryString("SESSDATA", cc));
                            //导出cookie
                            File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "BBDown.data"), "SESSDATA=" + GetQueryString("SESSDATA", cc));
                            File.Delete("qrcode.png");
                            break;
                        }
                    }
                }
                catch (Exception e) { LogError(e.Message); }
            });

            //TV登录
            loginTVCommand.Handler = CommandHandler.Create(delegate
            {
                try
                {
                    string loginUrl = "https://passport.snm0516.aisee.tv/x/passport-tv-login/qrcode/auth_code";
                    string pollUrl  = "https://passport.bilibili.com/x/passport-tv-login/qrcode/poll";
                    var parms       = GetTVLoginParms();
                    Log("获取登录地址...");
                    WebClient webClient  = new WebClient();
                    byte[] responseArray = webClient.UploadValues(loginUrl, parms);
                    string web           = Encoding.UTF8.GetString(responseArray);
                    string url           = JObject.Parse(web)["data"]["url"].ToString();
                    string authCode      = JObject.Parse(web)["data"]["auth_code"].ToString();
                    Log("生成二维码...");
                    QRCodeGenerator qrGenerator = new QRCodeGenerator();
                    QRCodeData qrCodeData       = qrGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.Q);
                    QRCode qrCode      = new QRCode(qrCodeData);
                    Bitmap qrCodeImage = qrCode.GetGraphic(7);
                    qrCodeImage.Save("qrcode.png", System.Drawing.Imaging.ImageFormat.Png);
                    Log("生成二维码成功:qrcode.png, 请打开并扫描");
                    parms.Set("auth_code", authCode);
                    parms.Set("ts", GetTimeStamp(true));
                    parms.Remove("sign");
                    parms.Add("sign", GetSign(ToQueryString(parms)));
                    while (true)
                    {
                        Thread.Sleep(1000);
                        responseArray = webClient.UploadValues(pollUrl, parms);
                        web           = Encoding.UTF8.GetString(responseArray);
                        string code   = JObject.Parse(web)["code"].ToString();
                        if (code == "86038")
                        {
                            LogColor("二维码已过期, 请重新执行登录指令.");
                            break;
                        }
                        else if (code == "86039") //等待扫码
                        {
                            continue;
                        }
                        else
                        {
                            string cc = JObject.Parse(web)["data"]["access_token"].ToString();
                            Log("登录成功: AccessToken=" + cc);
                            //导出cookie
                            File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "BBDownTV.data"), "access_token=" + cc);
                            File.Delete("qrcode.png");
                            break;
                        }
                    }
                }
                catch (Exception e) { LogError(e.Message); }
            });

            rootCommand.Handler = CommandHandler.Create <MyOption>(async(myOption) =>
            {
                //Console.WriteLine(myOption.ToString());
                await DoWorkAsync(myOption);
            });

            return(rootCommand.InvokeAsync(args).Result);
        }
Exemplo n.º 35
0
        static bool HandleBanHelper(BanMode mode, StringArguments args, CommandHandler handler)
        {
            if (args.Empty())
            {
                return(false);
            }

            string nameOrIP = args.NextString();

            if (string.IsNullOrEmpty(nameOrIP))
            {
                return(false);
            }

            uint   duration;
            string durationStr = args.NextString();

            if (string.IsNullOrEmpty(durationStr) || !uint.TryParse(durationStr, out duration))
            {
                return(false);
            }

            string reasonStr = args.NextString("");

            if (string.IsNullOrEmpty(reasonStr))
            {
                return(false);
            }

            switch (mode)
            {
            case BanMode.Character:
                if (!ObjectManager.NormalizePlayerName(ref nameOrIP))
                {
                    handler.SendSysMessage(CypherStrings.PlayerNotFound);
                    return(false);
                }
                break;

            case BanMode.IP:
                IPAddress address;
                if (!IPAddress.TryParse(nameOrIP, out address))
                {
                    return(false);
                }
                break;
            }

            string author = handler.GetSession() ? handler.GetSession().GetPlayerName() : "Server";

            switch (Global.WorldMgr.BanAccount(mode, nameOrIP, durationStr, reasonStr, author))
            {
            case BanReturn.Success:
                if (uint.Parse(durationStr) > 0)
                {
                    if (WorldConfig.GetBoolValue(WorldCfg.ShowBanInWorld))
                    {
                        Global.WorldMgr.SendWorldText(CypherStrings.BanAccountYoubannedmessageWorld, author, nameOrIP, Time.secsToTimeString(Time.TimeStringToSecs(durationStr)).ToString(), reasonStr);
                    }
                    else
                    {
                        handler.SendSysMessage(CypherStrings.BanYoubanned, nameOrIP, Time.secsToTimeString(Time.TimeStringToSecs(durationStr), true), reasonStr);
                    }
                }
                else
                {
                    if (WorldConfig.GetBoolValue(WorldCfg.ShowBanInWorld))
                    {
                        Global.WorldMgr.SendWorldText(CypherStrings.BanAccountYoupermbannedmessageWorld, author, nameOrIP, reasonStr);
                    }
                    else
                    {
                        handler.SendSysMessage(CypherStrings.BanYoupermbanned, nameOrIP, reasonStr);
                    }
                }
                break;

            case BanReturn.SyntaxError:
                return(false);

            case BanReturn.Notfound:
                switch (mode)
                {
                default:
                    handler.SendSysMessage(CypherStrings.BanNotfound, "account", nameOrIP);
                    break;

                case BanMode.Character:
                    handler.SendSysMessage(CypherStrings.BanNotfound, "character", nameOrIP);
                    break;

                case BanMode.IP:
                    handler.SendSysMessage(CypherStrings.BanNotfound, "ip", nameOrIP);
                    break;
                }

                return(false);
            }

            return(true);
        }
Exemplo n.º 36
0
 static bool HandleUnBanAccountByCharCommand(StringArguments args, CommandHandler handler)
 {
     return(HandleUnBanHelper(BanMode.Character, args, handler));
 }
Exemplo n.º 37
0
 public CommandRegistration(string command, CommandHandler handler, string help)
 {
     this.command = command;
     this.Handler = handler;
     this.help    = help;
 }
Exemplo n.º 38
0
 /// <summary>
 /// Initializes the command system provider
 /// </summary>
 private void Initialize()
 {
     registeredCommands = new Dictionary <string, CommandCallback>();
     commandHandler     = new CommandHandler(ChatCommandCallback, registeredCommands.ContainsKey);
 }
Exemplo n.º 39
0
        public static int Main(string[] args)
        {
            var root = new RootCommand(typeof(Program).Assembly.GetCustomAttribute <AssemblyTitleAttribute> ().Title);

            root.AddLicenseOption();


            var cmdPak = new Command("pak", "Process PAK files");

            root.Add(cmdPak);

            var cmdPakList = new Command("list", "List contents of a PAK file")
            {
                IsHidden = true
            };

            cmdPakList.AddArgument(new Argument <FileInfo> ("source", "Path to the PAK file").ExistingOnly());
            cmdPakList.AddOption(new Option <LocalHeaderField[]> ("--local-header")
            {
                IsHidden = true
            });                                                                                                           //uglifies help output
            cmdPakList.AddOption(new Option("--sort"));
            cmdPakList.Handler = CommandHandler.Create <FileInfo, LocalHeaderField[], bool> (DoPakList);
            cmdPak.Add(cmdPakList);

            var cmdPakPack = new Command("pack", "Pack contents of a directory into a single PAK file");

            cmdPakPack.AddArgument(new Argument <DirectoryInfo> ("source", "Path to the directory containing files").ExistingOnly());
            cmdPakPack.AddArgument(new Argument <FileInfo> ("target", "Path to a PAK file that will be created").NonExistingOnly());
            cmdPakPack.AddOption(new Option("--mixed-cache-block", "Indicates the source directory contains mixed contents of initial.pak and initial.pak\\initial.cache_block"));
            cmdPakPack.Handler = CommandHandler.Create <DirectoryInfo, FileInfo, bool> (DoPakPack);
            cmdPak.Add(cmdPakPack);


            var cmdCacheBlock = new Command("cache_block", "Process cache_block files");

            cmdCacheBlock.AddAlias("cb");
            root.Add(cmdCacheBlock);

            var cmdCacheBlockList = new Command("list", "List contents of a cache_block file");

            cmdCacheBlockList.AddArgument(new Argument <FileInfo> ("source", "Path to the cache_block file").ExistingOnly());
            cmdCacheBlockList.Handler = CommandHandler.Create <FileInfo> (DoCacheBlockList);
            cmdCacheBlock.Add(cmdCacheBlockList);

            var cmdCacheBlockUnpack             = new Command("unpack", "Unpack contents of a cache_block file into a directory");
            var cmdCacheBlockUnpack_AllowMixing = new Option("--allow-mixing", "Allow mixing of contents for initial.pak and initial.pak\\initial.cache_block");

            cmdCacheBlockUnpack.AddArgument(new Argument <FileInfo> ("source", "Path to the cache_block file").ExistingOnly());
            cmdCacheBlockUnpack.AddArgument(new Argument <DirectoryInfo> ("target", "Path to a directory that will be created to unpack into").NonExistingOnly(unless: cmdCacheBlockUnpack_AllowMixing));
            cmdCacheBlockUnpack.AddOption(cmdCacheBlockUnpack_AllowMixing);
            cmdCacheBlockUnpack.Handler = CommandHandler.Create <FileInfo, DirectoryInfo, bool> (DoCacheBlockUnpack);
            cmdCacheBlock.Add(cmdCacheBlockUnpack);

            var cmdCacheBlockPack = new Command("pack", "Pack contents of a directory into a single cache_block file");

            cmdCacheBlockPack.AddArgument(new Argument <DirectoryInfo> ("source", "Path to the directory containing files").ExistingOnly());
            cmdCacheBlockPack.AddArgument(new Argument <FileInfo> ("target", "Path to a cache_block file that will be created").NonExistingOnly());
            cmdCacheBlockPack.AddOption(new Option("--mixed-cache-block", "Indicates the source directory contains mixed contents of initial.pak and initial.pak\\initial.cache_block"));
            cmdCacheBlockPack.Handler = CommandHandler.Create <DirectoryInfo, FileInfo, bool> (DoCacheBlockPack);
            cmdCacheBlock.Add(cmdCacheBlockPack);


            var cmdLoadList = new Command("load_list", "Process load_list files");

            cmdLoadList.AddAlias("ll");
            root.Add(cmdLoadList);

            var cmdLoadListList = new Command("list", "List contents of a load_list file");

            cmdLoadListList.AddOption(new Option("--compact", "Use compact format (internal names only)"));
            cmdLoadListList.AddArgument(new Argument <FileInfo> ("source", "Path to the load_list file").ExistingOnly());
            cmdLoadListList.Handler = CommandHandler.Create <FileInfo, bool> (DoLoadListList);
            cmdLoadList.Add(cmdLoadListList);

            var cmdLoadListCreate = new Command("create-initial", "Create load_list file using conventions for initial.pak\\pak.load_list");

            cmdLoadListCreate.AddAlias("ci");
            cmdLoadListCreate.AddArgument(new Argument <FileInfo> ("target", "Path to a load_list file that will be created").NonExistingOnly());
            cmdLoadListCreate.AddArgument(new Argument <FileSystemInfo> ("initial", "Path to the initial.pak file or a directory with its contents").ExistingOnly());
            cmdLoadListCreate.AddArgument(new Argument <FileSystemInfo> ("shared", "Path to the shared.pak file or a directory with its contents").ExistingOnly());
            cmdLoadListCreate.AddArgument(new Argument <FileSystemInfo> ("shared_sound", "Path to the shared_sound.pak file or a directory with its contents").ExistingOnly());
            cmdLoadListCreate.Handler = CommandHandler.Create <FileInfo, FileSystemInfo, FileSystemInfo, FileSystemInfo> (DoLoadListCreate);
            cmdLoadList.Add(cmdLoadListCreate);


            var cmdSoundList = new Command("sound_list", "Process sound_list files");

            cmdSoundList.AddAlias("sl");
            root.Add(cmdSoundList);

            var cmdSoundListList = new Command("list", "List contents of a sound_list file");

            cmdSoundListList.AddArgument(new Argument <FileInfo> ("source", "Path to the sound_list file").ExistingOnly());
            cmdSoundListList.Handler = CommandHandler.Create <FileInfo> (DoSoundListList);
            cmdSoundList.Add(cmdSoundListList);

            var cmdSoundListCreate = new Command("create", "Create sound_list file");

            cmdSoundListCreate.AddArgument(new Argument <FileSystemInfo> ("source", "Path to the PAK file or a directory containing PCM files").ExistingOnly());
            cmdSoundListCreate.AddArgument(new Argument <FileInfo> ("target", "Path to the sound_list file").NonExistingOnly());
            cmdSoundListCreate.Handler = CommandHandler.Create <FileSystemInfo, FileInfo> (DoSoundListCreate);
            cmdSoundList.Add(cmdSoundListCreate);

            return(root.InvokeWithMiddleware(args, CommandLineExtensions.MakePrintLicenseResourceMiddleware(typeof(Program))));
        }
Exemplo n.º 40
0
        public StatsService(DiscordSocketClient client, CommandHandler cmdHandler,
                            IBotCredentials creds, NadekoBot nadeko,
                            IDataCache cache)
        {
            _log    = LogManager.GetCurrentClassLogger();
            _client = client;
            _creds  = creds;
            _redis  = cache.Redis;

            _started = DateTime.UtcNow;
            _client.MessageReceived    += _ => Task.FromResult(Interlocked.Increment(ref _messageCounter));
            cmdHandler.CommandExecuted += (_, e) => Task.FromResult(Interlocked.Increment(ref _commandsRan));

            _client.ChannelCreated += (c) =>
            {
                var _ = Task.Run(() =>
                {
                    if (c is ITextChannel)
                    {
                        Interlocked.Increment(ref _textChannels);
                    }
                    else if (c is IVoiceChannel)
                    {
                        Interlocked.Increment(ref _voiceChannels);
                    }
                });

                return(Task.CompletedTask);
            };

            _client.ChannelDestroyed += (c) =>
            {
                var _ = Task.Run(() =>
                {
                    if (c is ITextChannel)
                    {
                        Interlocked.Decrement(ref _textChannels);
                    }
                    else if (c is IVoiceChannel)
                    {
                        Interlocked.Decrement(ref _voiceChannels);
                    }
                });

                return(Task.CompletedTask);
            };

            _client.GuildAvailable += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, tc);
                    Interlocked.Add(ref _voiceChannels, vc);
                });
                return(Task.CompletedTask);
            };

            _client.JoinedGuild += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, tc);
                    Interlocked.Add(ref _voiceChannels, vc);
                });
                return(Task.CompletedTask);
            };

            _client.GuildUnavailable += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, -tc);
                    Interlocked.Add(ref _voiceChannels, -vc);
                });

                return(Task.CompletedTask);
            };

            _client.LeftGuild += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, -tc);
                    Interlocked.Add(ref _voiceChannels, -vc);
                });

                return(Task.CompletedTask);
            };

            if (_client.ShardId == 0)
            {
                _carbonitexTimer = new Timer(async(state) =>
                {
                    if (string.IsNullOrWhiteSpace(_creds.CarbonKey))
                    {
                        return;
                    }
                    try
                    {
                        using (var http = new HttpClient())
                        {
                            using (var content = new FormUrlEncodedContent(
                                       new Dictionary <string, string> {
                                { "servercount", nadeko.GuildCount.ToString() },
                                { "key", _creds.CarbonKey }
                            }))
                            {
                                content.Headers.Clear();
                                content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                                await http.PostAsync("https://www.carbonitex.net/discord/data/botdata.php", content).ConfigureAwait(false);
                            }
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));
            }

            _botlistTimer = new Timer(async(state) =>
            {
                if (string.IsNullOrWhiteSpace(_creds.BotListToken))
                {
                    return;
                }
                try
                {
                    using (var http = new HttpClient())
                    {
                        using (var content = new FormUrlEncodedContent(
                                   new Dictionary <string, string> {
                            { "shard_count", _creds.TotalShards.ToString() },
                            { "shard_id", client.ShardId.ToString() },
                            { "server_count", client.Guilds.Count().ToString() }
                        }))
                        {
                            content.Headers.Clear();
                            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                            http.DefaultRequestHeaders.Add("Authorization", _creds.BotListToken);

                            await http.PostAsync($"https://discordbots.org/api/bots/{client.CurrentUser.Id}/stats", content).ConfigureAwait(false);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _log.Error(ex);
                    // ignored
                }
            }, null, TimeSpan.FromMinutes(5), TimeSpan.FromHours(1));

            var platform = "other";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                platform = "linux";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                platform = "osx";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                platform = "windows";
            }

            _dataTimer = new Timer(async(state) =>
            {
                try
                {
                    using (var http = new HttpClient())
                    {
                        using (var content = new FormUrlEncodedContent(
                                   new Dictionary <string, string> {
                            { "id", string.Concat(MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(_creds.ClientId.ToString())).Select(x => x.ToString("X2"))) },
                            { "guildCount", nadeko.GuildCount.ToString() },
                            { "version", BotVersion },
                            { "platform", platform }
                        }))
                        {
                            content.Headers.Clear();
                            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                            await http.PostAsync("https://selfstats.nadekobot.me/", content).ConfigureAwait(false);
                        }
                    }
                }
                catch
                {
                    // ignored
                }
            }, null, TimeSpan.FromSeconds(1), TimeSpan.FromHours(1));
        }
Exemplo n.º 41
0
        public ConvertImageCommand() : base("convert", "Converts one image to another format.")
        {
            Add(new Option(new[]
            {
                "--cicm-xml", "-x"
            }, "Take metadata from existing CICM XML sidecar.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option("--comments", "Image comments.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option(new[]
            {
                "--count", "-c"
            }, "How many sectors to convert at once.")
            {
                Argument = new Argument <int>(() => 64), Required = false
            });

            Add(new Option("--creator", "Who (person) created the image?.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option("--drive-manufacturer",
                           "Manufacturer of the drive used to read the media represented by the image.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option("--drive-model", "Model of the drive used to read the media represented by the image.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option("--drive-revision",
                           "Firmware revision of the drive used to read the media represented by the image.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option("--drive-serial",
                           "Serial number of the drive used to read the media represented by the image.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option(new[]
            {
                "--force", "-f"
            }, "Continue conversion even if sector or media tags will be lost in the process.")
            {
                Argument = new Argument <bool>(() => false), Required = false
            });

            Add(new Option(new[]
            {
                "--format", "-p"
            },
                           "Format of the output image, as plugin name or plugin id. If not present, will try to detect it from output image extension.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option("--media-barcode", "Barcode of the media represented by the image.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option("--media-lastsequence",
                           "Last media of the sequence the media represented by the image corresponds to.")
            {
                Argument = new Argument <int>(() => 0), Required = false
            });

            Add(new Option("--media-manufacturer", "Manufacturer of the media represented by the image.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option("--media-model", "Model of the media represented by the image.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option("--media-partnumber", "Part number of the media represented by the image.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option("--media-sequence", "Number in sequence for the media represented by the image.")
            {
                Argument = new Argument <int>(() => 0), Required = false
            });

            Add(new Option("--media-serial", "Serial number of the media represented by the image.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option("--media-title", "Title of the media represented by the image.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option(new[]
            {
                "--options", "-O"
            }, "Comma separated name=value pairs of options to pass to output image plugin.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            Add(new Option(new[]
            {
                "--resume-file", "-r"
            }, "Take list of dump hardware from existing resume file.")
            {
                Argument = new Argument <string>(() => null), Required = false
            });

            AddArgument(new Argument <string>
            {
                Arity = ArgumentArity.ExactlyOne, Description = "Input image path", Name = "input-path"
            });

            AddArgument(new Argument <string>
            {
                Arity = ArgumentArity.ExactlyOne, Description = "Output image path", Name = "output-path"
            });

            Handler = CommandHandler.Create(GetType().GetMethod(nameof(Invoke)));
        }
Exemplo n.º 42
0
 /// <summary>
 /// Initializes the command system
 /// </summary>
 public HurtworldCommandSystem()
 {
     registeredCommands = new Dictionary <string, CommandCallback>();
     commandHandler     = new CommandHandler(ChatCommandCallback, registeredCommands.ContainsKey);
     consolePlayer      = new HurtworldConsolePlayer();
 }
Exemplo n.º 43
0
        public static async Task <int> Main(string[] args)
        {
            // Get any App settings
            var builder = new ConfigurationBuilder().AddJsonFile($"appsettings.json", true, true);
            var config  = builder.Build();

            // Are there Oauth config in the appsettings file?
            OauthSettings.ConsumerKey ??= config["key"] ?? null;
            OauthSettings.ConsumerSecret ??= config["secret"] ?? null;
            if (string.IsNullOrEmpty(OauthSettings.ConsumerKey) || string.IsNullOrEmpty(OauthSettings.ConsumerSecret))
            {
                Console.WriteLine("Need to supply Tumblr API Key (Consumer key & Secret) Get these at https://www.tumblr.com/oauth/apps");
                Console.WriteLine("Use a json formatted file named \"appsettings.json\"");
                Console.WriteLine("{\n\t\"key\": \"your-consumer-key\",\n\t\"secret\": \"your-secret-key\"\n}");
                return(1);
            }

            var hugo = new Command("hugo", "Convert blog posts to Hugo.")
            {
                new Argument <string>("blog", "Your blog."),
                new Argument <DirectoryInfo>("posts", "Output Directory for posts."),
                new Argument <DirectoryInfo>("media", "Output Directory for images, etc."),
                new Option <bool>(new[] { "--published", "-p" }, "Get public posts"),
                new Option <bool>(new[] { "--restricted", "-r" }, "Get private posts"),
                new Option <bool>(new[] { "--drafts", "-d" }, "Get draft posts"),
                new Option <bool>(new[] { "--queued", "-q" }, "Get queued posts"),
                new Option <bool>(new[] { "--noreblogs", "-n" }, "Only processes original posts, no reblogs"),
                new Option <bool>(new[] { "--authenticate", "-a" }, "Always use user authentication (required to get private or censored posts)"),
                new Option <DateTime>(new[] { "--since", "-s" }, "Only process posts newer than this date"),
                new Option <FileInfo>(new[] { "--jsonout", "-o" }, "Writes raw tumblr post json to a file"),
                new Option <FileInfo>(new[] { "--jsonin", "-i" }, "Reads raw tumblr post json from a file"),
                new Option <bool>(new[] { "--verbose", "-v" }, "Verbose mode"),
                new Option <bool>(new[] { "--test", "-t" }, "Test output")
            };

            var hugoPostBundle = new Command("hugopagebundle", "Convert blog posts to Hugo post bundles.")
            {
                new Argument <string>("blog", "Your blog."),
                new Argument <DirectoryInfo>("output", "Output Directory for posts, images, etc."),
                new Option <bool>(new[] { "--published", "-p" }, "Get public posts"),
                new Option <bool>(new[] { "--restricted", "-r" }, "Get private posts"),
                new Option <bool>(new[] { "--drafts", "-d" }, "Get draft posts"),
                new Option <bool>(new[] { "--queued", "-q" }, "Get queued posts"),
                new Option <bool>(new[] { "--noreblogs", "-n" }, "Only processes original posts, no reblogs"),
                new Option <bool>(new[] { "--authenticate", "-a" }, "Always use user authentication (required to get private or censored posts)"),
                new Option <DateTime>(new[] { "--since", "-s" }, "Only process posts newer than this date"),
                new Option <FileInfo>(new[] { "--jsonout", "-o" }, "Writes raw tumblr post json to a file"),
                new Option <FileInfo>(new[] { "--jsonin", "-i" }, "Reads raw tumblr post json from a file"),
                new Option <bool>(new[] { "--verbose", "-v" }, "Verbose mode"),
                new Option <bool>(new[] { "--test", "-t" }, "Test output")
            };

            var mediaOnly = new Command("mediaonly", "Copy original media (images etc) from blog")
            {
                new Argument <string>("blog", "Your blog."),
                new Argument <DirectoryInfo>("media", "Output Directory for images, etc."),
                new Option <DateTime>(new[] { "--since", "-s" }, "Only process posts newer than this date"),
                new Option <bool>(new[] { "--test", "-t" }, "Test output")
            };

            var cmd = new RootCommand
            {
                hugo,
                hugoPostBundle,
                mediaOnly
            };

            hugo.Handler           = CommandHandler.Create <HugoOptions>(new HugoProcessor().Run);
            hugoPostBundle.Handler = CommandHandler.Create <HugoPageBundleOptions>(new HugoPageBundleProcessor().Run);
            mediaOnly.Handler      = CommandHandler.Create <MediaOptions>(new MediaOnlyProcessor().Run);

            return(await cmd.InvokeAsync(args));
        }
Exemplo n.º 44
0
 private void registerCommand(string command, CommandHandler handler, string help)
 {
     commands.Add(command, new CommandRegistration(command, handler, help));
 }
Exemplo n.º 45
0
        static bool HandleBanListHelper(SQLResult result, CommandHandler handler)
        {
            handler.SendSysMessage(CypherStrings.BanlistMatchingaccount);

            // Chat short output
            if (handler.GetSession())
            {
                do
                {
                    uint accountid = result.Read <uint>(0);

                    SQLResult banResult = DB.Login.Query("SELECT account.username FROM account, account_banned WHERE account_banned.id='{0}' AND account_banned.id=account.id", accountid);
                    if (!banResult.IsEmpty())
                    {
                        handler.SendSysMessage(banResult.Read <string>(0));
                    }
                }while (result.NextRow());
            }
            // Console wide output
            else
            {
                handler.SendSysMessage(CypherStrings.BanlistAccounts);
                handler.SendSysMessage(" ===============================================================================");
                handler.SendSysMessage(CypherStrings.BanlistAccountsHeader);
                do
                {
                    handler.SendSysMessage("-------------------------------------------------------------------------------");

                    uint accountId = result.Read <uint>(0);

                    string accountName;

                    // "account" case, name can be get in same query
                    if (result.GetRowCount() > 1)
                    {
                        accountName = result.Read <string>(1);
                    }
                    // "character" case, name need extract from another DB
                    else
                    {
                        Global.AccountMgr.GetName(accountId, out accountName);
                    }

                    // No SQL injection. id is uint32.
                    SQLResult banInfo = DB.Login.Query("SELECT bandate, unbandate, bannedby, banreason FROM account_banned WHERE id = {0} ORDER BY unbandate", accountId);
                    if (!banInfo.IsEmpty())
                    {
                        do
                        {
                            long     timeBan = banInfo.Read <uint>(0);
                            DateTime tmBan;
                            tmBan = Time.UnixTimeToDateTime(timeBan);
                            string bannedby  = banInfo.Read <string>(2).Substring(0, 15);
                            string banreason = banInfo.Read <string>(3).Substring(0, 15);

                            if (banInfo.Read <uint>(0) == banInfo.Read <uint>(1))
                            {
                                handler.SendSysMessage("|{0}|{1:D2}-{2:D2}-{3:D2} {4:D2}:{5:D2}|   permanent  |{6}|{7}|",
                                                       accountName.Substring(0, 15), tmBan.Year % 100, tmBan.Month + 1, tmBan.Day, tmBan.Hour, tmBan.Minute,
                                                       bannedby, banreason);
                            }
                            else
                            {
                                long     timeUnban = banInfo.Read <uint>(1);
                                DateTime tmUnban;
                                tmUnban = Time.UnixTimeToDateTime(timeUnban);
                                handler.SendSysMessage("|{0}|{1:D2}-{2:D2}-{3:D2} {4:D2}:{5:D2}|{6:D2}-{7:D2}-{8:D2} {9:D2}:{10:D2}|{11}|{12}|",
                                                       accountName.Substring(0, 15), tmBan.Year % 100, tmBan.Month + 1, tmBan.Day, tmBan.Hour, tmBan.Minute,
                                                       tmUnban.Year % 100, tmUnban.Month + 1, tmUnban.Day, tmUnban.Hour, tmUnban.Minute,
                                                       bannedby, banreason);
                            }
                        }while (banInfo.NextRow());
                    }
                }while (result.NextRow());

                handler.SendSysMessage(" ===============================================================================");
            }

            return(true);
        }
Exemplo n.º 46
0
 public InfoCommand() : base("info", "Display information about the bundle")
 {
     AddArgument(bundleFile);
     Handler = CommandHandler.Create <FileInfo>(ExecuteCommand);
 }
Exemplo n.º 47
0
 static bool HandleUnBanAccountCommand(StringArguments args, CommandHandler handler)
 {
     return(HandleUnBanHelper(BanMode.Account, args, handler));
 }
Exemplo n.º 48
0
        static int Main(string[] args)
        {
            Option methodOption = new Option <SolvingMethod>(
                new string[] { "--method", "-m" },
                getDefaultValue: () => SolvingMethod.Sequential,
                description: "The method used to solve the nonogram"
                );

            Option methodsOption = new Option <SolvingMethod[]>(
                new string[] { "--methods", "-mx" },
                getDefaultValue: () => new[] { SolvingMethod.Sequential, SolvingMethod.Parallel },
                description: "The methods used to benchmark the nonogram"
                );

            Option sourceOption = new Option <PuzzleSource>(
                new string[] { "--source", "-s" },
                getDefaultValue: () => PuzzleSource.WebPBN,
                description: "The source of the puzzle to be solved"
                );

            Option idOption = new Option <int>(
                new string[] { "--id" },
                getDefaultValue: () => 0,
                description: "The id of the puzzle to be solved"
                );

            Option idSetOption = new Option <string>(
                new string[] { "--idSet", "-ix" },
                getDefaultValue: () => "4",
                description: "The set of puzzle ids to benchmark (comma delimited)"
                );

            Option trialsOption = new Option <int>(
                new string[] { "--trials", "-t" },
                getDefaultValue: () => 5,
                description: "The number of trials to time per benchmark"
                );

            Option timeoutOption = new Option <int>(
                new string[] { "--timeout", "-to" },
                getDefaultValue: () => 10000,
                description: "The maximum number of milliseconds to wait for a solution"
                );

            Option directoryOption = new Option <DirectoryInfo>(
                new string[] { "--directory", "-d" },
                getDefaultValue: () => new DirectoryInfo(@"./"),
                description: "The working root directory for all I/O"
                );

            Option verboseOption = new Option <bool>(
                new string[] { "--verbose", "-v" },
                getDefaultValue: () => false,
                description: "Make program report all processes"
                );

            Option threadsOption = new Option <int>(
                new string[] { "--threads", "-t" },
                getDefaultValue: () => 2,
                description: "Sets number of threads to use for parallel solvers"
                );

            // Root command
            RootCommand rootCommand = new RootCommand();

            rootCommand.AddGlobalOption(directoryOption);
            rootCommand.AddGlobalOption(verboseOption);
            rootCommand.AddGlobalOption(timeoutOption);
            rootCommand.AddGlobalOption(sourceOption);

            // Solve command
            Command solveCommand = new Command("solve");

            solveCommand.AddOption(methodOption);

            solveCommand.AddOption(idOption);
            solveCommand.AddOption(threadsOption);

            solveCommand.Handler =
                CommandHandler.Create <PuzzleSource, SolvingMethod, DirectoryInfo, int, int, int, bool>(Solve);

            // Play command
            Command playCommand = new Command("play");

            playCommand.AddOption(idOption);

            playCommand.Handler =
                CommandHandler.Create <PuzzleSource, DirectoryInfo, int, bool>(Play);

            Command benchmarkCommand = new Command("benchmark");

            benchmarkCommand.AddOption(methodsOption);
            benchmarkCommand.AddOption(idSetOption);
            benchmarkCommand.AddOption(trialsOption);


            benchmarkCommand.Handler =
                CommandHandler.Create <PuzzleSource, SolvingMethod[], DirectoryInfo, string, int, int, bool>(Benchmark);

            rootCommand.AddCommand(benchmarkCommand);
            rootCommand.AddCommand(solveCommand);
            rootCommand.AddCommand(playCommand);

            return(rootCommand.InvokeAsync(args).Result);
        }
Exemplo n.º 49
0
        private async void HandleMessagesAsync()
        {
            _logger.UpdateLog("Chat handler - handling started");

            int charId;
            ChatMessageDetails details;
            List <Tuple <int, ChatMessageDetails> > tempMsgList = new List <Tuple <int, ChatMessageDetails> >();
            PlayerDetails        senderPlayer;
            CharacterData        senderCharacter;
            PlayerDetails        receiverPlayer;
            CharacterData        receiverCharacter;
            List <CharacterData> receiverCharacterList = new List <CharacterData>();
            double distance = 0;

            do
            {
                await Task.Factory.StartNew(() => Thread.Sleep(_timeIntervalMs));

                if (!_handlingInProgress)
                {
                    break;
                }

                //TEMP LIST CREATION
                lock (_chatMsgLock)
                {
                    if (_charIdMsgList.Count > 0)
                    {
                        foreach (Tuple <int, ChatMessageDetails> msgData in _charIdMsgList)
                        {
                            charId = msgData.Item1;
                            if (charId < 0)
                            {
                                continue;
                            }

                            tempMsgList.Add(Tuple.Create(charId, (ChatMessageDetails)msgData.Item2.Clone()));
                        }

                        _charIdMsgList.Clear();
                    }
                }

                //TEMP LIST HANDLING

                foreach (Tuple <int, ChatMessageDetails> msgData in tempMsgList)
                {
                    charId  = msgData.Item1;
                    details = msgData.Item2;

                    senderPlayer = await Task.Factory.StartNew(() => _playerHandler.GetPlayerByCurrentCharId(charId));

                    if (senderPlayer == null)
                    {
                        _logger.UpdateLog($"Chat handling - cannot find sender player by char. ID [{charId}]");
                        continue;
                    }

                    senderCharacter = await _characterInfo.GetCharacterByIdTaskStart(charId);

                    if (senderCharacter == null)
                    {
                        _logger.UpdateLog($"Chat handling - cannot find sender character by char. ID [{charId}]");
                        continue;
                    }

                    if (details.IsPrivate)
                    {
                        #region Private message
                        //PRIVATE MESSAGE

                        receiverCharacter = await _characterInfo.GetCharacterByNameTaskStart(details.To);

                        if (receiverCharacter == null)
                        {
                            CommandHandler.Send
                            (
                                new ChatMessageCmdBuilder
                                (
                                    new ChatMessageDetails()
                            {
                                IsPrivate = true,
                                From      = "SERVER",
                                To        = senderCharacter.Name,
                                Message   = $"Character [{details.To}] doesn't exist!"
                            }
                                ),
                                senderPlayer
                            );
                            continue;
                        }

                        if (receiverCharacter.GetDbData().IsNpc)
                        {
                            CommandHandler.Send
                            (
                                new ChatMessageCmdBuilder
                                (
                                    new ChatMessageDetails()
                            {
                                IsPrivate = true,
                                From      = "SERVER",
                                To        = senderCharacter.Name,
                                Message   = $"Cannot send message to NPC [{details.To}]"
                            }
                                ),
                                senderPlayer
                            );
                            continue;
                        }

                        receiverPlayer = _playerHandler.GetPlayerByCurrentCharId(receiverCharacter.CharId);
                        if (receiverPlayer == null)
                        {
                            CommandHandler.Send
                            (
                                new ChatMessageCmdBuilder
                                (
                                    new ChatMessageDetails()
                            {
                                IsPrivate = true,
                                From      = "SERVER",
                                To        = senderCharacter.Name,
                                Message   = $"Character's [{details.To}] player is not logged in!"
                            }
                                ),
                                senderPlayer
                            );
                            continue;
                        }

                        //============== success

                        CommandHandler.Send //to receiver
                        (
                            new ChatMessageCmdBuilder
                            (
                                new ChatMessageDetails()
                        {
                            IsPrivate = true,
                            From      = senderCharacter.Name,
                            To        = receiverCharacter.Name,
                            Message   = details.Message
                        }
                            ),
                            receiverPlayer
                        );

                        CommandHandler.Send //to sender
                        (
                            new ChatMessageCmdBuilder
                            (
                                new ChatMessageDetails()
                        {
                            IsPrivate = true,
                            From      = senderCharacter.Name,
                            To        = receiverCharacter.Name,
                            Message   = details.Message
                        }
                            ),
                            senderPlayer
                        );

                        #endregion
                    }
                    else
                    {
                        #region Public message
                        //PUBLIC MESSAGE
                        if (senderCharacter.IsOnWorldMap)
                        {
                            CommandHandler.Send(new InfoCmdBuilder("Cannot send public message on world map!"), senderPlayer);
                            continue;
                        }

                        await Task.Factory.StartNew
                        (
                            () =>
                        {
                            receiverCharacterList = _characterInfo.GetCharactersByWorldLocation(senderCharacter.WmId, senderCharacter.IsOnWorldMap, senderCharacter.ParentObjectId);
                            foreach (CharacterData receiverCharData in receiverCharacterList)
                            {
                                distance = Measure.GetDistanceBetweenPoints(senderCharacter.CurrentLoc, receiverCharData.CurrentLoc);
                                if (distance > _globalChatMaxDistance)
                                {
                                    continue;
                                }

                                receiverPlayer = _playerHandler.GetPlayerByCurrentCharId(receiverCharData.CharId);
                                if (receiverPlayer == null)
                                {
                                    continue;
                                }

                                CommandHandler.Send
                                (
                                    new ChatMessageCmdBuilder
                                    (
                                        new ChatMessageDetails()
                                {
                                    IsPrivate = false,
                                    From      = senderCharacter.Name,
                                    To        = String.Empty,
                                    Message   = details.Message
                                }
                                    ),
                                    receiverPlayer
                                );
                            }
                        }
                        );

                        receiverCharacterList.Clear();

                        #endregion
                    }
                }

                tempMsgList.Clear();
            }while (_handlingInProgress);

            _logger.UpdateLog("Chat handler - handling stopped!");
        }
Exemplo n.º 50
0
 public DirectoryCommand() : base("directory", $"The directory that contains {Constants.STORM_REPLAY_EXTENSION} files.")
 {
     Handler = CommandHandler.Create <CancellationToken>(ActionAsync);
 }
Exemplo n.º 51
0
        static void Main(string[] args)
        {
            var startOption = new Option(new string[] { "--start", "-s" }, "Start time (earliest videos to download)")
            {
                Argument   = new Argument <DateTime>("start", () => DateTime.MinValue),
                IsRequired = false
            };

            var endOption = new Option(new string[] { "--end", "-e" }, "End time (latest videos to download)")
            {
                Argument   = new Argument <DateTime>("end", () => DateTime.MaxValue),
                IsRequired = false
            };

            var pathOption = new Option(new string[] { "--path" }, "Path to save videos to")
            {
                Argument   = new Argument <string>("path", () => string.Empty),
                IsRequired = false
            };

            var passwordOption = new Option(new string[] { "--password", "-p" }, "Ring account password")
            {
                Argument   = new Argument <string>("password", () => string.Empty),
                IsRequired = false
            };

            var userNameOption = new Option(new string[] { "--username", "-u" }, "Ring account username")
            {
                Argument   = new Argument <string>("username", () => string.Empty),
                IsRequired = false
            };

            var starredOption = new Option(new string[] { "--starred" }, "Flag to only download Starred videos")
            {
                Argument   = new Argument <bool>("starred", () => false),
                IsRequired = false
            };

            var maxcountOption = new Option(new string[] { "--maxcount", "-m" }, "Maximum number of videos to download")
            {
                Argument   = new Argument <int>("maxcount", () => 1000),
                IsRequired = false
            };
            RootCommand rootCommand = new RootCommand(description: "Simple command line tool to download videos from your Ring account");

            var starCommand = new Command("starred", "Download only starred videos")
            {
                Handler = CommandHandler.Create <string, string, string, DateTime, DateTime, int>(GetStarredVideos)
            };
            var allCommand = new Command("all", "Download all videos (starred and unstarred)")
            {
                Handler = CommandHandler.Create <string, string, string, DateTime, DateTime, int>(GetAllVideos)
            };
            var snapshotCommand = new Command("snapshot", "Download only snapshot images")
            {
                Handler = CommandHandler.Create <string, string, string, DateTime, DateTime>(GetSnapshotImages)
            };

            rootCommand.Add(starCommand);
            rootCommand.Add(allCommand);
            rootCommand.Add(snapshotCommand);

            starCommand.Add(userNameOption);
            starCommand.Add(passwordOption);
            starCommand.Add(pathOption);
            starCommand.Add(startOption);
            starCommand.Add(endOption);
            starCommand.Add(maxcountOption);

            allCommand.Add(userNameOption);
            allCommand.Add(passwordOption);
            allCommand.Add(pathOption);
            allCommand.Add(startOption);
            allCommand.Add(endOption);
            allCommand.Add(maxcountOption);

            snapshotCommand.Add(userNameOption);
            snapshotCommand.Add(passwordOption);
            snapshotCommand.Add(pathOption);
            snapshotCommand.Add(startOption);
            snapshotCommand.Add(endOption);


            var services = new ServiceCollection();

            ConfigureServices(services, args);
            using (ServiceProvider serviceProvider = services.BuildServiceProvider())
            {
                app  = serviceProvider.GetService <RingVideoApplication>();
                auth = Configuration.GetSection("Authentication").Get <Authentication>();
                if (auth != null)
                {
                    auth.Decrypt();
                }
                else
                {
                    auth = new Authentication();
                }
                filter = Configuration.GetSection("Filter").Get <Filter>();
                if (filter == null)
                {
                    filter = new Filter();
                }

                Task <int> val = rootCommand.InvokeAsync(args);
                val.Wait();

                SaveSettings(Program.filter, Program.auth, val.Result);
            }
        }
Exemplo n.º 52
0
        public async Task RunAsync(params string[] args)
        {
            SetupLogger();
            _log = LogManager.GetCurrentClassLogger();

            _log.Info("Starting NadekoBot v" + StatsService.BotVersion);


            Credentials = new BotCredentials();

            //create client
            Client = new ShardedDiscordClient(new DiscordSocketConfig
            {
                AudioMode         = Discord.Audio.AudioMode.Outgoing,
                MessageCacheSize  = 10,
                LogLevel          = LogSeverity.Warning,
                TotalShards       = Credentials.TotalShards,
                ConnectionTimeout = int.MaxValue
            });

            //initialize Services
            CommandService = new CommandService();
            Localizer      = new Localization();
            Google         = new GoogleApiService();
            CommandHandler = new CommandHandler(Client, CommandService);
            Stats          = new StatsService(Client, CommandHandler);

            //setup DI
            var depMap = new DependencyMap();

            depMap.Add <ILocalization>(Localizer);
            depMap.Add <ShardedDiscordClient>(Client);
            depMap.Add <CommandService>(CommandService);
            depMap.Add <IGoogleApiService>(Google);


            //setup typereaders
            CommandService.AddTypeReader <PermissionAction>(new PermissionActionTypeReader());
            CommandService.AddTypeReader <Command>(new CommandTypeReader());
            CommandService.AddTypeReader <Module>(new ModuleTypeReader());
            CommandService.AddTypeReader <IGuild>(new GuildTypeReader());

            //connect
            await Client.LoginAsync(TokenType.Bot, Credentials.Token).ConfigureAwait(false);

            await Client.ConnectAsync().ConfigureAwait(false);

            await Client.DownloadAllUsersAsync().ConfigureAwait(false);

            _log.Info("Connected");

            //load commands and prefixes
            using (var uow = DbHandler.UnitOfWork())
            {
                ModulePrefixes = new ConcurrentDictionary <string, string>(uow.BotConfig.GetOrCreate().ModulePrefixes.ToDictionary(m => m.ModuleName, m => m.Prefix));
            }
            // start handling messages received in commandhandler
            await CommandHandler.StartHandling().ConfigureAwait(false);

            await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly, depMap).ConfigureAwait(false);

#if !GLOBAL_NADEKO
            await CommandService.Load(new Music(Localizer, CommandService, Client, Google)).ConfigureAwait(false);
#endif
            Ready = true;
            Console.WriteLine(await Stats.Print().ConfigureAwait(false));
        }
Exemplo n.º 53
0
 public void CreateCommandHandler(string prefix)
 {
     CommandHandler = new CommandHandler(prefix, this);
 }
Exemplo n.º 54
0
 static bool HandleBanIPCommand(StringArguments args, CommandHandler handler)
 {
     return(HandleBanHelper(BanMode.IP, args, handler));
 }
Exemplo n.º 55
0
 /// <summary>
 /// Initializes the command system
 /// </summary>
 public RustCommandSystem()
 {
     registeredCommands = new Dictionary <string, RegisteredCommand>();
     commandHandler     = new CommandHandler(CommandCallback, registeredCommands.ContainsKey);
     consolePlayer      = new RustConsolePlayer();
 }
Exemplo n.º 56
0
        static int Main(string[] args)
        {
            var rootCommand = new RootCommand
            {
                new Option <int>(
                    aliases: new string[] { "--keep-number", "-n" },
                    getDefaultValue: () => 0,
                    description: "Keep at least this number of files."),
                new Option <int>(
                    aliases: new string[] { "--keep-days", "-d" },
                    getDefaultValue: () => 0,
                    description: "Keep files that are newer than this number of days."),
                new Option <int>(
                    aliases: new string[] { "--security-level", "-l" },
                    getDefaultValue: () => 0,
                    description: "Number of passes of security overwriting."),
                new Option <bool>(
                    aliases: new string[] { "--whatif", "-t" },
                    "Test mode, does not actually purge any files."),
                new Option <bool>(
                    aliases: new string[] { "--force", "-f" },
                    "Force deletion of read-only files."),
                new Option <bool>(
                    aliases: new string[] { "--prompt", "-p" },
                    "Prompt for confirmation before deleting each file."),
                new Argument <string>("FileSpec",
                                      description: "File search pattern. ex. test*.zip")
            };

            rootCommand.Description = "Advanced file purging";

            rootCommand.Handler = CommandHandler.Create <int, int, int, bool, bool, bool, string>
                                      ((keepNumber,
                                        keepDays,
                                        securityLevel,
                                        whatIf,
                                        force,
                                        prompt,
                                        fileSpec) =>
            {
                Console.WriteLine($"Keep Number = {keepNumber}");
                Console.WriteLine($"Keep Days = {keepDays}");
                Console.WriteLine($"Security Level = {securityLevel}");
                Console.WriteLine($"Whatif = {whatIf}");
                Console.WriteLine($"Force = {force}");
                Console.WriteLine($"Prompt = {prompt}");
                Console.WriteLine($"File Spec = {fileSpec}");

                if (securityLevel < 0 || securityLevel > 50)
                {
                    Console.WriteLine("Security level must be in the range of 0-50");
                }
                else if (keepDays < 0)
                {
                    Console.WriteLine("Keep days must be zero or greater");
                }
                else if (keepNumber < 0)
                {
                    Console.WriteLine("Keep number must be zero or greater");
                }
                else
                {
                    PurgeProcessor pp = new PurgeProcessor(keepNumber, keepDays, securityLevel, whatIf, force, prompt, fileSpec);
                }
            });

            return(rootCommand.InvokeAsync(args).Result);
        }
Exemplo n.º 57
0
        public static async Task <int> Main(params string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 2048;
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
            {
                return(true);
            };

            var rootCommand = new RootCommand
            {
                new Argument <string>(
                    "url",
                    description: "视频地址 或 av|bv|BV|ep|ss"),
                new Option <bool>(
                    new string[] { "--use-tv-api", "-tv" },
                    "使用TV端解析模式"),
                new Option <bool>(
                    new string[] { "--use-app-api", "-app" },
                    "使用APP端解析模式"),
                new Option <bool>(
                    new string[] { "--use-intl-api", "-intl" },
                    "使用国际版解析模式"),
                new Option <bool>(
                    new string[] { "--use-mp4box" },
                    "使用MP4Box来混流"),
                new Option <bool>(
                    new string[] { "--only-hevc", "-hevc" },
                    "只下载hevc编码"),
                new Option <bool>(
                    new string[] { "--only-avc", "-avc" },
                    "只下载avc编码"),
                new Option <bool>(
                    new string[] { "--only-show-info", "-info" },
                    "仅解析而不进行下载"),
                new Option <bool>(
                    new string[] { "--hide-streams", "-hs" },
                    "不要显示所有可用音视频流"),
                new Option <bool>(
                    new string[] { "--interactive", "-ia" },
                    "交互式选择清晰度"),
                new Option <bool>(
                    new string[] { "--show-all" },
                    "展示所有分P标题"),
                new Option <bool>(
                    new string[] { "--use-aria2c" },
                    "调用aria2c进行下载(你需要自行准备好二进制可执行文件)"),
                new Option <string>(
                    new string[] { "--aria2c-proxy" },
                    "调用aria2c进行下载时的代理地址配置"),
                new Option <bool>(
                    new string[] { "--multi-thread", "-mt" },
                    "使用多线程下载"),
                new Option <string>(
                    new string[] { "--select-page", "-p" },
                    "选择指定分p或分p范围:(-p 8 或 -p 1,2 或 -p 3-5 或 -p ALL)"),
                new Option <bool>(
                    new string[] { "--audio-only" },
                    "仅下载音频"),
                new Option <bool>(
                    new string[] { "--video-only" },
                    "仅下载视频"),
                new Option <bool>(
                    new string[] { "--sub-only" },
                    "仅下载字幕"),
                new Option <bool>(
                    new string[] { "--no-padding-page-num" },
                    "不给分P序号补零"),
                new Option <bool>(
                    new string[] { "--debug" },
                    "输出调试日志"),
                new Option <bool>(
                    new string[] { "--skip-mux" },
                    "跳过混流步骤"),
                new Option <bool>(
                    new string[] { "--skip-subtitle" },
                    "跳过字幕下载"),
                new Option <bool>(
                    new string[] { "--skip-cover" },
                    "跳过封面下载"),
                new Option <string>(
                    new string[] { "--language" },
                    "设置混流的音频语言(代码),如chi, jpn等"),
                new Option <string>(
                    new string[] { "--cookie", "-c" },
                    "设置字符串cookie用以下载网页接口的会员内容"),
                new Option <string>(
                    new string[] { "--access-token", "-token" },
                    "设置access_token用以下载TV/APP接口的会员内容"),
                new Option <string>(
                    new string[] { "--work-dir" },
                    "设置程序的工作目录"),
                new Option <string>(
                    new string[] { "--delay-per-page" },
                    "设置下载合集分P之间的下载间隔时间(单位: 秒, 默认无间隔)")
            };

            Command loginCommand = new Command(
                "login",
                "通过APP扫描二维码以登录您的WEB账号");

            rootCommand.AddCommand(loginCommand);
            Command loginTVCommand = new Command(
                "logintv",
                "通过APP扫描二维码以登录您的TV账号");

            rootCommand.AddCommand(loginTVCommand);
            rootCommand.Description = "BBDown是一个免费且便捷高效的哔哩哔哩下载/解析软件.";
            rootCommand.TreatUnmatchedTokensAsErrors = true;

            //WEB登录
            loginCommand.Handler = CommandHandler.Create(async delegate
            {
                try
                {
                    Log("获取登录地址...");
                    string loginUrl = "https://passport.bilibili.com/qrcode/getLoginUrl";
                    string url      = JsonDocument.Parse(await GetWebSourceAsync(loginUrl)).RootElement.GetProperty("data").GetProperty("url").ToString();
                    string oauthKey = GetQueryString("oauthKey", url);
                    //Log(oauthKey);
                    //Log(url);
                    bool flag = false;
                    Log("生成二维码...");
                    QRCodeGenerator qrGenerator = new QRCodeGenerator();
                    QRCodeData qrCodeData       = qrGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.Q);
                    QRCode qrCode      = new QRCode(qrCodeData);
                    Bitmap qrCodeImage = qrCode.GetGraphic(7);
                    qrCodeImage.Save("qrcode.png", System.Drawing.Imaging.ImageFormat.Png);
                    Log("生成二维码成功:qrcode.png, 请打开并扫描");
                    while (true)
                    {
                        await Task.Delay(1000);
                        string w    = await GetLoginStatusAsync(oauthKey);
                        string data = JsonDocument.Parse(w).RootElement.GetProperty("data").ToString();
                        if (data == "-2")
                        {
                            LogColor("二维码已过期, 请重新执行登录指令.");
                            break;
                        }
                        else if (data == "-4") //等待扫码
                        {
                            continue;
                        }
                        else if (data == "-5") //等待确认
                        {
                            if (!flag)
                            {
                                Log("扫码成功, 请确认...");
                                flag = !flag;
                            }
                        }
                        else
                        {
                            string cc = JsonDocument.Parse(w).RootElement.GetProperty("data").GetProperty("url").ToString();
                            Log("登录成功: SESSDATA=" + GetQueryString("SESSDATA", cc));
                            //导出cookie
                            File.WriteAllText(Path.Combine(APP_DIR, "BBDown.data"), cc.Substring(cc.IndexOf('?') + 1).Replace("&", ";"));
                            File.Delete("qrcode.png");
                            break;
                        }
                    }
                }
                catch (Exception e) { LogError(e.Message); }
            });

            //TV登录
            loginTVCommand.Handler = CommandHandler.Create(async delegate
            {
                try
                {
                    string loginUrl = "https://passport.snm0516.aisee.tv/x/passport-tv-login/qrcode/auth_code";
                    string pollUrl  = "https://passport.bilibili.com/x/passport-tv-login/qrcode/poll";
                    var parms       = GetTVLoginParms();
                    Log("获取登录地址...");
                    byte[] responseArray = await(await AppHttpClient.PostAsync(loginUrl, new FormUrlEncodedContent(parms.ToDictionary()))).Content.ReadAsByteArrayAsync();
                    string web           = Encoding.UTF8.GetString(responseArray);
                    string url           = JsonDocument.Parse(web).RootElement.GetProperty("data").GetProperty("url").ToString();
                    string authCode      = JsonDocument.Parse(web).RootElement.GetProperty("data").GetProperty("auth_code").ToString();
                    Log("生成二维码...");
                    QRCodeGenerator qrGenerator = new QRCodeGenerator();
                    QRCodeData qrCodeData       = qrGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.Q);
                    QRCode qrCode      = new QRCode(qrCodeData);
                    Bitmap qrCodeImage = qrCode.GetGraphic(7);
                    qrCodeImage.Save("qrcode.png", System.Drawing.Imaging.ImageFormat.Png);
                    Log("生成二维码成功:qrcode.png, 请打开并扫描");
                    parms.Set("auth_code", authCode);
                    parms.Set("ts", GetTimeStamp(true));
                    parms.Remove("sign");
                    parms.Add("sign", GetSign(ToQueryString(parms)));
                    while (true)
                    {
                        await Task.Delay(1000);
                        responseArray = await(await AppHttpClient.PostAsync(pollUrl, new FormUrlEncodedContent(parms.ToDictionary()))).Content.ReadAsByteArrayAsync();
                        web           = Encoding.UTF8.GetString(responseArray);
                        string code   = JsonDocument.Parse(web).RootElement.GetProperty("code").ToString();
                        if (code == "86038")
                        {
                            LogColor("二维码已过期, 请重新执行登录指令.");
                            break;
                        }
                        else if (code == "86039") //等待扫码
                        {
                            continue;
                        }
                        else
                        {
                            string cc = JsonDocument.Parse(web).RootElement.GetProperty("data").GetProperty("access_token").ToString();
                            Log("登录成功: AccessToken=" + cc);
                            //导出cookie
                            File.WriteAllText(Path.Combine(APP_DIR, "BBDownTV.data"), "access_token=" + cc);
                            File.Delete("qrcode.png");
                            break;
                        }
                    }
                }
                catch (Exception e) { LogError(e.Message); }
            });

            rootCommand.Handler = CommandHandler.Create <MyOption>(async(myOption) =>
            {
                await DoWorkAsync(myOption);
            });

            return(await rootCommand.InvokeAsync(args));
        }
Exemplo n.º 58
0
 public static void RegisterCommandHandler(string keyword, CommandHandler handler)
 {
     _commandHandlers[keyword] = handler;
 }
Exemplo n.º 59
0
        public static async Task <int> Main(string[] args)
        {
            /*args = new string[] {
             *  "-i", "Sprint_11945.xml",
             *  "-k", "900000,060005,020000"
             * };*/

            //Parsing Command Line Arguments
            RootCommand rootCommand = new RootCommand(
                description: "Convert xml content to html schema");
            Option inputOption = new Option(
                aliases: new string[] { "--input", "-i" }
                , description: "The path to the xml file to be converted.");

            inputOption.IsRequired = true;
            inputOption.Argument   = new Argument <string>();
            rootCommand.AddOption(inputOption);
            Option idsOption = new Option(
                aliases: new string[] { "--ids", "-k" }
                , description: "A list of selected key attribute ids to be extracted as single html files");

            idsOption.Argument   = new Argument <string>();
            idsOption.IsRequired = false;
            rootCommand.AddOption(idsOption);

            Option entryTagOption = new Option(
                aliases: new string[] { "--entrytag", "-t" }
                , description: "The tag of the Elements to be extracted from the document");

            entryTagOption.Argument   = new Argument <string>();
            entryTagOption.IsRequired = false;
            rootCommand.AddOption(entryTagOption);
            Option subSetAttKey = new Option(
                aliases: new string[] { "--subattkey", "-a" }
                , description: "The attribute key to be considered for list subset extraction using the specified ids");

            subSetAttKey.Argument   = new Argument <string>();
            subSetAttKey.IsRequired = false;
            rootCommand.AddOption(subSetAttKey);

            //IXmlHtmlConverter transformer = new Xml2HtmlTransformer();
            //IXmlHtmlConverter transformer = new Xml2HtmlTransformer("note", "ownerId");

            //Create Action for conversion and add console commands
            Action <string, string, string, string> performConversion = (string input, string ids, string entryTag, string subAttKey) =>
            {
                Console.WriteLine(input);
                Console.WriteLine(ids);

                IXmlHtmlConverter transformer = new Xml2HtmlTransformer(entryTag, subAttKey);

                transformer.ConvertXmlDoc2Html(input, ids);

                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            };

            rootCommand.Handler = CommandHandler.Create <string, string, string, string>(performConversion);

            //Pass args to commandline parser
            return(await rootCommand.InvokeAsync(args));
        }
Exemplo n.º 60
0
 static bool HandleLearnAllMyPetTalentsCommand(StringArguments args, CommandHandler handler)
 {
     return(true);
 }