Example #1
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            btnConnect.Enabled = false;
            Properties.Settings.Default.Username = txtUsernm.Text;
            Properties.Settings.Default.Password = txtPasswd.Text;
            Properties.Settings.Default.Server   = txtSvr.Text;
            Properties.Settings.Default.Port     = int.Parse(txtPort.Text);
            Properties.Settings.Default.Save();
            updaterProgressBar1.EndColor   = Color.FromArgb(0, 211, 40);
            updaterProgressBar1.StartColor = Color.FromArgb(0, 211, 40);
            updaterProgressBar1.Value      = 0;
            Server s = new Server(txtSvr.Text, txtSvr.Text, int.Parse(txtPort.Text));

            Connection = s.GetConnection();
            Connection.RegisterUser(txtUsernm.Text, txtPasswd.Text);
            TaskManager.AddAsyncTask(delegate
            {
                Connection.ProgressChange += new Connection.ProgressChangeEvent(c_ProgressChange);
                try
                {
                    Connection.Connect();
                }
                catch (LoginFailedException ex)
                {
                    failReason = ex.Message;
                }
            });
        }
 public void Listen()
 {
     Console.WriteLine("Master Server at {0} is online and listening.", Properties.Settings.Default.Port);
     TaskManager.AddAsyncTask(delegate
     {
         string ver;
         bool api;
         if (Extras.CheckForUpdate("master", Program.Version, out ver, out api))
         {
             if (!api)
             {
                 Console.WriteLine("Version {0} is now available for Minecraft Mod Updater.", ver);
             }
             else
             {
                 Console.WriteLine("Version {0} is now available for Minecraft Mod Updater API.", ver);
             }
         }
     });
     while (Online)
     {
         Socket s = listen.AcceptSocket();
         TaskManager.AddAsyncTask(delegate
         {
             Client c              = new Client(this, new PacketHandler(s));
             c.ClientDisconnected += delegate
             {
                 c = null;
             };
         });
     }
 }
 internal static void Open()
 {
     TaskManager.AddAsyncTask(delegate
     {
         new CommandPromptForm().ShowDialog();
     });
 }
 public void Start()
 {
     Address = IPAddress.Loopback;
     try
     {
         string     direction = "";
         WebRequest request   = WebRequest.Create("http://checkip.dyndns.org/");
         using (WebResponse response = request.GetResponse())
         {
             using (StreamReader stream = new StreamReader(response.GetResponseStream()))
             {
                 direction = stream.ReadToEnd();
             }
         }
         int first = direction.IndexOf("Address: ") + 9;
         int last  = direction.LastIndexOf("</body>");
         direction = direction.Substring(first, last - first);
         Address   = IPAddress.Parse(direction);
     }
     catch (Exception e) { MinecraftModUpdater.Logger.Log(e); }
     MinecraftModUpdater.Logger.Log(Logger.Level.Info, "Server IP Address is: " + Address.ToString());
     TcpServer.Start();
     Online = true;
     TaskManager.AddAsyncTask(delegate { SimpleConsoleInputHandler(); });
     TaskManager.AddAsyncTask(delegate
     {
         if (Config.MasterServer != "")
         {
             Socket s  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             string ip = Config.MasterServer.Split(':')[0].Trim();
             int port  = int.Parse(Config.MasterServer.Split(':')[1].Trim());
             ConnectionHandler.ConnectTo(s, ip, port);
             PacketHandler ph = new PacketHandler(s);
             ph.Start();
             Thread.Sleep(1000);
             Packet.Send(new HandshakePacket {
                 Name = Config.ServerName, Port = Config.Port, Address = Address.ToString(), Type = HandshakePacket.SessionType.Server
             }, ph.Stream);
         }
     }, ThreadRole.Delayed, 1000);
     TaskManager.AddAsyncTask(delegate
     {
         string ver;
         bool api;
         if (Extras.CheckForUpdate("server", Program.Version, out ver, out api))
         {
             if (!api)
             {
                 MinecraftModUpdater.Logger.Log(Logger.Level.Info, "Version {0} is now available for Minecraft Mod Updater.", ver);
             }
             else
             {
                 MinecraftModUpdater.Logger.Log(Logger.Level.Info, "Version {0} is now available for Minecraft Mod Updater API.", ver);
             }
         }
     });
     Receive();
 }
