コード例 #1
0
        /// <summary>
        /// Set/Unset processing mode (thread-safe)
        /// </summary>
        private void SetProcessing(bool processing)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => SetProcessing(processing)));
            }
            currentlyProcessingImages = processing;

            textBoxInputDir.Enabled         = !processing;
            buttonInputDir.Enabled          = !processing;
            comboBoxInputPaging.Enabled     = !processing;
            comboBoxInputExtension.Enabled  = !processing;
            textBoxOutputDir.Enabled        = !processing;
            buttonOutputDir.Enabled         = !processing;
            textBoxOutputNaming.Enabled     = !processing;
            comboBoxOutputExtension.Enabled = !processing;
            comboBoxImageRotate.Enabled     = !processing;
            checkBoxReorder.Enabled         = !processing;
            checkBoxBackFlip.Enabled        = !processing;
            numericCropLeft.Enabled         = !processing;
            numericCropRight.Enabled        = !processing;
            numericCropTop.Enabled          = !processing;
            numericCropBottom.Enabled       = !processing;

            buttonLaunch.Text = processing
                ? Translations.Get("gui_btn_cancel")
                : Translations.Get("gui_btn_launch");
        }
コード例 #2
0
        /// <summary>
        /// Restore imageres from backup
        /// </summary>
        public static void Restore()
        {
            if (SystemIsWindowsVista7)
            {
                if (File.Exists(ImageresBak))
                {
                    if (FileSystemAdmin.IsAdmin())
                    {
                        FileSystemAdmin.GrantAll(System32);
                        FileSystemAdmin.GrantAll(ImageresBak);
                        FileSystemAdmin.GrantAll(Imageres);

                        try
                        {
                            //Move in-use DLL so that we can restore the original one
                            File.Delete(ImageresOld);
                            File.Move(Imageres, ImageresOld);
                        }
                        catch (UnauthorizedAccessException) { }

                        File.Delete(Imageres);
                        File.Move(ImageresBak, Imageres);
                    }
                    else
                    {
                        throw new UnauthorizedAccessException(Translations.Get("startup_patch_not_admin"));
                    }
                }
            }
            else
            {
                throw new InvalidOperationException(Translations.Get("startup_patch_not_windows7"));
            }
        }
