Skip to content

Commit

Permalink
Cache when reading embedded resources
Browse files Browse the repository at this point in the history
  • Loading branch information
2dust committed Jan 31, 2025
1 parent 331d11a commit 4faa94b
Show file tree
Hide file tree
Showing 10 changed files with 94 additions and 83 deletions.
61 changes: 61 additions & 0 deletions v2rayN/ServiceLib/Common/EmbedUtils.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using System.Collections.Concurrent;
using System.Reflection;

namespace ServiceLib.Common;

public static class EmbedUtils
{
private static readonly string _tag = "EmbedUtils";
private static readonly ConcurrentDictionary<string, string> _dicEmbedCache = new();

/// <summary>
/// Get embedded text resources
/// </summary>
/// <param name="res"></param>
/// <returns></returns>
public static string GetEmbedText(string res)
{
if (_dicEmbedCache.TryGetValue(res, out var value))
{
return value;
}
var result = string.Empty;

try
{
var assembly = Assembly.GetExecutingAssembly();
using var stream = assembly.GetManifestResourceStream(res);
ArgumentNullException.ThrowIfNull(stream);
using StreamReader reader = new(stream);
result = reader.ReadToEnd();
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
}

_dicEmbedCache.TryAdd(res, result);
return result;
}

/// <summary>
/// Get local storage resources
/// </summary>
/// <returns></returns>
public static string? LoadResource(string? res)
{
try
{
if (File.Exists(res))
{
return File.ReadAllText(res);
}
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
}

return null;
}
}
50 changes: 0 additions & 50 deletions v2rayN/ServiceLib/Common/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,56 +17,6 @@ public class Utils
{
private static readonly string _tag = "Utils";

#region 资源操作

/// <summary>
/// 获取嵌入文本资源
/// </summary>
/// <param name="res"></param>
/// <returns></returns>
public static string GetEmbedText(string res)
{
var result = string.Empty;

try
{
var assembly = Assembly.GetExecutingAssembly();
using var stream = assembly.GetManifestResourceStream(res);
ArgumentNullException.ThrowIfNull(stream);
using StreamReader reader = new(stream);
result = reader.ReadToEnd();
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
}

return result;
}

/// <summary>
/// 取得存储资源
/// </summary>
/// <returns></returns>
public static string? LoadResource(string? res)
{
try
{
if (File.Exists(res))
{
return File.ReadAllText(res);
}
}
catch (Exception ex)
{
Logging.SaveLog(_tag, ex);
}

return null;
}

#endregion 资源操作

#region 转换函数

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion v2rayN/ServiceLib/Handler/AutoStartupHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ private static async Task SetTaskLinux()
{
try
{
var linuxConfig = Utils.GetEmbedText(Global.LinuxAutostartConfig);
var linuxConfig = EmbedUtils.GetEmbedText(Global.LinuxAutostartConfig);
if (linuxConfig.IsNotEmpty())
{
linuxConfig = linuxConfig.Replace("$ExecPath$", Utils.GetExePath());
Expand Down
8 changes: 4 additions & 4 deletions v2rayN/ServiceLib/Handler/ConfigHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class ConfigHandler
public static Config? LoadConfig()
{
Config? config = null;
var result = Utils.LoadResource(Utils.GetConfigPath(_configRes));
var result = EmbedUtils.LoadResource(Utils.GetConfigPath(_configRes));
if (Utils.IsNotEmpty(result))
{
config = JsonUtils.Deserialize<Config>(result);
Expand Down Expand Up @@ -1735,7 +1735,7 @@ public static async Task<int> InitBuiltinRouting(Config config, bool blImportAdv
Url = string.Empty,
Sort = maxSort + 1,
};
await AddBatchRoutingRules(item2, Utils.GetEmbedText(Global.CustomRoutingFileName + "white"));
await AddBatchRoutingRules(item2, EmbedUtils.GetEmbedText(Global.CustomRoutingFileName + "white"));

//Blacklist
var item3 = new RoutingItem()
Expand All @@ -1744,7 +1744,7 @@ public static async Task<int> InitBuiltinRouting(Config config, bool blImportAdv
Url = string.Empty,
Sort = maxSort + 2,
};
await AddBatchRoutingRules(item3, Utils.GetEmbedText(Global.CustomRoutingFileName + "black"));
await AddBatchRoutingRules(item3, EmbedUtils.GetEmbedText(Global.CustomRoutingFileName + "black"));

//Global
var item1 = new RoutingItem()
Expand All @@ -1753,7 +1753,7 @@ public static async Task<int> InitBuiltinRouting(Config config, bool blImportAdv
Url = string.Empty,
Sort = maxSort + 3,
};
await AddBatchRoutingRules(item1, Utils.GetEmbedText(Global.CustomRoutingFileName + "global"));
await AddBatchRoutingRules(item1, EmbedUtils.GetEmbedText(Global.CustomRoutingFileName + "global"));

if (!blImportAdvancedRules)
{
Expand Down
2 changes: 1 addition & 1 deletion v2rayN/ServiceLib/Handler/PacHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ private static async Task InitText()
var path = Path.Combine(_configPath, "pac.txt");
if (!File.Exists(path))
{
var pac = Utils.GetEmbedText(Global.PacFileName);
var pac = EmbedUtils.GetEmbedText(Global.PacFileName);
await File.AppendAllTextAsync(path, pac);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public async Task<RetResult> GenerateClientCustomConfig(ProfileItem node, string
//enable tun mode
if (_config.TunModeItem.EnableTun)
{
string tun = Utils.GetEmbedText(Global.ClashTunYaml);
string tun = EmbedUtils.GetEmbedText(Global.ClashTunYaml);
if (Utils.IsNotEmpty(tun))
{
var tunContent = YamlUtils.FromYaml<Dictionary<string, object>>(tun);
Expand Down
22 changes: 11 additions & 11 deletions v2rayN/ServiceLib/Services/CoreConfig/CoreConfigSingboxService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public async Task<RetResult> GenerateClientConfigContent(ProfileItem node)

ret.Msg = ResUI.InitialConfiguration;

string result = Utils.GetEmbedText(Global.SingboxSampleClient);
string result = EmbedUtils.GetEmbedText(Global.SingboxSampleClient);
if (Utils.IsNullOrEmpty(result))
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
Expand Down Expand Up @@ -91,8 +91,8 @@ public async Task<RetResult> GenerateClientSpeedtestConfig(List<ServerTestItem>

ret.Msg = ResUI.InitialConfiguration;

var result = Utils.GetEmbedText(Global.SingboxSampleClient);
var txtOutbound = Utils.GetEmbedText(Global.SingboxSampleOutbound);
var result = EmbedUtils.GetEmbedText(Global.SingboxSampleClient);
var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound);
if (Utils.IsNullOrEmpty(result) || txtOutbound.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
Expand Down Expand Up @@ -255,8 +255,8 @@ public async Task<RetResult> GenerateClientMultipleLoadConfig(List<ProfileItem>

ret.Msg = ResUI.InitialConfiguration;

string result = Utils.GetEmbedText(Global.SingboxSampleClient);
string txtOutbound = Utils.GetEmbedText(Global.SingboxSampleOutbound);
string result = EmbedUtils.GetEmbedText(Global.SingboxSampleClient);
string txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound);
if (Utils.IsNullOrEmpty(result) || txtOutbound.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
Expand Down Expand Up @@ -546,7 +546,7 @@ private async Task<int> GenInbounds(SingboxConfig singboxConfig)
_config.TunModeItem.Stack = Global.TunStacks.First();
}

var tunInbound = JsonUtils.Deserialize<Inbound4Sbox>(Utils.GetEmbedText(Global.TunSingboxInboundFileName)) ?? new Inbound4Sbox { };
var tunInbound = JsonUtils.Deserialize<Inbound4Sbox>(EmbedUtils.GetEmbedText(Global.TunSingboxInboundFileName)) ?? new Inbound4Sbox { };
tunInbound.interface_name = Utils.IsOSX() ? $"utun{new Random().Next(99)}" : "singbox_tun";
tunInbound.mtu = _config.TunModeItem.Mtu;
tunInbound.strict_route = _config.TunModeItem.StrictRoute;
Expand Down Expand Up @@ -867,7 +867,7 @@ private async Task<int> GenMoreOutbounds(ProfileItem node, SingboxConfig singbox

//current proxy
var outbound = singboxConfig.outbounds.First();
var txtOutbound = Utils.GetEmbedText(Global.SingboxSampleOutbound);
var txtOutbound = EmbedUtils.GetEmbedText(Global.SingboxSampleOutbound);

//Previous proxy
var prevNode = await AppHandler.Instance.GetProfileItemViaRemarks(subItem.PrevProfile);
Expand Down Expand Up @@ -934,7 +934,7 @@ private async Task<int> GenRouting(SingboxConfig singboxConfig)
{
singboxConfig.route.auto_detect_interface = true;

var tunRules = JsonUtils.Deserialize<List<Rule4Sbox>>(Utils.GetEmbedText(Global.TunSingboxRulesFileName));
var tunRules = JsonUtils.Deserialize<List<Rule4Sbox>>(EmbedUtils.GetEmbedText(Global.TunSingboxRulesFileName));
if (tunRules != null)
{
singboxConfig.route.rules.AddRange(tunRules);
Expand Down Expand Up @@ -1171,11 +1171,11 @@ private async Task<int> GenDns(ProfileItem? node, SingboxConfig singboxConfig)
var strDNS = string.Empty;
if (_config.TunModeItem.EnableTun)
{
strDNS = Utils.IsNullOrEmpty(item?.TunDNS) ? Utils.GetEmbedText(Global.TunSingboxDNSFileName) : item?.TunDNS;
strDNS = Utils.IsNullOrEmpty(item?.TunDNS) ? EmbedUtils.GetEmbedText(Global.TunSingboxDNSFileName) : item?.TunDNS;
}
else
{
strDNS = Utils.IsNullOrEmpty(item?.NormalDNS) ? Utils.GetEmbedText(Global.DNSSingboxNormalFileName) : item?.NormalDNS;
strDNS = Utils.IsNullOrEmpty(item?.NormalDNS) ? EmbedUtils.GetEmbedText(Global.DNSSingboxNormalFileName) : item?.NormalDNS;
}

var dns4Sbox = JsonUtils.Deserialize<Dns4Sbox>(strDNS);
Expand Down Expand Up @@ -1326,7 +1326,7 @@ static void AddRuleSets(List<string> ruleSets, List<string>? rule_set)
var routing = await ConfigHandler.GetDefaultRouting(_config);
if (Utils.IsNotEmpty(routing.CustomRulesetPath4Singbox))
{
var result = Utils.LoadResource(routing.CustomRulesetPath4Singbox);
var result = EmbedUtils.LoadResource(routing.CustomRulesetPath4Singbox);
if (Utils.IsNotEmpty(result))
{
customRulesets = (JsonUtils.Deserialize<List<Ruleset4Sbox>>(result) ?? [])
Expand Down
22 changes: 11 additions & 11 deletions v2rayN/ServiceLib/Services/CoreConfig/CoreConfigV2rayService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Net;
using System.Net;
using System.Net.NetworkInformation;
using System.Text.Json.Nodes;

Expand Down Expand Up @@ -36,7 +36,7 @@ public async Task<RetResult> GenerateClientConfigContent(ProfileItem node)

ret.Msg = ResUI.InitialConfiguration;

var result = Utils.GetEmbedText(Global.V2raySampleClient);
var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient);
if (Utils.IsNullOrEmpty(result))
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
Expand Down Expand Up @@ -91,8 +91,8 @@ public async Task<RetResult> GenerateClientMultipleLoadConfig(List<ProfileItem>

ret.Msg = ResUI.InitialConfiguration;

string result = Utils.GetEmbedText(Global.V2raySampleClient);
string txtOutbound = Utils.GetEmbedText(Global.V2raySampleOutbound);
string result = EmbedUtils.GetEmbedText(Global.V2raySampleClient);
string txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);
if (Utils.IsNullOrEmpty(result) || txtOutbound.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
Expand Down Expand Up @@ -214,8 +214,8 @@ public async Task<RetResult> GenerateClientSpeedtestConfig(List<ServerTestItem>

ret.Msg = ResUI.InitialConfiguration;

var result = Utils.GetEmbedText(Global.V2raySampleClient);
var txtOutbound = Utils.GetEmbedText(Global.V2raySampleOutbound);
var result = EmbedUtils.GetEmbedText(Global.V2raySampleClient);
var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);
if (Utils.IsNullOrEmpty(result) || txtOutbound.IsNullOrEmpty())
{
ret.Msg = ResUI.FailedGetDefaultConfiguration;
Expand Down Expand Up @@ -428,7 +428,7 @@ private async Task<int> GenInbounds(V2rayConfig v2rayConfig)

private Inbounds4Ray GetInbound(InItem inItem, EInboundProtocol protocol, bool bSocks)
{
string result = Utils.GetEmbedText(Global.V2raySampleInbound);
string result = EmbedUtils.GetEmbedText(Global.V2raySampleInbound);
if (Utils.IsNullOrEmpty(result))
{
return new();
Expand Down Expand Up @@ -992,7 +992,7 @@ private async Task<int> GenBoundStreamSettings(ProfileItem node, Outbounds4Ray o
};

//request Host
string request = Utils.GetEmbedText(Global.V2raySampleHttpRequestFileName);
string request = EmbedUtils.GetEmbedText(Global.V2raySampleHttpRequestFileName);
string[] arrHost = host.Split(',');
string host2 = string.Join(",".AppendQuotes(), arrHost);
request = request.Replace("$requestHost$", $"{host2.AppendQuotes()}");
Expand Down Expand Up @@ -1028,7 +1028,7 @@ private async Task<int> GenDns(ProfileItem? node, V2rayConfig v2rayConfig)
var domainStrategy4Freedom = item?.DomainStrategy4Freedom;
if (Utils.IsNullOrEmpty(normalDNS))
{
normalDNS = Utils.GetEmbedText(Global.DNSV2rayNormalFileName);
normalDNS = EmbedUtils.GetEmbedText(Global.DNSV2rayNormalFileName);
}

//Outbound Freedom domainStrategy
Expand Down Expand Up @@ -1196,7 +1196,7 @@ private async Task<int> GenMoreOutbounds(ProfileItem node, V2rayConfig v2rayConf

//current proxy
var outbound = v2rayConfig.outbounds.First();
var txtOutbound = Utils.GetEmbedText(Global.V2raySampleOutbound);
var txtOutbound = EmbedUtils.GetEmbedText(Global.V2raySampleOutbound);

//Previous proxy
var prevNode = await AppHandler.Instance.GetProfileItemViaRemarks(subItem.PrevProfile);
Expand Down Expand Up @@ -1247,4 +1247,4 @@ private async Task<int> GenMoreOutbounds(ProfileItem node, V2rayConfig v2rayConf

#endregion private gen function
}
}
}
6 changes: 3 additions & 3 deletions v2rayN/ServiceLib/ViewModels/DNSSettingViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,14 @@ public DNSSettingViewModel(Func<EViewAction, object?, Task<bool>>? updateView)

ImportDefConfig4V2rayCmd = ReactiveCommand.CreateFromTask(async () =>
{
normalDNS = Utils.GetEmbedText(Global.DNSV2rayNormalFileName);
normalDNS = EmbedUtils.GetEmbedText(Global.DNSV2rayNormalFileName);
await Task.CompletedTask;
});

ImportDefConfig4SingboxCmd = ReactiveCommand.CreateFromTask(async () =>
{
normalDNS2 = Utils.GetEmbedText(Global.DNSSingboxNormalFileName);
tunDNS2 = Utils.GetEmbedText(Global.TunSingboxDNSFileName);
normalDNS2 = EmbedUtils.GetEmbedText(Global.DNSSingboxNormalFileName);
tunDNS2 = EmbedUtils.GetEmbedText(Global.TunSingboxDNSFileName);
await Task.CompletedTask;
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ public async Task ImportRulesFromFileAsync(string fileName)
return;
}

var result = Utils.LoadResource(fileName);
var result = EmbedUtils.LoadResource(fileName);
if (Utils.IsNullOrEmpty(result))
{
return;
Expand Down

0 comments on commit 4faa94b

Please sign in to comment.