Skip to content

Commit

Permalink
Switch to System.Text.Json \w De/serialization Source Generation pt. 2
Browse files Browse the repository at this point in the history
  • Loading branch information
neon-nyan committed Oct 9, 2022
1 parent aeefab4 commit 8d260a3
Show file tree
Hide file tree
Showing 22 changed files with 179 additions and 122 deletions.
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
using ColorThiefDotNet;
using Hi3Helper;
using Hi3Helper.Http;
using Hi3Helper.Shared.ClassStruct;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media.Animation;
using Microsoft.UI.Xaml.Media.Imaging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
Expand Down Expand Up @@ -72,7 +73,8 @@ private async Task FetchLauncherResourceAsRegion()
using (MemoryStream memoryStream = new MemoryStream())
{
await Http.Download(CurrentConfigV2.LauncherResourceURL, memoryStream, null, null, default);
regionResourceProp = JsonConvert.DeserializeObject<RegionResourceProp>(Encoding.UTF8.GetString(memoryStream.ToArray()));
memoryStream.Position = 0;
regionResourceProp = (RegionResourceProp)JsonSerializer.Deserialize(memoryStream, typeof(RegionResourceProp), RegionResourcePropContext.Default);
}
}

Expand All @@ -85,7 +87,8 @@ private async Task<RegionResourceProp> TryGetMultiLangResourceProp()
if (!PassFirstTry)
{
await Http.Download(string.Format(CurrentConfigV2.LauncherSpriteURL, Lang.LanguageID.ToLower()), memoryStream, null, null, default);
ret = JsonConvert.DeserializeObject<RegionResourceProp>(Encoding.UTF8.GetString(memoryStream.GetBuffer()));
memoryStream.Position = 0;
ret = (RegionResourceProp)JsonSerializer.Deserialize(memoryStream, typeof(RegionResourceProp), RegionResourcePropContext.Default);

NoData = ret.data.adv == null;
}
Expand All @@ -94,7 +97,8 @@ private async Task<RegionResourceProp> TryGetMultiLangResourceProp()
{
PassFirstTry = true;
await Http.Download(string.Format(CurrentConfigV2.LauncherSpriteURL, CurrentConfigV2.LauncherSpriteURLMultiLangFallback), memoryStream, null, null, default);
ret = JsonConvert.DeserializeObject<RegionResourceProp>(Encoding.UTF8.GetString(memoryStream.GetBuffer()));
memoryStream.Position = 0;
ret = (RegionResourceProp)JsonSerializer.Deserialize(memoryStream, typeof(RegionResourceProp), RegionResourcePropContext.Default);
}
}

Expand All @@ -109,7 +113,8 @@ private async Task<RegionResourceProp> TryGetSingleLangResourceProp()
using (MemoryStream memoryStream = new MemoryStream())
{
await Http.Download(CurrentConfigV2.LauncherSpriteURL, memoryStream, null, null, default);
ret = JsonConvert.DeserializeObject<RegionResourceProp>(Encoding.UTF8.GetString(memoryStream.GetBuffer()));
memoryStream.Position = 0;
ret = (RegionResourceProp)JsonSerializer.Deserialize(memoryStream, typeof(RegionResourceProp), RegionResourcePropContext.Default);
}

return ret;
Expand Down
9 changes: 4 additions & 5 deletions CollapseLauncher/Classes/CachesManagement/CachesCheck.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
using Hi3Helper.Shared.ClassStruct;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using static Hi3Helper.Data.ConverterTool;
Expand Down Expand Up @@ -100,11 +101,9 @@ private async Task FetchCachesAPI()
http.DownloadProgress += DataFetchingProgress;
await http.Download(cachesAPIURL, cachesStream, null, null, cancellationTokenSource.Token);
http.DownloadProgress -= DataFetchingProgress;
cachesStream.Position = 0;

cacheCatalog = JsonConvert.DeserializeObject<DataProperties>(
Encoding.UTF8.GetString(
(cachesStream as MemoryStream).GetBuffer()
));
cacheCatalog = (DataProperties)JsonSerializer.Deserialize(cachesStream, typeof(DataProperties), DataPropertiesContext.Default);

