Beispiel #1
0
        public static void ReadServerData(byte[] compressedData, RemoteData remoteInfo)
        {
            var data = new ByteReader(GZipStream.UncompressBuffer(compressedData));

            var modCount = data.ReadInt32();

            for (int i = 0; i < modCount; i++)
            {
                var packageId = data.ReadString();
                var name      = data.ReadString();
                var steamId   = data.ReadULong();
                var source    = (ContentSource)data.ReadByte();

                remoteInfo.remoteMods.Add(new ModInfo()
                {
                    packageId = packageId, name = name, steamId = steamId, source = source
                });
            }

            var rootCount = data.ReadInt32();

            for (int i = 0; i < rootCount; i++)
            {
                var modId     = data.ReadString();
                var mod       = GetInstalledMod(modId);
                var fileCount = data.ReadInt32();

                for (int j = 0; j < fileCount; j++)
                {
                    var relPath = data.ReadString();
                    var hash    = data.ReadInt32();
                    //hash++;// todo for testing
                    string absPath = null;

                    if (mod != null)
                    {
                        absPath = Path.Combine(mod.RootDir.FullName, relPath);
                    }

                    remoteInfo.remoteFiles.Add(modId, new ModFile(absPath, relPath, hash));
                }
            }

            remoteInfo.hasConfigs = data.ReadBool();
            if (remoteInfo.hasConfigs)
            {
                var configCount = data.ReadInt32();
                for (int i = 0; i < configCount; i++)
                {
                    const int MaxConfigContentLen = 8388608; // 8 megabytes

                    var modId    = data.ReadString();
                    var fileName = data.ReadString();
                    var contents = data.ReadString(MaxConfigContentLen);

                    remoteInfo.remoteModConfigs.Add(new ModConfig(modId, fileName, contents));
                    //remoteInfo.remoteModConfigs[trimmedPath] = remoteInfo.remoteModConfigs[trimmedPath].Insert(0, "a"); // todo for testing
                }
            }
        }
Beispiel #2
0
 public byte[] GetData()
 {
     if (IsCompressed)
     {
         return(GZipStream.UncompressBuffer(Data));
     }
     return(Data);
 }
Beispiel #3
0
 public string GetString()
 {
     if (IsCompressed)
     {
         return(Context.I.DefaultEncoding.GetString(GZipStream.UncompressBuffer(Data)));
     }
     return(Context.I.DefaultEncoding.GetString(Data));
 }
Beispiel #4
0
        internal static Stream Uncompress(this BinaryReader input)
        {
            uint length = input.ReadUInt32();

            byte[] header = new byte[length];
            input.Read(header, 0, header.Length);
            return(new MemoryStream(GZipStream.UncompressBuffer(header)));
        }
Beispiel #5
0
        // From old EventDataBlob format
        private static byte[] FromData_Legacy(byte[] data, int requestedSeriesID, int eventID, AdoDataConnection connection)
        {
            byte[] resultData = null;
            byte[] uncompressedData;
            int    offset;

            DateTime[] times;
            int        seriesID;

            uncompressedData = GZipStream.UncompressBuffer(data);
            offset           = 0;

            int m_samples = LittleEndian.ToInt32(uncompressedData, offset);

            offset += sizeof(int);

            times = new DateTime[m_samples];

            for (int i = 0; i < m_samples; i++)
            {
                times[i] = new DateTime(LittleEndian.ToInt64(uncompressedData, offset));
                offset  += sizeof(long);
            }

            while (offset < uncompressedData.Length)
            {
                seriesID = LittleEndian.ToInt32(uncompressedData, offset);
                offset  += sizeof(int);

                List <DataPoint> points = new List <DataPoint>();

                for (int i = 0; i < m_samples; i++)
                {
                    points.Add(new DataPoint()
                    {
                        Time  = times[i],
                        Value = LittleEndian.ToDouble(uncompressedData, offset)
                    });

                    offset += sizeof(double);
                }

                if (seriesID == requestedSeriesID)
                {
                    resultData = ToData(points, seriesID, m_samples);
                }

                // Insert into correct ChannelData.....
                connection.ExecuteNonQuery("UPDATE ChannelData SET TimeDomainData = {0} WHERE SeriesID = {1} AND EventID = {2}", ToData(points, seriesID, m_samples), seriesID, eventID);
            }

            //Remove EventData
            int eventDataID = connection.ExecuteScalar <int>("SELECT EventDataID FROM ChannelData WHERE SeriesID = {0} AND EventID = {1}", requestedSeriesID, eventID);

            connection.ExecuteNonQuery("DELETE FROM EventData WHERE ID = {0}", eventDataID);

            return(resultData);
        }
        public void HandleWorldData(ByteReader data)
        {
            connection.State = ConnectionStateEnum.ClientPlaying;
            Log.Message("Game data size: " + data.Length);

            int factionId = data.ReadInt32();

            Multiplayer.session.myFactionId = factionId;

            int tickUntil = data.ReadInt32();

            byte[] worldData = GZipStream.UncompressBuffer(data.ReadPrefixedBytes());
            OnMainThread.cachedGameData = worldData;

            List <int> mapsToLoad = new List <int>();

            int mapCmdsCount = data.ReadInt32();

            for (int i = 0; i < mapCmdsCount; i++)
            {
                int mapId = data.ReadInt32();

                int mapCmdsLen = data.ReadInt32();
                List <ScheduledCommand> mapCmds = new List <ScheduledCommand>(mapCmdsLen);
                for (int j = 0; j < mapCmdsLen; j++)
                {
                    mapCmds.Add(ScheduledCommand.Deserialize(new ByteReader(data.ReadPrefixedBytes())));
                }

                OnMainThread.cachedMapCmds[mapId] = mapCmds;
            }

            int mapDataCount = data.ReadInt32();

            for (int i = 0; i < mapDataCount; i++)
            {
                int    mapId      = data.ReadInt32();
                byte[] rawMapData = data.ReadPrefixedBytes();

                byte[] mapData = GZipStream.UncompressBuffer(rawMapData);
                OnMainThread.cachedMapData[mapId] = mapData;
                mapsToLoad.Add(mapId);
            }

            Multiplayer.session.localCmdId = data.ReadInt32();

            TickPatch.tickUntil = tickUntil;

            TickPatch.SkipTo(
                toTickUntil: true,
                onFinish: () => Multiplayer.Client.Send(Packets.Client_WorldReady),
                cancelButtonKey: "Quit",
                onCancel: GenScene.GoToMainMenu
                );

            ReloadGame(mapsToLoad);
        }
