예제 #1
0
    void HandleInput()
    {
        switch (CubeState)
        {
        case (EnumState.STATE_IDLE):
            if (Input.GetKeyDown("space"))
            {
                GetComponent <Rigidbody>().AddForce(transform.up * 300);
                CubeState = EnumState.STATE_JUMPING;
            }
            break;

        case (EnumState.STATE_JUMPING):
            if (Input.GetKeyDown("space"))
            {
                GetComponent <Rigidbody>().AddForce(transform.up * 400);
                GetComponent <Rigidbody>().AddTorque(new Vector3(0f, 400f, 0f));
                CubeState = EnumState.STATE_DOUBLE_JUMPING;
            }
            break;

        case (EnumState.STATE_DOUBLE_JUMPING):
            if (Input.GetKeyDown("space"))
            {
                GetComponent <Rigidbody>().velocity = Vector3.zero;
                GetComponent <Rigidbody>().AddForce(transform.up * -2000);
                GetComponent <Rigidbody>().angularVelocity = new Vector3(0f, 20000f, 0f);
                CubeState = EnumState.STATE_SLAMMING;
            }
            break;

        case (EnumState.STATE_SLAMMING):
            break;
        }
    }
예제 #2
0
    public void Act()
    {
        switch (CubeState)
        {
        case (EnumState.STATE_IDLE):
            GetComponent <Rigidbody>().AddForce(transform.up * 300);
            CubeState = EnumState.STATE_JUMPING;
            break;

        case (EnumState.STATE_JUMPING):
            GetComponent <Rigidbody>().AddForce(transform.up * 400);
            GetComponent <Rigidbody>().AddTorque(new Vector3(0f, 400f, 0f));
            CubeState = EnumState.STATE_DOUBLE_JUMPING;
            break;

        case (EnumState.STATE_DOUBLE_JUMPING):
            GetComponent <Rigidbody>().velocity = Vector3.zero;
            GetComponent <Rigidbody>().AddForce(transform.up * -2000);
            GetComponent <Rigidbody>().angularVelocity = new Vector3(0f, 20000f, 0f);
            CubeState = EnumState.STATE_SLAMMING;
            break;

        case (EnumState.STATE_SLAMMING):
            break;
        }
    }
예제 #3
0
        internal void SetState(EnumState enumState)
        {
            this.enumState = enumState;
            switch (enumState)
            {
            case EnumState.Create:
                btnSave.Text = "Save";
                TextReadOnly(false);
                break;

            case EnumState.Update:
                btnSave.Text = "Update";
                TextReadOnly(false);
                break;

            case EnumState.Delete:
                btnSave.Text = "Delete";
                TextReadOnly(true);
                break;

            default:
                this.Enabled = false;
                break;
            }
        }
        private void ExtractNatives()
        {
            State = EnumState.EXTRACTING_PACKAGES;

            string nativesJar =
                Path.Combine(Properties.Settings.Default.MinecraftPath + "/bin", Path.GetFileName((uriList[uriList.Length - 1].LocalPath)));
            string nativesDir = Path.Combine(Properties.Settings.Default.MinecraftPath + "/bin", "natives");

            if (!Directory.Exists(nativesDir))
            {
                Directory.CreateDirectory(nativesDir);
            }

            using (ZipFile zf = new ZipFile(nativesJar))
            {
                MinecraftModUpdater.Logger.Log(Logger.Level.Info, string.Format("Extracting natives from {0} to {1}", nativesJar, nativesDir));
                ExtractRecursive(zf, nativesDir);
            }

            if (Directory.Exists(Path.Combine(nativesDir, "META-INF")))
            {
                Directory.Delete(Path.Combine(nativesDir, "META-INF"), true);
            }

            File.Delete(nativesJar);
        }
예제 #5
0
 public void OnEnable()
 {
     if (reset == true)
     {
         value = baseValue;
     }
 }
예제 #6
0
        public BinaryDeserializer()
        {
            _buffer     = new MemoryStream();
            _message    = null;
            _length     = -1;
            _partLength = 0;

            OnDeserializedValue += (value) => {
                if (_length == -1)
                {
                    _length = (int)value;
                }
                else
                {
                    if (_message == null)
                    {
                        _message = new Message((string)value);
                    }
                    else
                    {
                        _message.Add(value);
                    }

                    if (_length == _message.Count)
                    {
                        OnDeserializedMessage?.Invoke(_message);

                        _message = null;
                        _length  = -1;
                    }
                }

                State = EnumState.INIT;
            };
        }
예제 #7
0
 private static void Finish()
 {
     if (State != EnumState.Stop)
     {
         State = EnumState.Finished;
     }
 }
예제 #8
0
 public void ManualReset()
 {
     if (reset == true)
     {
         value = baseValue;
     }
 }
