void Init()
    {
        PlatformController currentPlatformController;
        GameObject configObject = GameObject.FindWithTag("config");
        GameObject currentPlatform, currentAIController;
        Vector3 currentPlatformPosition;
        float currentAngle = 0;
        int numEnemies = 1;
        int difficulty = 1;
        int numPlatforms = 1;

        if (configObject) {
            cfgHandler = GameObject.FindWithTag("config").GetComponent<ConfigHandler>();
        }

        if (cfgHandler) {
            if (cfgHandler.numEnemies > 0) {
                numEnemies = cfgHandler.numEnemies;
            }
            if (cfgHandler.difficulty > 0) {
                difficulty = cfgHandler.difficulty;
            }
        }

        int[] cells = cfgHandler.platformIdentities[0];
        platformDistance = Mathf.Sqrt(cells.Length) * 64;

        numPlatforms += numEnemies;
        platforms = new PlatformController[numPlatforms];

        for (int i = 0; i < numPlatforms; i++) {
            currentPlatformPosition = new Vector3(platformDistance * Mathf.Cos(currentAngle), platformDistance * Mathf.Sin(currentAngle), 0);

            currentPlatform = Instantiate(platformPrefab, currentPlatformPosition, Quaternion.identity) as GameObject;
            currentPlatformController = currentPlatform.GetComponent<PlatformController>();
            currentAngle += (2 * Mathf.PI) / numPlatforms;
            platforms[i] = currentPlatformController;

            currentPlatformController.team = i;
            currentPlatformController.owner = i;
            currentPlatformController.isPlayer = (i == 0) ? true : false;

            if (i == 0) {
                uiHandler.playerPlatform = currentPlatformController;
                currentPlatformController.uiHandler = uiHandler;
            } else {
                currentAIController = Instantiate(aiControllerPrefab, currentPlatformPosition, Quaternion.identity) as GameObject;
                currentAIController.SendMessage("InitializeAI", currentPlatformController);
            }

            currentPlatformController.SendMessage("Construct", cells);
        }

        for (int i = 0; i < numPlatforms; i++) {
            platforms[i].GetComponent<PlatformController>().RetargetPlatform();
        }
    }
Exemple #2
0
        /// <summary>
        /// the subscription update process
        /// </summary>
        private void UpdateSubscriptionProcess()
        {
            AppendText(false, UIRes.I18N("MsgUpdateSubscriptionStart"));

            if (config.subItem == null || config.subItem.Count <= 0)
            {
                AppendText(false, UIRes.I18N("MsgNoValidSubscription"));
                return;
            }

            for (int k = 1; k <= config.subItem.Count; k++)
            {
                string id       = config.subItem[k - 1].id.TrimEx();
                string url      = config.subItem[k - 1].url.TrimEx();
                string hashCode = $"{k}->";
                if (config.subItem[k - 1].enabled == false)
                {
                    continue;
                }
                if (Utils.IsNullOrEmpty(id) || Utils.IsNullOrEmpty(url))
                {
                    AppendText(false, $"{hashCode}{UIRes.I18N("MsgNoValidSubscription")}");
                    continue;
                }

                DownloadHandle downloadHandle3 = new DownloadHandle();
                downloadHandle3.UpdateCompleted += (sender2, args) =>
                {
                    if (args.Success)
                    {
                        AppendText(false, $"{hashCode}{UIRes.I18N("MsgGetSubscriptionSuccessfully")}");
                        string result = Utils.Base64Decode(args.Msg);
                        if (Utils.IsNullOrEmpty(result))
                        {
                            AppendText(false, $"{hashCode}{UIRes.I18N("MsgSubscriptionDecodingFailed")}");
                            return;
                        }

                        ConfigHandler.RemoveServerViaSubid(ref config, id);
                        AppendText(false, $"{hashCode}{UIRes.I18N("MsgClearSubscription")}");
                        RefreshServers();
                        int ret = MainFormHandler.Instance.AddBatchServers(config, result, id);
                        if (ret > 0)
                        {
                            RefreshServers();
                        }
                        else
                        {
                            AppendText(false, $"{hashCode}{UIRes.I18N("MsgFailedImportSubscription")}");
                        }
                        AppendText(false, $"{hashCode}{UIRes.I18N("MsgUpdateSubscriptionEnd")}");
                    }
                    else
                    {
                        AppendText(false, args.Msg);
                    }
                };
                downloadHandle3.Error += (sender2, args) =>
                {
                    AppendText(true, args.GetException().Message);
                };

                downloadHandle3.WebDownloadString(url);
                AppendText(false, $"{hashCode}{UIRes.I18N("MsgStartGettingSubscriptions")}");
            }
        }
Exemple #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EarlyQuit"/> class.
 /// </summary>
 /// <param name="sst">The main class.</param>
 public EarlyQuit(SynServerTool sst)
 {
     _sst           = sst;
     _configHandler = new ConfigHandler();
     LoadConfig();
 }
Exemple #4
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            #region DEBUG初始化
            //debug
            logHandler = new LogHandler(true);
            AggregateExceptionCatched += (a, b) => logHandler.AppendFatal(b.AggregateException);
            if (e.Args.Contains("-debug"))
            {
                Windows.DebugWindow debugWindow = new Windows.DebugWindow();
                debugWindow.Show();
                logHandler.OnLog += (s, log) => debugWindow?.AppendLog(s, log);
            }
            #endregion

            config = new ConfigHandler();

            #region DEBUG初始化(基于配置文件)
            if (config.MainConfig.Launcher.Debug && !e.Args.Contains("-debug"))
            {
                Windows.DebugWindow debugWindow = new Windows.DebugWindow();
                debugWindow.Show();
                logHandler.OnLog += (s, log) => debugWindow?.AppendLog(s, log);
            }
            #endregion

            #region MineRealms反馈API初始化

#if DEBUG
            MineRealmsAPIHandler = new MineRealmsLauncherCore.Net.PhalAPI.APIHandler(true);
#else
            MineRealmsAPIHandler = new MineRealmsLauncherCore.Net.PhalAPI.APIHandler(config.MainConfig.Launcher.NoTracking);
#endif

            #endregion

            #region 数据初始化
            Config.Environment env = config.MainConfig.Environment;

            javaList = Java.GetJavaList();

            //设置版本路径
            string gameroot = null;
            switch (env.GamePathType)
            {
            case GameDirEnum.ROOT:
                gameroot = Path.GetFullPath(".minecraft");
                break;

            case GameDirEnum.APPDATA:
                gameroot = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\.minecraft";
                break;

            case GameDirEnum.PROGRAMFILES:
                gameroot = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) + "\\.minecraft";
                break;

            case GameDirEnum.CUSTOM:
                gameroot = env.GamePath + "\\.minecraft";
                break;

            default:
                throw new ArgumentException("判断游戏目录类型时出现异常,请检查配置文件中GamePathType节点");
            }
            logHandler.AppendInfo("核心初始化->游戏根目录(默认则为空):" + gameroot);

            //设置JAVA
            Java java = null;
            if (env.AutoJava)
            {
                java = Java.GetSuitableJava(javaList);
            }
            else
            {
                java = javaList.Find(x => x.Path == env.JavaPath);
                if (java == null)
                {
                    java = Java.GetJavaInfo(env.JavaPath);
                }
            }
            if (java != null)
            {
                env.JavaPath = java.Path;
                logHandler.AppendInfo("核心初始化->Java路径:" + java.Path);
                logHandler.AppendInfo("核心初始化->Java版本:" + java.Version);
                logHandler.AppendInfo("核心初始化->Java位数:" + java.Arch);
            }
            else
            {
                logHandler.AppendWarn("核心初始化失败,当前电脑未匹配到JAVA");
            }

            //设置版本独立
            bool verIso = config.MainConfig.Environment.VersionIsolation;
            #endregion

            #region 启动核心初始化
            handler          = new LaunchHandler(gameroot, java, verIso);
            handler.GameLog += (s, log) => logHandler.AppendLog(s, new Log()
            {
                LogLevel = LogLevel.GAME, Message = log
            });
            handler.LaunchLog += (s, log) => logHandler.AppendLog(s, log);
            #endregion

            #region  载核心初始化
            ServicePointManager.DefaultConnectionLimit = 10;

            Download downloadCfg = config.MainConfig.Download;
            downloader = new MultiThreadDownloader();
            if (!string.IsNullOrWhiteSpace(downloadCfg.DownloadProxyAddress))
            {
                WebProxy proxy = new WebProxy(downloadCfg.DownloadProxyAddress, downloadCfg.DownloadProxyPort);
                if (!string.IsNullOrWhiteSpace(downloadCfg.ProxyUserName))
                {
                    NetworkCredential credential = new NetworkCredential(downloadCfg.ProxyUserName, downloadCfg.ProxyUserPassword);
                    proxy.Credentials = credential;
                }
                downloader.Proxy = proxy;
            }
            downloader.ProcessorSize = App.config.MainConfig.Download.DownloadThreadsSize;
            downloader.CheckFileHash = App.config.MainConfig.Download.CheckDownloadFileHash;
            downloader.DownloadLog  += (s, log) => logHandler?.AppendLog(s, log);
            #endregion

            #region 自定义主题初始化
            var custom = config.MainConfig.Customize;
            if (!string.IsNullOrWhiteSpace(custom.AccentColor) && !string.IsNullOrWhiteSpace(custom.AppThme))
            {
                logHandler.AppendInfo("自定义->更改主题颜色:" + custom.AccentColor);
                logHandler.AppendInfo("自定义->更改主题:" + custom.AppThme);
                ThemeManager.ChangeAppStyle(Current, ThemeManager.GetAccent(custom.AccentColor), ThemeManager.GetAppTheme(custom.AppThme));
            }
            #endregion
        }