Example #5
0
 private void MainForm_Load(object sender, EventArgs e)
 {
     TaskManager.AddAsyncTask(delegate
     {
         string direction   = "";
         WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
         using (WebResponse response = request.GetResponse())
         {
             using (StreamReader stream = new StreamReader(response.GetResponseStream()))
             {
                 direction = stream.ReadToEnd();
             }
         }
         int first    = direction.IndexOf("Address: ") + 9;
         int last     = direction.LastIndexOf("</body>");
         direction    = direction.Substring(first, last - first);
         LocalAddress = IPAddress.Parse(direction);
     });
     ExceptionHandler.CloseProgram += new ModUpdaterDelegate(ExceptionHandler_CloseProgram);
     Debug.Assert("Debug mode is enabled.  In-depth messages will be displayed.");
     if (ProgramOptions.Debug)
     {
         MinecraftModUpdater.Logger.Log(Logger.Level.Warning, "Client is running in debug-mode.");
     }
     if (ProgramOptions.CommandLine)
     {
         MinecraftModUpdater.Logger.Log(Logger.Level.Warning, "Client is running in commandline.");
     }
     TaskManager.AddAsyncTask(delegate
     {
         string ver;
         bool api;
         if (Extras.CheckForUpdate("client", Program.Version, out ver, out api))
         {
             UpdateForm.Open(ver, api);
         }
     });
     if (Properties.Settings.Default.FirstRun)
     {
         TaskManager.AddAsyncTask(delegate
         {
             SplashScreen.ShowSplashScreen();
         });
         OnFirstRun();
     }
     if (recover)
     {
         Recover();
         return;
     }
     if (!PrepareConnection())
     {
         Close();
     }
     Connect();
 }
 void HandleDisconnect(Packet p)
 {
     TaskManager.AddAsyncTask(delegate
     {
         ph.RemovePacketHandler(PacketId.Handshake);
         ph.RemovePacketHandler(PacketId.RequestMod);
         ph.RemovePacketHandler(PacketId.Log);
         ph.RemovePacketHandler(PacketId.Disconnect);
     });
     ph.Disconnect -= ClientLeft;
     ClientDisconnected(this, EventArgs.Empty);
 }
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                foreach (string s in args)
                {
                    switch (s)
                    {
                    case "-commandline":
                        CommandPromptForm.Open();
                        ProgramOptions.CommandLine = true;
                        break;

                    case "-debug":
                        ProgramOptions.Debug = true;
                        break;

                    case "-reset":
                        Properties.Settings.Default.Reset();
                        Properties.Settings.Default.Save();
                        break;
                    }
                }
            }
            ExceptionHandler.Init();
            AppStatus = Utility.AppStatus.Init;
            WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

            ProgramOptions.Administrator = pricipal.IsInRole(WindowsBuiltInRole.Administrator);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            TaskManager.AddAsyncTask(delegate
            {
                //throw new SystemException("Error", new SystemException("Other Error"));
            });
            string name = Process.GetCurrentProcess().ProcessName;

            if (Process.GetProcessesByName(name).Length != 1)
            {
                foreach (Process pr in Process.GetProcessesByName(name))
                {
                    if (pr.MainModule.BaseAddress == Process.GetCurrentProcess().MainModule.BaseAddress)
                    {
                        if (pr.Id != Process.GetCurrentProcess().Id)
                        {
                            pr.Kill();
                        }
                    }
                }
            }
            Application.Run(new MainForm());
        }
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            TaskManager.ExceptionRaised += new TaskManagerError(HandleException);
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

#if DEBUG
            TaskManager.AddAsyncTask(delegate { new LoggerForm().ShowDialog(); });