Beispiel #7
0
 private void HandleGzipPacked(long messageId, int sequence, BinaryReader messageReader)
 {
     byte[] packedData = GZipStream.UncompressBuffer(Serializers.Bytes.Read(messageReader));
     using (MemoryStream packedStream = new MemoryStream(packedData, false))
         using (BinaryReader compressedReader = new BinaryReader(packedStream))
         {
             ProcessMessage(messageId, sequence, compressedReader);
         }
 }
Beispiel #8
0
        public void FromData(Meter meter, byte[] data)
        {
            byte[] uncompressedData;
            int    offset;

            DateTime[] times;
            DataSeries series;
            int        seriesID;

            m_dataSeries.Clear();

            if (data.Length == 0)
            {
                return;
            }

            uncompressedData = GZipStream.UncompressBuffer(data);
            offset           = 0;

            m_samples = LittleEndian.ToInt32(uncompressedData, offset);
            offset   += sizeof(int);

            times = new DateTime[m_samples];

            for (int i = 0; i < m_samples; i++)
            {
                times[i] = new DateTime(LittleEndian.ToInt64(uncompressedData, offset));
                offset  += sizeof(long);
            }

            while (offset < uncompressedData.Length)
            {
                series   = new DataSeries();
                seriesID = LittleEndian.ToInt32(uncompressedData, offset);
                offset  += sizeof(int);

                if (seriesID > 0 && (object)meter != null)
                {
                    series.SeriesInfo = meter.Channels
                                        .SelectMany(channel => channel.Series)
                                        .FirstOrDefault(seriesInfo => seriesInfo.ID == seriesID);
                }

                for (int i = 0; i < m_samples; i++)
                {
                    series.DataPoints.Add(new DataPoint()
                    {
                        Time  = times[i],
                        Value = LittleEndian.ToDouble(uncompressedData, offset)
                    });

                    offset += sizeof(double);
                }

                Add(series);
            }
        }
Beispiel #9
0
        private bool HandleGzipPacked(ulong messageId, int sequence, BinaryReader messageReader)
        {
            uint code = messageReader.ReadUInt32();

            byte[] packedData = GZipStream.UncompressBuffer(Serializers.Bytes.read(messageReader));
            using (MemoryStream packedStream = new MemoryStream(packedData, false))
                using (BinaryReader compressedReader = new BinaryReader(packedStream)) {
                    processMessage(messageId, sequence, compressedReader);
                }

            return(true);
        }
Beispiel #10
0
        private bool HandleGzipPacked(long messageId, int sequence, TBinaryReader messageReader, MTProtoRequest request)
        {
            uint code = messageReader.ReadUInt32();

            byte[] packedData = GZipStream.UncompressBuffer(messageReader.ReadBytes());
            using (MemoryStream packedStream = new MemoryStream(packedData, false))
                using (TBinaryReader compressedReader = new TBinaryReader(packedStream))
                {
                    processMessage(messageId, sequence, compressedReader, request);
                }

            return(true);
        }
Beispiel #11
0
        private bool HandleGzipPacked(ulong messageId, int sequence, BinaryReader messageReader, TLMethod request, CancellationToken token = default(CancellationToken))
        {
            token.ThrowIfCancellationRequested();

            uint code = messageReader.ReadUInt32();

            byte[] packedData = GZipStream.UncompressBuffer(Serializers.Bytes.Read(messageReader));
            using (MemoryStream packedStream = new MemoryStream(packedData, false))
                using (BinaryReader compressedReader = new BinaryReader(packedStream))
                {
                    processMessage(messageId, sequence, compressedReader, request, token);
                }

            return(true);
        }
Beispiel #12
0
        private void FromData_Legacy(Meter meter, byte[] data)
        {
            byte[] uncompressedData;
            int    offset;

            DateTime[] times;
            DataSeries series;
            int        seriesID;

            uncompressedData = GZipStream.UncompressBuffer(data);
            offset           = 0;

            m_samples = LittleEndian.ToInt32(uncompressedData, offset);
            offset   += sizeof(int);

            times = new DateTime[m_samples];

            for (int i = 0; i < m_samples; i++)
            {
                times[i] = new DateTime(LittleEndian.ToInt64(uncompressedData, offset));
                offset  += sizeof(long);
            }

            while (offset < uncompressedData.Length)
            {
                series   = new DataSeries();
                seriesID = LittleEndian.ToInt32(uncompressedData, offset);
                offset  += sizeof(int);

                if (seriesID > 0 && (object)meter != null)
                {
                    series.SeriesInfo = GetSeriesInfo(meter, seriesID);
                }

                for (int i = 0; i < m_samples; i++)
                {
                    series.DataPoints.Add(new DataPoint()
                    {
                        Time  = times[i],
                        Value = LittleEndian.ToDouble(uncompressedData, offset)
                    });

                    offset += sizeof(double);
                }

                Add(series);
            }
        }
        public byte[] DecompressGZipStream(byte[] compressedBytes)
        {
            return(GZipStream.UncompressBuffer(compressedBytes));

            //using (var source = new MemoryStream(compressedBytes))
            //{
            //    var lengthBytes = new byte[4];
            //    source.Read(lengthBytes, 0, 4);

            //    int length = BitConverter.ToInt32(lengthBytes, 0);
            //    using (var decompressionStream = new GZipStream(source, CompressionMode.Decompress))
            //    {
            //        var result = new byte[length];
            //        decompressionStream.Read(result, 0, length);
            //        //decompressionStream.Flush();
            //        return result;
            //    }
            //}
        }