예제 #9
0
        public State GetState(EnumState type)
        {
            State newState = null;

            switch (type)
            {
            case EnumState.LOGIN:
                newState = new LoginState();
                break;

            case EnumState.CHARACTER_SELECT:
                newState = new CharacterSelectState();
                break;

            case EnumState.CHARACTER_CREATION:
                newState = new CharacterCreationState();
                break;

            case EnumState.HUB:
                newState = new HubState();
                break;

            case EnumState.GAME:

                break;

            case EnumState.TEST:
                newState = new TestState();
                break;
            }

            return(newState);
        }
 public void Play()
 {
     _eState           = EnumState.ePlaying;
     _timeStartPlaying = Time.realtimeSinceStartup;
     _source.time      = _timeline;
     _source.Play();
 }
 /// <summary>
 /// Converts the value of this instance to an equivalent EnumState value.
 /// </summary>
 /// <returns>A valid EnumState, assuming the source value can be correctly converted.</returns>
 public EnumState ToEnumState(EnumPairCollection enumPairs)
 {
     if (_value == null)
         return new EnumState(enumPairs.EnumIds);
     else
         return EnumState.FromWireValue(enumPairs, ToString(CultureInfo.InvariantCulture));
 }
예제 #12
0
        private void handleStates()
        {
            switch (currentState)
            {
            case EnumState.none: win.Close();
                break;

            case EnumState.main: gameState = new MainMenue();
                break;

            case EnumState.ingame: gameState = new InGame();
                break;

            case EnumState.won: gameState = new GameOver();
                break;

            case EnumState.controls: gameState = new Controls();
                break;

            case EnumState.credits: gameState = new Credits();
                break;
            }
            gameState.initialize();
            gameState.load();
            prevState = currentState;
        }
예제 #13
0
    public void setItem(ItemRadio item)
    {
        this.radioItem = item;

        this.state = EnumState.WAIT;

        this.playClipOnRadio(ItemRadio.EnumClip.SENDING_HELP);
    }
예제 #14
0
 void OnCollisionEnter(Collision contact)
 {
     if (contact.gameObject.CompareTag("Floor"))
     {
         GetComponent <Rigidbody>().velocity = Vector3.zero;
         CubeState = EnumState.STATE_IDLE;
     }
 }
예제 #15
0
 public override void update(GameTime gTime)
 {
     if (currentState != prevState)
     {
         handleStates();
     }
     currentState = gameState.update(gTime);
 }
예제 #16
0
 public void PlayAnimation()
 {
     if (Enabled)
     {
         m_Animator.Play("Open", -1);
         m_State = EnumState.Open;
     }
 }
        public void UpdateGame()
        {
            try
            {
                State    = EnumState.CHECKING_CACHE;
                Progress = 5;

                // Get a list of URLs to download from
                LoadJarURLs();

                // Create the bin directory if it doesn't exist
                if (!Directory.Exists(Properties.Settings.Default.MinecraftPath + "/bin"))
                {
                    Directory.CreateDirectory(Properties.Settings.Default.MinecraftPath + "/bin");
                }

                string binDir = Properties.Settings.Default.MinecraftPath + "/bin";
                if (this.latestVersion != null)
                {
                    string versionFile    = Path.Combine(binDir, "version");
                    bool   cacheAvailable = false;

                    if (!forceUpdate && File.Exists(versionFile) &&
                        (latestVersion.Equals("-1") ||
                         latestVersion.Equals(File.ReadAllText(versionFile))))
                    {
                        cacheAvailable = true;
                        Progress       = 90;
                    }

                    if ((forceUpdate) || (!cacheAvailable))
                    {
                        shouldUpdate = true;
                        if (this.shouldUpdate)
                        {
                            WriteVersionFile(versionFile, latestVersion);

                            try
                            {
                                DownloadJars();
                            }
                            catch (WebException e)
                            {
                                throw new Exception("An error occurred when downloading packages.", e);
                            }
                            ExtractNatives();
                            Progress = 100;
                        }
                    }
                }
            }
            catch (WebException e)
            {
                MCModUpdaterExceptionHandler.HandleException(this, new Exception("An error occurred when trying to download Minecraft.", e));

                return;
            }
        }
예제 #18
0
        void Start()
        {
            Debug.Assert(!string.IsNullOrEmpty(Name), "Name is null or empty, are you sure this is interactive?");
            Debug.Assert(!string.IsNullOrEmpty(Name), "Name is null or empty, are you sure this is interactive?");
            Debug.Assert(GOAnimator != null, "Animator is null!");

            m_Animator = GOAnimator.GetComponent <Animator>();
            m_State    = EnumState.Close;
        }