#endif
            Application.Run(new MainForm());
        }
 public void Receive()
 {
     while (Online)
     {
         try
         {
             Socket s = TcpServer.AcceptSocket();
             TaskManager.SpawnTaskThread(ThreadRole.Standard);
             TaskManager.AddAsyncTask(delegate
             {
                 AcceptClient(s);
             });
         }
         catch { }
     }
 }
Example #10
0
 public static void HandleException(Exception e, object sender)
 {
     if (ProgramCrashed)
     {
         return;
     }
     ProgramCrashed = true;
     try
     {
         MainForm.Instance.Invoke(new ModUpdaterDelegate(delegate
         {
             new ExceptionHandler(e, sender).ShowDialog();
         }));
     }
     catch { TaskManager.AddAsyncTask(delegate { new ExceptionHandler(e, sender).ShowDialog(); }, ThreadRole.Important); }
 }
Example #11
0
        private bool PrepareConnection()
        {
            ConnectionForm cf = new ConnectionForm();

            if (cf.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return(false);
            }
            TaskManager.AddAsyncTask(delegate
            {
                SplashScreen.ShowSplashScreen();
            });
            Debug.Assert("Launching Program.");
            SplashScreen.UpdateStatusTextWithStatus("Preparing to connect to the update server...", TypeOfMessage.Warning);
            Thread.Sleep(3000);
            SplashScreen.GetScreen().Progress.Step = 20;
            Program.AppStatus = AppStatus.Connecting;
            SplashScreen.UpdateStatusText("Connecting...");
            SplashScreen.GetScreen().Progress.PerformStep();
            return(true);
        }