Beispiel #14
0
        public static byte[] Decompress(byte[] data, string type)
        {
            switch (type)
            {
            case CompressionAlgorithm.Zlib:
                return(ZlibStream.UncompressBuffer(data));

            case CompressionAlgorithm.Deflate:
                return(DeflateStream.UncompressBuffer(data));

            case CompressionAlgorithm.GZip:
                return(GZipStream.UncompressBuffer(data));

            case CompressionAlgorithm.Lzma:
                return(SevenZipHelper.Decompress(data));
            }

            return(data);
        }
Beispiel #15
0
        public void HandleMapResponse(ByteReader data)
        {
            int mapId = data.ReadInt32();

            int mapCmdsLen = data.ReadInt32();
            List <ScheduledCommand> mapCmds = new List <ScheduledCommand>(mapCmdsLen);

            for (int j = 0; j < mapCmdsLen; j++)
            {
                mapCmds.Add(ScheduledCommand.Deserialize(new ByteReader(data.ReadPrefixedBytes())));
            }

            OnMainThread.cachedMapCmds[mapId] = mapCmds;

            byte[] mapData = GZipStream.UncompressBuffer(data.ReadPrefixedBytes());
            OnMainThread.cachedMapData[mapId] = mapData;

            //ClientJoiningState.ReloadGame(TickPatch.tickUntil, Find.Maps.Select(m => m.uniqueID).Concat(mapId).ToList());
            // todo Multiplayer.client.Send(Packets.CLIENT_MAP_LOADED);
        }
Beispiel #16
0
        public void HandleWorldData(ByteReader data)
        {
            connection.State = ConnectionStateEnum.ClientPlaying;
            Log.Message("Game data size: " + data.Length);

            int factionId = data.ReadInt32();

            Multiplayer.session.myFactionId = factionId;

            int tickUntil = data.ReadInt32();

            var dataSnapshot = new GameDataSnapshot();

            byte[] worldData = GZipStream.UncompressBuffer(data.ReadPrefixedBytes());
            dataSnapshot.gameData = worldData;

            byte[] semiPersistentData = GZipStream.UncompressBuffer(data.ReadPrefixedBytes());
            dataSnapshot.semiPersistentData = semiPersistentData;

            List <int> mapsToLoad = new List <int>();

            int mapCmdsCount = data.ReadInt32();

            for (int i = 0; i < mapCmdsCount; i++)
            {
                int mapId = data.ReadInt32();

                int mapCmdsLen = data.ReadInt32();
                List <ScheduledCommand> mapCmds = new List <ScheduledCommand>(mapCmdsLen);
                for (int j = 0; j < mapCmdsLen; j++)
                {
                    mapCmds.Add(ScheduledCommand.Deserialize(new ByteReader(data.ReadPrefixedBytes())));
                }

                dataSnapshot.mapCmds[mapId] = mapCmds;
            }

            int mapDataCount = data.ReadInt32();

            for (int i = 0; i < mapDataCount; i++)
            {
                int    mapId      = data.ReadInt32();
                byte[] rawMapData = data.ReadPrefixedBytes();

                byte[] mapData = GZipStream.UncompressBuffer(rawMapData);
                dataSnapshot.mapData[mapId] = mapData;
                mapsToLoad.Add(mapId);
            }

            Session.dataSnapshot           = dataSnapshot;
            Multiplayer.session.localCmdId = data.ReadInt32();
            TickPatch.shouldPause          = data.ReadBool();
            TickPatch.tickUntil            = tickUntil;

            TickPatch.SetSimulation(
                toTickUntil: true,
                onFinish: () => Multiplayer.Client.Send(Packets.Client_WorldReady),
                cancelButtonKey: "Quit",
                onCancel: GenScene.GoToMainMenu // Calls StopMultiplayer through a patch
                );

            ReloadGame(mapsToLoad, true, false);
        }
Beispiel #17
0
 public static byte[] Uncompress(byte[] data)
 {
     return(GZipStream.UncompressBuffer(data));
 }
Beispiel #18
0
 byte[] UnZip(byte[] output)
 {
     return(GZipStream.UncompressBuffer(output));
 }
Beispiel #19
0
        // from new EvendData Blob format
        private static byte[] ProcessLegacyBlob(int eventID, int requestedSeriesID, AdoDataConnection connection)
        {
            int eventDataID = connection.ExecuteScalar <int>("SELECT EventDataID FROM ChannelData WHERE SeriesID = {0} AND EventID = {1}", requestedSeriesID, eventID);

            byte[] timeDomainData = connection.ExecuteScalar <byte[]>("SELECT TimeDomainData FROM EventData WHERE ID = {0}", eventDataID);
            byte[] resultData     = null;

            // If the blob contains the GZip header,
            // use the legacy deserialization algorithm
            if (timeDomainData[0] == 0x1F && timeDomainData[1] == 0x8B)
            {
                return(FromData_Legacy(timeDomainData, requestedSeriesID, eventID, connection));
            }

            // Restore the GZip header before uncompressing
            timeDomainData[0] = 0x1F;
            timeDomainData[1] = 0x8B;

            byte[] uncompressedData = GZipStream.UncompressBuffer(timeDomainData);
            int    offset           = 0;

            int m_samples = LittleEndian.ToInt32(uncompressedData, offset);

            offset += sizeof(int);

            List <DateTime> times = new List <DateTime>();

            while (times.Count < m_samples)
            {
                int timeValues = LittleEndian.ToInt32(uncompressedData, offset);
                offset += sizeof(int);

                long currentValue = LittleEndian.ToInt64(uncompressedData, offset);
                offset += sizeof(long);
                times.Add(new DateTime(currentValue));

                for (int i = 1; i < timeValues; i++)
                {
                    currentValue += LittleEndian.ToUInt16(uncompressedData, offset);
                    offset       += sizeof(ushort);
                    times.Add(new DateTime(currentValue));
                }
            }

            while (offset < uncompressedData.Length)
            {
                List <DataPoint> dataSeries = new List <DataPoint>();
                int seriesID = LittleEndian.ToInt32(uncompressedData, offset);
                offset += sizeof(int);


                const ushort NaNValue            = ushort.MaxValue;
                double       decompressionOffset = LittleEndian.ToDouble(uncompressedData, offset);
                double       decompressionScale  = LittleEndian.ToDouble(uncompressedData, offset + sizeof(double));
                offset += 2 * sizeof(double);

                for (int i = 0; i < m_samples; i++)
                {
                    ushort compressedValue = LittleEndian.ToUInt16(uncompressedData, offset);
                    offset += sizeof(ushort);

                    double decompressedValue = decompressionScale * compressedValue + decompressionOffset;

                    if (compressedValue == NaNValue)
                    {
                        decompressedValue = double.NaN;
                    }

                    dataSeries.Add(new DataPoint()
                    {
                        Time  = times[i],
                        Value = decompressedValue
                    });
                }
                if (seriesID == requestedSeriesID)
                {
                    resultData = ToData(dataSeries, seriesID, m_samples);
                }

                // Insert into correct ChannelData.....
                connection.ExecuteNonQuery("UPDATE ChannelData SET TimeDomainData = {0} WHERE SeriesID = {1} AND EventID = {2}", ToData(dataSeries, seriesID, m_samples), seriesID, eventID);
            }

            connection.ExecuteNonQuery("DELETE FROM EventData WHERE ID = {0}", eventDataID);

            return(resultData);
        }