예제 #19
0
    // Start is called before the first frame update
    void Start()
    {
        gameObject.GetComponent <SpriteRenderer>().sprite = sprites[0];
        _setCaster(0, true);
        _setCaster(1, false);
        _setCaster(2, false);

        _stableFlag = true;
        _state      = EnumState.Close;
    }
예제 #20
0
 /// <summary>
 /// Converts the value of this instance to an equivalent EnumState value.
 /// </summary>
 /// <returns>A valid EnumState, assuming the source value can be correctly converted.</returns>
 public EnumState ToEnumState(EnumPairCollection enumPairs)
 {
     if (_value == null)
     {
         return(new EnumState(enumPairs.EnumIds));
     }
     else
     {
         return(EnumState.FromWireValue(enumPairs, ToString(null)));
     }
 }
예제 #21
0
 public void ManualReset()
 {
     if (variable != null)
     {
         variable.ManualReset();
     }
     else
     {
         value = baseValue;
     }
 }
    public void Pause()
    {
        if (_eState == EnumState.ePlaying)
        {
            _timeline         = _timeline + (Time.realtimeSinceStartup - _timeStartPlaying);
            _timeline         = Mathf.Clamp(_timeline, 0, _source.clip.length);
            _timeStartPlaying = 0;
        }

        _eState = EnumState.ePausing;
        _source.Pause();
    }
예제 #23
0
 public Car(int id, string name, DateTime yearOfProduction, decimal price, string img, string model, EnumKind typeOfFuel,
            EnumState state, int mileage)
 {
     this.Id               = id;
     this.Name             = name;
     this.YearOfProduction = yearOfProduction;
     this.Img              = img;
     this.Model            = model;
     this.TypeOfFuel       = typeOfFuel;
     this.State            = state;
     this.Mileage          = mileage;
 }
예제 #24
0
    public void SetState(EnumState state)
    {
        if (currentState != null)
        {
            currentState.OnExit();
        }

        this.state = state;

        currentState = stateDictionary[state];
        currentState.OnStart();
    }
예제 #25
0
        public void SetState(int assignmentId, EnumState state, EnumStateActionTaken action, string userName)
        {
            var itemState = new LeadAssignmentState
            {
                LeadAssignmentId = assignmentId,
                StateId          = state.ToString(),
                Actor            = userName,
                Action           = action.ToString(),
                ActionTimestamp  = DateHelper.Now
            };

            _context.LeadAssignmentStates.Add(itemState);
        }
예제 #26
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="result"></param>
 public void SetResult(T result)
 {
     lock (innerlock)
     {
         if (State == EnumState.InPool)
         {
             throw new InvalidOperationException($"Task does not exist/任务不存在");
         }
         this.Result = result;
         State       = EnumState.Success;
         TryComplete();
     }
 }
예제 #27
0
        public static EnumState Next(this EnumState state)
        {
            switch (state)
            {
            case EnumState.CHOOSE_FILES:
                return(EnumState.VIEW_LOG);

            case EnumState.VIEW_LOG:
                return(EnumState.CHOOSE_FILES);
            }
            // Unreachable code?
            throw new NotImplementedException($"Для значения '{state}' enum '{nameof(EnumState)}' не предусмотрено перехода в следующее состояние!");
        }
예제 #28
0
    public void RegisterState <T>(EnumState stateId) where T : GameState, new()
    {
        if (m_stateMap == null)
        {
            return;
        }
        T gameState = new T
        {
            StateID = stateId
        };

        m_stateMap.Add(stateId, gameState);
    }
예제 #29
0
        public void SetState(Guid leadId, EnumState state, EnumStateActionTaken action, string userName)
        {
            var leadState = new LeadState()
            {
                LeadId          = leadId,
                StateId         = state.ToString(),
                Actor           = userName,
                Action          = action.ToString(),
                ActionTimestamp = DateHelper.Now
            };

            _context.LeadStates.Add(leadState);
        }
예제 #30
0
        /// <summary>
        ///
        /// </summary>
        public void CancelWithNotExceptionAndContinuation()
        {
            lock (innerlock)
            {
                if (State == EnumState.InPool)
                {
                    throw new InvalidOperationException($"Task does not exist/任务不存在");
                }

                Result = default;
                State  = EnumState.Faild;
                TryComplete();
            }
        }
        private void ExtractNatives()
        {
            State = EnumState.EXTRACTING_PACKAGES;

            string nativesJar =
                Path.Combine(Properties.Settings.Default.MinecraftPath + "/bin", Path.GetFileName((uriList[uriList.Length - 1].LocalPath)));
            string nativesDir = Path.Combine(Properties.Settings.Default.MinecraftPath + "/bin", "natives");

            if (!Directory.Exists(nativesDir))
                Directory.CreateDirectory(nativesDir);

            using (ZipFile zf = new ZipFile(nativesJar))
            {
                MinecraftModUpdater.Logger.Log(Logger.Level.Info, string.Format("Extracting natives from {0} to {1}", nativesJar, nativesDir));
                ExtractRecursive(zf, nativesDir);
            }

            if (Directory.Exists(Path.Combine(nativesDir, "META-INF")))
                Directory.Delete(Path.Combine(nativesDir, "META-INF"), true);

            File.Delete(nativesJar);
        }
 public bool IsOrigin(EnumState compared, EnumState value)
 {
     return (Interlocked.CompareExchange(ref this.OriginValue, (int)value, (int)compared) == (int)compared);
 }