Exemple #5
0
 private static string GetDesktopApplication()
 {
     return(ConfigHandler.GetValue("ConfigurationModuleWpfAppLocation"));
 }
        /// <summary>
        /// html编辑器配置
        /// </summary>
        public void UeditorConfig()
        {
            Handler action = null;

            switch (Request["action"])
            {
            case "config":
                action = new ConfigHandler(this);
                break;

            case "uploadimage":
                action = new UploadHandler(this, new UploadConfig()
                {
                    AllowExtensions = Config.GetStringList("imageAllowFiles"),
                    PathFormat      = Config.GetString("imagePathFormat"),
                    SizeLimit       = Config.GetInt("imageMaxSize"),
                    UploadFieldName = Config.GetString("imageFieldName")
                });
                break;

            case "uploadscrawl":
                action = new UploadHandler(this, new UploadConfig()
                {
                    AllowExtensions = new string[] { ".png" },
                    PathFormat      = Config.GetString("scrawlPathFormat"),
                    SizeLimit       = Config.GetInt("scrawlMaxSize"),
                    UploadFieldName = Config.GetString("scrawlFieldName"),
                    Base64          = true,
                    Base64Filename  = "scrawl.png"
                });
                break;

            case "uploadvideo":
                action = new UploadHandler(this, new UploadConfig()
                {
                    AllowExtensions = Config.GetStringList("videoAllowFiles"),
                    PathFormat      = Config.GetString("videoPathFormat"),
                    SizeLimit       = Config.GetInt("videoMaxSize"),
                    UploadFieldName = Config.GetString("videoFieldName")
                });
                break;

            case "uploadfile":
                action = new UploadHandler(this, new UploadConfig()
                {
                    AllowExtensions = Config.GetStringList("fileAllowFiles"),
                    PathFormat      = Config.GetString("filePathFormat"),
                    SizeLimit       = Config.GetInt("fileMaxSize"),
                    UploadFieldName = Config.GetString("fileFieldName")
                });
                break;

            case "listimage":
                action = new ListFileManager(this, Config.GetString("imageManagerListPath"), Config.GetStringList("imageManagerAllowFiles"));
                break;

            case "listfile":
                action = new ListFileManager(this, Config.GetString("fileManagerListPath"), Config.GetStringList("fileManagerAllowFiles"));
                break;

            case "catchimage":
                action = new CrawlerHandler(this);
                break;

            default:
                action = new NotSupportedHandler(this);
                break;
            }
            action.Process();
        }
        public void ProcessRequest(HttpContext context)
        {
            UserInfoOutputDto user = context.Session.GetByRedis <UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto();

            if (user.IsAdmin)
            {
                Handler action = new NotSupportedHandler(context);
                switch (context.Request["action"])
                {
                case "config":
                    action = new ConfigHandler(context);
                    break;

                case "uploadimage":
                    action = new UploadHandler(context, new UploadConfig()
                    {
                        AllowExtensions = Config.GetStringList("imageAllowFiles"),
                        PathFormat      = Config.GetString("imagePathFormat"),
                        SizeLimit       = Config.GetInt("imageMaxSize"),
                        UploadFieldName = Config.GetString("imageFieldName")
                    });
                    break;

                case "uploadscrawl":
                    action = new UploadHandler(context, new UploadConfig()
                    {
                        AllowExtensions = new string[] { ".png" },
                        PathFormat      = Config.GetString("scrawlPathFormat"),
                        SizeLimit       = Config.GetInt("scrawlMaxSize"),
                        UploadFieldName = Config.GetString("scrawlFieldName"),
                        Base64          = true,
                        Base64Filename  = "scrawl.png"
                    });
                    break;

                case "uploadvideo":
                    action = new UploadHandler(context, new UploadConfig()
                    {
                        AllowExtensions = Config.GetStringList("videoAllowFiles"),
                        PathFormat      = Config.GetString("videoPathFormat"),
                        SizeLimit       = Config.GetInt("videoMaxSize"),
                        UploadFieldName = Config.GetString("videoFieldName")
                    });
                    break;

                case "uploadfile":
                    action = new UploadHandler(context, new UploadConfig()
                    {
                        AllowExtensions = Config.GetStringList("fileAllowFiles"),
                        PathFormat      = Config.GetString("filePathFormat"),
                        SizeLimit       = Config.GetInt("fileMaxSize"),
                        UploadFieldName = Config.GetString("fileFieldName")
                    });
                    break;

                case "listimage":
                    action = new ListFileManager(context, Config.GetString("imageManagerListPath"), Config.GetStringList("imageManagerAllowFiles"));
                    break;

                case "listfile":
                    action = new ListFileManager(context, Config.GetString("fileManagerListPath"), Config.GetStringList("fileManagerAllowFiles"));
                    break;

                case "catchimage":
                    action = new CrawlerHandler(context);
                    break;
                }
                action.Process();
            }
        }
Exemple #8
0
 public EventHelper(Random random, GuildHelper GH, DiscordSocketClient client, ConfigHandler CH,
                    MethodHelper MH, WebhookService WS)
 {
     Client           = client;
     Random           = random;
     GuildHelper      = GH;
     ConfigHandler    = CH;
     MethodHelper     = MH;
     WebhookService   = WS;
     XPUserList       = new Dictionary <ulong, DateTime>();
     CleverbotTracker = new Dictionary <ulong, Response>();
 }
Exemple #9
0
        public ActionResult FileUploader()
        {
            HttpContext context = System.Web.HttpContext.Current;
            Handler     action  = new NotSupportedHandler(context);

            switch (Request["action"])//管理员用
            {
            case "config":
                action = new ConfigHandler(context);
                break;

            case "uploadimage":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = UeditorConfig.GetStringList("imageAllowFiles"),
                    PathFormat      = UeditorConfig.GetString("imagePathFormat"),
                    SizeLimit       = UeditorConfig.GetInt("imageMaxSize"),
                    UploadFieldName = UeditorConfig.GetString("imageFieldName")
                });
                break;

            case "uploadscrawl":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = new[] { ".png" },
                    PathFormat      = UeditorConfig.GetString("scrawlPathFormat"),
                    SizeLimit       = UeditorConfig.GetInt("scrawlMaxSize"),
                    UploadFieldName = UeditorConfig.GetString("scrawlFieldName"),
                    Base64          = true,
                    Base64Filename  = "scrawl.png"
                });
                break;

            case "catchimage":
                action = new CrawlerHandler(context);
                break;

            case "uploadvideo":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = UeditorConfig.GetStringList("videoAllowFiles"),
                    PathFormat      = UeditorConfig.GetString("videoPathFormat"),
                    SizeLimit       = UeditorConfig.GetInt("videoMaxSize"),
                    UploadFieldName = UeditorConfig.GetString("videoFieldName")
                });
                break;

            case "uploadfile":
                action = new UploadHandler(context, new UploadConfig()
                {
                    AllowExtensions = UeditorConfig.GetStringList("fileAllowFiles"),
                    PathFormat      = UeditorConfig.GetString("filePathFormat"),
                    SizeLimit       = UeditorConfig.GetInt("fileMaxSize"),
                    UploadFieldName = UeditorConfig.GetString("fileFieldName")
                });
                break;

            case "listimage":
                action = new ListFileManager(context, UeditorConfig.GetString("imageManagerListPath"), UeditorConfig.GetStringList("imageManagerAllowFiles"));
                break;

            case "listfile":
                action = new ListFileManager(context, UeditorConfig.GetString("fileManagerListPath"), UeditorConfig.GetStringList("fileManagerAllowFiles"));
                break;
            }
            #region 用户通用方法
            //switch (Request["action"])//通用
            //{
            //    case "config":
            //        action = new ConfigHandler(context);
            //        break;
            //    case "uploadimage":
            //        action = new UploadHandler(context, new UploadConfig()
            //        {
            //            AllowExtensions = UeditorConfig.GetStringList("imageAllowFiles"),
            //            PathFormat = UeditorConfig.GetString("imagePathFormat"),
            //            SizeLimit = UeditorConfig.GetInt("imageMaxSize"),
            //            UploadFieldName = UeditorConfig.GetString("imageFieldName")
            //        });
            //        break;
            //    case "uploadscrawl":
            //        action = new UploadHandler(context, new UploadConfig()
            //        {
            //            AllowExtensions = new[] { ".png" },
            //            PathFormat = UeditorConfig.GetString("scrawlPathFormat"),
            //            SizeLimit = UeditorConfig.GetInt("scrawlMaxSize"),
            //            UploadFieldName = UeditorConfig.GetString("scrawlFieldName"),
            //            Base64 = true,
            //            Base64Filename = "scrawl.png"
            //        });
            //        break;
            //    case "catchimage":
            //        action = new CrawlerHandler(context);
            //        break;
            //}
            #endregion
            #region 管理员权限使用方法
            //UserInfoOutputDto user = HttpContext.Session.GetByRedis<UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto();
            //if (user.IsAdmin)
            //{
            //    switch (Request["action"])//管理员用
            //    {
            //        case "uploadvideo":
            //            action = new UploadHandler(context, new UploadConfig()
            //            {
            //                AllowExtensions = UeditorConfig.GetStringList("videoAllowFiles"),
            //                PathFormat = UeditorConfig.GetString("videoPathFormat"),
            //                SizeLimit = UeditorConfig.GetInt("videoMaxSize"),
            //                UploadFieldName = UeditorConfig.GetString("videoFieldName")
            //            });
            //            break;
            //        case "uploadfile":
            //            action = new UploadHandler(context, new UploadConfig()
            //            {
            //                AllowExtensions = UeditorConfig.GetStringList("fileAllowFiles"),
            //                PathFormat = UeditorConfig.GetString("filePathFormat"),
            //                SizeLimit = UeditorConfig.GetInt("fileMaxSize"),
            //                UploadFieldName = UeditorConfig.GetString("fileFieldName")
            //            });
            //            break;
            //        case "listimage":
            //            action = new ListFileManager(context, UeditorConfig.GetString("imageManagerListPath"), UeditorConfig.GetStringList("imageManagerAllowFiles"));
            //            break;
            //        case "listfile":
            //            action = new ListFileManager(context, UeditorConfig.GetString("fileManagerListPath"), UeditorConfig.GetStringList("fileManagerAllowFiles"));
            //            break;
            //    }
            //}
            #endregion
            string result = action.Process();
            return(Content(result, ContentType.Json, Encoding.UTF8));
        }
 private static string GetDataFromResourceFile(string keyName)
 {
     return(new ResXConfigHandler(ConfigHandler.GetValue("ControlIdentifiersFile")).GetValue(keyName));
 }