Beispiel #20
0
 public static byte[] GZipUnCompress(byte[] bytes)
 {
     return(GZipStream.UncompressBuffer(bytes));
 }
        // These two data types are supported in DotNetZip, but only if .NET Framework is targeted.
        //private SelfExtractorFlavor _selfExtractorFlavor;
        //private SelfExtractorSaveOptions _selfExtractorSaveOptions;

        public void CallAll()
        {
            // These two apis are supported in DotNetZip, but only if .NET Framework is targeted.
            //_zipFile.SaveSelfExtractor(_string, _selfExtractorFlavor);
            //_zipFile.SaveSelfExtractor(_string, _selfExtractorSaveOptions);

            //Project: Ionic.Zip
            _bZip2InputStream.Close();
            _bZip2InputStream.Flush();
            _int  = _bZip2InputStream.Read(_bytes, _int, _int);
            _int  = _bZip2InputStream.ReadByte();
            _long = _bZip2InputStream.Seek(_long, _seekOrigin);
            _bZip2InputStream.SetLength(_long);
            _bZip2InputStream.Write(_bytes, _int, _int);
            _bZip2OutputStream.Close();
            _bZip2OutputStream.Flush();
            _int  = _bZip2OutputStream.Read(_bytes, _int, _int);
            _long = _bZip2OutputStream.Seek(_long, _seekOrigin);
            _bZip2OutputStream.SetLength(_long);
            _bZip2OutputStream.Write(_bytes, _int, _int);
            _parallelBZip2OutputStream.Close();
            _parallelBZip2OutputStream.Flush();
            _int  = _parallelBZip2OutputStream.Read(_bytes, _int, _int);
            _long = _parallelBZip2OutputStream.Seek(_long, _seekOrigin);
            _parallelBZip2OutputStream.SetLength(_long);
            _parallelBZip2OutputStream.Write(_bytes, _int, _int);
            _crc32.Combine(_int, _int);
            _int = _crc32.ComputeCrc32(_int, _byte);
            _int = _crc32.GetCrc32(_stream);
            _int = _crc32.GetCrc32AndCopy(_stream, _stream);
            _crc32.Reset();
            _crc32.SlurpBlock(_bytes, _int, _int);
            _crc32.UpdateCRC(_byte);
            _crc32.UpdateCRC(_byte, _int);
            _crcCalculatorStream.Close();
            _crcCalculatorStream.Flush();
            _int  = _crcCalculatorStream.Read(_bytes, _int, _int);
            _long = _crcCalculatorStream.Seek(_long, _seekOrigin);
            _crcCalculatorStream.SetLength(_long);
            _crcCalculatorStream.Write(_bytes, _int, _int);
            _zipEntriesCollection = _fileSelector.SelectEntries(_zipFile);
            _zipEntriesCollection = _fileSelector.SelectEntries(_zipFile, _string);
            _stringsCollection    = _fileSelector.SelectFiles(_string);
            _stringsReadOnly      = _fileSelector.SelectFiles(_string, _bool);
            _string = _fileSelector.ToString();
            _bool   = _comHelper.CheckZip(_string);
            _bool   = _comHelper.CheckZipPassword(_string, _string);
            _comHelper.FixZipDirectory(_string);
            _string = _comHelper.GetZipLibraryVersion();
            _bool   = _comHelper.IsZipFile(_string);
            _bool   = _comHelper.IsZipFileWithExtract(_string);
            _countingStream.Adjust(_long);
            _countingStream.Flush();
            _int  = _countingStream.Read(_bytes, _int, _int);
            _long = _countingStream.Seek(_long, _seekOrigin);
            _countingStream.SetLength(_long);
            _countingStream.Write(_bytes, _int, _int);
            _zipEntry.Extract();
            _zipEntry.Extract(_extractExistingFileAction);
            _zipEntry.Extract(_string);
            _zipEntry.Extract(_string, _extractExistingFileAction);
            _zipEntry.Extract(_stream);
            _zipEntry.ExtractWithPassword(_extractExistingFileAction, _string);
            _zipEntry.ExtractWithPassword(_string);
            _zipEntry.ExtractWithPassword(_string, _extractExistingFileAction, _string);
            _zipEntry.ExtractWithPassword(_string, _string);
            _zipEntry.ExtractWithPassword(_stream, _string);
            _crcCalculatorStream = _zipEntry.OpenReader();
            _crcCalculatorStream = _zipEntry.OpenReader(_string);
            _zipEntry.SetEntryTimes(_datetime, _datetime, _datetime);
            _string   = _zipEntry.ToString();
            _zipEntry = _zipFile.AddDirectory(_string);
            _zipEntry = _zipFile.AddDirectory(_string, _string);
            _zipEntry = _zipFile.AddDirectoryByName(_string);
            _zipEntry = _zipFile.AddEntry(_string, _bytes);
            _zipEntry = _zipFile.AddEntry(_string, _openDelegate, _closeDelegate);
            _zipEntry = _zipFile.AddEntry(_string, _writeDelegate);
            _zipEntry = _zipFile.AddEntry(_string, _string);
            _zipEntry = _zipFile.AddEntry(_string, _string, _encoding);
            _zipEntry = _zipFile.AddEntry(_string, _stream);
            _zipEntry = _zipFile.AddFile(_string);
            _zipEntry = _zipFile.AddFile(_string, _string);
            _zipFile.AddFiles(_strings);
            _zipFile.AddFiles(_strings, _bool, _string);
            _zipFile.AddFiles(_strings, _string);
            _zipEntry = _zipFile.AddItem(_string);
            _zipEntry = _zipFile.AddItem(_string, _string);
            _zipFile.AddSelectedFiles(_string);
            _zipFile.AddSelectedFiles(_string, _bool);
            _zipFile.AddSelectedFiles(_string, _string);
            _zipFile.AddSelectedFiles(_string, _string, _bool);
            _zipFile.AddSelectedFiles(_string, _string, _string);
            _zipFile.AddSelectedFiles(_string, _string, _string, _bool);
            _bool = _zipFile.ContainsEntry(_string);
            _zipFile.Dispose();
            _zipFile.ExtractAll(_string);
            _zipFile.ExtractAll(_string, _extractExistingFileAction);
            _zipFile.ExtractSelectedEntries(_string);
            _zipFile.ExtractSelectedEntries(_string, _extractExistingFileAction);
            _zipFile.ExtractSelectedEntries(_string, _string);
            _zipFile.ExtractSelectedEntries(_string, _string, _string);
            _zipFile.ExtractSelectedEntries(_string, _string, _string, _extractExistingFileAction);
            _enumerator = _zipFile.GetNewEnum();
            _zipFile.Initialize(_string);
            _zipFile.RemoveEntries(_zipEntriesCollection);
            _zipFile.RemoveEntries(_stringsCollection);
            _zipFile.RemoveEntry(_zipEntry);
            _zipFile.RemoveEntry(_string);
            _int = _zipFile.RemoveSelectedEntries(_string);
            _int = _zipFile.RemoveSelectedEntries(_string, _string);
            _zipFile.Save();
            _zipFile.Save(_string);
            _zipFile.Save(_stream);
            _zipEntriesCollection = _zipFile.SelectEntries(_string);
            _zipEntriesCollection = _zipFile.SelectEntries(_string, _string);
            _string   = _zipFile.ToString();
            _zipEntry = _zipFile.UpdateDirectory(_string);
            _zipEntry = _zipFile.UpdateDirectory(_string, _string);
            _zipEntry = _zipFile.UpdateEntry(_string, _bytes);
            _zipEntry = _zipFile.UpdateEntry(_string, _openDelegate, _closeDelegate);
            _zipEntry = _zipFile.UpdateEntry(_string, _writeDelegate);
            _zipEntry = _zipFile.UpdateEntry(_string, _string);
            _zipEntry = _zipFile.UpdateEntry(_string, _string, _encoding);
            _zipEntry = _zipFile.UpdateEntry(_string, _stream);
            _zipEntry = _zipFile.UpdateFile(_string);
            _zipFile.UpdateFile(_string, _string);
            _zipFile.UpdateFiles(_strings);
            _zipFile.UpdateFiles(_strings, _string);
            _zipFile.UpdateItem(_string);
            _zipFile.UpdateItem(_string, _string);
            _zipFile.UpdateSelectedFiles(_string, _string, _string, _bool);
            _zipInputStream.Flush();
            _zipEntry = _zipInputStream.GetNextEntry();
            _int      = _zipInputStream.Read(_bytes, _int, _int);
            _long     = _zipInputStream.Seek(_long, _seekOrigin);
            _zipInputStream.SetLength(_long);
            _string = _zipInputStream.ToString();
            _zipInputStream.Write(_bytes, _int, _int);
            _bool = _zipOutputStream.ContainsEntry(_string);
            _zipOutputStream.Flush();
            _zipEntry = _zipOutputStream.PutNextEntry(_string);
            _int      = _zipOutputStream.Read(_bytes, _int, _int);
            _long     = _zipOutputStream.Seek(_long, _seekOrigin);
            _zipOutputStream.SetLength(_long);
            _string = _zipOutputStream.ToString();
            _zipOutputStream.Write(_bytes, _int, _int);
            _deflateStream.Flush();
            _int  = _deflateStream.Read(_bytes, _int, _int);
            _long = _deflateStream.Seek(_long, _seekOrigin);
            _deflateStream.SetLength(_long);
            _deflateStream.Write(_bytes, _int, _int);
            _gZipStream.Flush();
            _int  = _gZipStream.Read(_bytes, _int, _int);
            _long = _gZipStream.Seek(_long, _seekOrigin);
            _gZipStream.SetLength(_long);
            _gZipStream.Write(_bytes, _int, _int);
            _parallelDeflateOutputStream.Close();
            _parallelDeflateOutputStream.Flush();
            _int = _parallelDeflateOutputStream.Read(_bytes, _int, _int);
            _parallelDeflateOutputStream.Reset(_stream);
            _long = _parallelDeflateOutputStream.Seek(_long, _seekOrigin);
            _parallelDeflateOutputStream.SetLength(_long);
            _parallelDeflateOutputStream.Write(_bytes, _int, _int);

            // Static
            _bool = ZipFile.CheckZip(_string);
            _bool = ZipFile.CheckZip(_string, _bool, _textWriter);
            _bool = ZipFile.CheckZipPassword(_string, _string);
            ZipFile.FixZipDirectory(_string);
            _bool    = ZipFile.IsZipFile(_string);
            _bool    = ZipFile.IsZipFile(_string, _bool);
            _bool    = ZipFile.IsZipFile(_stream, _bool);
            _zipFile = ZipFile.Read(_string);
            _zipFile = ZipFile.Read(_string, _readOptions);
            _zipFile = ZipFile.Read(_stream);
            _zipFile = ZipFile.Read(_stream, _readOptions);
            _uint    = Adler.Adler32(_uint, _bytes, _int, _int);
            _bytes   = DeflateStream.CompressBuffer(_bytes);
            _bytes   = DeflateStream.CompressString(_string);
            _bytes   = DeflateStream.UncompressBuffer(_bytes);
            _string  = DeflateStream.UncompressString(_bytes);
            _bytes   = GZipStream.CompressBuffer(_bytes);
            _bytes   = GZipStream.CompressString(_string);
            _bytes   = GZipStream.UncompressBuffer(_bytes);
            _string  = GZipStream.UncompressString(_bytes);
            _bytes   = ZlibStream.CompressBuffer(_bytes);
            _bytes   = ZlibStream.CompressString(_string);
            _bytes   = ZlibStream.UncompressBuffer(_bytes);
            _string  = ZlibStream.UncompressString(_bytes);
        }
