Skip to content

Commit

Permalink
code style
Browse files Browse the repository at this point in the history
  • Loading branch information
Lightczx committed Oct 19, 2024
1 parent 4f35fd7 commit 8a0284e
Show file tree
Hide file tree
Showing 12 changed files with 88 additions and 234 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace Snap.Hutao.Service.Geetest;

internal sealed class AigisObject
internal sealed class AigisSession
{
[JsonPropertyName("session_id")]
public string SessionId { get; set; } = default!;
Expand Down
38 changes: 15 additions & 23 deletions src/Snap.Hutao/Snap.Hutao/Service/Geetest/GeetestService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,46 +19,46 @@ namespace Snap.Hutao.Service.Geetest;
internal sealed partial class GeetestService : IGeetestService
{
private readonly ICurrentXamlWindowReference currentXamlWindowReference;
private readonly HomaGeetestClient homaGeetestClient;
private readonly CustomGeetestClient customGeetestClient;
private readonly IInfoBarService infoBarService;
private readonly ITaskContext taskContext;
private readonly CardClient cardClient;

public async ValueTask<GeetestData?> TryVerifyAsync(string gt, string challenge, CancellationToken token = default)
public async ValueTask<GeetestData?> TryVerifyGtChallengeAsync(string gt, string challenge, CancellationToken token = default)
{
GeetestResponse response = await homaGeetestClient.VerifyAsync(gt, challenge, token).ConfigureAwait(false);
GeetestResponse response = await customGeetestClient.VerifyAsync(gt, challenge, token).ConfigureAwait(false);

if (response is { Code: 0, Data: { } data })
{
return data;
}

string? result = await VerifyByWebViewAsync(gt, challenge, false, token).ConfigureAwait(false);
string? result = await PrivateVerifyByWebViewAsync(gt, challenge, false, token).ConfigureAwait(false);
if (string.IsNullOrEmpty(result))
{
return default;
}

GeetestWebResponse? webResponse = JsonSerializer.Deserialize<GeetestWebResponse>(result);
ArgumentNullException.ThrowIfNull(webResponse);
GeetestData webData = new()

return new GeetestData()
{
Gt = gt,
Challenge = webResponse.Challenge,
Validate = webResponse.Validate,
};
return webData;
}

public async ValueTask<string?> TryValidateXrpcChallengeAsync(Model.Entity.User user, CardVerifiationHeaders headers, CancellationToken token = default)
public async ValueTask<string?> TryVerifyXrpcChallengeAsync(Model.Entity.User user, CardVerifiationHeaders headers, CancellationToken token = default)
{
Response<VerificationRegistration> registrationResponse = await cardClient.CreateVerificationAsync(user, headers, token).ConfigureAwait(false);
if (!ResponseValidator.TryValidate(registrationResponse, infoBarService, out VerificationRegistration? registration))
{
return default;
}

if (await TryVerifyAsync(registration.Gt, registration.Challenge, token).ConfigureAwait(false) is not { } data)
if (await TryVerifyGtChallengeAsync(registration.Gt, registration.Challenge, token).ConfigureAwait(false) is not { } data)
{
return default;
}
Expand All @@ -69,27 +69,23 @@ internal sealed partial class GeetestService : IGeetestService
return default;
}

if (result.Challenge is not null)
{
return result.Challenge;
}

return default;
return result.Challenge;
}

public async ValueTask<bool> TryResolveAigisAsync(IAigisProvider provider, string? rawSession, bool isOversea, CancellationToken token = default)
public async ValueTask<bool> TryVerifyAigisSessionAsync(IAigisProvider provider, string? rawSession, bool isOversea, CancellationToken token = default)
{
if (string.IsNullOrEmpty(rawSession))
{
return false;
}

AigisObject? session = JsonSerializer.Deserialize<AigisObject>(rawSession);
AigisSession? session = JsonSerializer.Deserialize<AigisSession>(rawSession);
ArgumentNullException.ThrowIfNull(session);

AigisData? sessionData = JsonSerializer.Deserialize<AigisData>(session.Data);
ArgumentNullException.ThrowIfNull(sessionData);

string? result = await VerifyByWebViewAsync(sessionData.GT, sessionData.Challenge, isOversea, token).ConfigureAwait(false);
string? result = await PrivateVerifyByWebViewAsync(sessionData.GT, sessionData.Challenge, isOversea, token).ConfigureAwait(false);

if (string.IsNullOrEmpty(result))
{
Expand All @@ -101,15 +97,11 @@ public async ValueTask<bool> TryResolveAigisAsync(IAigisProvider provider, strin
return true;
}

private async ValueTask<string?> VerifyByWebViewAsync(string gt, string challenge, bool isOversea, CancellationToken token)
private async ValueTask<string?> PrivateVerifyByWebViewAsync(string gt, string challenge, bool isOversea, CancellationToken token)
{
await taskContext.SwitchToMainThreadAsync();
GeetestWebView2ContentProvider contentProvider = new(gt, challenge, isOversea);

new ShowWebView2WindowAction
{
ContentProvider = contentProvider,
}.ShowAt(currentXamlWindowReference.GetXamlRoot());
ShowWebView2WindowAction.Show(contentProvider, currentXamlWindowReference.GetXamlRoot());

await taskContext.SwitchToBackgroundAsync();
return await contentProvider.GetResultAsync().ConfigureAwait(false);
Expand Down
6 changes: 3 additions & 3 deletions src/Snap.Hutao/Snap.Hutao/Service/Geetest/IGeetestService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ namespace Snap.Hutao.Service.Geetest;

internal interface IGeetestService
{
ValueTask<GeetestData?> TryVerifyAsync(string gt, string challenge, CancellationToken token = default);
ValueTask<GeetestData?> TryVerifyGtChallengeAsync(string gt, string challenge, CancellationToken token = default);

ValueTask<string?> TryValidateXrpcChallengeAsync(Model.Entity.User user, CardVerifiationHeaders headers, CancellationToken token = default);
ValueTask<string?> TryVerifyXrpcChallengeAsync(Model.Entity.User user, CardVerifiationHeaders headers, CancellationToken token = default);

ValueTask<bool> TryResolveAigisAsync(IAigisProvider provider, string? rawSession, bool isOversea, CancellationToken token = default);
ValueTask<bool> TryVerifyAigisSessionAsync(IAigisProvider provider, string? rawSession, bool isOversea, CancellationToken token = default);
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,23 @@ namespace Snap.Hutao.UI.Xaml.Behavior.Action;
[DependencyProperty("ContentProvider", typeof(IWebView2ContentProvider))]
internal sealed partial class ShowWebView2WindowAction : DependencyObject, IAction
{
public static ShowWebView2WindowAction Show<TProvider>(XamlRoot xamlRoot)
where TProvider : IWebView2ContentProvider, new()
{
return Show(new TProvider(), xamlRoot);
}

public static ShowWebView2WindowAction Show(IWebView2ContentProvider contentProvider, XamlRoot xamlRoot)
{
ShowWebView2WindowAction action = new()
{
ContentProvider = contentProvider,
};

action.ShowAt(xamlRoot);
return action;
}

public object? Execute(object sender, object parameter)
{
ShowAt(((FrameworkElement)sender).XamlRoot);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
namespace Snap.Hutao.UI.Xaml.View.Dialog;

[INotifyPropertyChanged]
[ConstructorGenerated(InitializeComponent = true)]
internal sealed partial class UserAccountPasswordDialog : ContentDialog, IPassportPasswordProvider
{
private readonly IServiceProvider serviceProvider;
Expand All @@ -22,14 +23,6 @@ internal sealed partial class UserAccountPasswordDialog : ContentDialog, IPasspo
private string? account;
private string? password;

public UserAccountPasswordDialog(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
geetestService = serviceProvider.GetRequiredService<IGeetestService>();
taskContext = serviceProvider.GetRequiredService<ITaskContext>();
InitializeComponent();
}

public string? Account { get => account; set => SetProperty(ref account, value); }

public string? Password
Expand Down Expand Up @@ -66,26 +59,19 @@ public string? Password
ArgumentNullException.ThrowIfNull(Account);
ArgumentNullException.ThrowIfNull(Password);

string? rawSession;
Response<LoginResult> response;

using (IServiceScope scope = serviceProvider.CreateScope())
{
IHoyoPlayPassportClient hoyoPlayPassportClient = scope.ServiceProvider.GetRequiredService<IOverseaSupportFactory<IHoyoPlayPassportClient>>().Create(isOversea);
(rawSession, response) = await hoyoPlayPassportClient.LoginByPasswordAsync(this).ConfigureAwait(false);
}
(string? rawSession, Response<LoginResult> response) = await hoyoPlayPassportClient.LoginByPasswordAsync(this).ConfigureAwait(false);

if (await geetestService.TryResolveAigisAsync(this, rawSession, isOversea).ConfigureAwait(false))
{
using (IServiceScope scope = serviceProvider.CreateScope())
if (await geetestService.TryVerifyAigisSessionAsync(this, rawSession, isOversea).ConfigureAwait(false))
{
IHoyoPlayPassportClient hoyoPlayPassportClient = scope.ServiceProvider.GetRequiredService<IOverseaSupportFactory<IHoyoPlayPassportClient>>().Create(isOversea);
(rawSession, response) = await hoyoPlayPassportClient.LoginByPasswordAsync(this).ConfigureAwait(false);
(_, response) = await hoyoPlayPassportClient.LoginByPasswordAsync(this).ConfigureAwait(false);
}
}

bool ok = ResponseValidator.TryValidate(response, serviceProvider, out LoginResult? result);
return new(ok, result);
bool ok = ResponseValidator.TryValidate(response, serviceProvider, out LoginResult? result);
return new(ok, result);
}
}

private void OnTextKeyDown(object sender, KeyRoutedEventArgs e)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
namespace Snap.Hutao.UI.Xaml.View.Dialog;

[INotifyPropertyChanged]
[ConstructorGenerated(InitializeComponent = true)]
internal sealed partial class UserMobileCaptchaDialog : ContentDialog, IPassportMobileCaptchaProvider
{
private readonly IServiceProvider serviceProvider;
Expand All @@ -23,14 +24,6 @@ internal sealed partial class UserMobileCaptchaDialog : ContentDialog, IPassport
private string? mobile;
private string? captcha;

public UserMobileCaptchaDialog(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
geetestService = serviceProvider.GetRequiredService<IGeetestService>();
taskContext = serviceProvider.GetRequiredService<ITaskContext>();
InitializeComponent();
}

public string? Mobile
{
get => mobile;
Expand Down Expand Up @@ -70,27 +63,20 @@ public async Task SendMobileCaptchaAsync()
{
ArgumentNullException.ThrowIfNull(Mobile);

string? rawSession;
Response<MobileCaptcha> response;

using (IServiceScope scope = serviceProvider.CreateScope())
{
IPassportClient passportClient = scope.ServiceProvider.GetRequiredService<IOverseaSupportFactory<IPassportClient>>().Create(false);
(rawSession, response) = await passportClient.CreateLoginCaptchaAsync(Mobile, null).ConfigureAwait(false);
}
(string? rawSession, Response<MobileCaptcha> response) = await passportClient.CreateLoginCaptchaAsync(Mobile, null).ConfigureAwait(false);

if (await geetestService.TryResolveAigisAsync(this, rawSession, false).ConfigureAwait(false))
{
using (IServiceScope scope = serviceProvider.CreateScope())
if (await geetestService.TryVerifyAigisSessionAsync(this, rawSession, false).ConfigureAwait(false))
{
IPassportClient passportClient = scope.ServiceProvider.GetRequiredService<IOverseaSupportFactory<IPassportClient>>().Create(false);
(rawSession, response) = await passportClient.CreateLoginCaptchaAsync(Mobile, Aigis).ConfigureAwait(false);
(_, response) = await passportClient.CreateLoginCaptchaAsync(Mobile, Aigis).ConfigureAwait(false);
}
}

if (ResponseValidator.TryValidate(response, serviceProvider, out MobileCaptcha? mobileCaptcha))
{
ActionType = mobileCaptcha.ActionType;
if (ResponseValidator.TryValidate(response, serviceProvider, out MobileCaptcha? mobileCaptcha))
{
ActionType = mobileCaptcha.ActionType;
}
}

// Prevent re-enable too soon, and user might not receive the short message
Expand Down
2 changes: 0 additions & 2 deletions src/Snap.Hutao/Snap.Hutao/UI/Xaml/View/UserView.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -429,13 +429,11 @@
</mxi:Interaction.Behaviors>
</AppBarButton>
<AppBarButton
x:Name="SignInRewardButton"
Width="{StaticResource LargeAppBarButtonWidth}"
MaxWidth="{StaticResource LargeAppBarButtonWidth}"
Margin="2,-4"
AllowFocusOnInteraction="True"
Command="{Binding ClaimSignInRewardCommand}"
CommandParameter="{Binding ElementName=SignInRewardButton}"
Icon="{shuxm:FontIcon Glyph={StaticResource FontIconContentGiftboxOpen}}"
Label="{shuxm:ResourceString Name=ViewUserCookieOperationSignInRewardAction}"
Style="{StaticResource DefaultAppBarButtonStyle}"/>
Expand Down
5 changes: 1 addition & 4 deletions src/Snap.Hutao/Snap.Hutao/ViewModel/TitleViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,7 @@ private void ShowUpdateLogWindowAfterUpdate()
if (LocalSetting.Get(SettingKeys.AlwaysIsFirstRunAfterUpdate, false) || XamlApplicationLifetime.IsFirstRunAfterUpdate)
{
XamlApplicationLifetime.IsFirstRunAfterUpdate = false;
new ShowWebView2WindowAction
{
ContentProvider = new UpdateLogContentProvider(),
}.ShowAt(currentXamlWindowReference.GetXamlRoot());
ShowWebView2WindowAction.Show<UpdateLogContentProvider>(currentXamlWindowReference.GetXamlRoot());
}
}

Expand Down
24 changes: 7 additions & 17 deletions src/Snap.Hutao/Snap.Hutao/ViewModel/User/UserViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,7 @@ private async Task LoginByThirdPartyOverseaAsync(string kind)

await taskContext.SwitchToMainThreadAsync();
OverseaThirdPartyLoginWebView2ContentProvider contentProvider = new(thirdPartyKind, cultureOptions.LanguageCode);

new ShowWebView2WindowAction
{
ContentProvider = contentProvider,
}.ShowAt(currentXamlWindowReference.GetXamlRoot());
ShowWebView2WindowAction.Show(contentProvider, currentXamlWindowReference.GetXamlRoot());

await taskContext.SwitchToBackgroundAsync();
ThirdPartyToken? token = await contentProvider.GetResultAsync().ConfigureAwait(false);
Expand Down Expand Up @@ -307,7 +303,7 @@ private async Task RefreshCookieTokenAsync()
}

[Command("ClaimSignInRewardCommand")]
private async Task ClaimSignInRewardAsync(AppBarButton? appBarButton)
private async Task ClaimSignInRewardAsync()
{
if (await userService.GetCurrentUserAndUidAsync().ConfigureAwait(false) is not { } userAndUid)
{
Expand All @@ -325,20 +321,14 @@ private async Task ClaimSignInRewardAsync(AppBarButton? appBarButton)

infoBarService.Warning(message);

if (appBarButton is null)
{
return;
}

// Manual webview
await taskContext.SwitchToMainThreadAsync();

new ShowWebView2WindowAction
MiHoYoJSBridgeWebView2ContentProvider provider = new()
{
ContentProvider = new MiHoYoJSBridgeWebView2ContentProvider
{
SourceProvider = new SignInJSBridgeUriSourceProvider(),
},
}.ShowAt(appBarButton.XamlRoot);
SourceProvider = new SignInJSBridgeUriSourceProvider(),
};

ShowWebView2WindowAction.Show(provider, currentXamlWindowReference.GetXamlRoot());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -109,18 +109,16 @@ public async ValueTask<Response<SignInResult>> SignAsync(UserAndUid userAndUid,

if (resp is { Data: { Success: 1, Gt: { } gt, Challenge: { } originChallenge } })
{
if (await geetestService.TryVerifyAsync(gt, originChallenge, token).ConfigureAwait(false) is { } data)
if (await geetestService.TryVerifyGtChallengeAsync(gt, originChallenge, token).ConfigureAwait(false) is { } data)
{
HttpRequestMessageBuilder verifiedBuilder = httpRequestMessageBuilderFactory.Create()
.SetRequestUri(apiEndpoints.LunaSolSign())
.SetUserCookieAndFpHeader(userAndUid, CookieType.CookieToken)
builder
.Resurrect()
.SetHeader("x-rpc-signgame", "hk4e")
.SetXrpcChallenge(data.Challenge, data.Validate)
.PostJson(new SignInData(apiEndpoints, userAndUid.Uid));
.SetXrpcChallenge(data.Challenge, data.Validate);

await verifiedBuilder.SignDataAsync(DataSignAlgorithmVersion.Gen1, SaltType.LK2, true).ConfigureAwait(false);
await builder.SignDataAsync(DataSignAlgorithmVersion.Gen1, SaltType.LK2, true).ConfigureAwait(false);

resp = await verifiedBuilder
resp = await builder
.SendAsync<Response<SignInResult>>(httpClient, logger, token)
.ConfigureAwait(false);
}
Expand Down
Loading

0 comments on commit 8a0284e

Please sign in to comment.