Exemple #11
0
 /// <summary>
 /// save current connect information to log
 /// </summary>
 public void Save()
 {
     ConfigHandler.LoadConnLog().AddConnLogRow("MsSql_UP", _server, _username, _password, "", DateTime.Now);
     ConfigHandler.SaveConnLog();
 }
        protected virtual void DownloadManifestEntry(ManifestEntry Entry, EModule Module)
        {
            ModuleDownloadProgressArgs.Module = Module;

            string baseRemoteURL;
            string baseLocalPath;

            switch (Module)
            {
            case EModule.Launcher:
            {
                baseRemoteURL = Config.GetLauncherBinariesURL();
                baseLocalPath = ConfigHandler.GetTempLauncherDownloadPath();
                break;
            }

            case EModule.Game:
            {
                baseRemoteURL = Config.GetGameURL();
                baseLocalPath = Config.GetGamePath();
                break;
            }

            default:
            {
                throw new ArgumentOutOfRangeException(nameof(Module), Module, "The module passed to DownloadManifestEntry was invalid.");
            }
            }

            // Build the access strings
            string remoteURL = $"{baseRemoteURL}{Entry.RelativePath}";
            string localPath = $"{baseLocalPath}{Path.DirectorySeparatorChar}{Entry.RelativePath}";

            // Make sure we have a directory to put the file in
            if (Path.GetDirectoryName(localPath) != null)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(localPath));
            }
            else
            {
                throw new ArgumentNullException(nameof(localPath), "The local path was null.");
            }

            // Reset the cookie
            File.WriteAllText(ConfigHandler.GetInstallCookiePath(), string.Empty);

            // Write the current file progress to the install cookie
            using (TextWriter textWriterProgress = new StreamWriter(ConfigHandler.GetInstallCookiePath()))
            {
                textWriterProgress.WriteLine(Entry);
                textWriterProgress.Flush();
            }

            if (File.Exists(localPath))
            {
                FileInfo fileInfo = new FileInfo(localPath);
                if (fileInfo.Length != Entry.Size)
                {
                    // If the file is partial, resume the download.
                    if (fileInfo.Length < Entry.Size)
                    {
                        Log.Info($"Resuming interrupted file \"{Path.GetFileNameWithoutExtension(Entry.RelativePath)}\" at byte {fileInfo.Length}.");
                        DownloadRemoteFile(remoteURL, localPath, Entry.Size, fileInfo.Length);
                    }
                    else
                    {
                        // If it's larger than expected, toss it in the bin and try again.
                        Log.Info($"Restarting interrupted file \"{Path.GetFileNameWithoutExtension(Entry.RelativePath)}\": File bigger than expected.");

                        File.Delete(localPath);
                        DownloadRemoteFile(remoteURL, localPath, Entry.Size);
                    }
                }
                else
                {
                    string localHash;
                    using (FileStream fs = File.OpenRead(localPath))
                    {
                        localHash = MD5Handler.GetStreamHash(fs);
                    }

                    if (localHash != Entry.Hash)
                    {
                        // If the hash doesn't match, toss it in the bin and try again.
                        Log.Info($"Redownloading file \"{Path.GetFileNameWithoutExtension(Entry.RelativePath)}\": " +
                                 $"Hash sum mismatch. Local: {localHash}, Expected: {Entry.Hash}");

                        File.Delete(localPath);
                        DownloadRemoteFile(remoteURL, localPath, Entry.Size);
                    }
                }
            }
            else
            {
                // No file, download it
                DownloadRemoteFile(remoteURL, localPath, Entry.Size);
            }

            if (ChecksHandler.IsRunningOnUnix())
            {
                // If we're dealing with a file that should be executable,
                string gameName = Config.GetGameName();
                bool   bFileIsGameExecutable = (Path.GetFileName(localPath).EndsWith(".exe")) || (Path.GetFileName(localPath) == gameName);
                if (bFileIsGameExecutable)
                {
                    // Set the execute bits
                    UnixHandler.MakeExecutable(localPath);
                }
            }

            // We've finished the download, so empty the cookie
            File.WriteAllText(ConfigHandler.GetInstallCookiePath(), string.Empty);
        }
        protected override void DownloadModule(EModule Module)
        {
            List <ManifestEntry> moduleManifest;

            switch (Module)
            {
            case EModule.Launcher:
            {
                RefreshModuleManifest(EModule.Launcher);


                ModuleInstallFinishedArgs.Module = EModule.Launcher;
                ModuleInstallFailedArgs.Module   = EModule.Launcher;
                moduleManifest = Manifest.LaunchpadManifest;
                break;
            }

            case EModule.Game:
            {
                RefreshModuleManifest(EModule.Game);


                ModuleInstallFinishedArgs.Module = EModule.Game;
                ModuleInstallFailedArgs.Module   = EModule.Game;
                moduleManifest = Manifest.GameManifest;
                break;
            }

            default:
            {
                throw new ArgumentOutOfRangeException(nameof(Module), Module, null);
            }
            }

            // In order to be able to resume downloading, we check if there is an entry
            // stored in the install cookie.

            // Attempt to parse whatever is inside the install cookie
            ManifestEntry lastDownloadedFile;

            if (ManifestEntry.TryParse(File.ReadAllText(ConfigHandler.GetInstallCookiePath()), out lastDownloadedFile))
            {
                // Loop through all the entries in the manifest until we encounter
                // an entry which matches the one in the install cookie

                foreach (ManifestEntry Entry in moduleManifest)
                {
                    if (lastDownloadedFile == Entry)
                    {
                        // Remove all entries before the one we were last at.
                        moduleManifest.RemoveRange(0, moduleManifest.IndexOf(Entry));
                    }
                }
            }

            int downloadedFiles = 0;

            foreach (ManifestEntry Entry in moduleManifest)
            {
                ++downloadedFiles;

                // Prepare the progress event contents
                ModuleDownloadProgressArgs.IndicatorLabelMessage = GetDownloadIndicatorLabelMessage(downloadedFiles, Path.GetFileName(Entry.RelativePath), moduleManifest.Count);
                OnModuleDownloadProgressChanged();

                DownloadManifestEntry(Entry, Module);
            }
        }
 public override string GetDataFilePath()
 {
     return(ConfigHandler.GetValue("OrderProcessingFile"));
 }
 private static string GetBrowserTitle()
 {
     return(new ResXConfigHandler(ConfigHandler.GetValue("ControlIdentifiersFile")).GetValue("SilverlightAppTitleRemoteModule"));
 }
 private static string GetSilverlightApplicationHostPath()
 {
     return(ConfigHandler.GetValue("RemoteModuleSilverlightAppHostRelativeLocation"));
 }
        /// <summary>
        /// Downloads the provided manifest entry.
        /// This function resumes incomplete files, verifies downloaded files and
        /// downloads missing files.
        /// </summary>
        /// <param name="Entry">The entry to download.</param>
        /// <param name="Module">The module to download the file for. Determines download location.</param>
        private void DownloadEntry(ManifestEntry Entry, EModule Module)
        {
            ModuleDownloadProgressArgs.Module = Module;

            string baseRemotePath;
            string baseLocalPath;

            if (Module == EModule.Game)
            {
                baseRemotePath = Config.GetGameURL();
                baseLocalPath  = Config.GetGamePath();
            }
            else
            {
                baseRemotePath = Config.GetLauncherBinariesURL();
                baseLocalPath  = ConfigHandler.GetTempLauncherDownloadPath();
            }

            string RemotePath = String.Format("{0}{1}",
                                              baseRemotePath,
                                              Entry.RelativePath);

            string LocalPath = String.Format("{0}{1}{2}",
                                             baseLocalPath,
                                             Path.DirectorySeparatorChar,
                                             Entry.RelativePath);

            // Make sure we have a directory to put the file in
            Directory.CreateDirectory(Path.GetDirectoryName(LocalPath));

            // Reset the cookie
            File.WriteAllText(ConfigHandler.GetInstallCookiePath(), String.Empty);

            // Write the current file progress to the install cookie
            using (TextWriter textWriterProgress = new StreamWriter(ConfigHandler.GetInstallCookiePath()))
            {
                textWriterProgress.WriteLine(Entry);
                textWriterProgress.Flush();
            }

            if (File.Exists(LocalPath))
            {
                FileInfo fileInfo = new FileInfo(LocalPath);
                if (fileInfo.Length != Entry.Size)
                {
                    // If the file is partial, resume the download.
                    if (fileInfo.Length < Entry.Size)
                    {
                        DownloadRemoteFile(RemotePath, LocalPath, fileInfo.Length);
                    }
                    else
                    {
                        // If it's larger than expected, toss it in the bin and try again.
                        File.Delete(LocalPath);
                        DownloadRemoteFile(RemotePath, LocalPath);
                    }
                }
                else
                {
                    string LocalHash;
                    using (FileStream fs = File.OpenRead(LocalPath))
                    {
                        LocalHash = MD5Handler.GetStreamHash(fs);
                    }

                    if (LocalHash != Entry.Hash)
                    {
                        File.Delete(LocalPath);
                        DownloadRemoteFile(RemotePath, LocalPath);
                    }
                }
            }
            else
            {
                //no file, download it
                DownloadRemoteFile(RemotePath, LocalPath);
            }

            if (ChecksHandler.IsRunningOnUnix())
            {
                //if we're dealing with a file that should be executable,
                string gameName = Config.GetGameName();
                bool   bFileIsGameExecutable = (Path.GetFileName(LocalPath).EndsWith(".exe")) || (Path.GetFileName(LocalPath) == gameName);
                if (bFileIsGameExecutable)
                {
                    //set the execute bits
                    UnixHandler.MakeExecutable(LocalPath);
                }
            }

            // We've finished the download, so empty the cookie
            File.WriteAllText(ConfigHandler.GetInstallCookiePath(), String.Empty);
        }
