Skip to content

Commit

Permalink
improve image cache
Browse files Browse the repository at this point in the history
  • Loading branch information
Lightczx committed Mar 28, 2024
1 parent 7b5a6cc commit 317b68b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/Snap.Hutao/Snap.Hutao/Core/Caching/ImageCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

using Snap.Hutao.Core.DependencyInjection.Annotation.HttpClient;
using Snap.Hutao.Core.IO;
using Snap.Hutao.Core.IO.Hashing;
using Snap.Hutao.Core.Logging;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.IO;
Expand Down Expand Up @@ -104,12 +106,12 @@ public async ValueTask<ValueFile> GetFileFromCacheAsync(Uri uri)
{
if (concurrentTasks.TryAdd(fileName, taskCompletionSource.Task))
{
logger.LogDebug("Begin downloading image file from '{Uri}' to '{File}'", uri, filePath);
logger.LogColorizedInformation("Begin to download file from '{Uri}' to '{File}'", (uri, ConsoleColor.Cyan), (filePath, ConsoleColor.Cyan));
await DownloadFileAsync(uri, filePath).ConfigureAwait(false);
}
else if (concurrentTasks.TryGetValue(fileName, out Task? task))
{
logger.LogDebug("Waiting for a queued image download task to complete for '{Uri}'", uri);
logger.LogDebug("Waiting for a queued image download task to complete for '{Uri}'", (uri, ConsoleColor.Cyan));
await task.ConfigureAwait(false);
}

Expand All @@ -132,10 +134,7 @@ public ValueFile GetFileFromCategoryAndName(string category, string fileName)

private static string GetCacheFileName(Uri uri)
{
string url = uri.ToString();
byte[] chars = Encoding.UTF8.GetBytes(url);
byte[] hash = SHA1.HashData(chars);
return System.Convert.ToHexString(hash);
return Hash.SHA1HexString(uri.ToString());
}

private static bool IsFileInvalid(string file, bool treatNullFileAsInvalid = true)
Expand Down
20 changes: 20 additions & 0 deletions src/Snap.Hutao/Snap.Hutao/Core/IO/Hashing/Hash.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright (c) DGP Studio. All rights reserved.
// Licensed under the MIT license.

using System.Security.Cryptography;
using System.Text;

namespace Snap.Hutao.Core.IO.Hashing;

internal static class Hash
{
public static string SHA1HexString(string input)
{
return HashCore(BitConverter.ToString, SHA1.HashData, Encoding.UTF8.GetBytes, input);
}

private static TResult HashCore<TInput, TResult>(Func<byte[], TResult> resultConverter, Func<byte[], byte[]> hashMethod, Func<TInput, byte[]> bytesConverter, TInput input)
{
return resultConverter(hashMethod(bytesConverter(input)));
}
}

0 comments on commit 317b68b

Please sign in to comment.