public async Task <string> DecryptAndSaveDetailsAsync(byte[] chiper, string fileName) { var message = string.Empty; try { var decryptedValue = _customEncryptionService.DecryptStringFromBytes(chiper); try { var zipFileInfo = new ZipFileInfo { FileHierarchy = decryptedValue, FileName = fileName }; await _dataContext.ZipFileInfo.AddAsync(zipFileInfo); await _dataContext.SaveChangesAsync(); } catch { message = "Error occurred while saving to database"; } } catch { message = "Error occurred while decrypting file hierarchy."; } return(message); }
public void ZipFileInfoNullParams() { Exception caughtEx; ZipInfo zipInfo = new ZipInfo("test.zip"); int txtSize = 10240; CompressionTestUtil.GenerateRandomFile("test00.txt", 0, txtSize); CompressionTestUtil.GenerateRandomFile("test01.txt", 1, txtSize); zipInfo.PackFiles(null, new string[] { "test00.txt", "test01.txt" }, null); ZipFileInfo zfi = new ZipFileInfo(zipInfo, "test01.txt"); caughtEx = null; try { new ZipFileInfo(null, "test00.txt"); } catch (Exception ex) { caughtEx = ex; } Assert.IsInstanceOfType(caughtEx, typeof(ArgumentNullException)); caughtEx = null; try { new ZipFileInfo(zipInfo, null); } catch (Exception ex) { caughtEx = ex; } Assert.IsInstanceOfType(caughtEx, typeof(ArgumentNullException)); caughtEx = null; try { zfi.CopyTo(null); } catch (Exception ex) { caughtEx = ex; } Assert.IsInstanceOfType(caughtEx, typeof(ArgumentNullException)); }
/// <summary> /// Gets a <see cref="ZipFileInfo"/> for the given <paramref name="fileName"/>. /// </summary> /// <param name="fileName">The name of the entry in the archive.</param> /// <returns>The entry in the archive.</returns> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="fileName"/> is <c>null</c></exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if <paramref name="fileName"/> is too long.</exception> /// <exception cref="System.InvalidOperationException">Thrown if archive was opened in write mode, or <paramref name="fileName"/> does not exist in the archive.</exception> private ZipFileInfo GetFile(string fileName) { var zipFileInfoObject = GetFileMethod.Value.Invoke(_zipArchiveObject, new object[] { fileName }); var zipFileInfo = new ZipFileInfo(zipFileInfoObject); return(zipFileInfo); }
/// <summary> /// Creates a new ZIP entry in the archive. /// </summary> /// <param name="fileName">The name of the entry in the archive.</param> /// <param name="compressionMethod">The compression method to use.</param> /// <returns>The new archive entry.</returns> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="fileName"/> is <c>null</c></exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if <paramref name="fileName"/> is too long, or <paramref name="compressionMethod"/> indicates improper compression or deflate mode.</exception> /// <exception cref="System.InvalidOperationException">Thrown if archive was opened in read mode, or <paramref name="fileName"/> already exists in the archive.</exception> private ICompressedArchiveEntry CreateZipEntry(string fileName, ZipArchiveCompressionMethod compressionMethod) { var compression = ZipArchiveCompressionMethodToNativeCompressionMethodEnum(compressionMethod); var deflate = ZipArchiveCompressionMethodToNativeDeflateOptionEnum(compressionMethod); var zipFileInfoObject = AddFileMethod.Value.Invoke(_zipArchiveObject, new object[] { fileName, compression, deflate }); var zipFileInfo = new ZipFileInfo(zipFileInfoObject); return(zipFileInfo); }
//------------------------------------------------------ // // Public Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Constructors // //------------------------------------------------------ #region Internal Constructors /// <summary> /// Constructs a ZipPackagePart for an atomic (i.e. non-interleaved) part. /// This is called from the ZipPackage class as a result of GetPartCore, /// GetPartsCore or CreatePartCore methods /// </summary> /// <param name="container"></param> /// <param name="zipFileInfo"></param> /// <param name="partUri"></param> /// <param name="compressionOption"></param> /// <param name="contentType"></param> internal ZipPackagePart(ZipPackage container, ZipFileInfo zipFileInfo, PackUriHelper.ValidatedPartUri partUri, string contentType, CompressionOption compressionOption) : base(container, partUri, contentType, compressionOption) { _zipArchive = zipFileInfo.ZipArchive; _zipFileInfo = zipFileInfo; }
public bool TryGetFileInfo(string subpath, out IFileInfo fileInfo) { fileInfo = null; if (subpath.StartsWith("/", StringComparison.Ordinal)) { subpath = subpath.Substring(1); } var entry = _zip.GetEntry(subpath); if (entry != null) { fileInfo = new ZipFileInfo(entry,subpath); return true; } return false; }
public void CreateZipFileInfoFromPackageNameTestShouldReturnCorrectPackageName() { string filename = "2020-09-22_2_dk.zip"; var actualZipFileInfo = _fileInfoService.CreateZipFileInfoFromPackageName(filename); var expectedZipFileInfo = new ZipFileInfo() { BatchNumber = 2, PackageDate = DateTime.Parse("2020-09-22"), Origin = "dk" }; Assert.AreEqual(expectedZipFileInfo.Origin, actualZipFileInfo.Origin); Assert.AreEqual(expectedZipFileInfo.BatchNumber, actualZipFileInfo.BatchNumber); Assert.AreEqual(expectedZipFileInfo.PackageDate, actualZipFileInfo.PackageDate); }
public void Init() { SetupMockConfiguration(); _zipFileInfoService = new Mock <IZipFileInfoService>(MockBehavior.Strict); _memoryCache = new MemoryCache(new MemoryCacheOptions()); _logger = new Mock <ILogger <CacheOperationsV3> >(); _zipFileInfo = new ZipFileInfo() { BatchNumber = 1, Origin = "dk", PackageDate = DateTime.UtcNow.AddDays(-1).Date }; _memoryCache.Set(_zipFileInfo.FileName, mockCacheResult); _cacheService = new CacheOperationsV3(_memoryCache, _configuration.Object, _logger.Object, _zipFileInfoService.Object); }
public void CheckIfPackageExistsTestShouldCheckForRightFile() { var date = DateTime.UtcNow; ZipFileInfo zipFileInfo = new ZipFileInfo() { BatchNumber = 2, Origin = "dk", PackageDate = date }; string zipFilesFolder = "ZipFilesFolder"; _fileSystem.Setup(x => x.FileExists(Path.Join(zipFilesFolder, zipFileInfo.Origin.ToLower(), zipFileInfo.FileName))).Returns(true); bool actualValue = _fileInfoService.CheckIfPackageExists(zipFileInfo, zipFilesFolder); Assert.IsTrue(actualValue); }
public IActionResult DownloadDiagnosisKeysFile(string packageName) { _logger.LogInformation("DownloadDiagnosisKeysFile endpoint called"); try { ZipFileInfo packageInfo = _zipFileInfoService.CreateZipFileInfoFromPackageName(packageName); string zipFilesFolder = _configuration["ZipFilesFolder"]; _logger.LogInformation("Package Date: " + packageInfo.PackageDate); _logger.LogInformation("Add days: " + DateTime.UtcNow.Date.AddDays(-14)); _logger.LogInformation("Utc now:" + DateTime.UtcNow); if (!IsDateValid(packageInfo.PackageDate, packageName)) { return(BadRequest("Package Date is invalid")); } var packageExists = _zipFileInfoService.CheckIfPackageExists(packageInfo, zipFilesFolder); if (packageExists) { var zipFileContent = _zipFileInfoService.ReadPackage(packageInfo, zipFilesFolder); var currentBatchNumber = packageInfo.BatchNumber; packageInfo.BatchNumber++; var nextPackageExists = _zipFileInfoService.CheckIfPackageExists(packageInfo, zipFilesFolder); AddResponseHeader(nextPackageExists, currentBatchNumber); _logger.LogInformation("Zip package fetched successfully"); return(File(zipFileContent, System.Net.Mime.MediaTypeNames.Application.Zip)); } else { _logger.LogInformation("Package does not exist"); return(NoContent()); } } catch (FormatException e) { _logger.LogError("Error when parsing data: " + e); return(BadRequest(e.Message)); } catch (Exception e) { _logger.LogError("Error when downloading package: " + e); return(StatusCode(500)); } }
public bool TryGetFileInfo(string subpath, out IFileInfo fileInfo) { fileInfo = null; if (subpath.StartsWith("/", StringComparison.Ordinal)) { subpath = subpath.Substring(1); } var entry = _zip.GetEntry(subpath); if (entry != null) { fileInfo = new ZipFileInfo(entry, subpath); return(true); } return(false); }
public void ReadPackageTestShouldReadRightFile() { var date = DateTime.UtcNow; ZipFileInfo zipFileInfo = new ZipFileInfo() { BatchNumber = 2, Origin = "dk", PackageDate = date }; string zipFilesFolder = "ZipFilesFolder"; byte[] expectedContent = new byte[] { 1, 2, 3, 4 }; _fileSystem.Setup(x => x.ReadFile(Path.Join(zipFilesFolder, zipFileInfo.Origin.ToLower(), zipFileInfo.FileName))).Returns(expectedContent); var actualContent = _fileInfoService.ReadPackage(zipFileInfo, zipFilesFolder); Assert.AreEqual(expectedContent, actualContent); }
//------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors internal PieceInfo(ZipFileInfo zipFileInfo, PackUriHelper.ValidatedPartUri partUri, string prefixName, int pieceNumber, bool isLastPiece) { Debug.Assert(zipFileInfo != null); Debug.Assert(prefixName != null && prefixName != String.Empty); Debug.Assert(pieceNumber >= 0); _zipFileInfo = zipFileInfo; // partUri can be null to indicate that the prefixname is not a valid part name _partUri = partUri; _prefixName = prefixName; _pieceNumber = pieceNumber; _isLastPiece = isLastPiece; // Currently as per the book, the prefix names/ logical names should be // compared in a case-insensitive manner. _normalizedPieceNamePrefix = _prefixName.ToUpperInvariant(); }
public ZipFileInfo CreateZipFileInfoFromPackageName(string zipFilename) { var zipFileInfo = new ZipFileInfo(); var tokens = zipFilename.Split("_"); if (tokens.Length == 3) { var dateString = tokens[0]; DateTime packageDate; int batchNumber = 0; bool successfullyParsed = DateTime.TryParse(dateString, out packageDate) && int.TryParse(tokens[1], out batchNumber); var originTokens = tokens[2].Split("."); if (successfullyParsed && originTokens.Count() == 2) { zipFileInfo.Origin = tokens[2].Split(".")[0]; zipFileInfo.BatchNumber = batchNumber; zipFileInfo.PackageDate = packageDate; return(zipFileInfo); } } throw new FormatException("Unexpected filename format"); }
//------------------------------------------------------ // // Private Methods // //------------------------------------------------------ private void EnsurePieceStream(bool isLastPiece) { if (_pieceStream != null) { // Normally, the pieces are actually closed automatically for us by the // underlying ZipIO logic, but in the case of the last piece (when we // are called by our own Dispose(bool) method) we must close it explicitly. if (isLastPiece) { _pieceStream.Close(); } // We detect that the stream has been closed by inspecting the CanWrite property // since this is guaranteed not to throw even when the stream is disposed. if (!_pieceStream.CanWrite) { // increment our piece number so we can generate the correct // one below checked { ++_currentPieceNumber; } // release it to trigger the new piece creation below _pieceStream = null; } } if (_pieceStream == null) { string pieceName = PieceNameHelper.CreatePieceName( _partName, _currentPieceNumber, isLastPiece); string pieceZipName = ZipPackage.GetZipItemNameFromOpcName(pieceName); ZipFileInfo zipFileInfo = _archive.AddFile(pieceZipName, _compressionMethod, _deflateOption); // We've just created the file, so the mode can only be Create, not CreateNew. // (At least, this is part of ZipFileInfo's belief system.) _pieceStream = zipFileInfo.GetStream(FileMode.Create, _access); } }
/// <summary> /// Return true and create a PieceInfo if the name in the input ZipFileInfo parses /// as a piece name. /// </summary> /// <remarks> /// No Uri validation is carried out at this level. All that is checked is valid piece /// syntax. So the _prefixName returned as part of the PieceInfo will not necessarily /// a part name. For example, it could be the name of the content type stream. /// </remarks> internal static bool TryCreatePieceInfo(ZipFileInfo zipFileInfo, out PieceInfo pieceInfo) { Invariant.Assert(zipFileInfo != null); pieceInfo = null; // Try to parse as a piece name. PieceNameInfo pieceNameConstituents; bool result = PieceNameHelper.TryParseAsPieceName(zipFileInfo.Name, out pieceNameConstituents); // Return the result and the output parameter. if (result) { pieceInfo = new PieceInfo(zipFileInfo, pieceNameConstituents.PartUri, pieceNameConstituents.PrefixName, pieceNameConstituents.PieceNumber, pieceNameConstituents.IsLastPiece); } return(result); }
public byte[] ReadPackage(ZipFileInfo packageInfo, string zipFilesFolder) { var filename = _fileSystem.JoinPaths(zipFilesFolder, packageInfo.Origin.ToLower(), packageInfo.FileName); return(_fileSystem.ReadFile(filename)); }
public bool CheckIfPackageExists(ZipFileInfo packageInfo, string zipFilesFolder) { var filename = _fileSystem.JoinPaths(zipFilesFolder, packageInfo.Origin.ToLower(), packageInfo.FileName); return(_fileSystem.FileExists(filename)); }
public async Task <IActionResult> DownloadDiagnosisKeysFile(string packageName) { _logger.LogInformation("DownloadDiagnosisKeysFile endpoint called"); try { if (packageName == "today") { packageName = ReplacePackageNameWithToday(); } ZipFileInfo packageInfo = _zipFileInfoService.CreateZipFileInfoFromPackageName(packageName); string zipFilesFolder = _appSettingsConfig.ZipFilesFolder; _logger.LogInformation("Package Date: " + packageInfo.PackageDate); _logger.LogInformation("Add days: " + DateTime.UtcNow.Date.AddDays(-14)); _logger.LogInformation("Utc now:" + DateTime.UtcNow); if (!IsDateValid(packageInfo.PackageDate, packageName)) { return(BadRequest("Package Date is invalid")); } var packageExists = _zipFileInfoService.CheckIfPackageExists(packageInfo, zipFilesFolder); if (packageExists) { byte[] zipFileContent = null; bool invalidateCache = false; if (Request.Headers.ContainsKey("Cache-Control") && Request.Headers["Cache-Control"] == "no-cache") { invalidateCache = true; zipFileContent = await _cacheOperations.GetCacheValue(packageInfo, zipFilesFolder, invalidateCache); } else { zipFileContent = await _cacheOperations.GetCacheValue(packageInfo, zipFilesFolder, invalidateCache); } var currentBatchNumber = packageInfo.BatchNumber; packageInfo.BatchNumber++; var nextPackageExists = _zipFileInfoService.CheckIfPackageExists(packageInfo, zipFilesFolder); AddResponseHeader(nextPackageExists, currentBatchNumber); _logger.LogInformation("Zip package fetched successfully"); return(File(zipFileContent, System.Net.Mime.MediaTypeNames.Application.Zip)); } else { _logger.LogInformation("Package does not exist"); return(NoContent()); } } catch (FormatException e) { _logger.LogError("Error when parsing data: " + e); return(BadRequest(e.Message)); } catch (Exception e) { _logger.LogError("Error when downloading package: " + e); return(StatusCode(500)); } }
/// <summary> /// If the logical end precedes the physical end, delete invalidated pieces /// and rename the logical end to a name containing ".last". /// </summary> private void UpdatePhysicalEndIfNecessary() { if (!_logicalEndPrecedesPhysicalEnd) { return; } // Delete invalidated pieces. int pieceNumber = _lastPieceIndex + 1; while (pieceNumber < _sortedPieceInfoList.Count) { _zipArchive.DeleteFile(_sortedPieceInfoList[pieceNumber].ZipFileInfo.Name); pieceNumber++; } _sortedPieceInfoList.RemoveRange(_lastPieceIndex + 1, _sortedPieceInfoList.Count - (_lastPieceIndex + 1)); // Since there is no rename in Zip I/O, getting the last piece to have .last // in its name necessarily involves creating a new piece. The simplest and most // effective solution consists in adding an empty terminal piece. // Number of the new physical last piece. int lastPiece = _lastPieceIndex + 1; // Record the compression parameters of the first piece to apply them to the new piece. // (Though this part will be created as empty, it may grow later.) ZipFileInfo firstPieceInfo = _sortedPieceInfoList[0].ZipFileInfo; CompressionMethodEnum compressionMethod = firstPieceInfo.CompressionMethod; DeflateOptionEnum deflateOption = firstPieceInfo.DeflateOption; // We have to special-case SetLength(0), because in that case, there is no nonempty // piece at all; and only the last piece is allowed to be empty. if (_lastPieceIndex == 0 && _pieceStreamInfoList[0].Stream.Length == 0) { _zipArchive.DeleteFile(firstPieceInfo.Name); // The list of piece descriptors now becomes totally empty. // This temporarily violates an invariant that should obtain again // on exiting this function. _indexOfLastPieceStreamInfoAccessed = -1; //Remove all the items in the list _pieceStreamInfoList.Clear(); lastPiece = 0; // Create "[0].last.piece" } string newLastPieceFileName = PieceNameHelper.CreatePieceName( _sortedPieceInfoList[0].PrefixName, lastPiece, true /* last piece */); ZipFileInfo newLastPieceInfo = _zipArchive.AddFile(newLastPieceFileName, compressionMethod, deflateOption); _lastPieceIndex = lastPiece; //We need to update the _sortedPieceInfoList with this new last piece information _sortedPieceInfoList.Add( new PieceInfo( newLastPieceInfo, _sortedPieceInfoList[0].PartUri, _sortedPieceInfoList[0].PrefixName, _lastPieceIndex, true /* last piece */)); // If we have been creating [0].last.piece, create a stream descriptor for it. // (In other cases, create on demand, as usual.) if (lastPiece == 0) { Stream pieceStream = newLastPieceInfo.GetStream(_fileMode, _fileAccess); _indexOfLastPieceStreamInfoAccessed = 0; //The list should be empty at this point Invariant.Assert(_pieceStreamInfoList.Count == 0); _pieceStreamInfoList.Add(new PieceStreamInfo(pieceStream, 0 /*startOffset*/)); } // Mark update complete. _logicalEndPrecedesPhysicalEnd = false; }
public override VirtualFileInfo getFileInfo(String filename) { ZipFileInfo info = zipFile.getFileInfo(parseURLInZip(filename)); return(new VirtualFileInfo(info.Name, info.DirectoryName, info.FullName, getFullPath(info.FullName), info.CompressedSize, info.UncompressedSize)); }
public async Task <byte[]> GetCacheValue(ZipFileInfo zipFileInfo, string zipFilesFolder, bool forceRefresh = false) { return(TryGetPackageCreateIfNotExisting(zipFileInfo, zipFilesFolder, forceRefresh)); }
private byte[] TryGetPackageCreateIfNotExisting(ZipFileInfo zipFileInfo, string zipFilesFolder, bool forceRefresh) { if (!_memoryCache.TryGetValue(zipFileInfo.FileName, out byte[] result))
private ModInfo ReadFromClassFile(ZipFileInfo file) { if (file.IsVolumeLabel || file.IsFolder || !file.Name.ToLower().EndsWith(".class")) { return(null); } ClassAnalyzer analyzer = null; using (Stream stream = file.OpenStream()) analyzer = ClassAnalyzer.Read(stream); if (analyzer == null) { return(null); } ModInfo info = new ModInfo(); foreach (JavaAttribute attribute in analyzer.Attributes) { if (attribute == null) { continue; } if (attribute is JavaRuntimeAnnotations) { foreach (JavaAnnotation annotation in ((JavaRuntimeAnnotations)attribute).Annotations) { if (annotation.Name.EndsWith("/fml/common/Mod;")) { if (annotation.Elements.ContainsKey("modid")) { info.ID = (string)annotation.Elements["modid"]; } if (annotation.Elements.ContainsKey("name")) { info.Name = (string)annotation.Elements["name"]; } if (annotation.Elements.ContainsKey("version")) { info.Version = (string)annotation.Elements["version"]; } if (annotation.Elements.ContainsKey("acceptedMinecraftVersions")) { info.MinecraftVersion = VersionTools.ToVersion((string)annotation.Elements["acceptedMinecraftVersions"]); } if (annotation.Elements.ContainsKey("dependencies")) { info.Dependencies = VersionTools.ToVersion((string)annotation.Elements["dependencies"]); } } else if (annotation.Name.EndsWith("/fml/relauncher/IFMLLoadingPlugin$Name;")) { info.Name = (string)annotation.Elements["value"]; if (info.ID == null) { info.ID = info.Name; } } else if (annotation.Name.EndsWith("/fml/relauncher/IFMLLoadingPlugin$MCVersion;")) { info.MinecraftVersion = VersionTools.ToVersion((string)annotation.Elements["value"]); } } } } return(info); }
public override bool isDirectory(string url) { ZipFileInfo info = zipFile.getFileInfo(parseURLInZip(url)); return(info != null && info.IsDirectory); }