XAML-Map-Control/MapControl/Shared/ImageFileCache.cs

180 lines
5.2 KiB
C#
Raw Normal View History

2021-06-30 17:56:02 +02:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
2022-01-14 20:22:56 +01:00
// © 2022 Clemens Fischer
2021-06-30 17:56:02 +02:00
// Licensed under the Microsoft Public License (Ms-PL)
using System;
using System.Diagnostics;
using System.IO;
2021-06-30 20:59:38 +02:00
using System.Linq;
2021-06-30 17:56:02 +02:00
using System.Text;
2021-06-30 20:59:38 +02:00
using System.Threading.Tasks;
2021-06-30 17:56:02 +02:00
namespace MapControl.Caching
{
/// <summary>
/// Image Cache implementation based on local image files.
2021-07-02 15:57:01 +02:00
/// The only valid data type for cached values is Tuple<byte[], DateTime>.
2021-06-30 17:56:02 +02:00
/// </summary>
public partial class ImageFileCache
{
private const string expiresTag = "EXPIRES:";
private readonly string rootDirectory;
public ImageFileCache(string directory)
{
if (string.IsNullOrEmpty(directory))
{
throw new ArgumentException("The directory argument must not be null or empty.", nameof(directory));
}
rootDirectory = directory;
2021-07-01 15:43:52 +02:00
Debug.WriteLine($"Created ImageFileCache in {rootDirectory}");
2021-06-30 17:56:02 +02:00
}
2021-06-30 20:59:38 +02:00
public Task Clean()
{
return Task.Factory.StartNew(CleanRootDirectory, TaskCreationOptions.LongRunning);
}
2021-06-30 17:56:02 +02:00
private string GetPath(string key)
{
try
{
return Path.Combine(rootDirectory, Path.Combine(key.Split('/', ':', ';', ',')));
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Invalid key {rootDirectory}/{key}: {ex.Message}");
2021-06-30 17:56:02 +02:00
}
return null;
}
2021-06-30 20:59:38 +02:00
private void CleanRootDirectory()
{
2021-07-02 11:35:20 +02:00
try
2021-06-30 20:59:38 +02:00
{
2021-07-02 11:35:20 +02:00
foreach (var dir in new DirectoryInfo(rootDirectory).EnumerateDirectories())
2021-06-30 20:59:38 +02:00
{
2021-07-02 11:35:20 +02:00
var deletedFileCount = CleanDirectory(dir);
if (deletedFileCount > 0)
{
Debug.WriteLine($"ImageFileCache: Cleaned {deletedFileCount} files in {dir}");
2021-07-02 11:35:20 +02:00
}
2021-06-30 20:59:38 +02:00
}
}
2021-07-02 11:35:20 +02:00
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed enumerating directories in {rootDirectory}: {ex.Message}");
2021-07-02 11:35:20 +02:00
}
2021-06-30 20:59:38 +02:00
}
private static int CleanDirectory(DirectoryInfo directory)
{
var deletedFileCount = 0;
2021-07-02 11:35:20 +02:00
try
{
deletedFileCount += directory.EnumerateDirectories().Sum(dir => CleanDirectory(dir));
2021-06-30 20:59:38 +02:00
2021-07-02 11:35:20 +02:00
deletedFileCount += directory.EnumerateFiles().Sum(file => CleanFile(file));
2021-06-30 20:59:38 +02:00
2021-07-02 11:35:20 +02:00
if (!directory.EnumerateFileSystemInfos().Any())
2021-06-30 20:59:38 +02:00
{
directory.Delete();
}
2021-07-02 11:35:20 +02:00
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed cleaning {directory.FullName}: {ex.Message}");
2021-07-02 11:35:20 +02:00
}
return deletedFileCount;
}
private static int CleanFile(FileInfo file)
{
var deletedFileCount = 0;
try
{
if (ReadExpiration(file) < DateTime.UtcNow)
2021-06-30 20:59:38 +02:00
{
2021-07-02 11:35:20 +02:00
file.Delete();
deletedFileCount = 1;
2021-06-30 20:59:38 +02:00
}
}
2021-07-02 11:35:20 +02:00
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed cleaning {file.FullName}: {ex.Message}");
2021-07-02 11:35:20 +02:00
}
2021-06-30 20:59:38 +02:00
return deletedFileCount;
}
private static DateTime ReadExpiration(FileInfo file)
{
DateTime? expiration = null;
if (file.Length > 16)
{
var buffer = new byte[16];
using (var stream = file.OpenRead())
{
stream.Seek(-16, SeekOrigin.End);
if (stream.Read(buffer, 0, 16) == 16)
{
expiration = ReadExpiration(buffer);
}
}
}
return expiration ?? DateTime.Today;
}
2021-06-30 17:56:02 +02:00
private static DateTime ReadExpiration(ref byte[] buffer)
{
DateTime? expiration = ReadExpiration(buffer);
if (expiration.HasValue)
{
Array.Resize(ref buffer, buffer.Length - 16);
2021-07-01 15:43:52 +02:00
2021-06-30 17:56:02 +02:00
return expiration.Value;
}
return DateTime.Today;
}
private static DateTime? ReadExpiration(byte[] buffer)
{
2021-06-30 20:59:38 +02:00
DateTime? expiration = null;
2021-06-30 17:56:02 +02:00
if (buffer.Length >= 16 &&
Encoding.ASCII.GetString(buffer, buffer.Length - 16, 8) == expiresTag)
{
2021-06-30 20:59:38 +02:00
expiration = new DateTime(BitConverter.ToInt64(buffer, buffer.Length - 8), DateTimeKind.Utc);
2021-06-30 17:56:02 +02:00
}
2021-06-30 20:59:38 +02:00
return expiration;
2021-06-30 17:56:02 +02:00
}
2021-07-01 15:43:52 +02:00
private static void WriteExpiration(Stream stream, DateTime expiration)
{
stream.Write(Encoding.ASCII.GetBytes(expiresTag), 0, 8);
stream.Write(BitConverter.GetBytes(expiration.Ticks), 0, 8);
}
private static async Task WriteExpirationAsync(Stream stream, DateTime expiration)
{
await stream.WriteAsync(Encoding.ASCII.GetBytes(expiresTag), 0, 8);
await stream.WriteAsync(BitConverter.GetBytes(expiration.Ticks), 0, 8);
}
2021-06-30 17:56:02 +02:00
}
}