Survivalcraft API 1.8.2.3 v1.8.2.3
Survivalcraft 2.4
载入中...
搜索中...
未找到
MotdManager.cs
浏览该文件的文档.
1using System.Globalization;
2using System.Text.Json;
3using System.Xml.Linq;
4using Engine;
6using XmlUtilities;
7
8namespace Game {
9 public static class MotdManager {
10 public class Message {
11 public List<Line> Lines = [];
12 }
13
14 public class Line {
15 public float Time;
16
17 public XElement Node;
18
19 public string Text;
20 }
21
22 public class Bulletin {
23 public string Title = string.Empty;
24
25 public string EnTitle = string.Empty;
26
27 public string Time = string.Empty;
28
29 public string Content = string.Empty;
30
31 public string EnContent = string.Empty;
32 }
33
34 public class FilterMod {
35 public string Name = string.Empty;
36
37 public string PackageName = string.Empty;
38
39 public string Version = string.Empty;
40
41 public string FilterAPIVersion = string.Empty;
42
43 public string Explanation = string.Empty;
44 }
45
46 public static Bulletin m_bulletin;
47
48 public static bool CanShowBulletin;
49
50 public static bool CanDownloadMotd = true;
51
52 public static List<FilterMod> FilterModAll = [];
53
54 public static Message m_message;
55
56 public static JsonDocument UpdateResult;
57
58 public static bool m_isAdmin;
59
60 public static Message MessageOfTheDay {
61 get => m_message;
62 set {
63 m_message = value;
64 MessageOfTheDayUpdated?.Invoke();
65 }
66 }
67
68 public static event Action MessageOfTheDayUpdated;
69
70 public static void ForceRedownload() {
71 SettingsManager.MotdLastUpdateTime = DateTime.MinValue;
72 }
73
74 public static void Initialize() {
77 }
78 }
79
80 public static void UpdateVersion() {
81 string url = string.Format(
87 );
89 url,
90 null,
91 null,
93 data => { UpdateResult = JsonDocument.Parse(data, JsonDocumentReader.DefaultJsonOptions); },
94 ex => { Log.Warning($"Failed processing Update check. Reason: {ex.Message}"); }
95 );
96 }
97
98 public static void DownloadMotd() {
99 string url = GetMotdUrl();
101 url,
102 null,
103 null,
104 null,
105 delegate(byte[] result) {
106 try {
107 string motdLastDownloadedData = UnpackMotd(result);
108 MessageOfTheDay = null;
109 SettingsManager.MotdLastDownloadedData = motdLastDownloadedData;
110 Log.Information("Downloaded MOTD");
111 }
112 catch (Exception ex) {
113 Log.Warning($"Failed processing MOTD string. Reason: {ex.Message}");
114 }
115 },
116 delegate(Exception error) { Log.Warning($"Failed downloading MOTD. Reason: {error.Message}"); }
117 );
118 }
119
120 public static void Update() {
121 //if (Time.PeriodicEvent(1.0, 0.0) && ModsManager.ConfigLoaded)
122 //{
123 //var t = TimeSpan.FromHours(SettingsManager.MotdUpdatePeriodHours);
124 //DateTime now = DateTime.Now;
125 //if (now >= SettingsManager.MotdLastUpdateTime + t)
126 //{
127 // SettingsManager.MotdLastUpdateTime = now;
128 // DownloadMotd();
129 // UpdateVersion();
130 //}
131 //}
132#if DEBUG
133 CanDownloadMotd = false;
134#endif
135 if (CanDownloadMotd) {
136 DownloadMotd();
137 CommunityContentManager.IsAdmin(new CancellableProgress(), delegate(bool isAdmin) { m_isAdmin = isAdmin; }, delegate { });
138 CanDownloadMotd = false;
139 }
140 if (MessageOfTheDay == null
141 && !string.IsNullOrEmpty(SettingsManager.MotdLastDownloadedData)) {
143 if (MessageOfTheDay == null) {
145 }
146 if (m_bulletin != null
148 if (IsCNLanguageType()
149 && m_bulletin.Title.ToLower() != "null") {
150 CanShowBulletin = true;
151 }
152 else if (!IsCNLanguageType()
153 && m_bulletin.EnTitle.ToLower() != "null") {
154 CanShowBulletin = true;
155 }
156 }
157 }
158 }
159
160 public static string UnpackMotd(byte[] data) {
161 using (MemoryStream stream = new(data)) {
162 return new StreamReader(stream).ReadToEnd();
163 }
164 //throw new InvalidOperationException("\"motd.xml\" file not found in Motd zip archive.");
165 }
166
167 public static Message ParseMotd(string dataString) {
168 try {
169 int num = dataString.IndexOf("<Motd");
170 if (num < 0) {
171 throw new InvalidOperationException("Invalid MOTD data string.");
172 }
173 int num2 = dataString.IndexOf("</Motd>");
174 if (num2 >= 0
175 && num2 > num) {
176 num2 += 7;
177 }
178 XElement xElement = XmlUtils.LoadXmlFromString(dataString.Substring(num, num2 - num), true);
179 SettingsManager.MotdUpdatePeriodHours = XmlUtils.GetAttributeValue(xElement, "UpdatePeriodHours", 24);
181 Message message = new();
182 foreach (XElement item2 in xElement.Elements()) {
184 Line item = new() {
185 Time = XmlUtils.GetAttributeValue<float>(item2, "Time"), Node = item2.Elements().FirstOrDefault(), Text = item2.Value
186 };
187 message.Lines.Add(item);
188 }
189 }
190 LoadBulletin(dataString);
191 LoadFilterMods(dataString);
192 return message;
193 }
194 catch (Exception ex) {
195 Log.Warning($"Failed extracting MOTD string. Reason: {ex.Message}");
196 }
197 return null;
198 }
199
200 public static void LoadBulletin(string dataString) {
201 int num = dataString.IndexOf("<Motd2");
202 if (num < 0) {
203 throw new InvalidOperationException("Invalid MOTD2 data string.");
204 }
205 int num2 = dataString.IndexOf("</Motd2>");
206 if (num2 >= 0
207 && num2 > num) {
208 num2 += 8;
209 }
210 XElement xElement = XmlUtils.LoadXmlFromString(dataString.Substring(num, num2 - num), true);
211 string languageType = !ModsManager.Configs.TryGetValue("Language", out string config) ? "zh-CN" : config;
212 foreach (XElement item in xElement.Elements()) {
213 if (item.Name.LocalName == "Bulletin") {
214 XAttribute title = item.Attribute("Title");
215 if (title == null) {
216 break;
217 }
218 XAttribute enTitle = item.Attribute("EnTitle");
219 if (enTitle == null) {
220 break;
221 }
222 XAttribute time = item.Attribute("Time");
223 if (time == null) {
224 break;
225 }
226 XElement content = item.Element("Content");
227 if (content == null) {
228 break;
229 }
230 XElement enContent = item.Element("EnContent");
231 if (enContent == null) {
232 break;
233 }
234 m_bulletin = new Bulletin {
235 Title = title.Value,
236 EnTitle = enTitle.Value,
237 Time = $"{languageType}${time.Value}",
238 Content = content.Value,
239 EnContent = enContent.Value
240 };
241 break;
242 }
243 }
244 }
245
246 public static void SaveBulletin(string dataString, CancellableProgress progress, Action<byte[]> success, Action<Exception> failure) {
247 progress = progress ?? new CancellableProgress();
249 failure(new InvalidOperationException("Internet connection is unavailable."));
250 return;
251 }
252 Dictionary<string, string> header = new() { { "Content-Type", "application/x-www-form-urlencoded" } };
253 Dictionary<string, string> dictionary = new() { { "Operater", SettingsManager.ScpboxAccessToken }, { "Content", dataString } };
255 "https://m.schub.top/com/api/zh/setnotice",
256 null,
257 header,
259 progress,
260 success,
261 failure
262 );
263 }
264
265 public static void LoadFilterMods(string dataString) {
266 int num = dataString.IndexOf("<Motd3");
267 if (num < 0) {
268 throw new InvalidOperationException("Invalid MOTD3 data string.");
269 }
270 int num2 = dataString.IndexOf("</Motd3>");
271 if (num2 >= 0
272 && num2 > num) {
273 num2 += 8;
274 }
275 XElement xElement = XmlUtils.LoadXmlFromString(dataString.Substring(num, num2 - num), true);
276 FilterModAll.Clear();
277 foreach (XElement item in xElement.Elements()) {
278 if (item.Name.LocalName == "FilterMod") {
279 XAttribute name = item.Attribute("Name");
280 if (name == null) {
281 continue;
282 }
283 XAttribute packageName = item.Attribute("PackageName");
284 if (packageName == null) {
285 continue;
286 }
287 XAttribute version = item.Attribute("Version");
288 if (version == null) {
289 continue;
290 }
291 XAttribute filterAPIVersion = item.Attribute("FilterAPIVersion");
292 if (filterAPIVersion == null) {
293 continue;
294 }
295 FilterMod filterMod = new() {
296 Name = name.Value,
297 PackageName = packageName.Value,
298 Version = version.Value,
299 FilterAPIVersion = filterAPIVersion.Value,
300 Explanation = item.Value
301 };
302 FilterModAll.Add(filterMod);
303 }
304 }
305 }
306
307 public static void ShowBulletin() {
308 try {
309 string time = m_bulletin.Time.Contains('$') ? m_bulletin.Time.Split('$', StringSplitOptions.RemoveEmptyEntries)[1] : string.Empty;
310 if (!string.IsNullOrEmpty(time)) {
311 time = (IsCNLanguageType() ? "公告发布时间: " : "Time: ") + time;
312 }
313 string title = IsCNLanguageType() ? m_bulletin.Title : m_bulletin.EnTitle;
314 string content = IsCNLanguageType() ? m_bulletin.Content : m_bulletin.EnContent;
315 BulletinDialog bulletinDialog = new(
316 title,
317 content,
318 time,
319 delegate { SettingsManager.BulletinTime = m_bulletin.Time; },
320 delegate(LabelWidget titleLabel, LabelWidget contentLabel) {
322 null,
323 new TextBoxDialog(
324 "请输入标题",
325 titleLabel.Text,
326 1024,
327 delegate(string inputTitle) {
329 null,
330 new TextBoxDialog(
331 "请输入内容",
332 contentLabel.Text.Replace("\n", "[n]"),
333 8192,
334 delegate(string inputContent) {
335 if (!string.IsNullOrEmpty(inputTitle)
336 && !string.IsNullOrEmpty(inputContent)) {
337 titleLabel.Text = inputTitle;
338 contentLabel.Text = inputContent.Replace("[n]", "\n");
339 if (IsCNLanguageType()) {
340 m_bulletin.Title = titleLabel.Text;
341 m_bulletin.Content = contentLabel.Text;
342 }
343 else {
344 m_bulletin.EnTitle = titleLabel.Text;
345 m_bulletin.EnContent = contentLabel.Text;
346 }
347 string languageType = !ModsManager.Configs.TryGetValue("Language", out string value)
348 ? "zh-CN"
349 : value;
350 m_bulletin.Time = $"{languageType}${DateTime.Now}";
351 }
352 },
353 delegate(TextBoxWidget textBox) { textBox.Text = textBox.Text.Replace("\n", "[n]"); }
354 )
355 );
356 }
357 )
358 );
359 },
360 delegate(LabelWidget titleLabel, LabelWidget contentLabel) {
361 int num = SettingsManager.MotdLastDownloadedData.IndexOf("<Motd2");
362 int num2 = SettingsManager.MotdLastDownloadedData.IndexOf("</Motd2>") + 8;
363 XElement xElement = XmlUtils.LoadXmlFromString(SettingsManager.MotdLastDownloadedData.Substring(num, num2 - num), true);
364 //string languageType = (!ModsManager.Configs.TryGetValue("Language", out string config)) ? "zh-CN" : config;
365 foreach (XElement item in xElement.Elements()) {
366 if (item.Name.LocalName == "Bulletin") {
367 if (IsCNLanguageType()) {
368 XAttribute titleAttribute = item.Attribute("Title");
369 if (titleAttribute != null) {
370 titleAttribute.Value = titleLabel.m_text;
371 }
372 XAttribute contentAttribute = item.Attribute("Content");
373 if (contentAttribute != null) {
374 contentAttribute.Value = contentLabel.m_text;
375 }
376 }
377 else {
378 XAttribute enTitleAttribute = item.Attribute("EnTitle");
379 if (enTitleAttribute != null) {
380 enTitleAttribute.Value = titleLabel.m_text;
381 }
382 XAttribute enContentAttribute = item.Attribute("EnContent");
383 if (enContentAttribute != null) {
384 enContentAttribute.Value = contentLabel.m_text;
385 }
386 }
387 XAttribute timeAttribute = item.Attribute("Time");
388 if (timeAttribute != null) {
389 timeAttribute.Value = DateTime.Now.ToString(CultureInfo.InvariantCulture);
390 }
391 break;
392 }
393 }
394 string newDownloadedData = SettingsManager.MotdLastDownloadedData.Substring(0, num);
395 newDownloadedData += xElement.ToString();
396 newDownloadedData += SettingsManager.MotdLastDownloadedData.Substring(num2);
397 CancellableBusyDialog busyDialog = new("操作等待中", false);
398 DialogsManager.ShowDialog(null, busyDialog);
400 newDownloadedData,
401 busyDialog.Progress,
402 delegate(byte[] data) {
403 DialogsManager.HideDialog(busyDialog);
404 JsonElement result = JsonDocument.Parse(data, JsonDocumentReader.DefaultJsonOptions).RootElement;
405 bool success = result[0].GetInt32() == 200;
406 string msg = success ? "公告已更新,建议重启游戏检查效果" : result[1].GetString();
407 if (success) {
408 SettingsManager.MotdLastDownloadedData = newDownloadedData;
409 }
410 DialogsManager.ShowDialog(null, new MessageDialog("操作成功", msg, LanguageControl.Ok, null, null));
411 },
412 delegate(Exception e) {
413 DialogsManager.HideDialog(busyDialog);
414 Log.Warning($"SaveBulletin:{e.Message}");
415 }
416 );
417 }
418 );
419 CommunityContentManager.IsAdmin(new CancellableProgress(), delegate(bool isAdmin) { m_isAdmin = isAdmin; }, delegate { });
420 bulletinDialog.m_editButton.IsVisible = m_isAdmin;
421 bulletinDialog.m_updateButton.IsVisible = m_isAdmin;
422 DialogsManager.ShowDialog(null, bulletinDialog);
423 CanShowBulletin = false;
424 }
425 catch (Exception ex) {
426 Log.Warning($"Failed ShowBulletin. Reason: {ex.Message}");
427 }
428 }
429
430 public static bool IsCNLanguageType() {
431 string languageType = !ModsManager.Configs.TryGetValue("Language", out string value) ? "zh-CN" : value;
432 return languageType == "zh-CN";
433 }
434
435 public static string GetMotdUrl() {
436 string languageType = !ModsManager.Configs.TryGetValue("Language", out string value) ? "zh-CN" : value;
437 return string.Format(SettingsManager.MotdUpdateUrl, VersionsManager.SerializationVersion, languageType);
438 }
439 }
440}
static void Information(object message)
定义 Log.cs:56
static void Warning(object message)
定义 Log.cs:68
static void IsAdmin(CancellableProgress progress, Action< bool > success, Action< Exception > failure)
static void HideDialog(Dialog dialog)
static void ShowDialog(ContainerWidget parentWidget, Dialog dialog)
static readonly JsonDocumentOptions DefaultJsonOptions
override string Text
static string LName()
当前设置中的语言的标识符,如果是在加载完成后获取语言,建议改用CurrentLanguageName
static Message m_message
static Action MessageOfTheDayUpdated
static void LoadFilterMods(string dataString)
static Bulletin m_bulletin
static bool IsCNLanguageType()
static JsonDocument UpdateResult
static void ShowBulletin()
static void Initialize()
static List< FilterMod > FilterModAll
static string GetMotdUrl()
static bool CanDownloadMotd
static void ForceRedownload()
static string UnpackMotd(byte[] data)
static bool CanShowBulletin
static Message MessageOfTheDay
static void UpdateVersion()
static Message ParseMotd(string dataString)
static void LoadBulletin(string dataString)
static void SaveBulletin(string dataString, CancellableProgress progress, Action< byte[]> success, Action< Exception > failure)
static void DownloadMotd()
static DateTime MotdLastUpdateTime
static void Post(string address, Dictionary< string, string > parameters, Dictionary< string, string > headers, Stream data, CancellableProgress progress, Action< byte[]> success, Action< Exception > failure)
static bool IsInternetConnectionAvailable()
static MemoryStream UrlParametersToStream(Dictionary< string, string > values)
static void Get(string address, Dictionary< string, string > parameters, Dictionary< string, string > headers, CancellableProgress progress, Action< byte[]> success, Action< Exception > failure)
static bool IsNodeIncludedOnCurrentPlatform(XElement node)
static string APIVersionString
static Dictionary< string, string > Configs
static object GetAttributeValue(XElement node, string attributeName, Type type)
static XElement LoadXmlFromString(string data, bool throwOnError)