Example #12
0
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (lsModsToUpdate.Items.Count == 0)
            {
                if (Properties.Settings.Default.LaunchAfterUpdate)
                {
                    if (Properties.Settings.Default.FirstRun || !File.Exists(Properties.Settings.Default.MinecraftPath + "/bin/version"))
                    {
                        Program.UpdateMinecraft();
                    }
                    SplashScreen.CloseSplashScreen();
                    Hide();
                    Program.StartMinecraft();
                }
                Program.RunOnUIThread(delegate
                {
                    Close();
                });
                return;
            }
            Program.AppStatus = AppStatus.Updating;
            if (!Properties.Settings.Default.AutoUpdate)
            {
                if (MessageBox.Show("Are you sure you want to update " + lsModsToUpdate.Items.Count + " mods and delete " + lsModsToDelete.Items.Count + " more?", "Confirm Update Action", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
                {
                    return;
                }
            }
            foreach (object m in lsModsToUpdate.Items)
            {
                progress[3] += (int)((Mod)m).Size;
            }
            if (!Properties.Settings.Default.AutoUpdate)
            {
                TaskManager.AddAsyncTask(delegate
                {
                    SplashScreen.ShowSplashScreen();
                });
            }
            while (SplashScreen.GetScreen() == null)
            {
                ;
            }
            while (SplashScreen.GetScreen().Opacity != 1)
            {
                ;
            }
            if (Properties.Settings.Default.FirstRun || !File.Exists(Properties.Settings.Default.MinecraftPath + "/bin/version"))
            {
                Program.UpdateMinecraft();
            }
            SplashScreen.UpdateStatusText("Downloading Updates...");
            SplashScreen.GetScreen().Invoke(new ModUpdaterDelegate(delegate
            {
                SplashScreen.GetScreen().lblTitle.Font.Dispose();
                SplashScreen.GetScreen().lblTitle.Font       = new Font(FontFamily.GenericSansSerif, Server.FontSize);
                SplashScreen.GetScreen().lblTitle.Text       = Server.Name;
                SplashScreen.GetScreen().lblProgress.Visible = true;
                SplashScreen.GetScreen().lblProgress.Text    = "0%";
            }));
            foreach (object o in lsModsToDelete.Items)
            {
                string m    = (string)o;
                string path = Properties.Settings.Default.MinecraftPath + "\\" + Path.GetDirectoryName(m) + Path.GetFileName(m).TrimEnd('\\').Replace("clientmods", "mods");
                File.Delete(Properties.Settings.Default.MinecraftPath + @"\mods\" + Path.GetFileName(m));
            }
            Mod mod = (Mod)lsModsToUpdate.Items[progress[0]];

            if (lsModsToUpdate.Items.Contains(mod))
            {
                Packet.Send(new RequestModPacket {
                    Type = RequestModPacket.RequestType.Download, Identifier = mod.Identifier
                }, ph.Stream);
            }
            TaskManager.AddAsyncTask(delegate
            {
                while (CurrentDownload == null)
                {
                    ;
                }
                int i    = 5;
                int kbps = 0;
                while (warnDisconnect == true)
                {
                    SplashScreen.GetScreen().Invoke(new ModUpdaterDelegate(delegate
                    {
                        SplashScreen.GetScreen().lblProgress.Text = string.Format(string.Format("{0:0%}", percentage) + " at {0} KB/s", kbps);
                        SplashScreen.GetScreen().Progress.Value   = Convert.ToInt32(percentage.ToString("0%").Replace("%", ""));
                        if (i == 10)
                        {
                            kbps         = (dlThisSecond) / 1000;
                            dlThisSecond = 0;
                            i            = 0;
                        }
                    }));
                    i++;

                    Thread.Sleep(100);
                }
            });
            Hide();
        }
Example #13
0
        private void Connect()
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket = s;
            Debug.Assert("Creating Objects.");
            try
            {
                string srv  = Server.Address;
                int    port = Server.Port;
                if (srv == LocalAddress.ToString())
                {
                    srv = "127.0.0.1";
                }
                ConnectionHandler.ConnectTo(s, srv, port);
                SplashScreen.GetScreen().Progress.PerformStep();
            }
            catch (SocketException ex)
            {
                Debug.Assert(ex);
                MessageBox.Show("There was an error while connecting to the update server.  I will now self destruct.");
                Thread.Sleep(1000);
                SplashScreen.UpdateStatusTextWithStatus("Boom!!!", TypeOfMessage.Error);
                Thread.Sleep(5000);
                SplashScreen.UpdateStatusTextWithStatus("That was a joke, by the way.", TypeOfMessage.Warning);
                Thread.Sleep(1000);
                SplashScreen.CloseSplashScreen();
                Thread.Sleep(3000);
                Close();
                return;
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex, this);
            }
            modImages            = new ImageList();
            modImages.ImageSize  = new Size(230, 180);
            modImages.ColorDepth = ColorDepth.Depth32Bit;
            SplashScreen.GetScreen().Progress.PerformStep();
            TaskManager.AddAsyncTask(delegate
            {
                while (s.Connected)
                {
                    ;
                }
                if (!warnDisconnect)
                {
                    return;
                }
                if (SplashScreen.GetScreen() != null)
                {
                    SplashScreen.UpdateStatusTextWithStatus("Lost connection to server.", TypeOfMessage.Error);
                    Thread.Sleep(5000);
                }
                else
                {
                    MessageBox.Show("Lost connection to server.");
                }
                Program.RunOnUIThread(delegate
                {
                    Close();
                });
            });
            MinecraftModUpdater.Logger.Log(Logger.Level.Info, "Logging started.");
            ph = new PacketHandler(s);
            ph.Start();
            for (int i = 0; i < 10; i++)
            {
                TaskManager.SpawnTaskThread(ThreadRole.Standard);
            }
            TaskManager.AddAsyncTask(delegate
            {
                ph.RegisterPacketHandler(PacketId.Metadata, ph_Metadata);
                ph.RegisterPacketHandler(PacketId.ModInfo, ph_ModInfo);
                ph.RegisterPacketHandler(PacketId.ModList, ph_ModList);
                ph.RegisterPacketHandler(PacketId.AllDone, ph_AllDone);
                ph.RegisterPacketHandler(PacketId.NextDownload, ph_NextDownload);
                ph.RegisterPacketHandler(PacketId.FilePart, ph_FilePart);
                ph.RegisterPacketHandler(PacketId.Image, ph_Image);
                Debug.Assert("Packet Handlers registered.");
                SplashScreen.GetScreen().Progress.PerformStep();
            });
            if ((new LoginForm()).ShowDialog() != DialogResult.OK)
            {
                MinecraftModUpdater.Logger.Log(Logger.Level.Error, "Login failed");
                SplashScreen.UpdateStatusTextWithStatus("Your login failed.", TypeOfMessage.Error);
                Thread.Sleep(2000);
                SplashScreen.CloseSplashScreen();
                Thread.Sleep(400);
                Close();
                return;
            }
            Thread.Sleep(1000);
            SplashScreen.UpdateStatusText("Connected to server.  Retreving Mod List.");
            Packet.Send(new HandshakePacket {
                Username = ProgramOptions.Username
            }, ph.Stream);
            Debug.Assert("Sent Handshake Packet.");
            Thread.Sleep(100);
            for (int i = 0; i < 5; i++)
            {
                SplashScreen.GetScreen().Progress.Value += 1;
                Thread.Sleep(20);
            }
        }
