public static byte[] Decompress(byte[] inputBytes) { byte[] result; using (LZMACoder coder = new LZMACoder()) using (MemoryStream input = new MemoryStream(inputBytes)) using (MemoryStream output = new MemoryStream()) { coder.Decompress(input, output); result = output.ToArray(); } return(result); }
private bool Download(CacheContentFile file) { var fileName = Path.Combine(Location, file.Name); var outputDirectory = Path.GetDirectoryName(fileName); var temporaryFile = Path.Combine(outputDirectory, file.SHA1Hash + ".cpart"); var URL = _server + file.Cache + "/" + file.Name; if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } int startAt = 0; Log.Info(String.Format("Starting to download {0}, {1} bytes.", file.Name, file.Size)); if (File.Exists(temporaryFile)) { //resume the download if (_usecpart) { var fi = new FileInfo(temporaryFile); startAt = (int)fi.Length; SendStatus(StatusChangedEnum.FileDownloading, new object[] { file.Name, file.CompressedSize, startAt }, startAt); Log.Info(String.Format("Partial file for {1} found, starting download at {0} bytes.", startAt, file.Name)); } else { File.Delete(temporaryFile); } } bool compressed = false; #if !DEBUG try { #endif if (Utilities.URLExists(URL + ".lzma")) { compressed = true; URL += ".lzma"; SendStatus(StatusChangedEnum.FileDownloadingLzma, file.Name, 0); Log.Info(String.Format("Found a compressed file for {0}.", fileName)); } Stream inStream, outStream; if (startAt != file.Size && startAt != file.CompressedSize) //if they equal, ._. { // initialize request var webRequest = (HttpWebRequest)WebRequest.Create(URL); webRequest.AddRange(startAt); var webResponse = (HttpWebResponse)webRequest.GetResponse(); inStream = webResponse.GetResponseStream(); outStream = File.Open(temporaryFile, FileMode.Append, FileAccess.Write, FileShare.Read); var buffer = new byte[2048]; var lastBytes = 0; while ((lastBytes = inStream.Read(buffer, 0, buffer.Length)) > 0) { outStream.Write(buffer, 0, lastBytes); SendStatus(StatusChangedEnum.FileDownloading, new object[] { file.Name, file.CompressedSize, lastBytes }, lastBytes); } // clean up the streams inStream.Close(); outStream.Close(); SendStatus(StatusChangedEnum.FileDownloadFinish, file.Name, 0); } if (compressed) { try { // decompress the temp file var tempDecPath = fileName + ".deco"; var decoder = new LZMACoder(); SendStatus(StatusChangedEnum.FileDecompressStart, file.Name, 0); Log.Info("decompressing " + file.Name); inStream = File.OpenRead(temporaryFile); outStream = File.Open(tempDecPath, FileMode.Create); try { decoder.Decompress(inStream, outStream); } catch (ApplicationException ex) { inStream.Close(); outStream.Close(); throw ex; } inStream.Close(); outStream.Close(); File.Delete(temporaryFile); File.Move(tempDecPath, temporaryFile); SendStatus(StatusChangedEnum.FileDecompressFinish, file.Name, 0); } catch (ApplicationException e) { // lzma sdk threw an error. File.Delete(temporaryFile); Log.Error(String.Format("LZMA file failed to decompress. {0}", e.ToString())); _lastException = e; return(false); } } // check the temp file's validity SendStatus(StatusChangedEnum.FileVerifyStart, file.Name, 0); var outHash = Utilities.GetFileSHA1(temporaryFile); var inHash = file.SHA1Hash; if (inHash != outHash) { _lastException = new Exception("Hash verification failed for " + fileName); Log.Error("Hash verification failed for " + fileName); File.Delete(temporaryFile); SendStatus(StatusChangedEnum.FileVerifyFailed, file.Name, 0); return(false); } SendStatus(StatusChangedEnum.FileVerifyFinish, file.Name, 0); // and rename the temp file, and then delete it File.Copy(temporaryFile, fileName, true); File.Delete(temporaryFile); return(true); #if !DEBUG } catch (Exception e) { Log.Error(String.Format("Error while downloading {0}.", e.ToString())); _lastException = e; } return(false); #endif }
/// <summary> /// Ctor - Read replay. /// </summary> /// <param name="path"></param> /// <param name="readHeaderless"></param> public Replay(string path, bool readHeaderless = false) { if (!File.Exists(path)) { throw new FileNotFoundException(); } // Read the replay data using (var fs = new FileStream(path, FileMode.Open)) using (var br = new BinaryReader(fs)) { if (!readHeaderless) { // Version None (Original data) ReplayVersion = br.ReadString(); MapMd5 = br.ReadString(); Md5 = br.ReadString(); PlayerName = br.ReadString(); Date = Convert.ToDateTime(br.ReadString(), CultureInfo.InvariantCulture); TimePlayed = br.ReadInt64(); // The dates are serialized incorrectly in older replays, so to keep compatibility, // use the time played. Date = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(TimePlayed); Mode = (GameMode)br.ReadInt32(); // The mirror mod is the 32-nd bit, which, when read as an Int32, results in a negative number. // To fix this, that case is handled separately. if (ReplayVersion == "0.0.1" || ReplayVersion == "None") { var mods = br.ReadInt32(); // First check if the mods are None, which is -1 (all bits set). This doesn't cause issues because // there are incompatible mods among the first 32 (like all the speed mods), so all first 32 bits // can't be 1 simultaneously unless it's a None. if (mods == -1) { Mods = ModIdentifier.None; mods = 0; } else if (mods < 0) { // If the 32-nd bit is set, add the Mirror mod and unset the 32-nd bit. Mods = ModIdentifier.Mirror; mods &= ~(1 << 31); } // Add the rest of the mods. Mods |= (ModIdentifier)mods; } else { Mods = (ModIdentifier)br.ReadInt64(); } Score = br.ReadInt32(); Accuracy = br.ReadSingle(); MaxCombo = br.ReadInt32(); CountMarv = br.ReadInt32(); CountPerf = br.ReadInt32(); CountGreat = br.ReadInt32(); CountGood = br.ReadInt32(); CountOkay = br.ReadInt32(); CountMiss = br.ReadInt32(); PauseCount = br.ReadInt32(); // Versions beyond None if (ReplayVersion != "None") { var replayVersion = new Version(ReplayVersion); if (replayVersion >= new Version("0.0.1")) { RandomizeModifierSeed = br.ReadInt32(); } } } // Create the new list of replay frames. Frames = new List <ReplayFrame>(); // Split the frames up by commas var frames = new List <string>(); if (!readHeaderless) { frames = Encoding.ASCII.GetString(LZMACoder.Decompress(br.BaseStream).ToArray()).Split(',').ToList(); } else { frames = Encoding.ASCII.GetString(LZMACoder.Decompress(br.ReadBytes((int)br.BaseStream.Length))).Split(',').ToList(); } // Add all the replay frames to the object foreach (var frame in frames) { try { // Split up the frame string by SongTime|KeyPressState var frameSplit = frame.Split('|'); Frames.Add(new ReplayFrame(int.Parse(frameSplit[0]), (ReplayKeyPressState)Enum.Parse(typeof(ReplayKeyPressState), frameSplit[1]))); } catch (Exception e) { continue; } } } }
/// <summary> /// Ctor - Read replay. /// </summary> /// <param name="path"></param> /// <param name="readHeaderless"></param> public Replay(string path, bool readHeaderless = false) { if (!File.Exists(path)) { throw new FileNotFoundException(); } // Read the replay data using (var fs = new FileStream(path, FileMode.Open)) using (var br = new BinaryReader(fs)) { if (!readHeaderless) { // Version None (Original data) ReplayVersion = br.ReadString(); MapMd5 = br.ReadString(); Md5 = br.ReadString(); PlayerName = br.ReadString(); Date = Convert.ToDateTime(br.ReadString(), CultureInfo.InvariantCulture); TimePlayed = br.ReadInt64(); // The dates are serialized incorrectly in older replays, so to keep compatibility, // use the time played. Date = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(TimePlayed); Mode = (GameMode)br.ReadInt32(); Mods = (ModIdentifier)br.ReadInt32(); Score = br.ReadInt32(); Accuracy = br.ReadSingle(); MaxCombo = br.ReadInt32(); CountMarv = br.ReadInt32(); CountPerf = br.ReadInt32(); CountGreat = br.ReadInt32(); CountGood = br.ReadInt32(); CountOkay = br.ReadInt32(); CountMiss = br.ReadInt32(); PauseCount = br.ReadInt32(); // Versions beyond None if (ReplayVersion != "None") { var replayVersion = new Version(ReplayVersion); if (replayVersion >= new Version("0.0.1")) { RandomizeModifierSeed = br.ReadInt32(); } } } // Create the new list of replay frames. Frames = new List <ReplayFrame>(); // Split the frames up by commas var frames = new List <string>(); if (!readHeaderless) { frames = Encoding.ASCII.GetString(LZMACoder.Decompress(br.BaseStream).ToArray()).Split(',').ToList(); } else { frames = Encoding.ASCII.GetString(LZMACoder.Decompress(br.ReadBytes((int)br.BaseStream.Length))).Split(',').ToList(); } // Add all the replay frames to the object foreach (var frame in frames) { try { // Split up the frame string by SongTime|KeyPressState var frameSplit = frame.Split('|'); Frames.Add(new ReplayFrame(int.Parse(frameSplit[0]), (ReplayKeyPressState)Enum.Parse(typeof(ReplayKeyPressState), frameSplit[1]))); } catch (Exception e) { continue; } } } }