예제 #33
0
        protected void LoadJarURLs()
        {
            State = EnumState.DETERMINING_PACKAGES;
            string[] jarList = new string[]
            {
                this.mainGameUrl, "lwjgl_util.jar", "jinput.jar", "lwjgl.jar"
            };

            this.uriList = new Uri[jarList.Length + 1];
            Uri forkkBaseUri = new Uri(Resources.ForkkMCDLUri);
            Uri mojangBaseUri = new Uri(Resources.MojangMCDLUri);

            for (int i = 0; i < jarList.Length; i++)
            {
                // minecraft.jar should be downloaded from mojang
                if (i == 0)
                    this.uriList[i] = new Uri(mojangBaseUri, jarList[i]);

                // The latest LWJGL should be downloaded from Forkk's dropbox
                // since minecraft's version doesn't work with MultiMC
                else
                    this.uriList[i] = new Uri(forkkBaseUri, jarList[i]);
            }

            string nativeJar = string.Empty;

            if (OSUtils.Windows)
                nativeJar = "windows_natives.jar";
            else if (OSUtils.Linux)
                nativeJar = "linux_natives.jar";
            else if (OSUtils.MacOSX)
                nativeJar = "macosx_natives.jar";
            else
            {
                OnErrorMessage("Your operating system is not supported.");
                Cancel();
            }

            this.uriList[this.uriList.Length - 1] = new Uri(forkkBaseUri, nativeJar);
        }
예제 #34
0
        protected void ExtractNatives()
        {
            State = EnumState.EXTRACTING_PACKAGES;

            string nativesJar =
                Path.Combine(Inst.BinDir, GetFileName(uriList[uriList.Length - 1]));
            string nativesDir = Path.Combine(Inst.BinDir, "native");

            if (!Directory.Exists(nativesDir))
                Directory.CreateDirectory(nativesDir);

            ZipFile zf = new ZipFile(nativesJar);
            Console.WriteLine(string.Format("Extracting natives from {0} to {1}", nativesJar, nativesDir));
            ExtractRecursive(zf, nativesDir);
            zf.Dispose();

            if (Directory.Exists(Path.Combine(nativesDir, "META-INF")))
                Directory.Delete(Path.Combine(nativesDir, "META-INF"), true);

            File.Delete(nativesJar);
        }