Example #14
0
        void ph_AllDone(Packet pa)
        {
            AllDonePacket p = pa as AllDonePacket;
            int           i = 0;

            while (progress[1] != progress[2])
            {
                if (i > 10)
                {
                    SplashScreen.UpdateStatusText("There was an error while downloading.  Retrying...");
                    Thread.Sleep(5000);
                    Packet.Send(new RequestModPacket {
                        Type = RequestModPacket.RequestType.Download, Identifier = p.Identifier
                    }, ph.Stream);
                    return;
                }
                i++;
                Thread.Sleep(1000);
            }
            Mod    m    = Mods.Find(p.Identifier);
            string path = Path.GetDirectoryName(Properties.Settings.Default.MinecraftPath + "\\" + m.File);

            File.WriteAllBytes(path + "\\" + Path.GetFileName(m.File), CurrentDownload.Contents);
            MinecraftModUpdater.Logger.Log(Logger.Level.Info, "Downloaded " + path + "\\" + Path.GetFileName(m.File));
            ProcessStartInfo pr = new ProcessStartInfo("cmd");

            pr.CreateNoWindow         = true;
            pr.UseShellExecute        = false;
            pr.RedirectStandardOutput = true;
            pr.RedirectStandardInput  = true;
            Process proc = new Process();

            proc.StartInfo = pr;
            proc.Start();
            foreach (string s in m.PostDownload)
            {
                try
                {
                    proc.StandardInput.WriteLine(s);
                }
                catch (Exception e) { ExceptionHandler.HandleException(e, this); }
            }
            proc.Kill();
            MinecraftModUpdater.Logger.Log(Logger.Level.Info, "[Post Download] " + proc.StandardOutput.ReadToEnd());
            if (GetLastModToUpdate().File == m.File)
            {
                SplashScreen.UpdateStatusText("All files downloaded!");
                Thread.Sleep(1000);
                warnDisconnect = false;
                Packet.Send(new LogPacket {
                    LogMessages = MinecraftModUpdater.Logger.GetMessages()
                }, ph.Stream);
                Packet.Send(new DisconnectPacket(), ph.Stream);
                ph.RemovePacketHandler(PacketId.Metadata);
                ph.RemovePacketHandler(PacketId.ModInfo);
                ph.RemovePacketHandler(PacketId.ModList);
                ph.RemovePacketHandler(PacketId.NextDownload);
                ph.RemovePacketHandler(PacketId.FilePart);
                ph.RemovePacketHandler(PacketId.AllDone);
                TaskManager.AddAsyncTask(delegate
                {
                    ph.Stop();
                }, ThreadRole.Delayed, 5000);
                if (Properties.Settings.Default.LaunchAfterUpdate)
                {
                    Program.RunOnUIThread(delegate
                    {
                        Program.StartMinecraft();
                    });
                }
                else
                {
                    SplashScreen.CloseSplashScreen();
                }
                Program.RunOnUIThread(delegate
                {
                    Close();
                });
                return;
            }
            progress[0]++;
            m = (Mod)lsModsToUpdate.Items[progress[0]];
            Packet.Send(new RequestModPacket {
                Type = RequestModPacket.RequestType.Download, Identifier = m.Identifier
            }, ph.Stream);
        }
