This commit is contained in:
yawaflua
2024-04-18 18:38:00 +03:00
parent 2a1317d393
commit 2df80a4c4b
14 changed files with 324 additions and 83 deletions

22
Deserialize.cs Normal file
View File

@@ -0,0 +1,22 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace spworlds
{
internal class Deserialize
{
public static T DeserializeObject<T>(string data) where T : class
{
T objectToReturn = JsonConvert.DeserializeObject<T>(data);
if (objectToReturn == null)
throw new Exception("User not player.");
else
return objectToReturn;
}
}
}

14
Types/Card.cs Normal file
View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace spworlds.Types
{
public class Card
{
public int Balance { get; set; }
public string Webhook { get; set; }
}
}

View File

@@ -1,8 +1,15 @@
namespace spworlds.Types;
public class Item
{
public string Name { get; set; }
public int Count { get; set; }
public int Price { get; set; }
public string? Comment { get; set; } = null;
}
public class PaymentData
{
public int Amount;
public Item[] Items;
public string RedirectUrl;
public string WebHookUrl;
public string Data;

41
Types/UserAccount.cs Normal file
View File

@@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace spworlds.Types
{
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class UserCard
{
public string id { get; set; }
public string name { get; set; }
public string number { get; set; }
public int color { get; set; }
}
public class City
{
public string id { get; set; }
public string name { get; set; }
public string description { get; set; }
public int x { get; set; }
public int z { get; set; }
public bool isMayor { get; set; }
}
public class UserAccount
{
public string id { get; set; }
public string username { get; set; }
public string minecraftUUID { get; set; }
public string status { get; set; }
public List<object> roles { get; set; }
public City city { get; set; }
public List<UserCard> cards { get; set; }
public DateTime createdAt { get; set; }
}
}

14
Types/UserCard.cs Normal file
View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace spworlds.Types
{
public class UserCard
{
public string Name { get; set; }
public int Number { get; set; }
}
}

14
Types/WebhookResponse.cs Normal file
View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace spworlds.Types
{
public class WebhookResponse
{
public int Id { get; set; }
public string Webhook { get; set; }
}
}

View File

@@ -16,7 +16,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyDescriptionAttribute("данная библиотека предназначена для работы с сайтом spworlds. Ознакомиться с доку" +
"ментацией можно в гитхабе проекта")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.5.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.5+c0805a7cd8abbd2deb3f3887f26df3ea891694a8")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.5+2a1317d393845b4d8c2aebe83482addf91da2948")]
[assembly: System.Reflection.AssemblyProductAttribute("spworlds")]
[assembly: System.Reflection.AssemblyTitleAttribute("spworlds")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.5.0")]

View File

@@ -1 +1 @@
1d5e88e75f835d7d540fe5df58387336023a0ed6689730e9ed5a2c7e28829bec
408e46d4b0c697d197fb7b372e95e1f96ce6875650810a4a0ad66dc759971202

View File

@@ -1,30 +1,77 @@
{
"version": 3,
"targets": {
"net6.0": {}
"net6.0": {
"Newtonsoft.Json/13.0.3": {
"type": "package",
"compile": {
"lib/net6.0/Newtonsoft.Json.dll": {
"related": ".xml"
}
},
"runtime": {
"lib/net6.0/Newtonsoft.Json.dll": {
"related": ".xml"
}
}
}
}
},
"libraries": {
"Newtonsoft.Json/13.0.3": {
"sha512": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==",
"type": "package",
"path": "newtonsoft.json/13.0.3",
"files": [
".nupkg.metadata",
".signature.p7s",
"LICENSE.md",
"README.md",
"lib/net20/Newtonsoft.Json.dll",
"lib/net20/Newtonsoft.Json.xml",
"lib/net35/Newtonsoft.Json.dll",
"lib/net35/Newtonsoft.Json.xml",
"lib/net40/Newtonsoft.Json.dll",
"lib/net40/Newtonsoft.Json.xml",
"lib/net45/Newtonsoft.Json.dll",
"lib/net45/Newtonsoft.Json.xml",
"lib/net6.0/Newtonsoft.Json.dll",
"lib/net6.0/Newtonsoft.Json.xml",
"lib/netstandard1.0/Newtonsoft.Json.dll",
"lib/netstandard1.0/Newtonsoft.Json.xml",
"lib/netstandard1.3/Newtonsoft.Json.dll",
"lib/netstandard1.3/Newtonsoft.Json.xml",
"lib/netstandard2.0/Newtonsoft.Json.dll",
"lib/netstandard2.0/Newtonsoft.Json.xml",
"newtonsoft.json.13.0.3.nupkg.sha512",
"newtonsoft.json.nuspec",
"packageIcon.png"
]
}
},
"libraries": {},
"projectFileDependencyGroups": {
"net6.0": []
"net6.0": [
"Newtonsoft.Json >= 13.0.3"
]
},
"packageFolders": {
"C:\\Users\\losev\\.nuget\\packages\\": {},
"C:\\Users\\yawaflua\\.nuget\\packages\\": {},
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages": {}
},
"project": {
"version": "1.0.5",
"restore": {
"projectUniqueName": "C:\\Users\\losev\\OneDrive\\Рабочий стол\\spworlds\\spworlds-csharp-library\\spworlds.csproj",
"projectUniqueName": "C:\\Users\\yawaflua\\Source\\Repos\\spworlds-csharp-library\\spworlds.csproj",
"projectName": "spworlds",
"projectPath": "C:\\Users\\losev\\OneDrive\\Рабочий стол\\spworlds\\spworlds-csharp-library\\spworlds.csproj",
"packagesPath": "C:\\Users\\losev\\.nuget\\packages\\",
"outputPath": "C:\\Users\\losev\\OneDrive\\Рабочий стол\\spworlds\\spworlds-csharp-library\\obj\\",
"projectPath": "C:\\Users\\yawaflua\\Source\\Repos\\spworlds-csharp-library\\spworlds.csproj",
"packagesPath": "C:\\Users\\yawaflua\\.nuget\\packages\\",
"outputPath": "C:\\Users\\yawaflua\\Source\\Repos\\spworlds-csharp-library\\obj\\",
"projectStyle": "PackageReference",
"fallbackFolders": [
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages"
],
"configFilePaths": [
"C:\\Users\\losev\\AppData\\Roaming\\NuGet\\NuGet.Config",
"C:\\Users\\yawaflua\\AppData\\Roaming\\NuGet\\NuGet.Config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.FallbackLocation.config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
],
@@ -45,11 +92,22 @@
"warnAsError": [
"NU1605"
]
},
"restoreAuditProperties": {
"enableAudit": "true",
"auditLevel": "low",
"auditMode": "direct"
}
},
"frameworks": {
"net6.0": {
"targetAlias": "net6.0",
"dependencies": {
"Newtonsoft.Json": {
"target": "Package",
"version": "[13.0.3, )"
}
},
"imports": [
"net461",
"net462",
@@ -66,7 +124,7 @@
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\7.0.401\\RuntimeIdentifierGraph.json"
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\8.0.204\\RuntimeIdentifierGraph.json"
}
}
}

View File

@@ -1,8 +1,10 @@
{
"version": 2,
"dgSpecHash": "p7cKQ/JzbW/pFxNjOXo5Xhfj5ODn4c+I/3V85sntBWgUuc5uosay2iPDLl5YmDVFkvR7Suoevt+A+2w9fpQxjw==",
"dgSpecHash": "wn8UpI/92drj7Y9CQl+s7VBYfOMeRffRtWpQCB7W3D+sZ2Noiue7K9viVJxtJpvymvDsYPRnQ4JHorfg+z+nsQ==",
"success": true,
"projectFilePath": "C:\\Users\\losev\\OneDrive\\Рабочий стол\\spworlds\\spworlds-csharp-library\\spworlds.csproj",
"expectedPackageFiles": [],
"projectFilePath": "C:\\Users\\yawaflua\\Source\\Repos\\spworlds-csharp-library\\spworlds.csproj",
"expectedPackageFiles": [
"C:\\Users\\yawaflua\\.nuget\\packages\\newtonsoft.json\\13.0.3\\newtonsoft.json.13.0.3.nupkg.sha512"
],
"logs": []
}

View File

@@ -1,23 +1,23 @@
{
"format": 1,
"restore": {
"C:\\Users\\losev\\OneDrive\\Рабочий стол\\spworlds\\spworlds-csharp-library\\spworlds.csproj": {}
"C:\\Users\\yawaflua\\Source\\Repos\\spworlds-csharp-library\\spworlds.csproj": {}
},
"projects": {
"C:\\Users\\losev\\OneDrive\\Рабочий стол\\spworlds\\spworlds-csharp-library\\spworlds.csproj": {
"C:\\Users\\yawaflua\\Source\\Repos\\spworlds-csharp-library\\spworlds.csproj": {
"version": "1.0.5",
"restore": {
"projectUniqueName": "C:\\Users\\losev\\OneDrive\\Рабочий стол\\spworlds\\spworlds-csharp-library\\spworlds.csproj",
"projectUniqueName": "C:\\Users\\yawaflua\\Source\\Repos\\spworlds-csharp-library\\spworlds.csproj",
"projectName": "spworlds",
"projectPath": "C:\\Users\\losev\\OneDrive\\Рабочий стол\\spworlds\\spworlds-csharp-library\\spworlds.csproj",
"packagesPath": "C:\\Users\\losev\\.nuget\\packages\\",
"outputPath": "C:\\Users\\losev\\OneDrive\\Рабочий стол\\spworlds\\spworlds-csharp-library\\obj\\",
"projectPath": "C:\\Users\\yawaflua\\Source\\Repos\\spworlds-csharp-library\\spworlds.csproj",
"packagesPath": "C:\\Users\\yawaflua\\.nuget\\packages\\",
"outputPath": "C:\\Users\\yawaflua\\Source\\Repos\\spworlds-csharp-library\\obj\\",
"projectStyle": "PackageReference",
"fallbackFolders": [
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages"
],
"configFilePaths": [
"C:\\Users\\losev\\AppData\\Roaming\\NuGet\\NuGet.Config",
"C:\\Users\\yawaflua\\AppData\\Roaming\\NuGet\\NuGet.Config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.FallbackLocation.config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
],
@@ -38,11 +38,22 @@
"warnAsError": [
"NU1605"
]
},
"restoreAuditProperties": {
"enableAudit": "true",
"auditLevel": "low",
"auditMode": "direct"
}
},
"frameworks": {
"net6.0": {
"targetAlias": "net6.0",
"dependencies": {
"Newtonsoft.Json": {
"target": "Package",
"version": "[13.0.3, )"
}
},
"imports": [
"net461",
"net462",
@@ -59,7 +70,7 @@
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\7.0.401\\RuntimeIdentifierGraph.json"
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\8.0.204\\RuntimeIdentifierGraph.json"
}
}
}

View File

@@ -5,12 +5,12 @@
<RestoreTool Condition=" '$(RestoreTool)' == '' ">NuGet</RestoreTool>
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">$(MSBuildThisFileDirectory)project.assets.json</ProjectAssetsFile>
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">$(UserProfile)\.nuget\packages\</NuGetPackageRoot>
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">C:\Users\losev\.nuget\packages\;C:\Program Files (x86)\Microsoft Visual Studio\Shared\NuGetPackages</NuGetPackageFolders>
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">C:\Users\yawaflua\.nuget\packages\;C:\Program Files (x86)\Microsoft Visual Studio\Shared\NuGetPackages</NuGetPackageFolders>
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">6.7.0</NuGetToolVersion>
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">6.9.2</NuGetToolVersion>
</PropertyGroup>
<ItemGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<SourceRoot Include="C:\Users\losev\.nuget\packages\" />
<SourceRoot Include="C:\Users\yawaflua\.nuget\packages\" />
<SourceRoot Include="C:\Program Files (x86)\Microsoft Visual Studio\Shared\NuGetPackages\" />
</ItemGroup>
</Project>

View File

@@ -6,8 +6,11 @@ using System.Security.Cryptography;
using System.Runtime.InteropServices;
using spworlds.Types;
using System.Text.Json.Serialization;
using Newtonsoft.Json.Converters;
namespace spworlds;
public class SPWorlds
{
private readonly HttpClient client;
@@ -24,49 +27,65 @@ public class SPWorlds
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Base64BearerToken);
}
private async Task<bool> ValidateWebHook(string webHook, string bodyHash)
/// <summary>
/// Validating wenhook from site
/// </summary>
/// <param name="requestBody">Body of request</param>
/// <param name="base64Hash">X-Body-Hash</param>
/// <returns></returns>
public bool ValidateWebhook(string requestBody, string base64Hash)
{
byte[] body = Encoding.UTF8.GetBytes(bodyHash);
byte[] webhook = Encoding.UTF8.GetBytes(webHook);
var key = new HMACSHA256(Encoding.UTF8.GetBytes(token));
string webhook64 = Convert.ToBase64String(key.ComputeHash(webhook));
return webhook64.Equals(body);
}
private async Task<string> SendRequest(string endpoint, Boolean getResult = true, Dictionary<string, object>? body = null)
{
string respond;
string jsonBody;
if (body == null)
byte[] requestData = Encoding.UTF8.GetBytes(requestBody);
using (HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(token)))
{
return respond = client.GetAsync(endpoint).Result.Content.ReadAsStringAsync().Result;
byte[] hashBytes = hmac.ComputeHash(requestData);
string computedHash = Convert.ToBase64String(hashBytes);
return base64Hash.Equals(computedHash);
}
}
private async Task<string> SendRequest(string endpoint, bool getResult = true, HttpMethod method = null, object body = null)
{
method ??= body == null ? HttpMethod.Get : HttpMethod.Post;
HttpResponseMessage message;
using (var requestMessage = new HttpRequestMessage(method, client.BaseAddress + endpoint))
{
requestMessage.Content = new StringContent(
JsonSerializer.Serialize(body),
Encoding.UTF8, "application/json"
);
requestMessage.Headers.Authorization = client.DefaultRequestHeaders.Authorization;
message = await client.SendAsync(requestMessage);
}
if (getResult)
return await message.Content.ReadAsStringAsync();
else
{
jsonBody = JsonSerializer.Serialize(body);
var payload = new StringContent(jsonBody, Encoding.UTF8, "application/json");
return null;
if (getResult)
return respond = client.PostAsync(endpoint, payload).Result.Content.ReadAsStringAsync().Result;
else
await client.PostAsync(endpoint, payload);
}
return null;
}
public async Task<int> GetBalance()
{
string respond = await SendRequest("card");
var card = JsonObject.Parse(respond);
var balance = card["balance"];
/// <summary>
/// Get card from spworlds
/// </summary>
/// <returns></returns>
public async Task<Card> GetCard()
=> Deserialize.DeserializeObject<Card>(await SendRequest("card"));
return (int)balance;
}
public async Task CreateTransaction(string receiver, int amount, string comment)
/// <summary>
/// Create transaction
/// </summary>
/// <param name="receiver">receiver card</param>
/// <param name="amount">amount of AR</param>
/// <param name="comment">comment to transaction</param>
/// <returns>balance of card</returns>
public async Task<int> CreateTransaction(string receiver, int amount, string comment)
{
var transitionInfo = new Dictionary<string, object>
{
@@ -75,21 +94,41 @@ public class SPWorlds
{ "comment", comment }
};
await SendRequest(endpoint: "transactions", body: transitionInfo);
var response = JsonObject.Parse(await SendRequest(endpoint: "transactions", body: transitionInfo, getResult: true));
return (int)response["balance"];
}
/// <summary>
/// Get user cards by nickname
/// </summary>
/// <param name="username">Username of player</param>
/// <returns>Array of cards</returns>
public async Task<UserCard[]> GetUserCardsAsync(string username)
=> Deserialize.DeserializeObject<UserCard[]>(await SendRequest($"accounts/{username}/cards"));
/// <summary>
/// Get user info from site
/// </summary>
/// <param name="discordId">Discord id of user</param>
/// <returns></returns>
public async Task<User> GetUser(string discordId)
{
string userName = (string)JsonObject.Parse(await SendRequest($"users/{discordId}"))["username"];
User user = await User.CreateUser(userName);
return (User)user;
}
public async Task<string> InitPayment(int amount, string redirectUrl, string webhookUrl, string data)
=> Deserialize.DeserializeObject<User>(await SendRequest($"users/{discordId}"));
/// <summary>
/// Create payment url
/// </summary>
/// <param name="items">List of items</param>
/// <param name="redirectUrl">User will be redirected to this url</param>
/// <param name="webhookUrl">Webhook will be sended to this url</param>
/// <param name="data">Data, returned with webhook</param>
/// <returns></returns>
public async Task<string> InitPayment(Item[] items, string redirectUrl, string webhookUrl, string data)
{
var paymentInfo = new Dictionary<string, object>
{
{ "amount", amount },
{ "items", JsonSerializer.Serialize(items)},
{ "redirectUrl", redirectUrl },
{ "webhookUrl", webhookUrl },
{ "data", data }
@@ -101,20 +140,34 @@ public class SPWorlds
return (string)url;
}
/// <summary>
/// Create payment url
/// </summary>
/// <param name="paymentData"></param>
/// <returns></returns>
public async Task<string> InitPayment(PaymentData paymentData)
{
var paymentInfo = new Dictionary<string, object>
{
{ "amount", paymentData.Amount },
{ "redirectUrl", paymentData.RedirectUrl },
{ "webhookUrl", paymentData.WebHookUrl },
{ "data", paymentData.Data }
};
var payment = JsonObject.Parse(await SendRequest(endpoint: $"payment", body: paymentInfo));
var url = payment["url"];
return (string)url;
var payment = JsonObject.Parse(await SendRequest(endpoint: $"payment", body: JsonSerializer.Serialize(paymentData)));
return (string)payment["url"];
}
/// <summary>
/// Setting up a webhook to card
/// </summary>
/// <param name="webhookUrl">Url of webhook</param>
/// <returns></returns>
public async Task<WebhookResponse> SetWebhook(string webhookUrl)
=> Deserialize.DeserializeObject<WebhookResponse>(
await SendRequest(
"card/webhook",
true,
HttpMethod.Put,
new Dictionary<string, string>()
{
{ "url", webhookUrl }
}
)
);
public async Task<UserAccount> GetMeAsync()
=> Deserialize.DeserializeObject<UserAccount>(await SendRequest("accounts/me"));
}

View File

@@ -16,6 +16,11 @@
<ItemGroup>
<None Include="README.md" Pack="true" PackagePath="\"/>
<None Include="README.md" Pack="true" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project>