mirror of
https://github.com/Cleanuparr/Cleanuparr.git
synced 2026-05-09 07:13:59 -04:00
68 lines
2.4 KiB
C#
68 lines
2.4 KiB
C#
using System.Collections.Immutable;
|
|
using Cleanuparr.Persistence.Models.Configuration;
|
|
|
|
namespace Cleanuparr.Infrastructure.Features.Context;
|
|
|
|
public static class ContextProvider
|
|
{
|
|
private static readonly AsyncLocal<ImmutableDictionary<string, object>> _asyncLocalDict = new();
|
|
|
|
public static void Set(string key, object value)
|
|
{
|
|
ImmutableDictionary<string, object> currentDict = _asyncLocalDict.Value ?? ImmutableDictionary<string, object>.Empty;
|
|
_asyncLocalDict.Value = currentDict.SetItem(key, value);
|
|
}
|
|
|
|
public static void Set<T>(T value) where T : class
|
|
{
|
|
string key = typeof(T).Name ?? throw new Exception("Type name is null");
|
|
Set(key, value);
|
|
}
|
|
|
|
public static object? Get(string key)
|
|
{
|
|
return _asyncLocalDict.Value?.TryGetValue(key, out object? value) is true ? value : null;
|
|
}
|
|
|
|
public static T Get<T>(string key) where T : class
|
|
{
|
|
return Get(key) as T ?? throw new Exception($"failed to get \"{key}\" from context");
|
|
}
|
|
|
|
public static T Get<T>() where T : class
|
|
{
|
|
string key = typeof(T).Name ?? throw new Exception("Type name is null");
|
|
return Get<T>(key);
|
|
}
|
|
|
|
public const string JobRunIdKey = "JobRunId";
|
|
|
|
public static Guid GetJobRunId() =>
|
|
Get(JobRunIdKey) as Guid? ?? throw new InvalidOperationException("JobRunId not set in context");
|
|
|
|
public static Guid? TryGetJobRunId() => Get(JobRunIdKey) as Guid?;
|
|
|
|
public static void SetJobRunId(Guid id) => Set(JobRunIdKey, id);
|
|
|
|
public static void SetDownloadClient(DownloadClientConfig config)
|
|
{
|
|
Set(Keys.DownloadClientUrl, config.ExternalOrInternalUrl);
|
|
Set(Keys.DownloadClientId, config.Id);
|
|
Set(Keys.DownloadClientType, config.TypeName);
|
|
Set(Keys.DownloadClientName, config.Name);
|
|
}
|
|
|
|
public static class Keys
|
|
{
|
|
public const string Version = "version";
|
|
public const string ItemName = "itemName";
|
|
public const string Hash = "hash";
|
|
public const string DownloadClientUrl = "downloadClientUrl";
|
|
public const string DownloadClientId = "downloadClientId";
|
|
public const string DownloadClientType = "downloadClientType";
|
|
public const string DownloadClientName = "downloadClientName";
|
|
public const string ArrInstanceId = "arrInstanceId";
|
|
public const string ArrInstanceUrl = "arrInstanceUrl";
|
|
}
|
|
}
|