Example #15
0
        public Mod(string ConfigFile)
        {
            ModName          = "Unnamed";
            Author           = "No Author Given.";
            ModFile          = "";
            PostDownloadCLI  = new string[0];
            BlacklistedUsers = new List <string>();
            WhitelistedUsers = new List <string>();
            FileSize         = 0;
            Description      = "No description given.";

            modFile   = new XmlDocument();
            FileParts = new List <List <byte> >();
            modFile.Load(ConfigFile);
            this.ConfigFile = ConfigFile;
            XmlNodeList nodes = modFile.SelectNodes("/Mod");
            XmlNode     n     = nodes[0];

            try
            {
                ModName = n["Name"].InnerText;
            }
            catch
            {
                n.AppendChild(modFile.CreateElement("Name"));
            }
            try
            {
                Author = n["Author"].InnerText;
            }
            catch { n.AppendChild(modFile.CreateElement("Author")); }
            try
            {
                ModFile = n["File"].InnerText;
            }
            catch { n.AppendChild(modFile.CreateElement("File")); }
            try
            {
                Optional = bool.Parse(n["Optional"].InnerText);
            }
            catch { Optional = false; }
            try
            {
                PostDownloadCLI = new string[0];
                XmlNode node = n["PostDownload"];
                PostDownloadCLI = new string[node.ChildNodes.Count];
                int i = 0;
                foreach (XmlNode action in node)
                {
                    if (action.Name != "Action")
                    {
                        continue;
                    }
                    PostDownloadCLI[i] = action.InnerText;
                    i++;
                }
            }
            catch { n.AppendChild(modFile.CreateElement("PostDownload")); }
            try
            {
                WhitelistedUsers = new List <string>();
                XmlNode node = n["Whitelist"];
                int     i    = 0;
                foreach (XmlNode user in node)
                {
                    if (user.Name != "Username")
                    {
                        continue;
                    }
                    WhitelistedUsers.Add(user.InnerText);
                    i++;
                }
            }
            catch { n.AppendChild(modFile.CreateElement("Whitelist")); }
            try
            {
                BlacklistedUsers = new List <string>();
                XmlNode node = n["Blacklist"];
                int     i    = 0;
                foreach (XmlNode user in node)
                {
                    if (user.Name != "Username")
                    {
                        continue;
                    }
                    BlacklistedUsers.Add(user.InnerText);
                    i++;
                }
            }
            catch { n.AppendChild(modFile.CreateElement("Blacklist")); }
            try
            {
                if (!string.IsNullOrEmpty(n["Description"].InnerText))
                {
                    Description = n["Description"].InnerText;
                }
            }
            catch { n.AppendChild(modFile.CreateElement("Description")); }
            try
            {
                Identifier = n["Identifier"].InnerText;
            }
            catch
            {
                n.AppendChild(modFile.CreateElement("Identifier"));
                string unix = Extras.GenerateHashFromString(new UnixTime().ToString());
                string id   = "";
                for (int i = 0; i < 8; i++)
                {
                    id += unix[i];
                }
                n["Identifier"].InnerText = "";
            }
            if (ModFile.Contains("minecraft.jar"))
            {
                TaskManager.AddAsyncTask(delegate
                {
                    for (int i = 0; i < 10; i++)
                    {
                        Console.Beep();
                        Thread.Sleep(50);
                    }
                    MinecraftModUpdater.Logger.Log(Logger.Level.Info, "WARNING: Sending minecraft.jar is not allowed under the Minecraft Terms of Use.  Please send jar mods in bin/jarmods.jar.");
                });
            }
            ReadFile();
        }
