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

349 lines
10 KiB
C#
Raw Normal View History

2021-06-30 17:56:02 +02:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
2024-02-03 20:53:32 +01:00
// Copyright © 2024 Clemens Fischer
2021-06-30 17:56:02 +02:00
// Licensed under the Microsoft Public License (Ms-PL)
2024-02-03 20:53:32 +01:00
using Microsoft.Extensions.Caching.Distributed;
2021-06-30 17:56:02 +02:00
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;
2024-02-03 20:53:32 +01:00
using System.Threading;
2021-06-30 20:59:38 +02:00
using System.Threading.Tasks;
2021-06-30 17:56:02 +02:00
namespace MapControl.Caching
{
/// <summary>
2024-02-03 20:53:32 +01:00
/// IDistributedCache implementation based on local image files.
2021-06-30 17:56:02 +02:00
/// </summary>
2024-02-03 20:53:32 +01:00
public class ImageFileCache : IDistributedCache
2021-06-30 17:56:02 +02:00
{
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);
}
2024-02-03 20:53:32 +01:00
public byte[] Get(string key)
{
byte[] buffer = null;
var path = GetPath(key);
try
{
if (path != null && File.Exists(path))
{
buffer = File.ReadAllBytes(path);
CheckExpiration(path, ref buffer);
}
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed reading {path}: {ex.Message}");
}
return buffer;
}
public async Task<byte[]> GetAsync(string key, CancellationToken token = default)
{
byte[] buffer = null;
var path = GetPath(key);
try
{
if (path != null && File.Exists(path))
{
#if NETFRAMEWORK
using (var stream = File.OpenRead(path))
{
buffer = new byte[stream.Length];
var offset = 0;
while (offset < buffer.Length)
{
offset += await stream.ReadAsync(buffer, offset, buffer.Length - offset, token).ConfigureAwait(false);
}
}
#else
buffer = await File.ReadAllBytesAsync(path, token).ConfigureAwait(false);
#endif
CheckExpiration(path, ref buffer);
}
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed reading {path}: {ex.Message}");
}
return buffer;
}
public void Set(string key, byte[] buffer, DistributedCacheEntryOptions options)
{
var path = GetPath(key);
if (path != null && buffer != null && buffer.Length > 0)
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
using (var stream = File.Create(path))
{
stream.Write(buffer, 0, buffer.Length);
var expiration = GetExpiration(options);
if (expiration.HasValue)
{
stream.Write(Encoding.ASCII.GetBytes(expiresTag), 0, 8);
stream.Write(BitConverter.GetBytes(expiration.Value.Ticks), 0, 8);
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed writing {path}: {ex.Message}");
}
}
}
public async Task SetAsync(string key, byte[] buffer, DistributedCacheEntryOptions options, CancellationToken token = default)
{
var path = GetPath(key);
if (path != null && buffer != null && buffer.Length > 0)
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
using (var stream = File.Create(path))
{
await stream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
var expiration = GetExpiration(options);
if (expiration.HasValue)
{
await stream.WriteAsync(Encoding.ASCII.GetBytes(expiresTag), 0, 8).ConfigureAwait(false);
await stream.WriteAsync(BitConverter.GetBytes(expiration.Value.Ticks), 0, 8).ConfigureAwait(false);
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed writing {path}: {ex.Message}");
}
}
}
public void Refresh(string key)
{
throw new NotSupportedException();
}
public Task RefreshAsync(string key, CancellationToken token = default)
{
throw new NotSupportedException();
}
public void Remove(string key)
{
var path = GetPath(key);
try
{
if (path != null && File.Exists(path))
{
File.Delete(path);
}
}
catch (Exception ex)
{
Debug.WriteLine($"ImageFileCache: Failed deleting {path}: {ex.Message}");
}
}
public Task RemoveAsync(string key, CancellationToken token = default)
{
Remove(key);
return Task.CompletedTask;
}
2021-06-30 17:56:02 +02:00
private string GetPath(string key)
{
try
{
return Path.Combine(rootDirectory, Path.Combine(key.Split('/')));
2021-06-30 17:56:02 +02:00
}
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
{
2024-02-03 20:53:32 +01:00
var expiration = ReadExpiration(file);
if (expiration.HasValue && expiration.Value <= DateTimeOffset.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;
}
2024-02-03 20:53:32 +01:00
private static DateTimeOffset? GetExpiration(DistributedCacheEntryOptions options)
2021-06-30 20:59:38 +02:00
{
2024-02-03 20:53:32 +01:00
DateTimeOffset? expiration = null;
if (options.AbsoluteExpiration.HasValue)
{
expiration = options.AbsoluteExpiration.Value;
}
else if (options.AbsoluteExpirationRelativeToNow.HasValue)
{
expiration = DateTimeOffset.UtcNow.Add(options.AbsoluteExpirationRelativeToNow.Value);
}
else if (options.SlidingExpiration.HasValue)
{
expiration = DateTimeOffset.UtcNow.Add(options.SlidingExpiration.Value);
}
return expiration;
}
private static void CheckExpiration(string path, ref byte[] buffer)
{
var expiration = ReadExpiration(ref buffer);
if (expiration.HasValue && expiration.Value <= DateTimeOffset.UtcNow)
{
File.Delete(path);
buffer = null;
}
}
private static DateTimeOffset? ReadExpiration(FileInfo file)
{
DateTimeOffset? expiration = null;
2021-06-30 20:59:38 +02:00
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);
}
}
}
2024-02-03 20:53:32 +01:00
return expiration;
2021-06-30 20:59:38 +02:00
}
2024-02-03 20:53:32 +01:00
private static DateTimeOffset? ReadExpiration(ref byte[] buffer)
2021-06-30 17:56:02 +02:00
{
2024-02-03 20:53:32 +01:00
var expiration = ReadExpiration(buffer);
2021-06-30 17:56:02 +02:00
if (expiration.HasValue)
{
Array.Resize(ref buffer, buffer.Length - 16);
}
2024-02-03 20:53:32 +01:00
return expiration;
2021-06-30 17:56:02 +02:00
}
2024-02-03 20:53:32 +01:00
private static DateTimeOffset? ReadExpiration(byte[] buffer)
2021-06-30 17:56:02 +02:00
{
2024-02-03 20:53:32 +01:00
DateTimeOffset? expiration = null;
2021-06-30 20:59:38 +02:00
2021-06-30 17:56:02 +02:00
if (buffer.Length >= 16 &&
Encoding.ASCII.GetString(buffer, buffer.Length - 16, 8) == expiresTag)
{
2024-02-03 20:53:32 +01:00
expiration = new DateTimeOffset(BitConverter.ToInt64(buffer, buffer.Length - 8), TimeSpan.Zero);
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
}
}
}