using dodohold.core; using System.Security.Cryptography; using System.Text; namespace molilian.core { public static class TaobaoShortLinkCacheCore { public const int CacheExpireSeconds = 7 * 86400; public static async Task GetAsync(string shortUrl) { try { string longUrl = await CenterHub.Redis.GetAsync(GetCacheKey(shortUrl)); return IsLongUrl(longUrl) ? longUrl : null; } catch (Exception ex) { LogFailure("read", ex); return null; } } public static string? Get(string shortUrl) { try { string longUrl = CenterHub.Redis.Get(GetCacheKey(shortUrl)); return IsLongUrl(longUrl) ? longUrl : null; } catch (Exception ex) { LogFailure("read", ex); return null; } } public static async Task SaveAsync(string shortUrl, string longUrl) { if (!IsLongUrl(longUrl)) return; try { await CenterHub.Redis.SetAsync(GetCacheKey(shortUrl), longUrl, CacheExpireSeconds); } catch (Exception ex) { LogFailure("write", ex); } } public static void Save(string shortUrl, string longUrl) { if (!IsLongUrl(longUrl)) return; try { CenterHub.Redis.Set(GetCacheKey(shortUrl), longUrl, CacheExpireSeconds); } catch (Exception ex) { LogFailure("write", ex); } } private static bool IsLongUrl(string? url) { return Uri.TryCreate(url, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) && !AlimamaPlus.IsShortLink(url!); } private static string GetCacheKey(string shortUrl) { string hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(shortUrl.Trim()))); return $"cache:taobao:short_link_http:v1:{hash}"; } private static void LogFailure(string operation, Exception ex) { _ = new LoggerLibrary("taobao_short_link_cache", operation) .Info(ex.Message, ex.StackTrace) .SaveAsync(); } } }