if (cacheCatalog.HashSalt != null)
Pkcs1Salt = cacheCatalog.HashSalt;
Expand Down
13 changes: 13 additions & 0 deletions CollapseLauncher/Classes/ClassesContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Hi3Helper.Shared.ClassStruct;
using System.Text.Json.Serialization;

namespace CollapseLauncher
{
[JsonSerializable(typeof(Prop))]
[JsonSourceGenerationOptions(WriteIndented = true)]
internal partial class PropContext : JsonSerializerContext { }

[JsonSerializable(typeof(NotificationPush))]
[JsonSourceGenerationOptions(WriteIndented = true)]
internal partial class NotificationPushContext : JsonSerializerContext { }
}
30 changes: 15 additions & 15 deletions CollapseLauncher/Classes/EventsManagement/EventsHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media.Animation;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
Expand Down Expand Up @@ -46,8 +46,8 @@ public static async void StartCheckUpdate()
using (MemoryStream RemoteData = new MemoryStream())
{
await new Http().Download(ChannelURL + "fileindex.json", RemoteData, null, null, new CancellationToken());
string UpdateJSON = Encoding.UTF8.GetString(RemoteData.ToArray());
UpdateProperty = JsonConvert.DeserializeObject<Prop>(UpdateJSON);
RemoteData.Position = 0;
UpdateProperty = (Prop)JsonSerializer.Deserialize(RemoteData, typeof(Prop), PropContext.Default);
}

if (CompareVersion(AppCurrentVersion, UpdateProperty.ver))
Expand Down Expand Up @@ -89,20 +89,20 @@ public static bool CompareVersion(string CurrentVer, string ComparedVer)

return concatRemoteVer > concatLocalVer;
}
}

public class Prop
{
public string ver { get; set; }
public long time { get; set; }
public List<fileProp> f { get; set; }
}
public class Prop
{
public string ver { get; set; }
public long time { get; set; }
public List<fileProp> f { get; set; }
}

public class fileProp
{
public string p { get; set; }
public string crc { get; set; }
public long s { get; set; }
}
public class fileProp
{
public string p { get; set; }
public string crc { get; set; }
public long s { get; set; }
}

internal class LauncherUpdateInvoker
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@
using Hi3Helper.Http;
using Hi3Helper.Preset;
using Hi3Helper.Shared.ClassStruct;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using static Hi3Helper.Data.ConverterTool;
Expand Down Expand Up @@ -66,15 +65,17 @@ public async Task StartPreparation()
DownloadProgress += FetchIngredientsAPI_Progress;
await Download(SourceBaseURL + "index.json", buffer, null, null, Token);
DownloadProgress -= FetchIngredientsAPI_Progress;
SourceFileRemote = JsonConvert.DeserializeObject<List<FilePropertiesRemote>>(Encoding.UTF8.GetString(buffer.ToArray()));
buffer.Position = 0;
SourceFileRemote = (List<FilePropertiesRemote>)JsonSerializer.Deserialize(buffer, typeof(List<FilePropertiesRemote>), L_FilePropertiesRemoteContext.Default);
}
using (MemoryStream buffer = new MemoryStream())
{
ConvertDetail = Lang._InstallConvert.Step2Subtitle;
DownloadProgress += FetchIngredientsAPI_Progress;
await Download(TargetBaseURL + "index.json", buffer, null, null, Token);
DownloadProgress -= FetchIngredientsAPI_Progress;
TargetFileRemote = JsonConvert.DeserializeObject<List<FilePropertiesRemote>>(Encoding.UTF8.GetString(buffer.ToArray()));
buffer.Position = 0;
TargetFileRemote = (List<FilePropertiesRemote>)JsonSerializer.Deserialize(buffer, typeof(List<FilePropertiesRemote>), L_FilePropertiesRemoteContext.Default);
}

SourceFileManifest = BuildManifest(SourceFileRemote);
Expand Down Expand Up @@ -164,34 +165,6 @@ await Task.Run(() =>
return BrokenManifest;
}