Exemple #18
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            string remarks = txtRemarks.Text;
            string address = txtAddress.Text;
            string port    = txtPort.Text;

            string id       = string.Empty;
            string alterId  = string.Empty;
            string security = string.Empty;
            string flow     = string.Empty;

            switch (eConfigType)
            {
            case EConfigType.Vmess:
                id       = txtId.Text;
                alterId  = txtAlterId.Text;
                security = cmbSecurity.Text;
                break;

            case EConfigType.Shadowsocks:
                id       = txtId3.Text;
                security = cmbSecurity3.Text;
                break;

            case EConfigType.Socks:
                id       = txtId4.Text;
                security = txtSecurity4.Text;
                break;

            case EConfigType.VLESS:
                id       = txtId5.Text;
                flow     = cmbFlow5.Text;
                security = cmbSecurity5.Text;
                break;

            case EConfigType.Trojan:
                id   = txtId6.Text;
                flow = cmbFlow6.Text;
                break;
            }

            if (Utils.IsNullOrEmpty(address))
            {
                UI.Show(UIRes.I18N("FillServerAddress"));
                return;
            }
            if (Utils.IsNullOrEmpty(port) || !Utils.IsNumberic(port))
            {
                UI.Show(UIRes.I18N("FillCorrectServerPort"));
                return;
            }
            if (eConfigType == EConfigType.Shadowsocks)
            {
                if (Utils.IsNullOrEmpty(id))
                {
                    UI.Show(UIRes.I18N("FillPassword"));
                    return;
                }
                if (Utils.IsNullOrEmpty(security))
                {
                    UI.Show(UIRes.I18N("PleaseSelectEncryption"));
                    return;
                }
            }
            if (eConfigType != EConfigType.Socks)
            {
                if (Utils.IsNullOrEmpty(id))
                {
                    UI.Show(UIRes.I18N("FillUUID"));
                    return;
                }
            }

            transportControl.EndBindingServer();

            vmessItem.remarks  = remarks;
            vmessItem.address  = address;
            vmessItem.port     = Utils.ToInt(port);
            vmessItem.id       = id;
            vmessItem.alterId  = Utils.ToInt(alterId);
            vmessItem.security = security;

            if (Utils.IsNullOrEmpty(cmbCoreType.Text))
            {
                vmessItem.coreType = null;
            }
            else
            {
                vmessItem.coreType = (ECoreType)Enum.Parse(typeof(ECoreType), cmbCoreType.Text);
            }

            int ret = -1;

            switch (eConfigType)
            {
            case EConfigType.Vmess:
                ret = ConfigHandler.AddServer(ref config, vmessItem);
                break;

            case EConfigType.Shadowsocks:
                ret = ConfigHandler.AddShadowsocksServer(ref config, vmessItem);
                break;

            case EConfigType.Socks:
                ret = ConfigHandler.AddSocksServer(ref config, vmessItem);
                break;

            case EConfigType.VLESS:
                vmessItem.flow = flow;
                ret            = ConfigHandler.AddVlessServer(ref config, vmessItem);
                break;

            case EConfigType.Trojan:
                vmessItem.flow = flow;
                ret            = ConfigHandler.AddTrojanServer(ref config, vmessItem);
                break;
            }

            if (ret == 0)
            {
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                UI.ShowWarning(UIRes.I18N("OperationFailed"));
            }
        }
Exemple #19
0
 public EventHelper(Random random, GuildHelper guildHelper, DiscordSocketClient client, ConfigHandler configHandler)
 {
     Client        = client;
     Random        = random;
     GuildHelper   = guildHelper;
     ConfigHandler = configHandler;
 }
 private static string GetDesktopApplicationTitle()
 {
     return(new ResXConfigHandler(ConfigHandler.GetValue("ControlIdentifiersFile")).GetValue("DesktopApplicationTitle"));
 }
Exemple #21
0
        public void Main(int siteId)
        {
            var queryString = HttpContext.Current.Request.QueryString;

            Handler action;

            switch (queryString["action"])
            {
            case "config":
                action = new ConfigHandler(HttpContext.Current);
                break;

            case "uploadimage":
                action = new UploadHandler(HttpContext.Current, new UploadConfig
                {
                    AllowExtensions = Config.GetStringList("imageAllowFiles"),
                    PathFormat      = Config.GetString("imagePathFormat"),
                    SizeLimit       = Config.GetInt("imageMaxSize"),
                    UploadFieldName = Config.GetString("imageFieldName")
                }, siteId, EUploadType.Image);
                break;

            case "uploadscrawl":
                action = new UploadHandler(HttpContext.Current, new UploadConfig
                {
                    AllowExtensions = new[] { ".png" },
                    PathFormat      = Config.GetString("scrawlPathFormat"),
                    SizeLimit       = Config.GetInt("scrawlMaxSize"),
                    UploadFieldName = Config.GetString("scrawlFieldName"),
                    Base64          = true,
                    Base64Filename  = "scrawl.png"
                }, siteId, EUploadType.Image);
                break;

            case "uploadvideo":
                action = new UploadHandler(HttpContext.Current, new UploadConfig
                {
                    AllowExtensions = Config.GetStringList("videoAllowFiles"),
                    PathFormat      = Config.GetString("videoPathFormat"),
                    SizeLimit       = Config.GetInt("videoMaxSize"),
                    UploadFieldName = Config.GetString("videoFieldName")
                }, siteId, EUploadType.Video);
                break;

            case "uploadfile":
                action = new UploadHandler(HttpContext.Current, new UploadConfig
                {
                    AllowExtensions = Config.GetStringList("fileAllowFiles"),
                    PathFormat      = Config.GetString("filePathFormat"),
                    SizeLimit       = Config.GetInt("fileMaxSize"),
                    UploadFieldName = Config.GetString("fileFieldName")
                }, siteId, EUploadType.File);
                break;

            case "listimage":
                action = new ListFileManager(HttpContext.Current, Config.GetString("imageManagerListPath"), Config.GetStringList("imageManagerAllowFiles"), siteId, EUploadType.Image);
                break;

            case "listfile":
                action = new ListFileManager(HttpContext.Current, Config.GetString("fileManagerListPath"), Config.GetStringList("fileManagerAllowFiles"), siteId, EUploadType.File);
                break;

            case "catchimage":
                action = new CrawlerHandler(HttpContext.Current, siteId);
                break;

            default:
                action = new NotSupportedHandler(HttpContext.Current);
                break;
            }
            action.Process();
        }
        //[Ignore]
        public void DesktopModulesLoadedOnStartup()
        {
            AutomationElement aeModuleA = ModularityPage <WpfAppLauncher> .ModuleA;

            Thread.Sleep(1000);
            AutomationElement aeClickToloadModuleA = aeModuleA.FindElementByContent(new ResXConfigHandler(ConfigHandler.GetValue("ControlIdentifiersFile")).GetValue("ClickToLoadTextBlock"));

            Assert.IsTrue(aeClickToloadModuleA.Current.IsOffscreen, "Module A is not initialized at startup");

            AutomationElement aeModuleD            = ModularityPage <WpfAppLauncher> .ModuleD;
            AutomationElement aeClickToloadModuleD = aeModuleD.FindElementByContent(new ResXConfigHandler(ConfigHandler.GetValue("ControlIdentifiersFile")).GetValue("ClickToLoadTextBlock"));

            Assert.IsTrue(aeClickToloadModuleD.Current.IsOffscreen, "Module D is not initialized at startup");
        }