Beispiel #22
0
 public byte[] unzipData(byte[] zdata)
 {
     return(GZipStream.UncompressBuffer(zdata));
 }
    protected IEnumerator LoadPlayerPrefs(string text)
    {
        WWW w = null;

        //if (!statsSaved)
        {
            var s = mainSite + "/players/" + playerName.ToLower() + "/prefs.txt";
            if (isDebug)
            {
                s += "?" + Random.value;
            }
            Debug.Log(s);
            w = new WWW(s);
            while (!w.isDone)
            {
                popupText = Tr("Logging in ") + ((int)w.progress * 100) + "%";
                yield return(null);
            }
        }
        try
        {
            StringBuilder sb = new StringBuilder();
            Dictionary <string, string> dict = ParseDict(text);
            modTypeInt = int.Parse(dict.TryGetDontSet("modType", "0"));
            //sb.AppendLine("parsed Rep: " + reputation);
            //sb.AppendLine("parsed medals: " + medals);
            //sb.AppendLine("parsed modType: " + modTypeInt);
            userId = int.Parse(dict.TryGetDontSet("id", "0"));
            print("parsed userId: " + userId);
            bool crypt         = false;
            bool ovrd          = false;
            var  plnameToLower = playerName;
            if (string.IsNullOrEmpty(w.error))
            {
                var buffer = w.bytes;
                try
                {
                    Xor(buffer);
                    buffer = GZipStream.UncompressBuffer(buffer);
                }
                catch (System.Exception) { Debug.LogWarning("Failed uncompress"); Xor(buffer); }
                if (buffer.Length > 0)
                {
                    using (var ms = new BinaryReader(buffer))
                    {
                        sb.AppendLine("loading stats ");
                        int i     = 0;
                        var local = playerPrefKeys.Count;
                        while (ms.Position < ms.Length)
                        {
                            var key   = ms.ReadString();
                            var value = ms.ReadString();
                            if (value.Length > MaxLength || key.Length > MaxLength)
                            {
                                Debug.LogError(string.Format("too big value {0} {1}", key, value));
                                continue;
                            }
#if !UNITY_WP8
                            if (crypt)
                            {
                                key   = ObscuredString.EncryptDecrypt(key);
                                value = ObscuredString.EncryptDecrypt(value);
                            }
#endif
                            if (key == "Enc" && value == "Enc")
                            {
                                Debug.LogWarning("Encoded");
                                crypt = true;
                                continue;
                            }

                            if (key == _DefinePrefsTime && loggedInTime != 0)
                            {
                                ovrd = loggedInTime < int.Parse(value);

                                //if (ovrd)
                                //lastError = "Override Detected";
                                LogEvent(EventGroup.Debug, "Override Detected");
                                Debug.Log("Set override to: " + ovrd);
                                ovrd = false;
                                continue;
                            }
                            i++;

                            //if (!playerPrefKeys.Contains(key)) //may be incorrect
                            //{

                            //if (string.IsNullOrEmpty(PlayerPrefsGetString(key)))
                            var lowerKey = key.ToLower();
                            if (ResLoader.isEditor && !lowerKey.StartsWith(plnameToLower))
                            {
                                continue;
                            }

                            if (ovrd || !PlayerPrefs.HasKey(lowerKey))
                            {
                                PlayerPrefsSetString(key, value);
                            }
                            else
                            {
                                playerPrefKeys.Add(key);
                            }
                            //}
                            sb.Append(string.Format("{0}:{1},", key, value));
                        }

                        Debug.LogWarning("loading player prefs local:" + local + " remote:" + i + " \n" + (Debug.isDebugBuild ? sb.ToString() : sb.Length.ToString()));
                        SetStrings.Clear();
                        //statsSaved = true;
                    }
                }
                else
                {
                    Debug.LogWarning("player prefs empty");
                }
                //}
            }
            else //if (!w.error.StartsWith("404") && w.error.ToLower().StartsWith("failed downloading"))
            {
                throw new Exception(w.error);
            }
            //if (!setting.disPlayerPrefs2)
            //{
            //print("reputation " + reputation);
            //if (reputation < 5)
            if (_Loader.vkSite)
            {
                StartCoroutine(AddMethod(delegate
                {
                    reputation       = Mathf.Max(int.Parse(dict.TryGetDontSet("reputation", "0")), reputation);
                    medals           = Mathf.Max(int.Parse(dict.TryGetDontSet("medals", "0")), medals);
                    _Awards.xp.count = Mathf.Max(int.Parse(dict.TryGetDontSet("xp", "0")), _Awards.xp.count);
                }));
            }

            allowSavePrefs = bool.Parse(dict.TryGetDontSet("allowSavePrefs", "true"));
            //}
        }
        catch (System.Exception e)
        {
            SetStrings.Clear();
            //if (!statsSaved)
            {
                Debug.LogError(e);
                lastError = e.Message.Replace("\r", "   ").Replace("\n", "    ");
                //GoOffline();
                LogEvent("Login Failed Critical Error");
                OnLoginFailed(e.Message + "\n" + Tr(" Critical Error"));
                yield break;
            }
        }
        RefreshPrefs();
        //SaveStrings();
        OnLoggedIn();
        WindowPool();
    }
 /// <summary>
 /// Decode the content
 /// </summary>
 /// <param name="data">Content to decode</param>
 /// <returns>Decoded content</returns>
 public byte[] Decode(byte[] data)
 {
     return(GZipStream.UncompressBuffer(data));
 }
