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

301 lines
9.4 KiB
C#
Raw Normal View History

2021-06-30 17:56:02 +02:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
2025-01-01 18:57:55 +01:00
// Copyright © 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;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
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;
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>
public sealed class ImageFileCache : IDistributedCache, IDisposable
2021-06-30 17:56:02 +02:00
{
2024-05-19 23:22:54 +02:00
private readonly MemoryDistributedCache memoryCache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()));
private readonly DirectoryInfo rootDirectory;
private readonly Timer cleanTimer;
private bool cleaning;
2021-06-30 17:56:02 +02:00
2024-08-15 19:46:14 +02:00
public ImageFileCache(string path)
: this(path, TimeSpan.FromHours(1))
{
}
public ImageFileCache(string path, TimeSpan autoCleanInterval)
2021-06-30 17:56:02 +02:00
{
2024-08-15 19:46:14 +02:00
if (string.IsNullOrEmpty(path))
2021-06-30 17:56:02 +02:00
{
2024-08-15 19:46:14 +02:00
throw new ArgumentException($"The {nameof(path)} argument must not be null or empty.", nameof(path));
2021-06-30 17:56:02 +02:00
}
rootDirectory = new DirectoryInfo(path);
2025-02-20 11:45:45 +01:00
rootDirectory.Create();
2021-07-01 15:43:52 +02:00
Debug.WriteLine($"{nameof(ImageFileCache)}: {rootDirectory.FullName}");
if (autoCleanInterval > TimeSpan.Zero)
{
cleanTimer = new Timer(_ => Clean(), null, TimeSpan.Zero, autoCleanInterval);
}
}
2021-06-30 17:56:02 +02:00
public void Dispose()
{
cleanTimer?.Dispose();
2021-06-30 20:59:38 +02:00
}
2024-02-03 20:53:32 +01:00
public byte[] Get(string key)
{
var buffer = memoryCache.Get(key);
2024-02-03 20:53:32 +01:00
if (buffer == null)
2024-02-03 20:53:32 +01:00
{
var file = GetFile(key);
try
2024-02-03 20:53:32 +01:00
{
if (file != null && file.Exists && file.CreationTime > DateTime.Now)
{
using (var stream = file.OpenRead())
{
buffer = new byte[stream.Length];
var offset = 0;
while (offset < buffer.Length)
{
offset += stream.Read(buffer, offset, buffer.Length - offset);
}
}
var options = new DistributedCacheEntryOptions { AbsoluteExpiration = file.CreationTime };
memoryCache.Set(key, buffer, options);
}
}
catch (Exception ex)
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed reading {file.FullName}: {ex.Message}");
2024-02-03 20:53:32 +01:00
}
}
return buffer;
}
public async Task<byte[]> GetAsync(string key, CancellationToken token = default)
2024-02-03 20:53:32 +01:00
{
var buffer = await memoryCache.GetAsync(key, token).ConfigureAwait(false);
2024-02-03 20:53:32 +01:00
2024-02-05 16:59:00 +01:00
if (buffer == null)
2024-02-03 20:53:32 +01:00
{
var file = GetFile(key);
try
2024-02-03 20:53:32 +01:00
{
2025-02-20 12:33:58 +01:00
if (file != null && file.Exists && file.CreationTime > DateTime.Now && !token.IsCancellationRequested)
2024-02-03 20:53:32 +01:00
{
using (var stream = file.OpenRead())
2024-08-23 23:05:34 +02:00
{
buffer = new byte[stream.Length];
var offset = 0;
while (offset < buffer.Length)
{
offset += await stream.ReadAsync(buffer, offset, buffer.Length - offset, token).ConfigureAwait(false);
2024-08-23 23:05:34 +02:00
}
}
var options = new DistributedCacheEntryOptions { AbsoluteExpiration = file.CreationTime };
await memoryCache.SetAsync(key, buffer, options, token).ConfigureAwait(false);
2024-02-03 20:53:32 +01:00
}
}
catch (Exception ex)
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed reading {file.FullName}: {ex.Message}");
}
2024-02-03 20:53:32 +01:00
}
return buffer;
}
public void Set(string key, byte[] buffer, DistributedCacheEntryOptions options)
{
2024-02-05 14:50:30 +01:00
memoryCache.Set(key, buffer, options);
var file = GetFile(key);
2024-02-03 20:53:32 +01:00
try
2024-02-03 20:53:32 +01:00
{
if (file != null && buffer?.Length > 0)
{
2025-02-20 11:45:45 +01:00
file.Directory.Create();
using (var stream = file.Create())
2024-02-05 14:50:30 +01:00
{
2024-08-23 23:05:34 +02:00
stream.Write(buffer, 0, buffer.Length);
2024-02-03 20:53:32 +01:00
}
2025-02-20 11:45:45 +01:00
SetExpiration(file, options);
2024-02-03 20:53:32 +01:00
}
}
catch (Exception ex)
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed writing {file.FullName}: {ex.Message}");
}
2024-02-03 20:53:32 +01:00
}
public async Task SetAsync(string key, byte[] buffer, DistributedCacheEntryOptions options, CancellationToken token = default)
2024-02-03 20:53:32 +01:00
{
await memoryCache.SetAsync(key, buffer, options, token).ConfigureAwait(false);
2024-02-05 14:50:30 +01:00
var file = GetFile(key);
2024-02-03 20:53:32 +01:00
2024-08-23 23:05:34 +02:00
try
2024-02-03 20:53:32 +01:00
{
if (file != null && buffer?.Length > 0 && !token.IsCancellationRequested)
2024-02-03 20:53:32 +01:00
{
2025-02-20 11:45:45 +01:00
file.Directory.Create();
using (var stream = file.Create())
2024-02-03 20:53:32 +01:00
{
await stream.WriteAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false);
2024-02-03 20:53:32 +01:00
}
2025-02-20 11:45:45 +01:00
SetExpiration(file, options);
2024-02-03 20:53:32 +01:00
}
2024-08-23 23:05:34 +02:00
}
catch (Exception ex)
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed writing {file.FullName}: {ex.Message}");
2024-02-03 20:53:32 +01:00
}
}
public void Refresh(string key)
{
memoryCache.Refresh(key);
2024-02-03 20:53:32 +01:00
}
public Task RefreshAsync(string key, CancellationToken token = default)
{
return memoryCache.RefreshAsync(key, token);
2024-02-03 20:53:32 +01:00
}
public void Remove(string key)
{
memoryCache.Remove(key);
var file = GetFile(key);
2024-02-03 20:53:32 +01:00
try
{
if (file != null && file.Exists)
2024-02-03 20:53:32 +01:00
{
file.Delete();
2024-02-03 20:53:32 +01:00
}
}
catch (Exception ex)
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed deleting {file.FullName}: {ex.Message}");
2024-02-03 20:53:32 +01:00
}
}
public async Task RemoveAsync(string key, CancellationToken token = default)
2024-02-03 20:53:32 +01:00
{
await memoryCache.RemoveAsync(key, token);
2024-02-05 14:50:30 +01:00
var file = GetFile(key);
2024-02-05 14:50:30 +01:00
try
{
if (file != null && file.Exists && !token.IsCancellationRequested)
2024-02-05 14:50:30 +01:00
{
file.Delete();
2024-02-05 14:50:30 +01:00
}
}
catch (Exception ex)
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed deleting {file.FullName}: {ex.Message}");
2024-02-05 14:50:30 +01:00
}
2024-02-03 20:53:32 +01:00
}
public void Clean()
2021-06-30 20:59:38 +02:00
{
if (!cleaning)
2021-07-02 11:35:20 +02:00
{
cleaning = true;
foreach (var directory in rootDirectory.EnumerateDirectories())
{
var deletedFileCount = CleanDirectory(directory);
if (deletedFileCount > 0)
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Deleted {deletedFileCount} expired files in {directory.Name}.");
}
}
cleaning = false;
2021-07-02 11:35:20 +02:00
}
2021-06-30 20:59:38 +02:00
}
public Task CleanAsync()
{
2024-08-31 11:55:59 +02:00
return Task.Run(Clean);
}
private FileInfo GetFile(string key)
{
try
{
return new FileInfo(Path.Combine(rootDirectory.FullName, Path.Combine(key.Split('/'))));
}
catch (Exception ex)
{
2024-08-31 16:39:49 +02:00
Debug.WriteLine($"{nameof(ImageFileCache)}: Invalid key {key}: {ex.Message}");
}
return null;
}
2025-02-20 11:45:45 +01:00
private static void SetExpiration(FileInfo file, DistributedCacheEntryOptions options)
2021-06-30 20:59:38 +02:00
{
2025-02-20 11:45:45 +01:00
file.CreationTime = options.AbsoluteExpiration.HasValue
? options.AbsoluteExpiration.Value.LocalDateTime
: DateTime.Now.Add(options.AbsoluteExpirationRelativeToNow ?? (options.SlidingExpiration ?? TimeSpan.FromDays(1)));
2021-07-02 11:35:20 +02:00
}
private static int CleanDirectory(DirectoryInfo directory)
2021-07-02 11:35:20 +02:00
{
var deletedFileCount = 0;
try
2021-07-02 11:35:20 +02:00
{
deletedFileCount = directory.EnumerateDirectories().Sum(CleanDirectory);
2024-02-11 16:17:35 +01:00
foreach (var file in directory.EnumerateFiles().Where(f => f.CreationTime <= DateTime.Now))
2021-06-30 20:59:38 +02:00
{
file.Delete();
deletedFileCount++;
2021-06-30 20:59:38 +02:00
}
if (!directory.EnumerateFileSystemInfos().Any())
2021-06-30 20:59:38 +02:00
{
directory.Delete();
2021-06-30 20:59:38 +02:00
}
2024-02-11 16:17:35 +01:00
}
catch (Exception ex)
2024-02-11 16:17:35 +01:00
{
Debug.WriteLine($"{nameof(ImageFileCache)}: Failed cleaning {directory.FullName}: {ex.Message}");
2021-06-30 17:56:02 +02:00
}
return deletedFileCount;
}
2021-06-30 17:56:02 +02:00
}
}