Skip to content

Commit

Permalink
🎨 fixs
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzaz committed Dec 20, 2023
1 parent 3ab34e5 commit 6888687
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 77 deletions.
21 changes: 21 additions & 0 deletions src/BD.SteamClient8.Impl/Extensions/SteamSessionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace BD.SteamClient8.Impl.Extensions;

/// <summary>
/// <see cref="SteamSession"/> 扩展方法
/// </summary>
public static class SteamSessionExtensions
{
/// <summary>
/// 空引用抛出异常,提示用户登录
/// </summary>
/// <param name="steamSession"></param>
/// <param name="steam_id"></param>
/// <returns></returns>
/// <exception cref="NullReferenceException"></exception>
public static SteamSession ThrowIsNull(this SteamSession? steamSession, string steam_id)
{
if (steamSession is null)
throw new NullReferenceException($"Unable to find session for {steam_id}, please login first");
return steamSession;
}
}
4 changes: 2 additions & 2 deletions src/BD.SteamClient8.Impl/WebApi/SteamAccountService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1290,9 +1290,9 @@ ValueTask<LoginHistoryItem> ParseLoginHistoryRow(IElement trElement)
}
}

public async Task<ApiRspImpl<bool>> CheckAccessTokenValidation(string accesstoken)
public async Task<ApiRspImpl<bool>> CheckAccessTokenValidation(string access_token)
{
var rsp = await CreateClient().GetAsync(string.Format(SteamApiUrls.STEAM_ACCOUNT_GET_STEAMNOTIFICATION, accesstoken));
var rsp = await CreateClient().GetAsync(string.Format(SteamApiUrls.STEAM_ACCOUNT_GET_STEAMNOTIFICATION, access_token));

if (rsp.IsSuccessStatusCode)
{
Expand Down
44 changes: 10 additions & 34 deletions src/BD.SteamClient8.Impl/WebApi/SteamAuthenticatorServiceImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ public SteamAuthenticatorServiceImpl(

public async Task<ApiRspImpl<IsAccountWaitingForEmailConfirmationResponse?>> AccountWaitingForEmailConfirmation(string steam_id)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

using var sendArgs = new WebApiClientSendArgs(SteamApiUrls.STEAM_AUTHENTICATOR_ACCOUNTWAITINGFOREMAILCONF.Format(steamSession.AccessToken))
{
Expand All @@ -43,9 +41,7 @@ public SteamAuthenticatorServiceImpl(

public async Task<ApiRspImpl<SteamDoLoginTfaJsonStruct?>> AddAuthenticatorAsync(string steam_id, string authenticator_time, string? device_identifier, string authenticator_type = "1", string sms_phone_id = "1")
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var data = new Dictionary<string, string>
{
Expand All @@ -67,9 +63,7 @@ public SteamAuthenticatorServiceImpl(

public async Task<ApiRspImpl<SteamAddPhoneNumberResponse?>> AddPhoneNumberAsync(string steam_id, string phone_number, string? contury_code)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var data = new Dictionary<string, string>
{
Expand All @@ -88,9 +82,7 @@ public SteamAuthenticatorServiceImpl(

public async Task<ApiRspImpl<SteamDoLoginFinalizeJsonStruct?>> FinalizeAddAuthenticatorAsync(string steam_id, string? activation_code, string authenticator_code, string authenticator_time, string validate_sms_code = "1")
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var data = new Dictionary<string, string>
{
Expand All @@ -111,9 +103,7 @@ public SteamAuthenticatorServiceImpl(

public async Task<ApiRspImpl<GetUserCountryResponse?>> GetUserCountry(string steam_id)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var param = new Dictionary<string, string>
{
Expand All @@ -130,9 +120,7 @@ public SteamAuthenticatorServiceImpl(

public async Task<ApiRspImpl<RemoveAuthenticatorResponse?>> RemoveAuthenticatorAsync(string steam_id, string? revocation_code, string steamguard_scheme, string revocation_reason = "1")
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var param = new Dictionary<string, string>
{
Expand All @@ -152,9 +140,7 @@ public SteamAuthenticatorServiceImpl(

public async Task<ApiRspImpl<CTwoFactor_RemoveAuthenticatorViaChallengeStart_Response?>> RemoveAuthenticatorViaChallengeStartSync(string steam_id)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var base64string = UrlEncoder.Default.Encode(new CTwoFactor_RemoveAuthenticatorViaChallengeStart_Request().ToByteString().ToBase64());
var data = new Dictionary<string, string>()
Expand All @@ -169,19 +155,13 @@ public SteamAuthenticatorServiceImpl(
};
sendArgs.SetHttpClient(steamSession.HttpClient!);

//var req = new HttpRequestMessage(HttpMethod.Post, SteamApiUrls.STEAM_AUTHENTICATOR_REMOVE_VIACHALLENGESTARTSYNC.Format(steamSession.AccessToken));
//req.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//req.Content = new FormUrlEncodedContent(data);
//var re = await (await steamSession.HttpClient!.SendAsync(req)).Content.ReadAsStringAsync();
var response = await SendAsync<Stream, Dictionary<string, string>>(sendArgs, data);
return CTwoFactor_RemoveAuthenticatorViaChallengeStart_Response.Parser.ParseFrom(response);
}

public async Task<ApiRspImpl<CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Response?>> RemoveAuthenticatorViaChallengeContinueSync(string steam_id, string? sms_code, bool generate_new_token = true)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var base64string = UrlEncoder.Default.Encode(new CTwoFactor_RemoveAuthenticatorViaChallengeContinue_Request
{
Expand All @@ -206,9 +186,7 @@ public SteamAuthenticatorServiceImpl(

public async Task<ApiRspImpl<bool>> SendPhoneVerificationCode(string steam_id)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
return string.Empty;
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

using var sendArgs = new WebApiClientSendArgs(SteamApiUrls.STEAM_AUTHENTICATOR_SEND_PHONEVERIFICATIONCODE.Format(steamSession.AccessToken))
{
Expand All @@ -230,9 +208,7 @@ public async Task<ApiRspImpl<bool>> SendPhoneVerificationCode(string steam_id)
[RequiresDynamicCode("Calls System.Text.Json.JsonSerializer.Deserialize<TValue>(String, JsonSerializerOptions)")]
public async Task<ApiRspImpl<string>> RefreshAccessToken(string steam_id)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

if (string.IsNullOrEmpty(steamSession.RefreshToken))
throw new Exception("Refresh token is empty");
Expand Down
10 changes: 4 additions & 6 deletions src/BD.SteamClient8.Impl/WebApi/SteamIdleCardServiceImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ public SteamIdleCardServiceImpl(
#region Public
public async Task<ApiRspImpl<(UserIdleInfo idleInfo, IEnumerable<Badge> badges)>> GetBadgesAsync(string steam_id, bool need_price = false, string currency = "CNY")
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, pelese login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var badges_url = SteamApiUrls.STEAM_BADGES_URL.Format(steamSession.SteamId, 1);
var pages = new List<string>() { "?p=1" };
Expand Down Expand Up @@ -115,9 +113,9 @@ public SteamIdleCardServiceImpl(
userIdle.UserLevel = ushort.TryParse(document.QuerySelector(".friendPlayerLevelNum")?.TextContent, out var after_userLevel) ? after_userLevel : default;
userIdle.CurrentExp = int.TryParse(Regex.Match(document.QuerySelector(".profile_xp_block_xp")?.TextContent ?? string.Empty, @"\d{1,3}(,\d{3})*").Value, NumberStyles.Number, CultureInfo.CurrentCulture, out var after_currentExp) ? after_currentExp : default;

var matchs = Regex.Matches(document.QuerySelector(".profile_xp_block_remaining")?.TextContent ?? string.Empty, @"\d{1,3}(,\d{3})*");
if (matchs.Count >= 2)
userIdle.UpExp = int.TryParse(matchs[1].Value, out var after_upExp) ? after_upExp : default;
var matches = Regex.Matches(document.QuerySelector(".profile_xp_block_remaining")?.TextContent ?? string.Empty, @"\d{1,3}(,\d{3})*");
if (matches.Count >= 2)
userIdle.UpExp = int.TryParse(matches[1].Value, out var after_upExp) ? after_upExp : default;

userIdle.NextLevelExpPercentage = short.TryParse(Regex.Match(document.QuerySelector(".profile_xp_block_remaining_bar_progress")?.OuterHtml ?? string.Empty, @"width:\s*(\d+)%").Groups[1].Value, out var nextLevelExpPercentage) ? nextLevelExpPercentage : default;
}
Expand Down
47 changes: 12 additions & 35 deletions src/BD.SteamClient8.Impl/WebApi/SteamTradeServiceImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,7 @@ public ApiRspImpl StopTask(string steam_id, TradeTaskEnum tradeTaskEnum)
#region Trade 交易报价
public async Task<ApiRspImpl<bool>> AcceptAllGiftTradeOfferAsync(string steam_id)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

if (string.IsNullOrEmpty(steamSession.APIKey))
return false;
Expand Down Expand Up @@ -115,9 +113,7 @@ public async Task<ApiRspImpl<bool>> AcceptAllGiftTradeOfferAsync(string steam_id

public async Task<ApiRspImpl<bool>> AcceptTradeOfferAsync(string steam_id, string trade_offer_id, TradeInfo? tradeInfo = null, IEnumerable<Confirmation>? confirmations = null)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

if (tradeInfo == null)
{
Expand Down Expand Up @@ -264,9 +260,7 @@ public async Task<ApiRspImpl<bool>> AcceptTradeOfferAsync(string steam_id, strin

public async Task<ApiRspImpl<bool>> SendTradeOfferAsync(string steam_id, List<Asset> my_items, List<Asset> them_items, string target_steam_id, string message)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var offer_string = GenerateJsonTradeOffer(my_items, them_items);
var sessionid = await FetchSessionId(steamSession);
Expand All @@ -282,7 +276,7 @@ public async Task<ApiRspImpl<bool>> SendTradeOfferAsync(string steam_id, List<As
{ "trade_offer_create_params", "{}" }
};

var partner_account_id = ToSteamId32(target_steam_id);
var partner_account_id = new SteamIdConvert(target_steam_id).Id32;
var tradeoffer_url = $"{SteamApiUrls.STEAM_COMMUNITY_URL}/tradeoffer/new/?partner={partner_account_id}";

using var sendArgs = new WebApiClientSendArgs(SteamApiUrls.STEAM_TRADEOFFER_SEND)
Expand All @@ -303,9 +297,7 @@ public async Task<ApiRspImpl<bool>> SendTradeOfferAsync(string steam_id, List<As

public async Task<ApiRspImpl<bool>> SendTradeOfferWithUrlAsync(string steam_id, string trade_offer_url, List<Asset> my_items, List<Asset> them_items, string message)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var uri = new Uri(trade_offer_url);
var querys = HttpUtility.ParseQueryString(uri.Query);
Expand All @@ -314,7 +306,7 @@ public async Task<ApiRspImpl<bool>> SendTradeOfferWithUrlAsync(string steam_id,
if (string.IsNullOrEmpty(partner) && string.IsNullOrEmpty(token))
return false;

var target_steam64_id = ToSteamId64(partner!);
var target_steam64_id = new SteamIdConvert(partner!).Id64;
var offer_string = GenerateJsonTradeOffer(my_items, them_items);
var sessionid = await FetchSessionId(steamSession);
var server_id = 1;
Expand Down Expand Up @@ -350,9 +342,7 @@ public async Task<ApiRspImpl<bool>> SendTradeOfferWithUrlAsync(string steam_id,

public async Task<ApiRspImpl<bool>> CancelTradeOfferAsync(string steam_id, string trade_offer_id)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var sessionid = await FetchSessionId(steamSession);
var param = new Dictionary<string, string>() { { "sessionid", sessionid.ThrowIsNull() } };
Expand All @@ -369,9 +359,7 @@ public async Task<ApiRspImpl<bool>> CancelTradeOfferAsync(string steam_id, strin

public async Task<ApiRspImpl<bool>> DeclineTradeOfferAsync(string steam_id, string trade_offer_id)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var sessionid = await FetchSessionId(steamSession);
var param = new Dictionary<string, string>() { { "sessionid", sessionid.ThrowIsNull() } };
Expand All @@ -390,9 +378,7 @@ public async Task<ApiRspImpl<bool>> DeclineTradeOfferAsync(string steam_id, stri
#region Confirmation 交易确认
public async Task<ApiRspImpl<IEnumerable<Confirmation>>> GetConfirmations(string steam_id)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var tag = TradeTag.CONF.GetDescription();
var queryString = CreateConfirmationParams(tag!, steamSession);
Expand Down Expand Up @@ -481,7 +467,7 @@ public async Task<ApiRspImpl<IEnumerable<Confirmation>>> GetConfirmations(string
public async Task<ApiRspImpl<(string[] my_items, string[] them_items)>> GetConfirmationImages(string steam_id, Confirmation confirmation)
{
// 获取登陆状态
var steamSession = _sessionService.RentSession(steam_id) ?? throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

// 构建请求参数
var tag = $"details{confirmation.Id}";
Expand Down Expand Up @@ -543,9 +529,7 @@ public async Task<ApiRspImpl<IEnumerable<Confirmation>>> GetConfirmations(string

public async Task<ApiRspImpl<bool>> SendConfirmation(string steam_id, Confirmation confirmation, bool accept)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

var tag = accept ? TradeTag.ALLOW.GetDescription() : TradeTag.CANCEL.GetDescription();
var queryString = CreateConfirmationParams(tag!, steamSession);
Expand Down Expand Up @@ -580,9 +564,7 @@ public async Task<ApiRspImpl<bool>> SendConfirmation(string steam_id, Confirmati

public async Task<ApiRspImpl<bool>> BatchSendConfirmation(string steam_id, Dictionary<string, string> trades, bool accept)
{
var steamSession = _sessionService.RentSession(steam_id);
if (steamSession == null)
throw new Exception($"Unable to find session for {steam_id}, please login first");
var steamSession = _sessionService.RentSession(steam_id).ThrowIsNull(steam_id);

if (!(trades.Count > 0))
return false;
Expand Down Expand Up @@ -636,7 +618,6 @@ private async Task RunTask(Action action, TimeSpan interval, CancellationToken c
}
catch (Exception ex)
{
// 处理异常,也可以选择记录日志等操作
Console.WriteLine($"Exception occurred in background task: {ex.Message}");
}
}
Expand All @@ -652,10 +633,6 @@ private async Task RunTask(Action action, TimeSpan interval, CancellationToken c
/// <returns></returns>
private static bool InvalidAPIKey(string content) => content.Contains("Access is denied. Retrying will not help. Please verify your <pre>key=</pre> parameter");

private static ulong ToSteamId64(string steam_id) => 76561197960265728ul + ulong.Parse(steam_id);

private static int ToSteamId32(string steam_id) => Convert.ToInt32((long.Parse(steam_id) >> 0) & 0xFFFFFFFF);

private static string GetTradeOfferUrl(string trade_offer_id) => SteamApiUrls.STEAM_TRADEOFFER_URL.Format(trade_offer_id);

/// <summary>
Expand Down

0 comments on commit 6888687

Please sign in to comment.