Beispiel #25
0
        public void FromData(Meter meter, byte[] data)
        {
            // If the blob contains the GZip header,
            // use the legacy deserialization algorithm
            if (data[0] == 0x1F && data[1] == 0x8B)
            {
                FromData_Legacy(meter, data);
                return;
            }

            // Restore the GZip header before uncompressing
            data[0] = 0x1F;
            data[1] = 0x8B;

            byte[] uncompressedData = GZipStream.UncompressBuffer(data);
            int    offset           = 0;

            m_samples = LittleEndian.ToInt32(uncompressedData, offset);
            offset   += sizeof(int);

            List <DateTime> times = new List <DateTime>();

            while (times.Count < m_samples)
            {
                int timeValues = LittleEndian.ToInt32(uncompressedData, offset);
                offset += sizeof(int);

                long currentValue = LittleEndian.ToInt64(uncompressedData, offset);
                offset += sizeof(long);
                times.Add(new DateTime(currentValue));

                for (int i = 1; i < timeValues; i++)
                {
                    currentValue += LittleEndian.ToUInt16(uncompressedData, offset);
                    offset       += sizeof(ushort);
                    times.Add(new DateTime(currentValue));
                }
            }

            while (offset < uncompressedData.Length)
            {
                DataSeries dataSeries = new DataSeries();
                int        seriesID   = LittleEndian.ToInt32(uncompressedData, offset);
                offset += sizeof(int);

                if (seriesID > 0 && (object)meter != null)
                {
                    dataSeries.SeriesInfo = GetSeriesInfo(meter, seriesID);
                }

                const ushort NaNValue            = ushort.MaxValue;
                double       decompressionOffset = LittleEndian.ToDouble(uncompressedData, offset);
                double       decompressionScale  = LittleEndian.ToDouble(uncompressedData, offset + sizeof(double));
                offset += 2 * sizeof(double);

                for (int i = 0; i < m_samples; i++)
                {
                    ushort compressedValue = LittleEndian.ToUInt16(uncompressedData, offset);
                    offset += sizeof(ushort);

                    double decompressedValue = decompressionScale * compressedValue + decompressionOffset;

                    if (compressedValue == NaNValue)
                    {
                        decompressedValue = double.NaN;
                    }

                    dataSeries.DataPoints.Add(new DataPoint()
                    {
                        Time  = times[i],
                        Value = decompressedValue
                    });
                }

                Add(dataSeries);
            }
        }