예제 #35
0
        protected void DownloadJars()
        {
            Properties md5s = new Properties();
            if (File.Exists(Path.Combine(Inst.BinDir, "md5s")))
                md5s.Load(Path.Combine(Inst.BinDir, "md5s"));
            State = EnumState.DOWNLOADING;

            int[] fileSizes = new int[this.uriList.Length];
            bool[] skip = new bool[this.uriList.Length];

            // Get the headers and decide what files to skip downloading
            for (int i = 0; i < uriList.Length; i++)
            {
                Console.WriteLine("Getting header " + uriList[i].ToString());

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uriList[i]);
                request.Method = "HEAD";

                string etagOnDisk = null;
                if (md5s.ContainsKey(GetFileName(uriList[i])))
                    etagOnDisk = md5s[GetFileName(uriList[i])];

                if (!forceUpdate && !string.IsNullOrEmpty(etagOnDisk))
                    request.Headers[HttpRequestHeader.IfNoneMatch] = etagOnDisk;

                HttpWebResponse response = ((HttpWebResponse)request.GetResponse());

                int code = (int)response.StatusCode;
                if (code == 300)
                    skip[i] = true;

                fileSizes[i] = (int)response.ContentLength;
                this.totalDownloadSize += fileSizes[i];
                Console.WriteLine("Got response: " + code + " and file size of " +
                                  fileSizes[i] + " bytes");
            }

            int initialPercentage = Progress;

            byte[] buffer = new byte[1024 * 10];
            for (int i = 0; i < this.uriList.Length; i++)
            {
                if (skip[i])
                {
                    Progress = (initialPercentage + fileSizes[i] * 45 / this.totalDownloadSize);
                }
                else
                {
                    string currentFile = GetFileName(uriList[i]);
                    md5s.Remove(currentFile);
                    md5s.Save(Path.Combine(Inst.BinDir, "md5s"));

                    int failedAttempts = 0;
                    const int MAX_FAILS = 3;
                    bool downloadFile = true;

                    // Download the files
                    while (downloadFile)
                    {
                        downloadFile = false;

                        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uriList[i]);
                        request.Headers[HttpRequestHeader.CacheControl] = "no-cache";

                        Console.WriteLine("Getting response");
                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                        Console.WriteLine("Done");

                        string etag = response.Headers[HttpResponseHeader.ETag];
                        etag = etag.TrimEnd('"').TrimStart('"');

                        Stream dlStream = response.GetResponseStream();
                        FileStream fos =
                            new FileStream(Path.Combine(Inst.BinDir, currentFile), FileMode.Create);
                        int fileSize = 0;

                        MD5 digest = MD5.Create();
                        digest.Initialize();
                        int readSize;
                        while ((readSize = dlStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
            //							Console.WriteLine("Read " + readSize + " bytes");
                            fos.Write(buffer, 0, readSize);

                            this.currentDownloadSize += readSize;
                            fileSize += readSize;

                            digest.TransformBlock(buffer, 0, readSize, null, 0);

            //							Progress = fileSize / fileSizes[i];

                            Progress = (initialPercentage + this.currentDownloadSize
                                        * 70 / this.totalDownloadSize);
                        }
                        digest.TransformFinalBlock(new byte[] {}, 0, 0);

                        dlStream.Close();
                        fos.Close();

                        string md5 = HexEncode(digest.Hash);

                        bool md5Matches = true;
                        if (etag != null)
                        {
                            md5Matches = md5.Equals(etag);
            //							Console.WriteLine(md5 + "\n" + etag);
                        }

                        if (md5Matches && fileSize == fileSizes[i] || fileSizes[i] <= 0)
                        {
                            md5s[(currentFile.Contains("natives") ?
                                  currentFile : currentFile)] = etag;
                            md5s.Save(Path.Combine(Inst.BinDir, "md5s"));
                        }
                        else
                        {
                            failedAttempts++;
                            if (failedAttempts < MAX_FAILS)
                            {
                                downloadFile = true;
                                this.currentDownloadSize -= fileSize;
                            }
                            else
                            {
                                OnErrorMessage("Failed to download " + currentFile +
                                               " MD5 sums did not match.");
                                Cancel();
                            }
                        }
                    }
                }
            }
        }
예제 #36
0
    bool SetState(EnumState state)
    {
        curState = state;
        switch(state)
        {
        case EnumState.ATTACK:
            if(distToPlayer < rangeAttack)
            {

            }
            break;

        //		case EnumState.FOLLOW:
        //			animation.Play("run");
        //			break;
        //
        //		case EnumState.DEAD:
        //			animation.Play("dead soft");
        //			break;
        //		case EnumState.HIT:
        //			animation.Play("hit front");
        //			break;
        }

        return true;
    }
예제 #37
0
        protected void LoadJarURLs()
        {
            State = EnumState.DETERMINING_PACKAGES;
            string[] jarList = new string[]
            {
                "lwjgl.jar", "jinput.jar", "lwjgl_util.jar", this.mainGameUrl
            };

            this.uriList = new Uri[jarList.Length + 1];
            Uri baseUri = new Uri(Resources.MinecraftDLUri);

            for (int i = 0; i < jarList.Length; i++)
                this.uriList[i] = new Uri(baseUri, jarList[i]);

            string nativeJar = string.Empty;

            if (OSUtils.Windows)
                nativeJar = "windows_natives.jar";
            else if (OSUtils.Linux)
                nativeJar = "linux_natives.jar";
            else if (OSUtils.MacOSX)
                nativeJar = "macosx_natives.jar";
            else
            {
                OnErrorMessage("Your operating system is not supported.");
                Cancel();
            }

            this.uriList[this.uriList.Length - 1] = new Uri(baseUri, nativeJar);
        }