private async Task Copy(string InputPath, string OutputPath, bool UseCopyTo = true)
{
byte[] buffer = new byte[20 << 20];
using (FileStream source = new FileStream(InputPath, FileMode.Open, FileAccess.Read))
{
using (FileStream dest = new FileStream(OutputPath, FileMode.Create, FileAccess.Write))
{
if (UseCopyTo)
{
await source.CopyToAsync(dest, Token);
MakeIngredientsRead += source.Length;
UpdateProgress(MakeIngredientsRead, MakeIngredientsTotalSize, 1, 1, ConvertSw.Elapsed, ConvertStatus, ConvertDetail);
}
else
{
int read = 0;
while ((read = await source.ReadAsync(buffer)) > 0)
{
Token.ThrowIfCancellationRequested();
dest.Write(buffer, 0, read);
MakeIngredientsRead += read;
UpdateProgress(MakeIngredientsRead, MakeIngredientsTotalSize, 1, 1, ConvertSw.Elapsed, ConvertStatus, ConvertDetail);
}
}
}
}
}

private List<FileProperties> BuildManifest(List<FilePropertiesRemote> FileRemote)
{
List<FileProperties> _out = new List<FileProperties>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@
using Hi3Helper.Shared.ClassStruct;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using static Hi3Helper.Data.ConverterTool;
using static Hi3Helper.Locale;
Expand Down Expand Up @@ -59,7 +58,8 @@ public async Task StartPreparation()
DownloadProgress += FetchIngredientsAPI_Progress;
await Download(SourceBaseURL + "index.json", buffer, null, null, Token);
DownloadProgress -= FetchIngredientsAPI_Progress;
SourceFileRemote = JsonConvert.DeserializeObject<List<FilePropertiesRemote>>(Encoding.UTF8.GetString(buffer.ToArray()));
buffer.Position = 0;
SourceFileRemote = (List<FilePropertiesRemote>)JsonSerializer.Deserialize(buffer, typeof(List<FilePropertiesRemote>), L_FilePropertiesRemoteContext.Default);
}