Example #16
0
 private void button4_Click(object sender, EventArgs e)
 {
     downloaded   = 0; //We're using this as uploaded now.
     downloadSize = 0; //Same here.
     foreach (Mod m in changedMods.ToArray())
     {
         if (m.Hash != Extras.GenerateHash(m.Contents))
         {
             downloadSize += m.Contents.Length;
         }
     }
     panel1.Controls.Add(new ControlDownloadProgress());
     TaskManager.AddAsyncTask(HandleSyncScreen);
     TaskManager.AddAsyncTask(delegate
     {
         foreach (Mod m in changedMods.ToArray())
         {
             currentDownload = mods.IndexOf(m); //Again, using this as an upload.
             Packet.Send(new AdminFileInfoPacket
             {
                 Author           = m.Author,
                 BlacklistedUsers = m.BlacklistedUsers.ToArray(),
                 Description      = m.Description,
                 File             = m.File,
                 FileSize         = m.Size,
                 Hash             = m.Hash,
                 ModName          = m.Name,
                 PostDownload     = m.PostDownloadCLI.ToArray(),
                 WhitelistedUsers = m.WhitelistedUsers.ToArray(),
                 Identifier       = m.Identifier,
                 Optional         = m.Optional,
                 Requires         = m.RequiredMods.ToArray()
             }, Connection.PacketHandler.Stream);
             if (m.Hash != Extras.GenerateHash(m.Contents))
             {
                 m.Hash = Extras.GenerateHash(m.Contents);
                 List <List <byte> > bytes = new List <List <byte> >();
                 byte[] file = m.Contents;
                 int k       = 0;
                 for (int i = 0; i < file.Length; i += 1024)
                 {
                     bytes.Add(new List <byte>());
                     for (int j = i; j < i + 1024; j++)
                     {
                         if (file.Length > j)
                         {
                             bytes[k].Add(file[j]);
                         }
                     }
                     k++;
                 }
                 Packet.Send(new UploadFilePacket {
                     Size = m.Size, Parts = bytes.Count, Identifier = m.Identifier
                 }, Connection.PacketHandler.Stream);
                 k = 0;
                 for (int i = 0; i < bytes.Count; i++)
                 {
                     byte[] b = bytes[i].ToArray();
                     Packet.Send(new FilePartPacket {
                         Part = b, Index = k
                     }, Connection.PacketHandler.Stream);
                     k          += bytes[i].Count;
                     downloaded += bytes[i].Count;
                     Thread.Sleep(25);
                 }
                 Packet.Send(new AllDonePacket {
                     Identifier = m.Identifier
                 }, Connection.PacketHandler.Stream);
             }
         }
     });
 }