Beispiel #26
0
 //TODO: move somewhere else
 public static Stream CreateGZipDecompressionStream(byte[] bytes)
 {
     return(new MemoryStream(GZipStream.UncompressBuffer(bytes)));
 }
Beispiel #27
0
        /// <summary>
        /// Deserializes the given leaf.
        /// </summary>
        /// <param name="typeModel"></param>
        /// <param name="data"></param>
        /// <param name="boxes"></param>
        /// <returns></returns>
        protected override List <Primitive2D> DeSerialize(RuntimeTypeModel typeModel,
                                                          byte[] data, out List <BoxF2D> boxes)
        {
            if (_compressed)
            { // decompress if needed.
                data = GZipStream.UncompressBuffer(data);
            }

            List <Primitive2D> dataLists = new List <Primitive2D>();

            boxes = new List <BoxF2D>();

            int scaleFactor = _scaleFactor;

            // Assume the following stuff already exists in the current scene:
            // - ZoomRanges
            // - Styles

            // deserialize the leaf data.
            SceneObjectBlock leafData = typeModel.Deserialize(
                new MemoryStream(data), null, typeof(SceneObjectBlock)) as SceneObjectBlock;

            // decode
            for (int idx = 0; idx < leafData.PointsX.Count; idx++)
            {
                leafData.PointsX[idx] = leafData.PointsX[idx] + leafData.PointsXMin;
                leafData.PointsY[idx] = leafData.PointsY[idx] + leafData.PointsYMin;
            }

            // store the next points.
            bool[] pointsStarts = new bool[leafData.PointsX.Count];
            // loop over all points.
            for (int idx = 0; idx < leafData.PointPointId.Count; idx++)
            {
                pointsStarts[leafData.PointPointId[idx]] = true;
            }
            // loop over all text-points.
            for (int idx = 0; idx < leafData.TextPointPointId.Count; idx++)
            {
                pointsStarts[leafData.TextPointPointId[idx]] = true;
            }
            // loop over all icons.
            for (int idx = 0; idx < leafData.IconPointId.Count; idx++)
            {
                pointsStarts[leafData.IconPointId[idx]] = true;
            }
            // loop over all lines.
            for (int idx = 0; idx < leafData.LinePointsId.Count; idx++)
            {
                pointsStarts[leafData.LinePointsId[idx]] = true;
            }
            // loop over all polygons.
            for (int idx = 0; idx < leafData.PolygonPointsId.Count; idx++)
            {
                pointsStarts[leafData.PolygonPointsId[idx]] = true;
            }
            // loop over all line-texts.
            for (int idx = 0; idx < leafData.LineTextPointsId.Count; idx++)
            {
                pointsStarts[leafData.LineTextPointsId[idx]] = true;
            }
            Dictionary <int, int> pointsBoundaries = new Dictionary <int, int>();
            int previous = 0;

            for (int idx = 1; idx < pointsStarts.Length; idx++)
            {
                if (pointsStarts[idx])
                { // there is a start here.
                    pointsBoundaries[previous] = idx - previous;
                    previous = idx;
                }
            }
            pointsBoundaries[previous] = pointsStarts.Length - previous;

            // loop over all points.
            for (int idx = 0; idx < leafData.PointPointId.Count; idx++)
            {
                // get properties.
                int  pointId = leafData.PointPointId[idx];
                uint styleId = leafData.PointStyleId[idx];

                // get point/style/zoomrange.
                double     x     = (double)leafData.PointsX[pointId] / (double)scaleFactor;
                double     y     = (double)leafData.PointsY[pointId] / (double)scaleFactor;
                StylePoint style = _index.PointStyles[styleId];

                // build the primitive.
                Point2D point = new Point2D(x, y, style.Color, style.Size);
                point.Layer   = style.Layer;
                point.MinZoom = style.MinZoom;
                point.MaxZoom = style.MaxZoom;

                dataLists.Add(point);
                boxes.Add(new BoxF2D(new PointF2D(x, y)));
            }

            // loop over all text-points.
            for (int idx = 0; idx < leafData.TextPointPointId.Count; idx++)
            {
                // get properties.
                int    pointId = leafData.TextPointPointId[idx];
                uint   styleId = leafData.TextPointStyleId[idx];
                string text    = leafData.TextPointText[idx];

                // get point/style/zoomrange.
                float     x     = (float)leafData.PointsX[pointId] / (float)scaleFactor;
                float     y     = (float)leafData.PointsY[pointId] / (float)scaleFactor;
                StyleText style = _index.TextStyles[styleId];

                // build the primitive.
                Text2D text2D = new Text2D(x, y, text, style.Color, style.Size);
                text2D.Layer      = style.Layer;
                text2D.HaloColor  = style.HaloColor;
                text2D.HaloRadius = style.HaloRadius;
                text2D.MinZoom    = style.MinZoom;
                text2D.MaxZoom    = style.MaxZoom;

                dataLists.Add(text2D);
                boxes.Add(new BoxF2D(new PointF2D(x, y)));
            }

            // loop over all icons.
            for (int idx = 0; idx < leafData.IconPointId.Count; idx++)
            {
                // get properties.
                int  pointId = leafData.IconPointId[idx];
                uint imageId = leafData.IconImageId[idx];

                // get point/style/zoomrange.
                double x     = (double)leafData.PointsX[pointId] / (double)scaleFactor;
                double y     = (double)leafData.PointsY[pointId] / (double)scaleFactor;
                byte[] image = _index.IconImage[(int)imageId];

                // build the primitive.
                Icon2D icon = new Icon2D(x, y, image);
                icon.Layer = 0;
                // TODO: layer and zoom level. style.MinZoom, style.MaxZoom

                dataLists.Add(icon);
                boxes.Add(new BoxF2D(new PointF2D(x, y)));
            }

            // loop over all lines.
            for (int idx = 0; idx < leafData.LinePointsId.Count; idx++)
            {
                // get properties.
                int  pointsId = leafData.LinePointsId[idx];
                uint styleId  = leafData.LineStyleId[idx];

                // get points/style/zoomrange.
                int      pointsCount = pointsBoundaries[pointsId];
                double[] x           =
                    leafData.PointsX.GetRange(pointsId, pointsCount).ConvertFromLongArray(scaleFactor);
                double[] y =
                    leafData.PointsY.GetRange(pointsId, pointsCount).ConvertFromLongArray(scaleFactor);
                StyleLine style = _index.LineStyles[styleId];

                // build the primitive.
                Line2D line = new Line2D(x, y, style.Color, style.Width, style.LineJoin, style.Dashes);
                line.Layer   = style.Layer;
                line.MinZoom = style.MinZoom;
                line.MaxZoom = style.MaxZoom;

                dataLists.Add(line);
                boxes.Add(new BoxF2D(x, y));
            }

            // loop over all polygons.
            for (int idx = 0; idx < leafData.PolygonPointsId.Count; idx++)
            {
                // get properties.
                int  pointsId = leafData.PolygonPointsId[idx];
                uint styleId  = leafData.PolygonStyleId[idx];

                // get points/style/zoomrange.
                int      pointsCount = pointsBoundaries[pointsId];
                double[] x           =
                    leafData.PointsX.GetRange(pointsId, pointsCount).ConvertFromLongArray(scaleFactor);
                double[] y =
                    leafData.PointsY.GetRange(pointsId, pointsCount).ConvertFromLongArray(scaleFactor);
                StylePolygon style = _index.PolygonStyles[styleId];

                // build the primitive.
                Polygon2D polygon = new Polygon2D(x, y, style.Color, style.Width, style.Fill);
                polygon.Layer   = style.Layer;
                polygon.MaxZoom = style.MaxZoom;
                polygon.MinZoom = style.MinZoom;

                dataLists.Add(polygon);
                boxes.Add(new BoxF2D(x, y));
            }

            // loop over all line-texts.
            for (int idx = 0; idx < leafData.LineTextPointsId.Count; idx++)
            {
                // get properties.
                int    pointsId = leafData.LineTextPointsId[idx];
                uint   styleId  = leafData.LineTextStyleId[idx];
                string text     = leafData.LineTextText[idx];

                // get points/style/zoomrange.
                int      pointsCount = pointsBoundaries[pointsId];
                double[] x           =
                    leafData.PointsX.GetRange(pointsId, pointsCount).ConvertFromLongArray(scaleFactor);
                double[] y =
                    leafData.PointsY.GetRange(pointsId, pointsCount).ConvertFromLongArray(scaleFactor);
                StyleText style = _index.TextStyles[styleId];

                // build the primitive.
                LineText2D lineText = new LineText2D(x, y, style.Color, style.Size, text);
                lineText.Layer      = style.Layer;
                lineText.Font       = style.Font;
                lineText.HaloColor  = style.HaloColor;
                lineText.HaloRadius = style.HaloRadius;
                lineText.MinZoom    = style.MinZoom;
                lineText.MaxZoom    = style.MaxZoom;

                dataLists.Add(lineText);
                boxes.Add(new BoxF2D(x, y));
            }
            return(dataLists);
        }