コード例 #3
0
        public string Command(string cmd, string[] args)
        {
            try
            {
                if (replay.RecordRunning)
                {
                    if (args.Length > 0)
                    {
                        switch (args[0].ToLower())
                        {
                        case "save":
                        {
                            replay.CreateBackupReplay(@"replay_recordings\" + replay.GetReplayDefaultName());
                            return(Translations.Get("bot.replayCapture.created"));
                        }

                        case "stop":
                        {
                            replay.OnShutDown();
                            return(Translations.Get("bot.replayCapture.stopped"));
                        }
                        }
                    }
                    return(Translations.Get("general.available_cmd", "save, stop"));
                }
                else
                {
                    return(Translations.Get("bot.replayCapture.restart"));
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
コード例 #4
0
 public override string Run(McClient handler, string command, Dictionary <string, object> localVars)
 {
     if (hasArg(command))
     {
         string[] temp = getArg(command).Split('=');
         if (temp.Length > 1)
         {
             if (Settings.SetVar(temp[0], getArg(command).Substring(temp[0].Length + 1)))
             {
                 return(""); //Success
             }
             else
             {
                 return(Translations.Get("cmd.set.format"));
             }
         }
         else
         {
             return(GetCmdDescTranslated());
         }
     }
     else
     {
         return(GetCmdDescTranslated());
     }
 }
コード例 #5
0
        /// <summary>
        /// Saves SessionToken's from SessionCache into cache file.
        /// </summary>
        private static void SaveToDisk()
        {
            if (Settings.DebugMessages)
            {
                Translations.WriteLineFormatted("cache.saving");
            }

            List <string> sessionCacheLines = new List <string>();

            sessionCacheLines.Add("# Generated by MCC v" + Program.Version + " - Edit at own risk!");
            sessionCacheLines.Add("# Login=SessionID,PlayerName,UUID,ClientID");
            foreach (KeyValuePair <string, SessionToken> entry in sessions)
            {
                sessionCacheLines.Add(entry.Key + '=' + entry.Value.ToString());
            }

            try
            {
                FileMonitor.WriteAllLinesWithRetries(SessionCacheFilePlaintext, sessionCacheLines);
            }
            catch (IOException e)
            {
                ConsoleIO.WriteLineFormatted(Translations.Get("cache.save_fail", e.Message));
            }
        }
コード例 #6
0
        /// <summary>
        /// Extract the default startup sound file
        /// </summary>
        /// <param name="outputFile">Output file path</param>
        public static void ExtractDefault(string outputFile)
        {
            if (SystemIsWindowsVista7)
            {
                if (File.Exists(Imageres) || File.Exists(ImageresBak))
                {
                    string sourceFile = ImageresBak;
                    if (!File.Exists(ImageresBak))
                    {
                        sourceFile = Imageres;
                    }

                    if (File.Exists(ResHackerExe))
                    {
                        Process.Start(ResHackerExe, "-extract \"" + sourceFile + "\", \"" + outputFile + "\", WAVE, " + WaveResourceNumber + ",").WaitForExit();
                    }
                    else
                    {
                        throw new FileNotFoundException(Translations.Get("startup_patch_no_resource_hacker"));
                    }
                }
                else
                {
                    throw new FileNotFoundException(Translations.Get("startup_patch_no_imageres_dll"));
                }
            }
            else
            {
                throw new InvalidOperationException(Translations.Get("startup_patch_not_windows7"));
            }
        }
コード例 #7
0
        private string GetCommandHelp(string cmd)
        {
            switch (cmd.ToLower())
            {
            case "load":
                return(Translations.Get("bot.autocraft.help.load"));

            case "list":
                return(Translations.Get("bot.autocraft.help.list"));

            case "reload":
                return(Translations.Get("bot.autocraft.help.reload"));

            case "resetcfg":
                return(Translations.Get("bot.autocraft.help.resetcfg"));

            case "start":
                return(Translations.Get("bot.autocraft.help.start"));

            case "stop":
                return(Translations.Get("bot.autocraft.help.stop"));

            case "help":
                return(Translations.Get("bot.autocraft.help.help"));

            default:
                return(GetHelp());
            }
        }
コード例 #8
0
ファイル: FormMain.cs プロジェクト: maxox/Sound-Manager
 /// <summary>
 /// Uninstall the application
 /// </summary>
 private void buttonUninstall_Click(object sender, EventArgs e)
 {
     if (File.Exists(UninstallProgram))
     {
         try
         {
             Process.Start(UninstallProgram);
             Close();
         }
         catch { /* Failed to start or user cancelled UAC prompt */ }
     }
     else
     {
         if (MessageBox.Show(
                 Translations.Get("uninstall_confirm_text"),
                 Translations.Get("uninstall_confirm_title"),
                 MessageBoxButtons.OKCancel,
                 MessageBoxIcon.Warning
                 ) == DialogResult.OK
             )
         {
             Program.Uninstall();
             Close();
         }
     }
 }
コード例 #9
0
        private void parseMain(string key, string value)
        {
            switch (key)
            {
            case "tablelocation":
                string[] values = value.Split(',');
                if (values.Length == 3)
                {
                    tableLocation.X = Convert.ToInt32(values[0]);
                    tableLocation.Y = Convert.ToInt32(values[1]);
                    tableLocation.Z = Convert.ToInt32(values[2]);
                }
                else
                {
                    throw new Exception(Translations.Get("bot.autoCraft.exception.invalid_table", key));
                }
                break;

            case "onfailure":
                abortOnFailure = value.ToLower() == "abort" ? true : false;
                break;

            case "updatedebounce":
                updateDebounceValue = Convert.ToInt32(value);
                break;
            }
        }
コード例 #10
0
        public override void Execute(ICommandContext context)
        {
            var player     = ((UnturnedUser)context.User).Player;
            var playerMeta = player.Container.Resolve <IMetadataStore>();

            if (!playerMeta.Has(META_KEY_POS) || !playerMeta.Has(META_KEY_DELAY))
            {
                throw new CommandWrongUsageException(Translations.Get("NOT_DIED_YET"));
            }

            var deathTime = playerMeta.Get <DateTime>(META_KEY_DELAY);
            var delta     = UEssentials.ConfigurationInstance.BackDelay - (DateTime.Now - deathTime).Seconds;

            if (delta > 0 && player.CheckPermission("essentials.bypass.backdelay") != PermissionResult.Grant)
            {
                throw new CommandWrongUsageException(Translations.Get("BACK_DELAY",
                                                                      TimeUtil.FormatSeconds((uint)delta)));
            }

            var backPosition = playerMeta.Get <Vector3>(META_KEY_POS);

            player.GetEntity().Teleport(backPosition.ToSystemVector());
            context.User.SendLocalizedMessage(Translations, "RETURNED");

            playerMeta.Remove(META_KEY_DELAY);
            playerMeta.Remove(META_KEY_POS);
        }
コード例 #11
0
ファイル: FormMain.cs プロジェクト: maxox/Sound-Manager
 /// <summary>
 /// Show sound event file in Windows Explorer
 /// </summary>
 private void soundContextMenu_OpenLocation_Click(object sender, EventArgs e)
 {
     if (soundList.FocusedItem != null)
     {
         SoundEvent soundEvent = soundList.FocusedItem.Tag as SoundEvent;
         try
         {
             if (File.Exists(soundEvent.FilePath))
             {
                 Process.Start("explorer", "/select, \"" + soundEvent.FilePath + '"');
             }
             else
             {
                 Process.Start("explorer", '"' + SoundEvent.DataDirectory + '"');
             }
         }
         catch (Exception browseException)
         {
             MessageBox.Show(
                 Translations.Get("browse_failed_text") + '\n' + browseException.Message,
                 Translations.Get("browse_failed_title"),
                 MessageBoxButtons.OK,
                 MessageBoxIcon.Error
                 );
         }
     }
 }
コード例 #12
0
ファイル: SchemeMeta.cs プロジェクト: maxox/Sound-Manager
 /// <summary>
 /// Reset all metadata to their default values.
 /// </summary>
 public static void ResetAll()
 {
     Thumbnail = null;
     Name      = Translations.Get("default_scheme_name");
     Author    = Translations.Get("default_scheme_author");
     About     = Translations.Get("default_scheme_about");
 }
コード例 #13
0
        public override string Run(McClient handler, string command, Dictionary <string, object> localVars)
        {
            if (!handler.GetInventoryEnabled())
            {
                return(Translations.Get("extra.inventory_required"));
            }

            if (hasArg(command))
            {
                short slot;
                try
                {
                    slot = Convert.ToInt16(getArg(command));
                }
                catch (FormatException)
                {
                    return(Translations.Get("cmd.changeSlot.nan"));
                }
                if (slot >= 1 && slot <= 9)
                {
                    if (handler.ChangeSlot(slot -= 1))
                    {
                        return(Translations.Get("cmd.changeSlot.changed", (slot += 1)));
                    }
                    else
                    {
                        return(Translations.Get("cmd.changeSlot.fail"));
                    }
                }
            }
            return(GetCmdDescTranslated());
        }
コード例 #14
0
        public override string Run(McClient handler, string command, Dictionary <string, object> localVars)
        {
            if (hasArg(command))
            {
                string[] args = getArgs(command);
                if (args.Length > 1)
                {
                    if (!Settings.SetAccount(args[1]))
                    {
                        return(Translations.Get("cmd.connect.unknown", args[1]));
                    }
                }

                if (Settings.SetServerIP(args[0]))
                {
                    Program.Restart();
                    return("");
                }
                else
                {
                    return(Translations.Get("cmd.connect.invalid_ip", args[0]));
                }
            }
            else
            {
                return(GetCmdDescTranslated());
            }
        }
コード例 #15
0
        private string GetSubCommandHelp(string cmd)
        {
            switch (cmd)
            {
            case "list":
                return(Translations.Get("cmd.inventory.help.list") + ' ' + Translations.Get("cmd.inventory.help.usage") + ": /inventory <player|container|<id>> list");

            case "close":
                return(Translations.Get("cmd.inventory.help.close") + ' ' + Translations.Get("cmd.inventory.help.usage") + ": /inventory <player|container|<id>> close");

            case "click":
                return(Translations.Get("cmd.inventory.help.click") + ' ' + Translations.Get("cmd.inventory.help.usage") + ": /inventory <player|container|<id>> click <slot> [left|right|middle]. \nDefault is left click");

            case "drop":
                return(Translations.Get("cmd.inventory.help.drop") + ' ' + Translations.Get("cmd.inventory.help.usage") + ": /inventory <player|container|<id>> drop <slot> [all]. \nAll means drop full stack");

            case "creativegive":
                return(Translations.Get("cmd.inventory.help.creativegive") + ' ' + Translations.Get("cmd.inventory.help.usage") + ": /inventory creativegive <slot> <itemtype> <amount>");

            case "creativedelete":
                return(Translations.Get("cmd.inventory.help.creativedelete") + ' ' + Translations.Get("cmd.inventory.help.usage") + ": /inventory creativedelete <slot>");

            case "help":
                return(GetHelp());

            default:
                return(Translations.Get("cmd.inventory.help.unknown") + GetAvailableActions());
            }
        }
コード例 #16
0
 public override string Run(McClient handler, string command, Dictionary <string, object> localVars)
 {
     if (hasArg(command))
     {
         string[] args = getArgs(command);
         if (args.Length > 0)
         {
             if (args[0] == "mainhand" || args[0] == "0")
             {
                 handler.DoAnimation(0);
                 return(Translations.Get("general.done"));
             }
             else if (args[0] == "offhand" || args[0] == "1")
             {
                 handler.DoAnimation(1);
                 return(Translations.Get("general.done"));
             }
             else
             {
                 return(GetCmdDescTranslated());
             }
         }
         else
         {
             return(GetCmdDescTranslated());
         }
     }
     else
     {
         return(GetCmdDescTranslated());
     }
 }
コード例 #17
0
        public override void Initialize()
        {
            //Load the given file from the startup parameters
            if (LookForScript(ref file))
            {
                lines  = System.IO.File.ReadAllLines(file, Encoding.UTF8);
                csharp = file.EndsWith(".cs");
                thread = null;

                if (!String.IsNullOrEmpty(owner))
                {
                    SendPrivateMessage(owner, Translations.Get("bot.script.pm.loaded", file));
                }
            }
            else
            {
                LogToConsoleTranslated("bot.script.file_not_found", System.IO.Path.GetFullPath(file));

                if (!String.IsNullOrEmpty(owner))
                {
                    SendPrivateMessage(owner, Translations.Get("bot.script.file_not_found", file));
                }

                UnloadBot(); //No need to keep the bot active
            }
        }
コード例 #18
0
        public string CommandHandler(string cmd, string[] args)
        {
            if (args.Length > 0)
            {
                switch (args[0])
                {
                case "load":
                    LoadConfig();
                    return("");

                case "list":
                    string names = string.Join(", ", recipes.Keys.ToList());
                    return(Translations.Get("bot.autoCraft.cmd.list", recipes.Count, names));

                case "reload":
                    recipes.Clear();
                    LoadConfig();
                    return("");

                case "resetcfg":
                    WriteDefaultConfig();
                    return(Translations.Get("bot.autoCraft.cmd.resetcfg"));

                case "start":
                    if (args.Length >= 2)
                    {
                        string name = args[1];
                        if (recipes.ContainsKey(name))
                        {
                            resetVar();
                            PrepareCrafting(recipes[name]);
                            return("");
                        }
                        else
                        {
                            return(Translations.Get("bot.autoCraft.recipe_not_exist"));
                        }
                    }
                    else
                    {
                        return(Translations.Get("bot.autoCraft.no_recipe_name"));
                    }

                case "stop":
                    StopCrafting();
                    return(Translations.Get("bot.autoCraft.stop"));

                case "help":
                    return(GetCommandHelp(args.Length >= 2 ? args[1] : ""));

                default:
                    return(GetHelp());
                }
            }
            else
            {
                return(GetHelp());
            }
        }
コード例 #19
0
        public override void Execute(ICommandContext context)
        {
            if (context.Parameters.Length == 0 || (context.Parameters.Length == 1 && !(context.User is UnturnedUser)))
            {
                throw new CommandWrongUsageException();
            }

            int amount = context.Parameters.Get <int>(0);

            if (amount > MAX_INPUT_VALUE || amount < -MAX_INPUT_VALUE)
            {
                throw new CommandWrongUsageException(Translations.Get("NUMBER_BETWEEN", -MAX_INPUT_VALUE, MAX_INPUT_VALUE));
            }

            if (context.Parameters.Length == 1)
            {
                GiveRep(((UnturnedUser)context.User).Player, amount);
                return;
            }

            if (context.Parameters[0] == "*")
            {
                var playerManager = context.Container.Resolve <IPlayerManager>();

                playerManager.OnlinePlayers
                .Select(c => c as UnturnedPlayer)
                .Where(c => c != null)
                .ForEach(p => GiveRep(p, amount));

                if (amount >= 0)
                {
                    context.User.SendLocalizedMessage(Translations, "REPUTATION_GIVEN", amount,
                                                      Translations.Get("EVERYONE"));
                }
                else
                {
                    context.User.SendLocalizedMessage(Translations, "REPUTATION_TAKE", -amount,
                                                      Translations.Get("EVERYONE"));
                }

                return;
            }

            if (!(context.Parameters.Get <IPlayer>(1) is UnturnedPlayer player))
            {
                throw new PlayerNameNotFoundException(context.Parameters[1]);
            }

            if (amount >= 0)
            {
                context.User.SendLocalizedMessage(Translations, "REPUTATION_GIVEN", amount, player.DisplayName);
            }
            else
            {
                context.User.SendLocalizedMessage(Translations, "REPUTATION_TAKE", -amount, player.DisplayName);
            }

            GiveRep(player, amount);
        }
コード例 #20
0
        /// <summary>
        /// Initialization of the Mailer bot
        /// </summary>
        public override void Initialize()
        {
            LogDebugToConsoleTranslated("bot.mailer.init");
            LogDebugToConsoleTranslated("bot.mailer.init.db" + Settings.Mailer_DatabaseFile);
            LogDebugToConsoleTranslated("bot.mailer.init.ignore" + Settings.Mailer_IgnoreListFile);
            LogDebugToConsoleTranslated("bot.mailer.init.public" + Settings.Mailer_PublicInteractions);
            LogDebugToConsoleTranslated("bot.mailer.init.max_mails" + Settings.Mailer_MaxMailsPerPlayer);
            LogDebugToConsoleTranslated("bot.mailer.init.db_size" + Settings.Mailer_MaxDatabaseSize);
            LogDebugToConsoleTranslated("bot.mailer.init.mail_retention" + Settings.Mailer_MailRetentionDays + " days");

            if (Settings.Mailer_MaxDatabaseSize <= 0)
            {
                LogToConsoleTranslated("bot.mailer.init_fail.db_size");
                UnloadBot();
                return;
            }

            if (Settings.Mailer_MaxMailsPerPlayer <= 0)
            {
                LogToConsoleTranslated("bot.mailer.init_fail.max_mails");
                UnloadBot();
                return;
            }

            if (Settings.Mailer_MailRetentionDays <= 0)
            {
                LogToConsoleTranslated("bot.mailer.init_fail.mail_retention");
                UnloadBot();
                return;
            }

            if (!File.Exists(Settings.Mailer_DatabaseFile))
            {
                LogToConsoleTranslated("bot.mailer.create.db", Path.GetFullPath(Settings.Mailer_DatabaseFile));
                new MailDatabase().SaveToFile(Settings.Mailer_DatabaseFile);
            }

            if (!File.Exists(Settings.Mailer_IgnoreListFile))
            {
                LogToConsoleTranslated("bot.mailer.create.ignore", Path.GetFullPath(Settings.Mailer_IgnoreListFile));
                new IgnoreList().SaveToFile(Settings.Mailer_IgnoreListFile);
            }

            lock (readWriteLock)
            {
                LogDebugToConsoleTranslated("bot.mailer.load.db", Path.GetFullPath(Settings.Mailer_DatabaseFile));
                mailDatabase = MailDatabase.FromFile(Settings.Mailer_DatabaseFile);

                LogDebugToConsoleTranslated("bot.mailer.load.ignore", Path.GetFullPath(Settings.Mailer_IgnoreListFile));
                ignoreList = IgnoreList.FromFile(Settings.Mailer_IgnoreListFile);
            }

            //Initialize file monitors. In case the bot needs to unload for some reason in the future, do not forget to .Dispose() them
            mailDbFileMonitor     = new FileMonitor(Path.GetDirectoryName(Settings.Mailer_DatabaseFile), Path.GetFileName(Settings.Mailer_DatabaseFile), FileMonitorCallback);
            ignoreListFileMonitor = new FileMonitor(Path.GetDirectoryName(Settings.Mailer_IgnoreListFile), Path.GetFileName(Settings.Mailer_IgnoreListFile), FileMonitorCallback);

            RegisterChatBotCommand("mailer", Translations.Get("bot.mailer.cmd"), "mailer <getmails|addignored|getignored|removeignored>", ProcessInternalCommand);
        }
コード例 #21
0
 /// <summary>
 /// Refreshes invalid token
 /// </summary>
 /// <param name="user">Login</param>
 /// <param name="session">In case of successful token refresh, will contain session information for multiplayer</param>
 /// <returns>Returns the status of the new token request (Success, Failure, etc.)</returns>
 public static LoginResult GetNewToken(SessionToken currentsession, out SessionToken session)
 {
     session = new SessionToken();
     try
     {
         string result       = "";
         string json_request = "{ \"accessToken\": \"" + JsonEncode(currentsession.ID) + "\", \"clientToken\": \"" + JsonEncode(currentsession.ClientID) + "\", \"selectedProfile\": { \"id\": \"" + JsonEncode(currentsession.PlayerID) + "\", \"name\": \"" + JsonEncode(currentsession.PlayerName) + "\" } }";
         int    code         = 0;
         if (Settings.AccountType == AccountType.MCLeaks || Settings.AccountType == AccountType.TheAltening)
         {
             //Impossible with MCLeaks and no clue if this is possible with theAltening
             code   = 403;
             result = "InvalidToken";
         }
         else
         {
             code = DoHTTPSPost("authserver.mojang.com", "/refresh", json_request, ref result);
         }
         if (code == 200)
         {
             if (result == null)
             {
                 return(LoginResult.NullError);
             }
             else
             {
                 Json.JSONData loginResponse = Json.ParseJson(result);
                 if (loginResponse.Properties.ContainsKey("accessToken") &&
                     loginResponse.Properties.ContainsKey("selectedProfile") &&
                     loginResponse.Properties["selectedProfile"].Properties.ContainsKey("id") &&
                     loginResponse.Properties["selectedProfile"].Properties.ContainsKey("name"))
                 {
                     session.ID         = loginResponse.Properties["accessToken"].StringValue;
                     session.PlayerID   = loginResponse.Properties["selectedProfile"].Properties["id"].StringValue;
                     session.PlayerName = loginResponse.Properties["selectedProfile"].Properties["name"].StringValue;
                     return(LoginResult.Success);
                 }
                 else
                 {
                     return(LoginResult.InvalidResponse);
                 }
             }
         }
         else if (code == 403 && result.Contains("InvalidToken"))
         {
             return(LoginResult.InvalidToken);
         }
         else
         {
             ConsoleIO.WriteLineFormatted(Translations.Get("error.auth", code));
             return(LoginResult.OtherError);
         }
     }
     catch
     {
         return(LoginResult.OtherError);
     }
 }
コード例 #22
0
        public override void Initialize()
        {
            SetNetworkPacketEventEnabled(true);
            replay = new ReplayHandler(GetProtocolVersion());
            replay.MetaData.serverName = GetServerHost() + GetServerPort();
            backupCounter = backupInterval;

            RegisterChatBotCommand("replay", Translations.Get("bot.replayCapture.cmd"), "replay <save|stop>", Command);
        }
コード例 #23
0
        private bool StartEncryption(string uuid, string username, string sessionID, byte[] token, string serverIDhash, byte[] serverKey)
        {
            System.Security.Cryptography.RSACryptoServiceProvider RSAService = CryptoHandler.DecodeRSAPublicKey(serverKey);
            byte[] secretKey = CryptoHandler.GenerateAESPrivateKey();

            if (Settings.DebugMessages)
            {
                Translations.WriteLineFormatted("debug.crypto");
            }

            if (serverIDhash != "-")
            {
                Translations.WriteLine("mcc.session");
                if (!ProtocolHandler.SessionCheck(uuid, sessionID, CryptoHandler.getServerHash(serverIDhash, serverKey, secretKey)))
                {
                    handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, Translations.Get("mcc.session_fail"));
                    return(false);
                }
            }

            //Encrypt the data
            byte[] key_enc   = RSAService.Encrypt(secretKey, false);
            byte[] token_enc = RSAService.Encrypt(token, false);
            byte[] keylen    = BitConverter.GetBytes((short)key_enc.Length);
            byte[] tokenlen  = BitConverter.GetBytes((short)token_enc.Length);

            Array.Reverse(keylen);
            Array.Reverse(tokenlen);

            //Building the packet
            byte[] data = new byte[5 + (short)key_enc.Length + (short)token_enc.Length];
            data[0] = 0xFC;
            keylen.CopyTo(data, 1);
            key_enc.CopyTo(data, 3);
            tokenlen.CopyTo(data, 3 + (short)key_enc.Length);
            token_enc.CopyTo(data, 5 + (short)key_enc.Length);

            //Send it back
            Send(data);

            //Getting the next packet
            byte[] pid = new byte[1];
            Receive(pid, 0, 1, SocketFlags.None);
            if (pid[0] == 0xFC)
            {
                readData(4);
                s         = CryptoHandler.getAesStream(c.GetStream(), secretKey);
                encrypted = true;
                return(true);
            }
            else
            {
                Translations.WriteLineFormatted("error.invalid_encrypt");
                return(false);
            }
        }
コード例 #24
0
        /// <summary>
        /// Get the packet type palette
        /// </summary>
        /// <param name="protocol">Protocol version to use</param>
        /// <returns></returns>
        public PacketTypePalette GetTypeHandler(int protocol)
        {
            PacketTypePalette p;

            if (protocol > Protocol18Handler.MC1182Version)
            {
                throw new NotImplementedException(Translations.Get("exception.palette.packet"));
            }
            if (protocol <= Protocol18Handler.MC18Version)
            {
                p = new PacketPalette17();
            }
            else if (protocol <= Protocol18Handler.MC1112Version)
            {
                p = new PacketPalette110();
            }
            else if (protocol <= Protocol18Handler.MC112Version)
            {
                p = new PacketPalette112();
            }
            else if (protocol <= Protocol18Handler.MC1122Version)
            {
                p = new PacketPalette1122();
            }
            else if (protocol <= Protocol18Handler.MC114Version)
            {
                p = new PacketPalette113();
            }
            else if (protocol <= Protocol18Handler.MC115Version)
            {
                p = new PacketPalette114();
            }
            else if (protocol <= Protocol18Handler.MC1152Version)
            {
                p = new PacketPalette115();
            }
            else if (protocol <= Protocol18Handler.MC1161Version)
            {
                p = new PacketPalette116();
            }
            else if (protocol <= Protocol18Handler.MC1165Version)
            {
                p = new PacketPalette1162();
            }
            else if (protocol <= Protocol18Handler.MC1171Version)
            {
                p = new PacketPalette117();
            }
            else
            {
                p = new PacketPalette118();
            }

            p.SetForgeEnabled(this.forgeEnabled);
            return(p);
        }
コード例 #25
0
 /// <summary>
 /// Show error message (thread-safe)
 /// </summary>
 private void ShowErrorMessage(string text)
 {
     if (InvokeRequired)
     {
         Invoke(new Action(() => ShowErrorMessage(text)));
         return;
     }
     MessageBox.Show(text, Translations.Get("gui_error_occured"), MessageBoxButtons.OK, MessageBoxIcon.Error);
     UpdateStatusLabel(Translations.Get("gui_error_occured") + " - " + text);
 }
コード例 #26
0
 /// <summary>
 /// Create a new sound event
 /// </summary>
 /// <param name="name">Sound name. Used for naming sound files and displaying translations</param>
 /// <param name="regKeys">Registry keys where the sound event is stored (some Windows versions may use different keys)</param>
 /// <param name="legacyFilename">Legacy file name for old sound archive format. Taken from Windows XP FR</param>
 /// <param name="imageres">Specify whether the sound is stored in imageres.dll on Windows 7</param>
 private SoundEvent(string name, string[] regKeys, string legacyFilename = null, bool imageres = false)
 {
     this._displayName    = Translations.Get("event_" + name.ToLower() + "_name");
     this._description    = Translations.Get("event_" + name.ToLower() + "_desc");
     this._filePath       = String.Concat(DataDirectory, Path.DirectorySeparatorChar, name, ".wav");
     this._legacyFileName = "Windows XP " + legacyFilename + ".wav";
     this._fileName       = name + ".wav";
     this._regKeys        = regKeys;
     this._imageres       = imageres;
 }
コード例 #27
0
ファイル: FormMain.cs プロジェクト: maxox/Sound-Manager
        /// <summary>
        /// Browse for a new scheme thumbnail
        /// </summary>
        private void imageContextMenu_Change_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = Translations.Get("browse_image_files") + "|*.bmp;*.png;*.jpg;*.jpeg;*.gif;*.tiff";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                changeSchemeThumbnail(dlg.FileName);
            }
        }
コード例 #28
0
ファイル: SoundArchive.cs プロジェクト: maxox/Sound-Manager
        /// <summary>
        /// Associate the SoundArchive file extension to the program
        /// </summary>
        public static void AssocFiles()
        {
            ShellFileType fileType = ShellFileType.GetOrCreateType(FileExtension);

            fileType.DefaultIcon = FileIconPath;
            fileType.Description = Translations.Get("scheme_file_desc");
            fileType.MenuItems[FileExtAction] = new ShellFileType.MenuItem(Translations.Get("button_open"), FileExtCommand);
            fileType.DefaultAction            = FileExtAction;
            fileType.Save();
        }
コード例 #29
0
ファイル: FormMain.cs プロジェクト: maxox/Sound-Manager
        /// <summary>
        /// Import a sound archive file
        /// </summary>
        private void buttonImport_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = String.Concat(Translations.Get("browse_scheme_files"), "|*.", SoundArchive.FileExtension);
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                ImportSoundScheme(dlg.FileName);
            }
        }
