/// <summary> /// Downloads the file. /// </summary> public async Task <Stream> DownloadFile(string fileName) { Log($"{fileName} is requested by the client."); string cachedFileLocation = Path.Combine(CommonConstants.CacheFilesLocation, $"{fileName}"); bool fileWasCached = CommonFunctionality.DoesFileExist(cachedFileLocation); if (fileWasCached) { Log($"{fileName} was previously cached."); byte[] allCachedBytes = System.IO.File.ReadAllBytes(cachedFileLocation); FileCurrentVersionStatus fileCurrentVersionStatus; using (ServerServiceClient serverServiceClient = new ServerServiceClient()) { fileCurrentVersionStatus = await serverServiceClient.IsCurrentVersionOfFileAsync(fileName, allCachedBytes.CalculateSha256Hash()); if (fileCurrentVersionStatus == FileCurrentVersionStatus.Modified) { Log($"{fileName} has been modified on the main server."); Stream downloadFile = await UpdateCachedFile(fileName, allCachedBytes, serverServiceClient, cachedFileLocation); MarkFileAsCached(fileName); return(downloadFile); } } if (fileCurrentVersionStatus == FileCurrentVersionStatus.UpToDate) { MarkFileAsCached(fileName); return(new MemoryStream(allCachedBytes)); } throw new FileNotFoundException(); } // File hasn't been cached before. using (ServerServiceClient serverServiceClient = new ServerServiceClient()) { Log($"{fileName} hasn't been cached before. Downloading it from the main server for the first time."); Stream downloadedFile = await serverServiceClient.DownloadFileAsync(fileName); byte[] fileContent = CommonFunctionality.ReadFully(downloadedFile); SaveToNewFile(fileContent, cachedFileLocation); MarkFileAsCached(fileName); return(new MemoryStream(fileContent)); } }