Example #17
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            ConnectionForm cf = new ConnectionForm();

            if (cf.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                Close();
                return;
            }
            listBox1.Items.AddRange(cf.Connection.Mods);
            mods.AddRange(cf.Connection.Mods);
            Connection   = cf.Connection;
            Text         = "MCModUpdater AdminCP (" + Connection.Server.Name + ")";
            InstancePath = string.Format("{0}{1}Servers{1}{2}{1}WorkingCopy{1}", Environment.CurrentDirectory, Path.DirectorySeparatorChar, Connection.Server.Name);
            if (!Directory.Exists(InstancePath))
            {
                Directory.CreateDirectory(InstancePath);
            }
            int count = 0;

            foreach (Mod m in mods)
            {
                bool exists = File.Exists(InstancePath + m.File);
                if (!exists)
                {
                    m.NeedsUpdate = true;
                    count++;
                    downloadSize += m.Contents.Length;
                    continue;
                }
                bool sameHash = Extras.GenerateHash(InstancePath + m.File) == m.Hash;
                if (!sameHash)
                {
                    m.NeedsUpdate = true;
                    count++;
                    downloadSize += m.Contents.Length;
                    continue;
                }
            }
            if (count > 0)
            {
                amountOfUpdates  = count;
                button1.Enabled  = false;
                listBox1.Enabled = false;
                panel1.Controls.Add(new ControlDownloadProgress());
                MessageBox.Show(string.Format("{0} mods need to be synced.", count), Text + " - Alert");
                Connection.PacketHandler.RegisterPacketHandler(PacketId.NextDownload, HandleDownloadInfo);
                Connection.PacketHandler.RegisterPacketHandler(PacketId.FilePart, HandleFilePart);
                Connection.PacketHandler.RegisterPacketHandler(PacketId.AllDone, HandleAllDone);
                foreach (Mod m in mods)
                {
                    if (m.NeedsUpdate)
                    {
                        Packet.Send(new RequestModPacket {
                            Identifier = m.Identifier, Type = RequestModPacket.RequestType.Download
                        }, Connection.PacketHandler.Stream);
                    }
                    else
                    {
                        m.Contents = File.ReadAllBytes(InstancePath + m.File);
                    }
                }
                TaskManager.AddAsyncTask(HandleSyncScreen);
            }
        }
        public static void UpdateMinecraft()
        {
            if (SplashScreen.GetScreen() == null)
            {
                TaskManager.AddAsyncTask(delegate
                {
                    SplashScreen.ShowSplashScreen();
                });
            }
            Thread.Sleep(100);
            GameUpdater update = new GameUpdater(ProgramOptions.LatestVersion, "minecraft.jar", true);

            SplashScreen.UpdateStatusText("Downloading Minecraft...");
            Thread.Sleep(1000);
            TaskManager.AddAsyncTask(delegate
            {
                SplashScreen.GetScreen().Invoke(new ModUpdaterDelegate(delegate
                {
                    SplashScreen.GetScreen().Progress.Value    = 0;
                    SplashScreen.GetScreen().Progress.MaxValue = 100;
                }));
                while (update.Progress != 100)
                {
                    SplashScreen.GetScreen().Invoke(new ModUpdaterDelegate(delegate
                    {
                        SplashScreen.GetScreen().Progress.Value = update.Progress;
                        SplashScreen.UpdateStatusText(update.Status);
                    }));
                    Thread.Sleep(10);
                }
            });
            update.UpdateGame();
            while (update.Progress != 100)
            {
                ;
            }
            if (!String.IsNullOrEmpty(MainForm.Instance.ClientVersion))
            {
                WebClient cl     = new WebClient();
                string    client = MainForm.Instance.ClientVersion + ".mcdiff";
                SplashScreen.UpdateStatusText("Downloading Patches...");
                byte[] b = cl.DownloadData("http://mcmodpdater.sourceforge.net/patches/1.3.0/" + client);
                using (FileStream output = File.Open("bspatch.exe", FileMode.Create))
                {
                    using (Stream input = Assembly.GetCallingAssembly().GetManifestResourceStream("ModUpdater.Client.Utility.bspatch.exe"))
                    {
                        byte[] buffer = new byte[1024 * 36];
                        int    count  = 0;
                        while ((count = input.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            output.Write(buffer, 0, count);
                        }
                    }
                }
                File.Move(Path.Combine(Properties.Settings.Default.MinecraftPath, "bin", "minecraft.jar"), "minecraft.jar");
                File.WriteAllBytes(client, b);
                SplashScreen.UpdateStatusText("If prompted, please press \"Yes\"");
                Process p = Process.Start("bspatch.exe", "minecraft.jar minecraft.jar " + client);
                while (!p.HasExited)
                {
                }
                File.Move("minecraft.jar", Path.Combine(Properties.Settings.Default.MinecraftPath, "bin", "minecraft.jar"));
                File.Delete("bspatch.exe");
                File.Delete(client);
            }
            using (ZipFile zf = ZipFile.Read(Path.Combine(Properties.Settings.Default.MinecraftPath, "bin", "minecraft.jar")))
            {
                List <ZipEntry> delete = new List <ZipEntry>();
                foreach (ZipEntry ze in zf)
                {
                    if (ze.FileName.Contains("META-INF"))
                    {
                        delete.Add(ze);
                    }
                }
                foreach (ZipEntry ze in delete)
                {
                    zf.RemoveEntry(ze);
                }
                zf.Save();
            }
        }