コード例 #30
0
        public static bool doPing(string host, int port, ref int protocolversion)
        {
            try
            {
                string    version = "";
                TcpClient tcp     = ProxyHandler.newTcpClient(host, port);
                tcp.ReceiveTimeout = 30000; // 30 seconds
                tcp.ReceiveTimeout = 5000;  //MC 1.7.2+ SpigotMC servers won't respond, so we need a reasonable timeout.
                byte[] ping = new byte[2] {
                    0xfe, 0x01
                };
                tcp.Client.Send(ping, SocketFlags.None);
                tcp.Client.Receive(ping, 0, 1, SocketFlags.None);

                if (ping[0] == 0xff)
                {
                    Protocol16Handler ComTmp = new Protocol16Handler(tcp);
                    string            result = ComTmp.readNextString();

                    if (Settings.DebugMessages)
                    {
                        // May contain formatting codes, cannot use WriteLineFormatted
                        Console.ForegroundColor = ConsoleColor.DarkGray;
                        ConsoleIO.WriteLine(result);
                        Console.ForegroundColor = ConsoleColor.Gray;
                    }

                    if (result.Length > 2 && result[0] == '§' && result[1] == '1')
                    {
                        string[] tmp = result.Split((char)0x00);
                        protocolversion = (byte)Int16.Parse(tmp[1]);
                        version         = tmp[2];

                        if (protocolversion == 127) //MC 1.7.2+
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        protocolversion = (byte)39;
                        version         = "B1.8.1 - 1.3.2";
                    }

                    ConsoleIO.WriteLineFormatted(Translations.Get("mcc.use_version", version, protocolversion));

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch { return(false); }
        }
コード例 #31
0
ファイル: Stats.cs プロジェクト: paulhare93/G2_GraWKolory
 public void TranslateAndSizeButton(Button btn, Text txt, Translate translateComponent, Translations tr)
 {
     txt.text = tr.Get(translateComponent.key);
     btn.image.rectTransform.sizeDelta = new Vector2(btn.GetComponentInChildren<Text>().preferredWidth + spaceWidth, spaceHeight);
 }