Exemple #23
0
 private static string GetDesktopApplicationProcess()
 {
     return(ConfigHandler.GetValue("ConfigurationModuleWpfAppProcessName"));
 }
        //[Ignore]
        public void DesktopLoadModuleBOnDemand()
        {
            //Check if Module B is already loaded
            AutomationElement aeModuleB            = ModularityPage <WpfAppLauncher> .ModuleB;
            AutomationElement aeClickToloadModuleB = aeModuleB.FindElementByContent(new ResXConfigHandler(ConfigHandler.GetValue("ControlIdentifiersFile")).GetValue("ClickToLoadTextBlock"));

            Assert.IsFalse(aeClickToloadModuleB.Current.IsOffscreen, "Module B is initialized");

            //Get the clickable point and click on it.
            System.Windows.Point clickablePoint = aeModuleB.GetClickablePoint();
            System.Windows.Forms.Cursor.Position = new System.Drawing.Point((int)clickablePoint.X, (int)clickablePoint.Y);
            Thread.Sleep(1000);
            MouseEvents.Click();
            //Check if Module B is loaded
            AutomationElement aeClickToloadModB = aeModuleB.FindElementByContent(new ResXConfigHandler(ConfigHandler.GetValue("ControlIdentifiersFile")).GetValue("ClickToLoadTextBlock"));

            Assert.IsTrue(aeClickToloadModB.Current.IsOffscreen, "Module B is not initialized");
        }
        public ActionResult UeditorFileUploader()
        {
            UserInfoOutputDto user   = HttpContext.Session.Get <UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto();
            Handler           action = new NotSupportedHandler(HttpContext);

            switch (Request.Query["action"])//通用
            {
            case "config":
                action = new ConfigHandler(HttpContext);
                break;

            case "uploadimage":
                action = new UploadHandler(HttpContext, new UploadConfig()
                {
                    AllowExtensions = UeditorConfig.GetStringList("imageAllowFiles"),
                    PathFormat      = UeditorConfig.GetString("imagePathFormat"),
                    SizeLimit       = UeditorConfig.GetInt("imageMaxSize"),
                    UploadFieldName = UeditorConfig.GetString("imageFieldName")
                });
                break;

            case "uploadscrawl":
                action = new UploadHandler(HttpContext, new UploadConfig()
                {
                    AllowExtensions = new[] { ".png" },
                    PathFormat      = UeditorConfig.GetString("scrawlPathFormat"),
                    SizeLimit       = UeditorConfig.GetInt("scrawlMaxSize"),
                    UploadFieldName = UeditorConfig.GetString("scrawlFieldName"),
                    Base64          = true,
                    Base64Filename  = "scrawl.png"
                });
                break;

            case "catchimage":
                action = new CrawlerHandler(HttpContext);
                break;
            }

            if (user.IsAdmin)
            {
                switch (Request.Query["action"])//管理员用
                {
                //case "uploadvideo":
                //    action = new UploadHandler(context, new UploadConfig()
                //    {
                //        AllowExtensions = UeditorConfig.GetStringList("videoAllowFiles"),
                //        PathFormat = UeditorConfig.GetString("videoPathFormat"),
                //        SizeLimit = UeditorConfig.GetInt("videoMaxSize"),
                //        UploadFieldName = UeditorConfig.GetString("videoFieldName")
                //    });
                //    break;
                case "uploadfile":
                    action = new UploadHandler(HttpContext, new UploadConfig()
                    {
                        AllowExtensions = UeditorConfig.GetStringList("fileAllowFiles"),
                        PathFormat      = UeditorConfig.GetString("filePathFormat"),
                        SizeLimit       = UeditorConfig.GetInt("fileMaxSize"),
                        UploadFieldName = UeditorConfig.GetString("fileFieldName")
                    });
                    break;
                    //case "listimage":
                    //    action = new ListFileManager(context, UeditorConfig.GetString("imageManagerListPath"), UeditorConfig.GetStringList("imageManagerAllowFiles"));
                    //    break;
                    //case "listfile":
                    //    action = new ListFileManager(context, UeditorConfig.GetString("fileManagerListPath"), UeditorConfig.GetStringList("fileManagerAllowFiles"));
                    //    break;
                }
            }

            string result = action.Process();

            return(Content(result, ContentType.Json));
        }
        public override void Install(ModuleManager manager)
        {
            manager.CreateCommands("", cgb =>
            {
                cgb.AddCheck(PermissionChecker.Instance);

                commands.ForEach(cmd => cmd.Init(cgb));

                cgb.CreateCommand(Prefix + "permrole")
                .Alias(Prefix + "pr")
                .Description("Sets a role which can change permissions. Or supply no parameters to find out the current one. Default one is 'Nadeko'.")
                .Parameter("role", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (string.IsNullOrWhiteSpace(e.GetArg("role")))
                    {
                        await e.Channel.SendMessage($"Current permissions role is `{PermissionsHandler.GetServerPermissionsRoleName(e.Server)}`").ConfigureAwait(false);
                        return;
                    }

                    var arg           = e.GetArg("role");
                    Discord.Role role = null;
                    try
                    {
                        role = PermissionHelper.ValidateRole(e.Server, arg);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        await e.Channel.SendMessage($"Role `{arg}` probably doesn't exist. Create the role with that name first.").ConfigureAwait(false);
                        return;
                    }
                    PermissionsHandler.SetPermissionsRole(e.Server, role.Name);
                    await e.Channel.SendMessage($"Role `{role.Name}` is now required in order to change permissions.").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "rpc")
                .Alias(Prefix + "rolepermissionscopy")
                .Description($"Copies BOT PERMISSIONS (not discord permissions) from one role to another.\n**Usage**:`{Prefix}rpc Some Role ~ Some other role`")
                .Parameter("from_to", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var arg = e.GetArg("from_to")?.Trim();
                    if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~'))
                    {
                        return;
                    }
                    var args = arg.Split('~').Select(a => a.Trim()).ToArray();
                    if (args.Length > 2)
                    {
                        await e.Channel.SendMessage("💢Invalid number of '~'s in the argument.");
                        return;
                    }
                    try
                    {
                        var fromRole = PermissionHelper.ValidateRole(e.Server, args[0]);
                        var toRole   = PermissionHelper.ValidateRole(e.Server, args[1]);

                        PermissionsHandler.CopyRolePermissions(fromRole, toRole);
                        await e.Channel.SendMessage($"Copied permission settings from **{fromRole.Name}** to **{toRole.Name}**.");
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage($"💢{ex.Message}");
                    }
                });
                cgb.CreateCommand(Prefix + "cpc")
                .Alias(Prefix + "channelpermissionscopy")
                .Description($"Copies BOT PERMISSIONS (not discord permissions) from one channel to another.\n**Usage**:`{Prefix}cpc Some Channel ~ Some other channel`")
                .Parameter("from_to", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var arg = e.GetArg("from_to")?.Trim();
                    if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~'))
                    {
                        return;
                    }
                    var args = arg.Split('~').Select(a => a.Trim()).ToArray();
                    if (args.Length > 2)
                    {
                        await e.Channel.SendMessage("💢Invalid number of '~'s in the argument.");
                        return;
                    }
                    try
                    {
                        var fromChannel = PermissionHelper.ValidateChannel(e.Server, args[0]);
                        var toChannel   = PermissionHelper.ValidateChannel(e.Server, args[1]);

                        PermissionsHandler.CopyChannelPermissions(fromChannel, toChannel);
                        await e.Channel.SendMessage($"Copied permission settings from **{fromChannel.Name}** to **{toChannel.Name}**.");
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage($"💢{ex.Message}");
                    }
                });
                cgb.CreateCommand(Prefix + "upc")
                .Alias(Prefix + "userpermissionscopy")
                .Description($"Copies BOT PERMISSIONS (not discord permissions) from one role to another.\n**Usage**:`{Prefix}upc @SomeUser ~ @SomeOtherUser`")
                .Parameter("from_to", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var arg = e.GetArg("from_to")?.Trim();
                    if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~'))
                    {
                        return;
                    }
                    var args = arg.Split('~').Select(a => a.Trim()).ToArray();
                    if (args.Length > 2)
                    {
                        await e.Channel.SendMessage("💢Invalid number of '~'s in the argument.");
                        return;
                    }
                    try
                    {
                        var fromUser = PermissionHelper.ValidateUser(e.Server, args[0]);
                        var toUser   = PermissionHelper.ValidateUser(e.Server, args[1]);

                        PermissionsHandler.CopyUserPermissions(fromUser, toUser);
                        await e.Channel.SendMessage($"Copied permission settings from **{fromUser.ToString()}**to * *{toUser.ToString()}**.");
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage($"💢{ex.Message}");
                    }
                });

                cgb.CreateCommand(Prefix + "verbose")
                .Alias(Prefix + "v")
                .Description("Sets whether to show when a command/module is blocked.\n**Usage**: ;verbose true")
                .Parameter("arg", ParameterType.Required)
                .Do(async e =>
                {
                    var arg = e.GetArg("arg");
                    var val = PermissionHelper.ValidateBool(arg);
                    PermissionsHandler.SetVerbosity(e.Server, val);
                    await e.Channel.SendMessage($"Verbosity set to {val}.").ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "serverperms")
                .Alias(Prefix + "sp")
                .Description("Shows banned permissions for this server.")
                .Do(async e =>
                {
                    var perms = PermissionsHandler.GetServerPermissions(e.Server);
                    if (string.IsNullOrWhiteSpace(perms?.ToString()))
                    {
                        await e.Channel.SendMessage("No permissions set for this server.").ConfigureAwait(false);
                    }
                    await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "roleperms")
                .Alias(Prefix + "rp")
                .Description("Shows banned permissions for a certain role. No argument means for everyone.\n**Usage**: ;rp AwesomeRole")
                .Parameter("role", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var arg  = e.GetArg("role");
                    var role = e.Server.EveryoneRole;
                    if (!string.IsNullOrWhiteSpace(arg))
                    {
                        try
                        {
                            role = PermissionHelper.ValidateRole(e.Server, arg);
                        }
                        catch (Exception ex)
                        {
                            await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false);
                            return;
                        }
                    }

                    var perms = PermissionsHandler.GetRolePermissionsById(e.Server, role.Id);

                    if (string.IsNullOrWhiteSpace(perms?.ToString()))
                    {
                        await e.Channel.SendMessage($"No permissions set for **{role.Name}** role.").ConfigureAwait(false);
                    }
                    await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "channelperms")
                .Alias(Prefix + "cp")
                .Description("Shows banned permissions for a certain channel. No argument means for this channel.\n**Usage**: ;cp #dev")
                .Parameter("channel", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var arg     = e.GetArg("channel");
                    var channel = e.Channel;
                    if (!string.IsNullOrWhiteSpace(arg))
                    {
                        try
                        {
                            channel = PermissionHelper.ValidateChannel(e.Server, arg);
                        }
                        catch (Exception ex)
                        {
                            await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false);
                            return;
                        }
                    }

                    var perms = PermissionsHandler.GetChannelPermissionsById(e.Server, channel.Id);
                    if (string.IsNullOrWhiteSpace(perms?.ToString()))
                    {
                        await e.Channel.SendMessage($"No permissions set for **{channel.Name}** channel.").ConfigureAwait(false);
                    }
                    await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "userperms")
                .Alias(Prefix + "up")
                .Description("Shows banned permissions for a certain user. No argument means for yourself.\n**Usage**: ;up Kwoth")
                .Parameter("user", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var user = e.User;
                    if (!string.IsNullOrWhiteSpace(e.GetArg("user")))
                    {
                        try
                        {
                            user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));
                        }
                        catch (Exception ex)
                        {
                            await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false);
                            return;
                        }
                    }

                    var perms = PermissionsHandler.GetUserPermissionsById(e.Server, user.Id);
                    if (string.IsNullOrWhiteSpace(perms?.ToString()))
                    {
                        await e.Channel.SendMessage($"No permissions set for user **{user.Name}**.").ConfigureAwait(false);
                    }
                    await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "sm").Alias(Prefix + "servermodule")
                .Parameter("module", ParameterType.Required)
                .Parameter("bool", ParameterType.Required)
                .Description("Sets a module's permission at the server level.\n**Usage**: ;sm [module_name] enable")
                .Do(async e =>
                {
                    try
                    {
                        var module = PermissionHelper.ValidateModule(e.GetArg("module"));
                        var state  = PermissionHelper.ValidateBool(e.GetArg("bool"));

                        PermissionsHandler.SetServerModulePermission(e.Server, module, state);
                        await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "sc").Alias(Prefix + "servercommand")
                .Parameter("command", ParameterType.Required)
                .Parameter("bool", ParameterType.Required)
                .Description("Sets a command's permission at the server level.\n**Usage**: ;sc [command_name] disable")
                .Do(async e =>
                {
                    try
                    {
                        var command = PermissionHelper.ValidateCommand(e.GetArg("command"));
                        var state   = PermissionHelper.ValidateBool(e.GetArg("bool"));

                        PermissionsHandler.SetServerCommandPermission(e.Server, command, state);
                        await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "rm").Alias(Prefix + "rolemodule")
                .Parameter("module", ParameterType.Required)
                .Parameter("bool", ParameterType.Required)
                .Parameter("role", ParameterType.Unparsed)
                .Description("Sets a module's permission at the role level.\n**Usage**: ;rm [module_name] enable [role_name]")
                .Do(async e =>
                {
                    try
                    {
                        var module = PermissionHelper.ValidateModule(e.GetArg("module"));
                        var state  = PermissionHelper.ValidateBool(e.GetArg("bool"));

                        if (e.GetArg("role")?.ToLower() == "all")
                        {
                            foreach (var role in e.Server.Roles)
                            {
                                PermissionsHandler.SetRoleModulePermission(role, module, state);
                            }
                            await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false);
                        }
                        else
                        {
                            var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));

                            PermissionsHandler.SetRoleModulePermission(role, module, state);
                            await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
                        }
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "rc").Alias(Prefix + "rolecommand")
                .Parameter("command", ParameterType.Required)
                .Parameter("bool", ParameterType.Required)
                .Parameter("role", ParameterType.Unparsed)
                .Description("Sets a command's permission at the role level.\n**Usage**: ;rc [command_name] disable [role_name]")
                .Do(async e =>
                {
                    try
                    {
                        var command = PermissionHelper.ValidateCommand(e.GetArg("command"));
                        var state   = PermissionHelper.ValidateBool(e.GetArg("bool"));

                        if (e.GetArg("role")?.ToLower() == "all")
                        {
                            foreach (var role in e.Server.Roles)
                            {
                                PermissionsHandler.SetRoleCommandPermission(role, command, state);
                            }
                            await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false);
                        }
                        else
                        {
                            var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));

                            PermissionsHandler.SetRoleCommandPermission(role, command, state);
                            await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
                        }
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "cm").Alias(Prefix + "channelmodule")
                .Parameter("module", ParameterType.Required)
                .Parameter("bool", ParameterType.Required)
                .Parameter("channel", ParameterType.Unparsed)
                .Description("Sets a module's permission at the channel level.\n**Usage**: ;cm [module_name] enable [channel_name]")
                .Do(async e =>
                {
                    try
                    {
                        var module     = PermissionHelper.ValidateModule(e.GetArg("module"));
                        var state      = PermissionHelper.ValidateBool(e.GetArg("bool"));
                        var channelArg = e.GetArg("channel");
                        if (channelArg?.ToLower() == "all")
                        {
                            foreach (var channel in e.Server.TextChannels)
                            {
                                PermissionsHandler.SetChannelModulePermission(channel, module, state);
                            }
                            await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false);
                        }
                        else if (string.IsNullOrWhiteSpace(channelArg))
                        {
                            PermissionsHandler.SetChannelModulePermission(e.Channel, module, state);
                            await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{e.Channel.Name}** channel.").ConfigureAwait(false);
                        }
                        else
                        {
                            var channel = PermissionHelper.ValidateChannel(e.Server, channelArg);

                            PermissionsHandler.SetChannelModulePermission(channel, module, state);
                            await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
                        }
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "cc").Alias(Prefix + "channelcommand")
                .Parameter("command", ParameterType.Required)
                .Parameter("bool", ParameterType.Required)
                .Parameter("channel", ParameterType.Unparsed)
                .Description("Sets a command's permission at the channel level.\n**Usage**: ;cc [command_name] enable [channel_name]")
                .Do(async e =>
                {
                    try
                    {
                        var command = PermissionHelper.ValidateCommand(e.GetArg("command"));
                        var state   = PermissionHelper.ValidateBool(e.GetArg("bool"));

                        if (e.GetArg("channel")?.ToLower() == "all")
                        {
                            foreach (var channel in e.Server.TextChannels)
                            {
                                PermissionsHandler.SetChannelCommandPermission(channel, command, state);
                            }
                            await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false);
                        }
                        else
                        {
                            var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));

                            PermissionsHandler.SetChannelCommandPermission(channel, command, state);
                            await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
                        }
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "um").Alias(Prefix + "usermodule")
                .Parameter("module", ParameterType.Required)
                .Parameter("bool", ParameterType.Required)
                .Parameter("user", ParameterType.Unparsed)
                .Description("Sets a module's permission at the user level.\n**Usage**: ;um [module_name] enable [user_name]")
                .Do(async e =>
                {
                    try
                    {
                        var module = PermissionHelper.ValidateModule(e.GetArg("module"));
                        var state  = PermissionHelper.ValidateBool(e.GetArg("bool"));
                        var user   = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));

                        PermissionsHandler.SetUserModulePermission(user, module, state);
                        await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false);
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "uc").Alias(Prefix + "usercommand")
                .Parameter("command", ParameterType.Required)
                .Parameter("bool", ParameterType.Required)
                .Parameter("user", ParameterType.Unparsed)
                .Description("Sets a command's permission at the user level.\n**Usage**: ;uc [command_name] enable [user_name]")
                .Do(async e =>
                {
                    try
                    {
                        var command = PermissionHelper.ValidateCommand(e.GetArg("command"));
                        var state   = PermissionHelper.ValidateBool(e.GetArg("bool"));
                        var user    = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));

                        PermissionsHandler.SetUserCommandPermission(user, command, state);
                        await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false);
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "asm").Alias(Prefix + "allservermodules")
                .Parameter("bool", ParameterType.Required)
                .Description("Sets permissions for all modules at the server level.\n**Usage**: ;asm [enable/disable]")
                .Do(async e =>
                {
                    try
                    {
                        var state = PermissionHelper.ValidateBool(e.GetArg("bool"));

                        foreach (var module in NadekoBot.Client.GetService <ModuleService>().Modules)
                        {
                            PermissionsHandler.SetServerModulePermission(e.Server, module.Name, state);
                        }
                        await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "asc").Alias(Prefix + "allservercommands")
                .Parameter("module", ParameterType.Required)
                .Parameter("bool", ParameterType.Required)
                .Description("Sets permissions for all commands from a certain module at the server level.\n**Usage**: ;asc [module_name] [enable/disable]")
                .Do(async e =>
                {
                    try
                    {
                        var state  = PermissionHelper.ValidateBool(e.GetArg("bool"));
                        var module = PermissionHelper.ValidateModule(e.GetArg("module"));

                        foreach (var command in NadekoBot.Client.GetService <CommandService>().AllCommands.Where(c => c.Category == module))
                        {
                            PermissionsHandler.SetServerCommandPermission(e.Server, command.Text, state);
                        }
                        await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "acm").Alias(Prefix + "allchannelmodules")
                .Parameter("bool", ParameterType.Required)
                .Parameter("channel", ParameterType.Unparsed)
                .Description("Sets permissions for all modules at the channel level.\n**Usage**: ;acm [enable/disable] [channel_name]")
                .Do(async e =>
                {
                    try
                    {
                        var state   = PermissionHelper.ValidateBool(e.GetArg("bool"));
                        var chArg   = e.GetArg("channel");
                        var channel = string.IsNullOrWhiteSpace(chArg) ? e.Channel :PermissionHelper.ValidateChannel(e.Server, chArg);
                        foreach (var module in NadekoBot.Client.GetService <ModuleService>().Modules)
                        {
                            PermissionsHandler.SetChannelModulePermission(channel, module.Name, state);
                        }

                        await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "acc").Alias(Prefix + "allchannelcommands")
                .Parameter("module", ParameterType.Required)
                .Parameter("bool", ParameterType.Required)
                .Parameter("channel", ParameterType.Unparsed)
                .Description("Sets permissions for all commands from a certain module at the channel level.\n**Usage**: ;acc [module_name] [enable/disable] [channel_name]")
                .Do(async e =>
                {
                    try
                    {
                        var state   = PermissionHelper.ValidateBool(e.GetArg("bool"));
                        var module  = PermissionHelper.ValidateModule(e.GetArg("module"));
                        var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
                        foreach (var command in NadekoBot.Client.GetService <CommandService>().AllCommands.Where(c => c.Category == module))
                        {
                            PermissionsHandler.SetChannelCommandPermission(channel, command.Text, state);
                        }
                        await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "arm").Alias(Prefix + "allrolemodules")
                .Parameter("bool", ParameterType.Required)
                .Parameter("role", ParameterType.Unparsed)
                .Description("Sets permissions for all modules at the role level.\n**Usage**: ;arm [enable/disable] [role_name]")
                .Do(async e =>
                {
                    try
                    {
                        var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
                        var role  = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
                        foreach (var module in NadekoBot.Client.GetService <ModuleService>().Modules)
                        {
                            PermissionsHandler.SetRoleModulePermission(role, module.Name, state);
                        }

                        await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "arc").Alias(Prefix + "allrolecommands")
                .Parameter("module", ParameterType.Required)
                .Parameter("bool", ParameterType.Required)
                .Parameter("channel", ParameterType.Unparsed)
                .Description("Sets permissions for all commands from a certain module at the role level.\n**Usage**: ;arc [module_name] [enable/disable] [role_name]")
                .Do(async e =>
                {
                    try
                    {
                        var state  = PermissionHelper.ValidateBool(e.GetArg("bool"));
                        var module = PermissionHelper.ValidateModule(e.GetArg("module"));
                        var role   = PermissionHelper.ValidateRole(e.Server, e.GetArg("channel"));
                        foreach (var command in NadekoBot.Client.GetService <CommandService>().AllCommands.Where(c => c.Category == module))
                        {
                            PermissionsHandler.SetRoleCommandPermission(role, command.Text, state);
                        }
                        await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
                    }
                    catch (ArgumentException exArg)
                    {
                        await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
                    }
                });

                cgb.CreateCommand(Prefix + "ubl")
                .Description("Blacklists a mentioned user.\n**Usage**: ;ubl [user_mention]")
                .Parameter("user", ParameterType.Unparsed)
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    await Task.Run(async() =>
                    {
                        if (!e.Message.MentionedUsers.Any())
                        {
                            return;
                        }
                        var usr = e.Message.MentionedUsers.First();
                        NadekoBot.Config.UserBlacklist.Add(usr.Id);
                        ConfigHandler.SaveConfig();
                        await e.Channel.SendMessage($"`Sucessfully blacklisted user {usr.Name}`").ConfigureAwait(false);
                    }).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "uubl")
                .Description($"Unblacklists a mentioned user.\n**Usage**: {Prefix}uubl [user_mention]")
                .Parameter("user", ParameterType.Unparsed)
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    await Task.Run(async() =>
                    {
                        if (!e.Message.MentionedUsers.Any())
                        {
                            return;
                        }
                        var usr = e.Message.MentionedUsers.First();
                        if (NadekoBot.Config.UserBlacklist.Contains(usr.Id))
                        {
                            NadekoBot.Config.UserBlacklist.Remove(usr.Id);
                            ConfigHandler.SaveConfig();
                            await e.Channel.SendMessage($"`Sucessfully unblacklisted user {usr.Name}`").ConfigureAwait(false);
                        }
                        else
                        {
                            await e.Channel.SendMessage($"`{usr.Name} was not in blacklist`").ConfigureAwait(false);
                        }
                    }).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "cbl")
                .Description("Blacklists a mentioned channel (#general for example).\n**Usage**: ;ubl [channel_mention]")
                .Parameter("channel", ParameterType.Unparsed)
                .Do(async e =>
                {
                    await Task.Run(async() =>
                    {
                        if (!e.Message.MentionedChannels.Any())
                        {
                            return;
                        }
                        var ch = e.Message.MentionedChannels.First();
                        NadekoBot.Config.UserBlacklist.Add(ch.Id);
                        ConfigHandler.SaveConfig();
                        await e.Channel.SendMessage($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false);
                    }).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "cubl")
                .Description("Unblacklists a mentioned channel (#general for example).\n**Usage**: ;cubl [channel_mention]")
                .Parameter("channel", ParameterType.Unparsed)
                .Do(async e =>
                {
                    await Task.Run(async() =>
                    {
                        if (!e.Message.MentionedChannels.Any())
                        {
                            return;
                        }
                        var ch = e.Message.MentionedChannels.First();
                        NadekoBot.Config.UserBlacklist.Remove(ch.Id);
                        ConfigHandler.SaveConfig();
                        await e.Channel.SendMessage($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false);
                    }).ConfigureAwait(false);
                });

                cgb.CreateCommand(Prefix + "sbl")
                .Description("Blacklists a server by a name or id (#general for example). **BOT OWNER ONLY**\n**Usage**: ;sbl [servername/serverid]")
                .Parameter("server", ParameterType.Unparsed)
                .AddCheck(SimpleCheckers.OwnerOnly())
                .Do(async e =>
                {
                    await Task.Run(async() =>
                    {
                        var arg = e.GetArg("server")?.Trim();
                        if (string.IsNullOrWhiteSpace(arg))
                        {
                            return;
                        }
                        var server = NadekoBot.Client.Servers.FirstOrDefault(s => s.Id.ToString() == arg) ??
                                     NadekoBot.Client.FindServers(arg.Trim()).FirstOrDefault();
                        if (server == null)
                        {
                            await e.Channel.SendMessage("Cannot find that server").ConfigureAwait(false);
                            return;
                        }
                        var serverId = server.Id;
                        NadekoBot.Config.ServerBlacklist.Add(serverId);
                        ConfigHandler.SaveConfig();
                        //cleanup trivias and typeracing
                        Modules.Games.Commands.Trivia.TriviaGame trivia;
                        TriviaCommands.RunningTrivias.TryRemove(serverId, out trivia);
                        TypingGame typeracer;
                        SpeedTyping.RunningContests.TryRemove(serverId, out typeracer);

                        await e.Channel.SendMessage($"`Sucessfully blacklisted server {server.Name}`").ConfigureAwait(false);
                    }).ConfigureAwait(false);
                });
            });
        }
Exemple #27
0
 private void MainForm_Load(object sender, EventArgs e)
 {
     ConfigHandler.LoadConfig(ref config);
     v2rayHandler = new V2rayHandler();
     v2rayHandler.ProcessEvent += v2rayHandler_ProcessEvent;
 }
Exemple #28
0
        private void menuScreenQRCodeScan_Click(object sender, EventArgs e)
        {
            Thread.Sleep(100);
            foreach (Screen screen in Screen.AllScreens)
            {
                Point screen_size = Utils.GetScreenPhysicalSize();
                using (Bitmap fullImage = new Bitmap(screen_size.X,
                                                     screen_size.Y))
                {
                    using (Graphics g = Graphics.FromImage(fullImage))
                    {
                        g.CopyFromScreen(screen.Bounds.X,
                                         screen.Bounds.Y,
                                         0, 0,
                                         fullImage.Size,
                                         CopyPixelOperation.SourceCopy);
                    }
                    for (int i = 0; i < 100; i++)
                    {
                        double    stretch;
                        Rectangle cropRect = Scan.GetScanRect(fullImage.Width, fullImage.Height, i, out stretch);
                        if (cropRect.Width == 0)
                        {
                            break;
                        }

                        string    url;
                        Rectangle rect;
                        if (stretch == 1 ? Scan.ScanQRCode(screen, fullImage, cropRect, out url, out rect) : Scan.ScanQRCodeStretch(screen, fullImage, cropRect, stretch, out url, out rect))
                        {
                            QRCodeSplashForm splash = new QRCodeSplashForm();

                            splash.FormClosed += splash_FormClosed;


                            splash.Location = new Point(screen.Bounds.X, screen.Bounds.Y);
                            double dpi = Screen.PrimaryScreen.Bounds.Width / (double)screen_size.X;
                            splash.TargetRect = new Rectangle(
                                (int)(rect.Left * dpi + screen.Bounds.X),
                                (int)(rect.Top * dpi + screen.Bounds.Y),
                                (int)(rect.Width * dpi),
                                (int)(rect.Height * dpi));
                            splash.Size = new Size(fullImage.Width, fullImage.Height);

                            VmessItem vmessItem = V2rayConfigHandler.ImportFromStrConfig(out string msg, url);
                            if (vmessItem != null && ConfigHandler.AddServer(ref config, vmessItem, -1) == 0)
                            {
                                splash.Show();
                                //刷新
                                RefreshServers();
                                LoadV2ray();
                            }
                            else
                            {
                                splash.Show();
                                UI.Show(msg);
                            }

                            //扫到一个二维码即退出
                            break;
                        }
                    }
                }
            }
        }
        public bool CanRun(Command command, User user, Channel channel, out string error)
        {
            error = String.Empty;

            if (!WizBot.Ready)
            {
                return(false);
            }

            if (channel.IsPrivate || channel.Server == null)
            {
                return(command.Category == "Help");
            }

            if (ConfigHandler.IsUserBlacklisted(user.Id) ||
                (!channel.IsPrivate &&
                 (ConfigHandler.IsServerBlacklisted(channel.Server.Id) || ConfigHandler.IsChannelBlacklisted(channel.Id))))
            {
                return(false);
            }

            if (timeBlackList.ContainsKey(user))
            {
                return(false);
            }

            timeBlackList.TryAdd(user, DateTime.Now);

            if (!channel.IsPrivate && !channel.Server.CurrentUser.GetPermissions(channel).SendMessages)
            {
                return(false);
            }
            //{
            //    user.SendMessage($"I ignored your command in {channel.Server.Name}/#{channel.Name} because i don't have permissions to write to it. Please use `;acm channel_name 0` in that server instead of muting me.").GetAwaiter().GetResult();
            //}

            try
            {
                //is it a permission command?
                // if it is, check if the user has the correct role
                // if yes return true, if no return false
                if (command.Category == "Permissions")
                {
                    Discord.Role role = null;
                    try
                    {
                        role = PermissionHelper.ValidateRole(user.Server,
                                                             PermissionsHandler.GetServerPermissionsRoleName(user.Server));
                    }
                    catch { }
                    if (user.Server.Owner.Id == user.Id || (role != null && user.HasRole(role)))
                    {
                        return(true);
                    }
                    ServerPermissions perms;
                    PermissionsHandler.PermissionsDict.TryGetValue(user.Server.Id, out perms);
                    throw new Exception($"You don't have the necessary role (**{(perms?.PermissionsControllerRole ?? "Wiz Bot")}**) to change permissions.");
                }

                var permissionType = PermissionsHandler.GetPermissionBanType(command, user, channel);

                string msg;

                if (permissionType == PermissionsHandler.PermissionBanType.ServerBanModule &&
                    command.Category.ToLower() == "nsfw")
                {
                    msg = $"**{command.Category}** module has been banned from use on this **server**.\nNSFW module is disabled by default. Server owner can type `;sm nsfw enable` to enable it.";
                }
                else
                {
                    switch (permissionType)
                    {
                    case PermissionsHandler.PermissionBanType.None:
                        return(true);

                    case PermissionsHandler.PermissionBanType.ServerBanCommand:
                        msg = $"**{command.Text}** command has been banned from use on this **server**.";
                        break;

                    case PermissionsHandler.PermissionBanType.ServerBanModule:
                        msg = $"**{command.Category}** module has been banned from use on this **server**.";
                        break;

                    case PermissionsHandler.PermissionBanType.ChannelBanCommand:
                        msg = $"**{command.Text}** command has been banned from use on this **channel**.";
                        break;

                    case PermissionsHandler.PermissionBanType.ChannelBanModule:
                        msg = $"**{command.Category}** module has been banned from use on this **channel**.";
                        break;

                    case PermissionsHandler.PermissionBanType.RoleBanCommand:
                        msg = $"You do not have a **role** which permits you the usage of **{command.Text}** command.";
                        break;

                    case PermissionsHandler.PermissionBanType.RoleBanModule:
                        msg = $"You do not have a **role** which permits you the usage of **{command.Category}** module.";
                        break;

                    case PermissionsHandler.PermissionBanType.UserBanCommand:
                        msg = $"{user.Mention}, You have been banned from using **{command.Text}** command.";
                        break;

                    case PermissionsHandler.PermissionBanType.UserBanModule:
                        msg = $"{user.Mention}, You have been banned from using **{command.Category}** module.";
                        break;

                    default:
                        return(true);
                    }
                }
                if (PermissionsHandler.PermissionsDict[user.Server.Id].Verbose) //if verbose - print errors
                {
                    error = msg;
                }
                return(false);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception in canrun: {ex}");
                try
                {
                    ServerPermissions perms;
                    if (PermissionsHandler.PermissionsDict.TryGetValue(user.Server.Id, out perms) && perms.Verbose)
                    {
                        //if verbose - print errors
                        error = ex.Message;
                    }
                }
                catch (Exception ex2)
                {
                    Console.WriteLine($"SERIOUS PERMISSION ERROR {ex2}\n\nUser:{user} Server: {user?.Server?.Name}/{user?.Server?.Id}");
                }
                return(false);
            }
        }
Exemple #30
0
 private void WordWrapToolStripMenuItem_Click(object sender, EventArgs e)
 {
     descriptionTextBox.WordWrap = wordWrapToolStripMenuItem.Checked;
     ConfigHandler.WordWrap      = wordWrapToolStripMenuItem.Checked.ToString();
     ConfigHandler.SaveConfig();
 }
Exemple #31
0
        private void WriteConfigToFile(object _sender, RoutedEventArgs _e)
        {
            string selectedComponent = currentTab.Header.ToString();
            string path = aautil.GetAaConfigFilePaths(GlobalConfigs.Instance.AaVersion, GlobalConfigs.Instance.AaInstance)[selectedComponent];

            if (string.IsNullOrEmpty(path))
            {
                logger.Error("Null config path");
                uiLogger.LogToUi("Config path is empty", currentTab.Header.ToString());
                return;
            }

            if (applyToAll.IsChecked == false)
            {
                List <string> installedComps = aautil.GetAaInstalledComponents(GlobalConfigs.Instance.AaVersion, GlobalConfigs.Instance.AaInstance);

                if (!loadedConfigs.ContainsKey(selectedComponent))
                {
                    loadedConfigs.Add(selectedComponent, new ConfigReader(path).ReadFromConfigFile());
                }

                MssqlConfig mssql = loadedConfigs[selectedComponent];

                switch (selectedComponent)
                {
                case "av.biz":
                    mssql.AvDbHost = dbServerTextBox_biz.Text;

                    // av db
                    mssql.AvDbName = avDBTextBox_biz.Text;
                    mssql.AvUser   = avDBUserTextBox_biz.Text;
                    mssql.SetAvDatabasePassword(avDBPasswordTextBox_biz.Password);

                    // jetspeed db
                    mssql.AvJetspeedDbName = jetspeedDBTextBox_biz.Text;
                    mssql.AvJetspeedUser   = jetspeedUserTextBox_biz.Text;
                    mssql.SetJetspeedDatabasePassword(jetspeedPasswordTextBox_biz.SecurePassword);

                    break;

                case "av.cfmx":
                    mssql.AvDbHost = dbServer_cfmx.Text;

                    // av db
                    mssql.AvDbName = avDBTextBox_cfmx.Text;
                    mssql.AvUser   = avDBUserTextBox_cfmx.Text;
                    mssql.SetAvDatabasePassword(avDBPasswordTextBox_cfmx.Password);

                    break;

                case "av.indexer":
                    mssql.AvDbHost = dbServer_indexer.Text;

                    // av db
                    mssql.AvDbName = avDBTextBox_indexer.Text;
                    mssql.AvUser   = avDBUserTextBox_indexer.Text;
                    mssql.SetAvDatabasePassword(avDBPasswordTextBox_indexer.Password);

                    break;

                case "av.web":
                    mssql.AvDbHost = dbServerTextBox_web.Text;

                    // av db
                    mssql.AvDbName = avDBTextBox_web.Text;
                    mssql.AvUser   = avDBUserTextBox_web.Text;
                    mssql.SetAvDatabasePassword(avDBPasswordTextBox_web.Password);

                    break;

                default:
                    logger.Warn("Attempted to write to a disabled or non existent component: " + mssql.ToString());
                    break;
                }

                ConfigHandler config = new ConfigHandler(path, mssql.AvComponent, GlobalConfigs.Instance.AaVersion, GlobalConfigs.Instance.AaInstance, uiLogger);

                try
                {
                    config.WriteConfigToFile(mssql);
                    uiLogger.LogToUi("Updated config successfully", selectedComponent);
                }
                catch (Exception e)
                {
                    logger.Error("Failed to update config at " + config.PathToConfigFile);
                    logger.Error(e.Message);
                    logger.Error(e.StackTrace);

                    RestoreBackup(config.PathToConfigFile + ".backup", config.PathToConfigFile);

                    mssql = config.ReadConfigFromFile();
                }
                finally
                {
                    UpdateUi(mssql);
                }
            }
            else
            {
                bool loadedSelectedComponent = false;

                foreach (string comp in aautil.GetAaInstalledComponents(GlobalConfigs.Instance.AaVersion, GlobalConfigs.Instance.AaInstance))
                {
                    MssqlConfig mssql;


                    if (loadedConfigs.ContainsKey(selectedComponent) && loadedSelectedComponent == false)
                    {
                        mssql = loadedConfigs[selectedComponent];
                        path  = aautil.GetAaConfigFilePaths(GlobalConfigs.Instance.AaVersion, GlobalConfigs.Instance.AaInstance)[selectedComponent];
                        ConfigHandler config = new ConfigHandler(path, comp, GlobalConfigs.Instance.AaVersion, GlobalConfigs.Instance.AaInstance, uiLogger);
                        mssql = new MssqlConfig
                        {
                            AvComponent      = selectedComponent,
                            AvDbHost         = dbServerTextBox_biz.Text,
                            AvDbName         = avDBTextBox_biz.Text,
                            AvUser           = avDBUserTextBox_biz.Text,
                            AvJetspeedDbName = jetspeedDBTextBox_biz.Text,
                            AvJetspeedUser   = jetspeedUserTextBox_biz.Text
                        };
                        mssql.SetAvDatabasePassword(avDBPasswordTextBox_biz.Password);
                        mssql.SetJetspeedDatabasePassword(jetspeedPasswordTextBox_biz.SecurePassword);

                        try
                        {
                            config.WriteConfigToFile(mssql);
                            uiLogger.LogToUi("Updated config successfully", selectedComponent);
                        }
                        catch (Exception e)
                        {
                            logger.Error("Failed to update config at " + config.PathToConfigFile);
                            logger.Error(e.Message);
                            logger.Error(e.StackTrace);

                            RestoreBackup(config.PathToConfigFile + ".backup", config.PathToConfigFile);

                            mssql = config.ReadConfigFromFile();
                        }
                        finally
                        {
                            UpdateUi(mssql);
                            loadedSelectedComponent = true;
                        }
                    }
                    else
                    {
                        path = aautil.GetAaConfigFilePaths(GlobalConfigs.Instance.AaVersion, GlobalConfigs.Instance.AaInstance)[comp];
                        ConfigHandler config = new ConfigHandler(path, comp, GlobalConfigs.Instance.AaVersion, GlobalConfigs.Instance.AaInstance, uiLogger);
                        mssql = new MssqlConfig {
                            AvComponent = comp, AvDbHost = dbServerTextBox_biz.Text, AvDbName = avDBTextBox_biz.Text, AvUser = avDBUserTextBox_biz.Text
                        };
                        mssql.SetAvDatabasePassword(avDBPasswordTextBox_biz.Password);

                        if (mssql.AvComponent == "av.biz")
                        {
                            // jetspeed db
                            mssql.AvJetspeedDbName = jetspeedDBTextBox_biz.Text;
                            mssql.AvJetspeedUser   = jetspeedUserTextBox_biz.Text;
                            mssql.SetJetspeedDatabasePassword(jetspeedPasswordTextBox_biz.SecurePassword);
                        }

                        try
                        {
                            config.WriteConfigToFile(mssql);
                            uiLogger.LogToUi("Updated config successfully", mssql.AvComponent);
                        }
                        catch (Exception e)
                        {
                            logger.Error("Failed to update config at " + config.PathToConfigFile);
                            logger.Error(e.Message);
                            logger.Error(e.StackTrace);

                            RestoreBackup(config.PathToConfigFile + ".backup", config.PathToConfigFile);

                            mssql = config.ReadConfigFromFile();
                        }
                        finally
                        {
                            UpdateUi(mssql);
                        }
                    }
                }
            }
        }
Exemple #32
0
 public void ProcessRequest(HttpContext context)
 {
     IUser user = UserContext.CurrentUser;
     if (user == null)
     {
         context.Response.Redirect(SiteUrls.Instance().Login());
     }
     Handler action = null;
     switch (context.Request["action"])
     {
         case "config":
             action = new ConfigHandler(context);
             break;
         case "uploadimage":
             action = new UploadHandler(context, new UploadConfig()
             {
                 AllowExtensions = Config.GetStringList("imageAllowFiles"),
                 PathFormat = Config.GetString("imagePathFormat"),
                 SizeLimit = Config.GetInt("imageMaxSize"),
                 UploadFieldName = Config.GetString("imageFieldName")
             });
             break;
         case "uploadscrawl":
             action = new UploadHandler(context, new UploadConfig()
             {
                 AllowExtensions = new string[] { ".png" },
                 PathFormat = Config.GetString("scrawlPathFormat"),
                 SizeLimit = Config.GetInt("scrawlMaxSize"),
                 UploadFieldName = Config.GetString("scrawlFieldName"),
                 Base64 = true,
                 Base64Filename = "scrawl.png"
             });
             break;
         case "uploadvideo":
             action = new UploadHandler(context, new UploadConfig()
             {
                 AllowExtensions = Config.GetStringList("videoAllowFiles"),
                 PathFormat = Config.GetString("videoPathFormat"),
                 SizeLimit = Config.GetInt("videoMaxSize"),
                 UploadFieldName = Config.GetString("videoFieldName")
             });
             break;
         case "uploadfile":
             action = new UploadHandler(context, new UploadConfig()
             {
                 AllowExtensions = Config.GetStringList("fileAllowFiles"),
                 PathFormat = Config.GetString("filePathFormat"),
                 SizeLimit = Config.GetInt("fileMaxSize"),
                 UploadFieldName = Config.GetString("fileFieldName")
             });
             break;
         case "listimage":
             action = new ListFileManager(context, Config.GetString("imageManagerListPath"), Config.GetStringList("imageManagerAllowFiles"));
             break;
         case "listfile":
             action = new ListFileManager(context, Config.GetString("fileManagerListPath"), Config.GetStringList("fileManagerAllowFiles"));
             break;
         case "catchimage":
             action = new CrawlerHandler(context);
             break;
         default:
             action = new NotSupportedHandler(context);
             break;
     }
     action.Process();
 }