-
Notifications
You must be signed in to change notification settings - Fork 821
Expand file tree
/
Copy pathLanguageEngine.cs
More file actions
211 lines (182 loc) · 7.87 KB
/
LanguageEngine.cs
File metadata and controls
211 lines (182 loc) · 7.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text.Json.Nodes;
using Jeffijoe.MessageFormat;
using UniGetUI.Core.Data;
using UniGetUI.Core.Logging;
using UniGetUI.Core.SettingsEngine;
using UniGetUI.PackageEngine.Enums;
namespace UniGetUI.Core.Language
{
public class LanguageEngine
{
private Dictionary<string, string> MainLangDict = [];
public static string SelectedLocale = "??";
[NotNull]
public string? Locale { get; private set; }
private MessageFormatter? Formatter;
public LanguageEngine(string ForceLanguage = "")
{
string LangName = Settings.GetValue(Settings.K.PreferredLanguage);
if (LangName is "default" or "")
{
LangName = CultureInfo.CurrentUICulture.ToString().Replace("-", "_");
}
LoadLanguage((ForceLanguage != "") ? ForceLanguage : LangName);
}
/// <summary>
/// Loads the specified language into the current instance
/// </summary>
/// <param name="lang">the language code</param>
public void LoadLanguage(string lang)
{
try
{
Locale = "en";
if (LanguageData.LanguageReference.ContainsKey(lang))
{
Locale = lang;
}
else if (LanguageData.LanguageReference.ContainsKey(lang[0..2].Replace("uk", "ua")))
{
Locale = lang[0..2].Replace("uk", "ua");
}
MainLangDict = LoadLanguageFile(Locale);
Formatter = new() { Locale = Locale.Replace('_', '-') };
LoadStaticTranslation();
SelectedLocale = Locale;
Logger.Info("Loaded language locale: " + Locale);
}
catch (Exception ex)
{
Logger.Error($"Could not load language file \"{lang}\"");
Logger.Error(ex);
}
}
public Dictionary<string, string> LoadLanguageFile(string LangKey)
{
try
{
string BundledLangFileToLoad = Path.Join(CoreData.UniGetUIExecutableDirectory, "Assets", "Languages", "lang_" + LangKey + ".json");
JsonObject BundledContents = [];
if (!File.Exists(BundledLangFileToLoad))
{
Logger.Error($"Tried to access a non-existing bundled language file! file={BundledLangFileToLoad}");
}
else
{
try
{
if (JsonNode.Parse(File.ReadAllText(BundledLangFileToLoad)) is JsonObject parsedObject)
BundledContents = parsedObject;
else
throw new ArgumentException($"parsedObject was null for lang file {BundledLangFileToLoad}");
}
catch (Exception ex)
{
Logger.Warn($"Something went wrong when parsing language file {BundledLangFileToLoad}");
Logger.Warn(ex);
}
}
Dictionary<string, string> LangDict = BundledContents.ToDictionary(x => x.Key, x => x.Value?.ToString() ?? "");
string CachedLangFileToLoad = Path.Join(CoreData.UniGetUICacheDirectory_Lang, "lang_" + LangKey + ".json");
if (Settings.Get(Settings.K.DisableLangAutoUpdater))
{
Logger.Warn("User has updated translations disabled");
}
else if (!File.Exists(CachedLangFileToLoad))
{
Logger.Warn($"Tried to access a non-existing cached language file! file={CachedLangFileToLoad}");
}
else
{
try
{
if (JsonNode.Parse(File.ReadAllText(CachedLangFileToLoad)) is JsonObject parsedObject)
foreach (var keyval in parsedObject.ToDictionary(x => x.Key, x => x.Value))
{
LangDict[keyval.Key] = keyval.Value?.ToString() ?? "";
}
else
throw new ArgumentException($"parsedObject was null for lang file {CachedLangFileToLoad}");
}
catch (Exception ex)
{
Logger.Warn($"Something went wrong when parsing language file {BundledLangFileToLoad}");
Logger.Warn(ex);
}
}
if (!Settings.Get(Settings.K.DisableLangAutoUpdater))
_ = DownloadUpdatedLanguageFile(LangKey);
return LangDict;
}
catch (Exception e)
{
Logger.Error($"LoadLanguageFile Failed for LangKey={LangKey}");
Logger.Error(e);
return [];
}
}
/// <summary>
/// Downloads and saves an updated version of the translations for the specified language.
/// </summary>
/// <param name="LangKey">The Id of the language to download</param>
public async Task DownloadUpdatedLanguageFile(string LangKey)
{
try
{
Uri NewFile = new("https://raw.githubusercontent.com/marticliment/UniGetUI/main/src/UniGetUI.Core.LanguageEngine/Assets/Languages/lang_" + LangKey + ".json");
HttpClient client = new();
client.DefaultRequestHeaders.UserAgent.ParseAdd(CoreData.UserAgentString);
string fileContents = await client.GetStringAsync(NewFile);
if (!Directory.Exists(CoreData.UniGetUICacheDirectory_Lang))
{
Directory.CreateDirectory(CoreData.UniGetUICacheDirectory_Lang);
}
File.WriteAllText(Path.Join(CoreData.UniGetUICacheDirectory_Lang, "lang_" + LangKey + ".json"), fileContents);
Logger.ImportantInfo("Lang files were updated successfully from GitHub");
}
catch (Exception e)
{
Logger.Warn("Could not download updated translations from GitHub");
Logger.Warn(e);
}
}
public void LoadStaticTranslation()
{
CommonTranslations.ScopeNames[PackageScope.Local] = Translate("User | Local");
CommonTranslations.ScopeNames[PackageScope.Global] = Translate("Machine | Global");
CommonTranslations.InvertedScopeNames.Clear();
CommonTranslations.InvertedScopeNames.Add(Translate("Machine | Global"), PackageScope.Global);
CommonTranslations.InvertedScopeNames.Add(Translate("User | Local"), PackageScope.Local);
}
public string Translate(string key)
{
if (key == "WingetUI")
{
if (MainLangDict.TryGetValue("formerly WingetUI", out var formerly) && formerly != "")
{
return "UniGetUI (" + formerly + ")";
}
return "UniGetUI (formerly WingetUI)";
}
if (key == "Formerly known as WingetUI")
{
return MainLangDict.GetValueOrDefault(key, key);
}
if (key is null or "")
{
return "";
}
if (MainLangDict.TryGetValue(key, out var value) && value != "")
{
return value.Replace("WingetUI", "UniGetUI");
}
return key.Replace("WingetUI", "UniGetUI");
}
public string Translate(string key, Dictionary<string, object?> dict)
{
return Formatter!.FormatMessage(Translate(key), dict);
}
}
}