예제 #38
0
        protected override void TaskStart()
        {
            OnStart();
            Console.WriteLine("updating");
            State = EnumState.CHECKING_CACHE;
            Progress = 5;

            // Get a list of URLs to download from
            LoadJarURLs();

            // Create the bin directory if it doesn't exist
            if (!Directory.Exists(Inst.BinDir))
                Directory.CreateDirectory(Inst.BinDir);

            string binDir = Inst.BinDir;
            if (this.latestVersion != null)
            {
                string versionFile = Path.Combine(binDir, "version");
                bool cacheAvailable = false;

                if (!forceUpdate && File.Exists(versionFile) &&
                    (latestVersion.Equals("-1") ||
                 latestVersion.Equals(File.ReadAllText(versionFile))))
                {
                    cacheAvailable = true;
                    Progress = 90;
                }

                if ((forceUpdate) || (!cacheAvailable))
                {
                    shouldUpdate = true;
                    if (!forceUpdate && File.Exists(versionFile))
                        AskToUpdate();
                    if (this.shouldUpdate)
                    {
                        File.WriteAllText(versionFile, "");

                        try
                        {
                            DownloadJars();

                        } catch (WebException e)
                        {
                            OnErrorMessage(
                                string.Format("An error occurred when downloading packages.\n" +
                                    "Details:\n{0}", e.ToString()));
                        }
                        ExtractNatives();
                        Progress = 100;
                    }
                }
            }
            OnComplete();
        }
        public void UpdateGame()
        {
            try
            {
                State = EnumState.CHECKING_CACHE;
                Progress = 5;

                // Get a list of URLs to download from
                LoadJarURLs();

                // Create the bin directory if it doesn't exist
                if (!Directory.Exists(Properties.Settings.Default.MinecraftPath + "/bin"))
                    Directory.CreateDirectory(Properties.Settings.Default.MinecraftPath + "/bin");

                string binDir = Properties.Settings.Default.MinecraftPath + "/bin";
                if (this.latestVersion != null)
                {
                    string versionFile = Path.Combine(binDir, "version");
                    bool cacheAvailable = false;

                    if (!forceUpdate && File.Exists(versionFile) &&
                        (latestVersion.Equals("-1") ||
                     latestVersion.Equals(File.ReadAllText(versionFile))))
                    {
                        cacheAvailable = true;
                        Progress = 90;
                    }

                    if ((forceUpdate) || (!cacheAvailable))
                    {
                        shouldUpdate = true;
                        if (this.shouldUpdate)
                        {
                            WriteVersionFile(versionFile, latestVersion);

                            try
                            {
                                DownloadJars();
                            }
                            catch (WebException e)
                            {
                                throw new Exception("An error occurred when downloading packages.", e);
                            }
                            ExtractNatives();
                            Progress = 100;
                        }
                    }
                }
            }
            catch (WebException e)
            {
                MCModUpdaterExceptionHandler.HandleException(this, new Exception("An error occurred when trying to download Minecraft.", e));

                return;
            }
        }
        private void DownloadJars()
        {
            Dictionary<string, string> md5s = new Dictionary<string, string>();
            if (File.Exists(Path.Combine(Properties.Settings.Default.MinecraftPath + "/bin/", "md5s")))
            {
                foreach (string s in File.ReadAllLines(Path.Combine(Properties.Settings.Default.MinecraftPath + "/bin/", "md5s")))
                {
                    string key, value;
                    key = s.Split('=')[0].Trim();
                    value = s.Split('=')[1].Trim();
                    md5s.Add(key, value);
                }
            }
            State = EnumState.DOWNLOADING;

            int[] fileSizes = new int[this.uriList.Length];
            bool[] skip = new bool[this.uriList.Length];

            // Get the headers and decide what files to skip downloading
            for (int i = 0; i < uriList.Length; i++)
            {
                MinecraftModUpdater.Logger.Log(Logger.Level.Info, "Getting header " + uriList[i].ToString());

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uriList[i]);
                request.Timeout = 1000 * 15; // Set a 15 second timeout
                request.Method = "HEAD";

                string etagOnDisk = null;
                if (md5s.ContainsKey(Path.GetFileName((uriList[i].LocalPath))))
                    etagOnDisk = md5s[Path.GetFileName((uriList[i].LocalPath))];

                if (!forceUpdate && !string.IsNullOrEmpty(etagOnDisk))
                    request.Headers[HttpRequestHeader.IfNoneMatch] = etagOnDisk;

                using (HttpWebResponse response = ((HttpWebResponse)request.GetResponse()))
                {
                    int code = (int)response.StatusCode;
                    if (code == 300)
                        skip[i] = true;

                    fileSizes[i] = (int)response.ContentLength;
                    this.totalDownloadSize += fileSizes[i];
                    MinecraftModUpdater.Logger.Log(Logger.Level.Info, "Got response: " + code + " and file size of " +
                                      fileSizes[i] + " bytes");
                }
            }

            int initialPercentage = Progress;

            byte[] buffer = new byte[1024 * 10];
            for (int i = 0; i < this.uriList.Length; i++)
            {
                if (skip[i])
                {
                    Progress = (initialPercentage + fileSizes[i] *
                                (100 - initialPercentage) / this.totalDownloadSize);
                }
                else
                {
                    string currentFile = Path.GetFileName((uriList[i].LocalPath));

                    if (currentFile == "minecraft.jar" && File.Exists("mcbackup.jar"))
                        File.Delete("mcbackup.jar");

                    md5s.Remove(currentFile);
                    List<string> lines = new List<string>();
                    foreach (var v in md5s)
                    {
                        lines.Add(v.Key + "=" + v.Value);
                    }
                    File.WriteAllLines(Path.Combine(Properties.Settings.Default.MinecraftPath + "/bin/", "md5s"), lines.ToArray());

                    int failedAttempts = 0;
                    const int MAX_FAILS = 3;
                    bool downloadFile = true;

                    // Download the files
                    while (downloadFile)
                    {
                        downloadFile = false;

                        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uriList[i]);
                        request.Headers[HttpRequestHeader.CacheControl] = "no-cache";

                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                        string etag = "";
                        // If downloading from Mojang, use ETag.
                        if (uriList[i].ToString().StartsWith(Resources.MCDownload))
                        {
                            etag = response.Headers[HttpResponseHeader.ETag];
                            etag = etag.TrimEnd('"').TrimStart('"');
                        }
                        // If downloading from dropbox, ignore MD5s
                        else
                        {
                            // TODO add a way to verify integrity of files downloaded from dropbox
                        }

                        Stream dlStream = response.GetResponseStream();
                        using (FileStream fos =
                            new FileStream(Path.Combine(Properties.Settings.Default.MinecraftPath + "/bin", currentFile), FileMode.Create))
                        {
                            int fileSize = 0;

                            using (MD5 digest = MD5.Create())
                            {
                                digest.Initialize();
                                int readSize;
                                while ((readSize = dlStream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    //							MinecraftModUpdater.Logger.Log(Logger.Level.Info"Read " + readSize + " bytes");
                                    fos.Write(buffer, 0, readSize);

                                    this.currentDownloadSize += readSize;
                                    fileSize += readSize;

                                    digest.TransformBlock(buffer, 0, readSize, null, 0);

                                    //							Progress = fileSize / fileSizes[i];

                                    Progress = (initialPercentage + this.currentDownloadSize *
                                                (100 - initialPercentage) / this.totalDownloadSize);
                                }
                                digest.TransformFinalBlock(new byte[] { }, 0, 0);

                                dlStream.Close();

                                string md5 = HexEncode(digest.Hash).Trim();
                                etag = etag.Trim();

                                bool md5Matches = true;
                                if (!string.IsNullOrEmpty(etag) && !string.IsNullOrEmpty(md5))
                                {
                                    // This is temporarily disabled since dropbox doesn't use MD5s as etags
                                    md5Matches = md5.Equals(etag);
                                    //							MinecraftModUpdater.Logger.Log(Logger.Level.Infomd5 + "\n" + etag + "\n");
                                }

                                if (md5Matches && fileSize == fileSizes[i] || fileSizes[i] <= 0)
                                {
                                    md5s[(currentFile.Contains("natives") ?
                                          currentFile : currentFile)] = etag;
                                    lines.Clear();
                                    foreach (var v in md5s)
                                    {
                                        lines.Add(v.Key + "=" + v.Value);
                                    }
                                    File.WriteAllLines(Path.Combine(Properties.Settings.Default.MinecraftPath + "/bin/", "md5s"), lines.ToArray());
                                }
                                else
                                {
                                    failedAttempts++;
                                    if (failedAttempts < MAX_FAILS)
                                    {
                                        downloadFile = true;
                                        this.currentDownloadSize -= fileSize;
                                    }
                                    else
                                    {
                                        MessageBox.Show("Failed to download " + currentFile +
                                                       " MD5 sums did not match.");
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #41
0
        protected void DownloadJars()
        {
            Properties md5s = new Properties();
            if (File.Exists(Path.Combine(Inst.BinDir, "md5s")))
                md5s.Load(Path.Combine(Inst.BinDir, "md5s"));
            State = EnumState.DOWNLOADING;

            int[] fileSizes = new int[this.uriList.Length];
            bool[] skip = new bool[this.uriList.Length];

            // Get the headers and decide what files to skip downloading
            for (int i = 0; i < uriList.Length; i++)
            {
                Console.WriteLine("Getting header " + uriList[i].ToString());

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uriList[i]);
                request.Timeout = 1000 * 15; // Set a 15 second timeout
                request.Method = "HEAD";

                string etagOnDisk = null;
                if (md5s.ContainsKey(GetFileName(uriList[i])))
                    etagOnDisk = md5s[GetFileName(uriList[i])];

                if (!forceUpdate && !string.IsNullOrEmpty(etagOnDisk))
                    request.Headers[HttpRequestHeader.IfNoneMatch] = etagOnDisk;

                using (HttpWebResponse response = ((HttpWebResponse)request.GetResponse()))
                {
                    int code = (int)response.StatusCode;
                    if (code == 300)
                        skip[i] = true;

                    fileSizes[i] = (int)response.ContentLength;
                    this.totalDownloadSize += fileSizes[i];
                    Console.WriteLine("Got response: " + code + " and file size of " +
                                      fileSizes[i] + " bytes");
                }
            }

            int initialPercentage = Progress;

            byte[] buffer = new byte[1024 * 10];
            for (int i = 0; i < this.uriList.Length; i++)
            {
                if (skip[i])
                {
                    Progress = (initialPercentage + fileSizes[i] *
                                (100 - initialPercentage) / this.totalDownloadSize);
                }
                else
                {
                    string currentFile = GetFileName(uriList[i]);

                    if (currentFile == "minecraft.jar" && File.Exists("mcbackup.jar"))
                        File.Delete("mcbackup.jar");

                    md5s.Remove(currentFile);
                    md5s.Save(Path.Combine(Inst.BinDir, "md5s"));

                    int failedAttempts = 0;
                    const int MAX_FAILS = 3;
                    bool downloadFile = true;

                    // Download the files
                    while (downloadFile)
                    {
                        downloadFile = false;

                        HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(uriList[i]);
                        request.Headers[HttpRequestHeader.CacheControl] = "no-cache";

                        HttpWebResponse response = (HttpWebResponse) request.GetResponse();

                        string etag = "";
                        // If downloading from Mojang, use ETag.
                        if (uriList[i].ToString().StartsWith(Resources.MojangMCDLUri))
                        {
                            etag = response.Headers[HttpResponseHeader.ETag];
                            etag = etag.TrimEnd('"').TrimStart('"');
                        }
                        // If downloading from dropbox, ignore MD5s
                        else
                        {
                            // TODO add a way to verify integrity of files downloaded from dropbox
                        }

                        Stream dlStream = response.GetResponseStream();
                        using (FileStream fos =
                            new FileStream(Path.Combine(Inst.BinDir, currentFile), FileMode.Create))
                        {
                            int fileSize = 0;

                            using (MD5 digest = MD5.Create())
                            {
                                digest.Initialize();
                                int readSize;
                                while ((readSize = dlStream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    //							Console.WriteLine("Read " + readSize + " bytes");
                                    fos.Write(buffer, 0, readSize);

                                    this.currentDownloadSize += readSize;
                                    fileSize += readSize;

                                    digest.TransformBlock(buffer, 0, readSize, null, 0);

                                    //							Progress = fileSize / fileSizes[i];

                                    Progress = (initialPercentage + this.currentDownloadSize *
                                                (100 - initialPercentage) / this.totalDownloadSize);
                                }
                                digest.TransformFinalBlock(new byte[] { }, 0, 0);

                                dlStream.Close();

                                string md5 = DataUtils.HexEncode(digest.Hash).Trim();
                                etag = etag.Trim();

                                bool md5Matches = true;
                                if (!string.IsNullOrEmpty(etag) && !string.IsNullOrEmpty(md5))
                                {
                                    // This is temporarily disabled since dropbox doesn't use MD5s as etags
                                    md5Matches = md5.Equals(etag);
                                    //							Console.WriteLine(md5 + "\n" + etag + "\n");
                                }

                                if (md5Matches && fileSize == fileSizes[i] || fileSizes[i] <= 0)
                                {
                                    md5s[(currentFile.Contains("natives") ?
                                          currentFile : currentFile)] = etag;
                                    md5s.Save(Path.Combine(Inst.BinDir, "md5s"));
                                }
                                else
                                {
                                    failedAttempts++;
                                    if (failedAttempts < MAX_FAILS)
                                    {
                                        downloadFile = true;
                                        this.currentDownloadSize -= fileSize;
                                    }
                                    else
                                    {
                                        OnErrorMessage("Failed to download " + currentFile +
                                                       " MD5 sums did not match.");
                                        Cancel();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        private void LoadJarURLs()
        {
            State = EnumState.DETERMINING_PACKAGES;
            string[] jarList = new string[]
            {
                this.mainGameUrl, "lwjgl_util.jar", "jinput.jar", "lwjgl.jar"
            };

            this.uriList = new Uri[jarList.Length + 1];
            Uri mojangBaseUri = new Uri(Resources.MCDownload);

            for (int i = 0; i < jarList.Length; i++)
            {
                this.uriList[i] = new Uri(mojangBaseUri, jarList[i]);
            }

            string nativeJar = string.Empty;

            if (OS.Windows)
                nativeJar = "windows_natives.jar";
            else if (OS.Linux)
                nativeJar = "linux_natives.jar";
            else if (OS.MacOSX)
                nativeJar = "macosx_natives.jar";
            else
            {
                MessageBox.Show("Your operating system is not supported.");
                return;
            }

            this.uriList[this.uriList.Length - 1] = new Uri(mojangBaseUri, nativeJar);
        }