SourceFileManifest = BuildManifest(SourceFileRemote);
Expand Down
12 changes: 6 additions & 6 deletions CollapseLauncher/Classes/InstallManagement/InstallManagement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
using Hi3Helper.Shared.ClassStruct;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Newtonsoft.Json;
using SevenZipExtractor;
using System;
using System.Collections.Generic;
using System.CommandLine.Parsing;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using static CollapseLauncher.Dialogs.SimpleDialogs;
Expand Down Expand Up @@ -482,7 +482,7 @@ private long GetHdiffSize(in IEnumerable<string> List)
string path;
foreach (string entry in List)
{
_Entry = JsonConvert.DeserializeObject<PkgVersionProperties>(entry);
_Entry = (PkgVersionProperties)JsonSerializer.Deserialize(entry, typeof(PkgVersionProperties), PkgVersionPropertiesContext.Default);
path = Path.Combine(GameDirPath, ConverterTool.NormalizePath(_Entry.remoteName) + ".hdiff");
file = new FileInfo(path);
outSize += file.Exists ? file.Length : 0;
Expand Down Expand Up @@ -515,7 +515,7 @@ private void ApplyHdiffPatch()
foreach (string _Entry in HPatchList)
{
i++;
Entry = JsonConvert.DeserializeObject<PkgVersionProperties>(_Entry);
Entry = (PkgVersionProperties)JsonSerializer.Deserialize(_Entry, typeof(PkgVersionProperties), PkgVersionPropertiesContext.Default);
FileSource = Path.Combine(GameDirPath, ConverterTool.NormalizePath(Entry.remoteName));
FilePatch = FileSource + ".hdiff";
FileOutput = FileSource + "_tmp";
Expand Down Expand Up @@ -823,7 +823,7 @@ private void BuildManifestPersistentList(string manifestPath, in List<PkgVersion
foreach (string data in File.ReadAllLines(manifestPath)
.Where(x => x.EndsWith(onlyAcceptExt, StringComparison.OrdinalIgnoreCase)))
{
Entry = JsonConvert.DeserializeObject<PkgVersionProperties>(data);
Entry = (PkgVersionProperties)JsonSerializer.Deserialize(data, typeof(PkgVersionProperties), PkgVersionPropertiesContext.Default);

IsHashHasValue = hashtable.ContainsKey(Entry.remoteName);
if (!IsHashHasValue)
Expand Down Expand Up @@ -911,7 +911,7 @@ private void BuildManifestList(string manifestPath, in List<PkgVersionProperties
foreach (string data in File.ReadAllLines(manifestPath)
.Where(x => x.EndsWith(onlyAcceptExt, StringComparison.OrdinalIgnoreCase)))
{
Entry = JsonConvert.DeserializeObject<PkgVersionProperties>(data);
Entry = (PkgVersionProperties)JsonSerializer.Deserialize(data, typeof(PkgVersionProperties), PkgVersionPropertiesContext.Default);
if (parentPath != "")
Entry.remoteName = $"{parentPath.Replace('\\', '/')}/{Entry.remoteName}";
Entry.remoteURL = $"{parentURL}/{Entry.remoteName}";
Expand Down
17 changes: 11 additions & 6 deletions CollapseLauncher/Classes/Properties/InnerLauncherConfig.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Hi3Helper.Preset;
using Hi3Helper;
using Hi3Helper.Preset;
using Hi3Helper.Shared.ClassStruct;
using Hi3Helper.Shared.Region;
using Microsoft.UI;
Expand All @@ -8,11 +9,11 @@
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using Windows.Foundation;
using Windows.UI;
using static Hi3Helper.Preset.ConfigV2Store;
Expand Down Expand Up @@ -147,17 +148,21 @@ public static void SaveLocalNotificationData()
AppPushIgnoreMsgIds = NotificationData.AppPushIgnoreMsgIds,
RegionPushIgnoreMsgIds = NotificationData.RegionPushIgnoreMsgIds
};
File.WriteAllText(LauncherConfig.AppNotifIgnoreFile, JsonConvert.SerializeObject(LocalNotificationData, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
File.WriteAllText(LauncherConfig.AppNotifIgnoreFile,
JsonSerializer.Serialize(LocalNotificationData, typeof(NotificationPush), NotificationPushContext.Default));
}

public static void LoadLocalNotificationData()
{
if (!File.Exists(LauncherConfig.AppNotifIgnoreFile))
File.WriteAllText(LauncherConfig.AppNotifIgnoreFile, JsonConvert.SerializeObject(new NotificationPush
{ AppPushIgnoreMsgIds = new List<int>(), RegionPushIgnoreMsgIds = new List<int>() }, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
File.WriteAllText(LauncherConfig.AppNotifIgnoreFile,
JsonSerializer.Serialize(new NotificationPush
{ AppPushIgnoreMsgIds = new List<int>(), RegionPushIgnoreMsgIds = new List<int>() },
typeof(NotificationPush),
NotificationPushContext.Default));

string Data = File.ReadAllText(LauncherConfig.AppNotifIgnoreFile);
NotificationPush LocalNotificationData = JsonConvert.DeserializeObject<NotificationPush>(Data);
NotificationPush LocalNotificationData = (NotificationPush)JsonSerializer.Deserialize(Data, typeof(NotificationPush), NotificationPushContext.Default);
if (NotificationData != null)
{
NotificationData.AppPushIgnoreMsgIds = LocalNotificationData.AppPushIgnoreMsgIds;
Expand Down
13 changes: 12 additions & 1 deletion CollapseLauncher/Classes/Properties/NotificationPushStructure.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Microsoft.UI.Xaml.Controls;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;

namespace Hi3Helper.Shared.ClassStruct
{
Expand All @@ -9,14 +10,24 @@ public class NotificationProp
public int MsgId { get; set; }
public bool? IsClosable { get; set; }
public bool? IsDisposable { get; set; }
public bool? Show { get; set; }
public string Title { get; set; }
public string Message { get; set; }
public InfoBarSeverity Severity { get; set; }
public NotifSeverity Severity { get; set; }
public string RegionProfile { get; set; }
public string ValidForVerAbove { get; set; }
public string ValidForVerBelow { get; set; }
}

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum NotifSeverity : uint
{
Informational,
Success,
Warning,
Error
}

public class NotificationPush
{
public List<NotificationProp> AppPush { get; set; }
Expand Down
Loading

0 comments on commit 8d260a3

Please sign in to comment.