Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1bc688d83 | ||
|
|
efe19edaf4 | ||
|
|
d12890f8eb | ||
|
|
69244ef832 | ||
|
|
d04afe2968 | ||
|
|
f19a5d3586 | ||
|
|
0e53d7dd8c | ||
|
|
f3a2a5d463 | ||
|
|
d065c6897e | ||
|
|
9238069d0e | ||
|
|
8516dce2ee | ||
|
|
7475a4ff32 | ||
|
|
254499b49a | ||
|
|
98bf51eb4c | ||
|
|
5858cc5db0 | ||
|
|
23291a1932 | ||
|
|
9f0209af6c | ||
|
|
0841f51a10 | ||
|
|
77e525b890 |
@@ -20,11 +20,11 @@ jobs:
|
|||||||
dotnet-version: 10.0.x
|
dotnet-version: 10.0.x
|
||||||
|
|
||||||
- name: Restore dependencies
|
- name: Restore dependencies
|
||||||
run: dotnet restore
|
run: dotnet restore backend/SpMega.Backend/SpMega.Backend.csproj
|
||||||
- name: Build
|
- name: Build
|
||||||
run: dotnet build --no-restore
|
run: dotnet build --no-restore backend/SpMega.Backend/SpMega.Backend.csproj
|
||||||
- name: Test
|
- name: Test
|
||||||
run: dotnet test --no-build --verbosity normal
|
run: dotnet test --no-build --verbosity normal backend/SpMega.Backend/SpMega.Backend.csproj
|
||||||
|
|
||||||
compose:
|
compose:
|
||||||
name: Push Docker image to ghcr.io
|
name: Push Docker image to ghcr.io
|
||||||
@@ -60,7 +60,7 @@ jobs:
|
|||||||
git.yawaflua.tech/yawaflua/spmega
|
git.yawaflua.tech/yawaflua/spmega
|
||||||
|
|
||||||
- name: Build and push API
|
- name: Build and push API
|
||||||
uses: docker/build-push-action@3b5e8027fcad23fda98b2e3ac259d8d67585f671
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: backend/
|
context: backend/
|
||||||
file: backend/SpMega.Backend/Dockerfile
|
file: backend/SpMega.Backend/Dockerfile
|
||||||
|
|||||||
+2
-1
@@ -20,7 +20,8 @@ hs_err_pid*
|
|||||||
# Common working directory
|
# Common working directory
|
||||||
run
|
run
|
||||||
|
|
||||||
backend/SpMega.Backend/src/*
|
backend/SpMega.Backend/bin/*
|
||||||
backend/SpMega.Backend/obj/*
|
backend/SpMega.Backend/obj/*
|
||||||
backend/SpMega.Backend/appsettings.json
|
backend/SpMega.Backend/appsettings.json
|
||||||
|
backend/SpMega.Backend/appsettings.Development.json
|
||||||
backend/SpMega.Backend/SpMega.Backend.http
|
backend/SpMega.Backend/SpMega.Backend.http
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|

|
||||||
# SPMega
|
# SPMega
|
||||||
|
|
||||||
SPMega - клиентский Fabric-мод с банковым UI для работы с картами и переводами через API `spworlds.ru`.
|
SPMega - клиентский Fabric-мод с банковым UI для работы с картами и переводами через API `spworlds.ru`.
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ using System.Net;
|
|||||||
using System.Net.Http.Headers;
|
using System.Net.Http.Headers;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Nodes;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
@@ -19,6 +20,7 @@ namespace SpMega.Backend.Controllers.v1;
|
|||||||
|
|
||||||
public record GetSessionIdBody(string userName, Guid userUUID);
|
public record GetSessionIdBody(string userName, Guid userUUID);
|
||||||
public record ValidateSessionBody(string sessionId, Guid userUUID);
|
public record ValidateSessionBody(string sessionId, Guid userUUID);
|
||||||
|
|
||||||
[Route("api/v1/auth")]
|
[Route("api/v1/auth")]
|
||||||
[ApiController]
|
[ApiController]
|
||||||
public class AuthController(AppDbContext dbContext, TokenService tokenService, ILogger<AuthController> logger) : ControllerBase
|
public class AuthController(AppDbContext dbContext, TokenService tokenService, ILogger<AuthController> logger) : ControllerBase
|
||||||
@@ -66,14 +68,39 @@ public class AuthController(AppDbContext dbContext, TokenService tokenService, I
|
|||||||
|
|
||||||
var resp = await httpClient.SendAsync(request);
|
var resp = await httpClient.SendAsync(request);
|
||||||
if (resp.StatusCode != HttpStatusCode.OK) throw new Exception("Mojang response is not OK");
|
if (resp.StatusCode != HttpStatusCode.OK) throw new Exception("Mojang response is not OK");
|
||||||
Console.WriteLine(await resp.Content.ReadAsStringAsync());
|
|
||||||
var dto = await resp.Content.ReadFromJsonAsync<MojangDto>();
|
var dto = await resp.Content.ReadFromJsonAsync<MojangDto>();
|
||||||
if (dto == null || dto.Name != session.UserName || Guid.Parse(dto.Id) != session.UserId) throw new Exception("Session expired, or dto is not acceptable.");
|
if (dto == null || dto.Name != session.UserName || Guid.Parse(dto.Id) != session.UserId) throw new Exception("Session expired, or dto is not acceptable.");
|
||||||
|
|
||||||
|
|
||||||
var token = tokenService.GenerateAccessToken(session.UserName, body.userUUID);
|
var token = tokenService.GenerateAccessToken(session.UserName, body.userUUID);
|
||||||
var user = await dbContext.Users.FirstOrDefaultAsync(k => k.Id == session.UserId);
|
var user = await dbContext.Users.FirstOrDefaultAsync(k => k.Id == session.UserId);
|
||||||
|
|
||||||
|
var shortId = string.Empty;
|
||||||
|
|
||||||
|
if (user?.ShortId == null)
|
||||||
|
{
|
||||||
|
shortId = Program.GenerateRandomString(2);
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var a = await dbContext.Users.FirstOrDefaultAsync(k => k.ShortId == shortId);
|
||||||
|
if (a != null)
|
||||||
|
{
|
||||||
|
shortId = Program.GenerateRandomString(2);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if (user != null)
|
if (user != null)
|
||||||
{
|
{
|
||||||
user.Token = token;
|
user.Token = token;
|
||||||
|
user.Username = session.UserName;
|
||||||
|
user.UpdatedAt = DateTime.UtcNow;
|
||||||
|
user.ShortId ??= shortId;
|
||||||
|
|
||||||
dbContext.Update(user);
|
dbContext.Update(user);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@@ -83,6 +110,8 @@ public class AuthController(AppDbContext dbContext, TokenService tokenService, I
|
|||||||
Id = body.userUUID,
|
Id = body.userUUID,
|
||||||
Username = session.UserName,
|
Username = session.UserName,
|
||||||
Token = token,
|
Token = token,
|
||||||
|
UpdatedAt = DateTime.UtcNow,
|
||||||
|
ShortId = shortId,
|
||||||
};
|
};
|
||||||
await dbContext.AddAsync(user);
|
await dbContext.AddAsync(user);
|
||||||
}
|
}
|
||||||
@@ -109,16 +138,18 @@ public class AuthController(AppDbContext dbContext, TokenService tokenService, I
|
|||||||
string Base64BearerToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(BearerToken));
|
string Base64BearerToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(BearerToken));
|
||||||
var resp = await SendRequest("/accounts/me", new("Bearer", Base64BearerToken));
|
var resp = await SendRequest("/accounts/me", new("Bearer", Base64BearerToken));
|
||||||
var me = JsonSerializer.Deserialize<UserAccountDTO>(resp);
|
var me = JsonSerializer.Deserialize<UserAccountDTO>(resp);
|
||||||
Console.WriteLine(resp);
|
|
||||||
var user = ((User)HttpContext.Items["@me"]);
|
var user = ((User)HttpContext.Items["@me"]);
|
||||||
Console.WriteLine(me.id);
|
|
||||||
Console.WriteLine(Guid.Parse(me.minecraftUUID));
|
|
||||||
Console.WriteLine(user.Id.ToString());
|
|
||||||
if (user == null || user.Id != Guid.Parse(me.minecraftUUID))
|
if (user == null || user.Id != Guid.Parse(me.minecraftUUID))
|
||||||
{
|
{
|
||||||
throw new Exception("Its not ur card");
|
throw new Exception("Its not ur card");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var balanceResp = await SendRequest("/public/card", new("Bearer", Base64BearerToken));
|
||||||
|
var balance = (int?)JsonNode.Parse(balanceResp)?["balance"];
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
var card = me.cards.First(k => k.id == body.id);
|
var card = me.cards.First(k => k.id == body.id);
|
||||||
var existingCard = user.Cards.FirstOrDefault(k => k.Id.ToString() == card.id);
|
var existingCard = user.Cards.FirstOrDefault(k => k.Id.ToString() == card.id);
|
||||||
if (existingCard == null)
|
if (existingCard == null)
|
||||||
@@ -126,6 +157,7 @@ public class AuthController(AppDbContext dbContext, TokenService tokenService, I
|
|||||||
{
|
{
|
||||||
Id = Guid.Parse(card.id),
|
Id = Guid.Parse(card.id),
|
||||||
Name = card.name,
|
Name = card.name,
|
||||||
|
Balance = balance ?? -1,
|
||||||
SpworldsID = card.number,
|
SpworldsID = card.number,
|
||||||
Token = Base64BearerToken,
|
Token = Base64BearerToken,
|
||||||
CreatedAt = DateTime.UtcNow,
|
CreatedAt = DateTime.UtcNow,
|
||||||
@@ -136,6 +168,7 @@ public class AuthController(AppDbContext dbContext, TokenService tokenService, I
|
|||||||
existingCard.Name = card.name;
|
existingCard.Name = card.name;
|
||||||
existingCard.SpworldsID = card.number;
|
existingCard.SpworldsID = card.number;
|
||||||
existingCard.Token = Base64BearerToken;
|
existingCard.Token = Base64BearerToken;
|
||||||
|
existingCard.Balance = balance ?? -1;
|
||||||
existingCard.UpdatedAt = DateTime.UtcNow;
|
existingCard.UpdatedAt = DateTime.UtcNow;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using SpMega.Backend.Persistent.Models.DTO;
|
||||||
|
using SpMega.Backend.Persistent.Models.Users;
|
||||||
|
|
||||||
|
namespace SpMega.Backend.Controllers.v1;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/v1/telemetry")]
|
||||||
|
[Authorize]
|
||||||
|
public class TelemetryController : ControllerBase
|
||||||
|
{
|
||||||
|
private static readonly ActivitySource Source = new("SpMega.ModTelemetry");
|
||||||
|
|
||||||
|
[HttpPost]
|
||||||
|
[AllowAnonymous]
|
||||||
|
public IActionResult Post([FromBody] ModTelemetryBatchDto batch)
|
||||||
|
{
|
||||||
|
if (batch?.Events == null || batch.Events.Count == 0)
|
||||||
|
{
|
||||||
|
return Ok(new { received = 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = HttpContext.Items["@me"] as User;
|
||||||
|
var userId = user?.Id.ToString() ?? User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value ?? "anonymous";
|
||||||
|
var sessionId = !string.IsNullOrEmpty(batch.SessionId) ? batch.SessionId : Guid.NewGuid().ToString("N");
|
||||||
|
|
||||||
|
foreach (var e in batch.Events)
|
||||||
|
{
|
||||||
|
using var activity = Source.StartActivity("mod.telemetry.event", ActivityKind.Client);
|
||||||
|
if (activity is null) continue;
|
||||||
|
|
||||||
|
activity.SetTag("user.id", userId);
|
||||||
|
activity.SetTag("session.id", sessionId);
|
||||||
|
activity.SetTag("client.version", batch.ClientVersion ?? string.Empty);
|
||||||
|
activity.SetTag("event.type", e.EventType);
|
||||||
|
activity.SetTag("event.timestamp", e.Timestamp.ToString("O"));
|
||||||
|
activity.SetTag("event.payload", JsonSerializer.Serialize(e.Payload));
|
||||||
|
activity.SetTag("batch.sent_at", batch.SentAt.ToString("O"));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(new { received = batch.Events.Count });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ using System.Text.Json.Nodes;
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using MongoDB.Bson;
|
||||||
|
using MongoDB.Driver;
|
||||||
using SpMega.Backend.Persistent.Database;
|
using SpMega.Backend.Persistent.Database;
|
||||||
using SpMega.Backend.Persistent.Models.Transactions;
|
using SpMega.Backend.Persistent.Models.Transactions;
|
||||||
using SpMega.Backend.Persistent.Models.Users;
|
using SpMega.Backend.Persistent.Models.Users;
|
||||||
@@ -16,6 +18,7 @@ namespace SpMega.Backend.Controllers.v1;
|
|||||||
[ApiController]
|
[ApiController]
|
||||||
public class TransactionsController(AppDbContext context, ILogger<TransactionsController> logger, IConfiguration config) : ControllerBase
|
public class TransactionsController(AppDbContext context, ILogger<TransactionsController> logger, IConfiguration config) : ControllerBase
|
||||||
{
|
{
|
||||||
|
private const int LIMIT = 10;
|
||||||
private const string BASE_URL = "https://spworlds.ru/api/public/";
|
private const string BASE_URL = "https://spworlds.ru/api/public/";
|
||||||
|
|
||||||
[HttpGet("{billId}")]
|
[HttpGet("{billId}")]
|
||||||
@@ -34,12 +37,7 @@ public class TransactionsController(AppDbContext context, ILogger<TransactionsCo
|
|||||||
ShortId = "00000000",
|
ShortId = "00000000",
|
||||||
ReceiverName = "yawaflua",
|
ReceiverName = "yawaflua",
|
||||||
ReceiverCardNumber = "00000",
|
ReceiverCardNumber = "00000",
|
||||||
Sender = new User
|
SenderMinecraftName = "yawaflua",
|
||||||
{
|
|
||||||
Id = default,
|
|
||||||
Username = "yawaflua",
|
|
||||||
Token = "123",
|
|
||||||
},
|
|
||||||
SenderCardNumber = "010101",
|
SenderCardNumber = "010101",
|
||||||
Amount = 42,
|
Amount = 42,
|
||||||
Comment = "API FIRST",
|
Comment = "API FIRST",
|
||||||
@@ -67,14 +65,19 @@ public class TransactionsController(AppDbContext context, ILogger<TransactionsCo
|
|||||||
return BadRequest(new { error = "Card not found" });
|
return BadRequest(new { error = "Card not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (cardToUse.Balance != -1 && cardToUse.Balance < body.amount)
|
||||||
|
{
|
||||||
|
return BadRequest(new { error = "Insufficient balance" });
|
||||||
|
}
|
||||||
|
|
||||||
var shortId = Program.GenerateRandomString(5);
|
|
||||||
|
var shortId = Program.GenerateRandomString(2);
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
var a = await context.Transactions.FirstOrDefaultAsync(k => k.ShortId == shortId);
|
var a = await context.Transactions.FirstOrDefaultAsync(k => k.ShortId == shortId && EF.Property<Guid>(k, "SenderId") == user.Id);
|
||||||
if (a != null)
|
if (a != null)
|
||||||
{
|
{
|
||||||
shortId = Program.GenerateRandomString(5);
|
shortId = Program.GenerateRandomString(2);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -84,31 +87,31 @@ public class TransactionsController(AppDbContext context, ILogger<TransactionsCo
|
|||||||
var transaction = new Transaction
|
var transaction = new Transaction
|
||||||
{
|
{
|
||||||
ReceiverName = body.receiverName,
|
ReceiverName = body.receiverName,
|
||||||
ShortId = shortId,
|
ShortId = $"{user.ShortId}{shortId}",
|
||||||
ReceiverCardNumber = body.receiverCard,
|
ReceiverCardNumber = body.receiverCard,
|
||||||
Sender = user,
|
Sender = user,
|
||||||
SenderCardNumber = body.cardId,
|
SenderCardNumber = cardToUse.SpworldsID,
|
||||||
|
SenderMinecraftName = user.Username,
|
||||||
Amount = body.amount,
|
Amount = body.amount,
|
||||||
Comment = body.comment,
|
Comment = body.comment
|
||||||
};
|
};
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var uri = "s.ywfl.dev" + "/" + shortId;
|
var uri = "ywfl.dev" + "/s" + shortId;
|
||||||
var transitionInfo = new Dictionary<string, object>
|
var transitionInfo = new Dictionary<string, object>
|
||||||
{
|
{
|
||||||
{ "receiver", body.receiverCard },
|
{ "receiver", body.receiverCard },
|
||||||
{ "amount", body.amount },
|
{ "amount", body.amount },
|
||||||
{ "comment", body.comment + ";Чек:"+ uri }
|
{ "comment", (body.comment)[10..] + "..;Чек:"+ uri }
|
||||||
};
|
};
|
||||||
Console.WriteLine((body.comment + ";Чек: "+ uri).Length);
|
var resp = await SendRequest(endpoint: "transactions", body: transitionInfo, AuthHeader: new("Bearer", cardToUse.Token));
|
||||||
Console.WriteLine((body.comment + ";Чек: "+ uri));
|
|
||||||
var resp = await SendRequest(endpoint: "transactions", body: transitionInfo,
|
|
||||||
AuthHeader: new("Bearer", cardToUse.Token));
|
|
||||||
var balance = (int?)JsonNode.Parse(resp)?["balance"];
|
var balance = (int?)JsonNode.Parse(resp)?["balance"];
|
||||||
if (balance == null)
|
if (balance == null)
|
||||||
{
|
{
|
||||||
throw new Exception("Failed to create transaction: " + resp);
|
throw new Exception("Failed to create transaction: " + resp);
|
||||||
}
|
}
|
||||||
|
cardToUse.Balance = balance.Value;
|
||||||
|
|
||||||
|
|
||||||
} catch (Exception exception)
|
} catch (Exception exception)
|
||||||
{
|
{
|
||||||
@@ -122,14 +125,24 @@ public class TransactionsController(AppDbContext context, ILogger<TransactionsCo
|
|||||||
{
|
{
|
||||||
Id = transaction.Id,
|
Id = transaction.Id,
|
||||||
ReceiverName = transaction.ReceiverName,
|
ReceiverName = transaction.ReceiverName,
|
||||||
|
ReceiverCardNumber = transaction.ReceiverCardNumber,
|
||||||
|
SenderMinecraftName = transaction.SenderMinecraftName,
|
||||||
|
SenderCardNumber = transaction.SenderCardNumber,
|
||||||
|
Amount = transaction.Amount,
|
||||||
|
Comment = transaction.Comment,
|
||||||
|
TransactionDate = transaction.TransactionDate
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet()]
|
[HttpGet()]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
public async Task<ActionResult<List<Transaction>>> GetAllTransactions()
|
public async Task<ActionResult<List<Transaction>>> GetAllTransactions([FromQuery] int p = 1)
|
||||||
{
|
{
|
||||||
return Ok(await context.Transactions.Where(k => k.Sender.Id == ((User)HttpContext.Items["@me"]).Id).ToListAsync());
|
return Ok(await context.Transactions
|
||||||
|
.Where(k => EF.Property<Guid>(k, "SenderId") == ((User)HttpContext.Items["@me"]).Id)
|
||||||
|
.Skip(p - 1 * LIMIT)
|
||||||
|
.Take(p * LIMIT)
|
||||||
|
.ToListAsync());
|
||||||
}
|
}
|
||||||
|
|
||||||
[NonAction]
|
[NonAction]
|
||||||
|
|||||||
@@ -0,0 +1,195 @@
|
|||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Nodes;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using MongoDB.Driver.Linq;
|
||||||
|
using SpMega.Backend.Persistent.Database;
|
||||||
|
using SpMega.Backend.Persistent.Models.Transactions;
|
||||||
|
using SpMega.Backend.Persistent.Models.Users;
|
||||||
|
|
||||||
|
namespace SpMega.Backend.Controllers.v1;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("/api/v1/webhook")]
|
||||||
|
public class WebhookController( AppDbContext dbContext, ILogger<WebhookController> logger, IConfiguration config) : ControllerBase
|
||||||
|
{
|
||||||
|
private const string BASE_URL = "https://spworlds.ru/api/public/";
|
||||||
|
|
||||||
|
|
||||||
|
[HttpPut("{cardId}")]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<IActionResult> RegisterWebhookForCard(Guid cardId)
|
||||||
|
{
|
||||||
|
var user = HttpContext.Items["@me"] as User;
|
||||||
|
if (user == null) return Unauthorized();
|
||||||
|
|
||||||
|
var cardToUse = user.Cards.FirstOrDefault(c => c.Id == cardId);
|
||||||
|
if (cardToUse == null)
|
||||||
|
return BadRequest("Card not found");
|
||||||
|
|
||||||
|
var shortId = Program.GenerateRandomString(6);
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var a = user.Cards.FirstOrDefault(k => k.ShortId == shortId);
|
||||||
|
if (a != null)
|
||||||
|
{
|
||||||
|
shortId = Program.GenerateRandomString(6);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cardToUse.ShortId = shortId;
|
||||||
|
cardToUse.WebhookConnected = true;
|
||||||
|
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
|
||||||
|
var webhookUrl = new UriBuilder();
|
||||||
|
webhookUrl.Scheme = "https";
|
||||||
|
webhookUrl.Host = config["Url"];
|
||||||
|
webhookUrl.Path = $"api/v1/webhook/{user.ShortId}/{cardToUse.ShortId}/{cardId}";
|
||||||
|
|
||||||
|
var resp = await SendRequest($"card/webhook", new AuthenticationHeaderValue("Bearer", cardToUse.Token), HttpMethod.Put, new { url = webhookUrl.ToString() });
|
||||||
|
var jsonResponse = JsonSerializer.Deserialize<JsonObject>(resp);
|
||||||
|
if (jsonResponse != null && jsonResponse.TryGetPropertyValue("id", out var respId)
|
||||||
|
&& respId?.GetValue<Guid>() == cardId) return Ok();
|
||||||
|
logger.LogError("Failed to register webhook for card {CardId}. Response: {Response}", cardId, resp);
|
||||||
|
cardToUse.WebhookConnected = false;
|
||||||
|
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
return BadRequest("Failed to register webhook for card");
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{userShortId}/{cardShortId}/{cardId}")]
|
||||||
|
public async Task<IActionResult> ReceiveWebhook(string userShortId, string cardShortId, Guid cardId)
|
||||||
|
{
|
||||||
|
var user = await dbContext.Users.FirstOrDefaultAsync(k => k.ShortId == userShortId);
|
||||||
|
if (user == null)
|
||||||
|
return BadRequest("User not found");
|
||||||
|
var cardToUse = user.Cards.FirstOrDefault(c => c.ShortId == cardShortId && c.Id == cardId && c.WebhookConnected == true);
|
||||||
|
if (cardToUse == null)
|
||||||
|
return BadRequest("Card not found");
|
||||||
|
|
||||||
|
var bodyHash = Request.Headers["X-Body-Hash"].ToString();
|
||||||
|
var rawBody = await new StreamReader(Request.Body).ReadToEndAsync();
|
||||||
|
var keyBytes = Encoding.UTF8.GetBytes(cardToUse.Token);
|
||||||
|
var messageBytes = Encoding.UTF8.GetBytes(rawBody);
|
||||||
|
|
||||||
|
using var hmac = new HMACSHA256(keyBytes);
|
||||||
|
var hashBytes = hmac.ComputeHash(messageBytes);
|
||||||
|
|
||||||
|
byte[] receivedHash;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
receivedHash = Convert.FromBase64String(bodyHash);
|
||||||
|
}
|
||||||
|
catch (FormatException)
|
||||||
|
{
|
||||||
|
return BadRequest("Invalid body hash");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!CryptographicOperations.FixedTimeEquals(hashBytes, receivedHash))
|
||||||
|
{
|
||||||
|
logger.LogError("Invalid body hash for webhook. Expected: {ExpectedHash}, Received: {ReceivedHash}", Convert.ToBase64String(hashBytes), bodyHash);
|
||||||
|
return BadRequest("Invalid body hash");
|
||||||
|
}
|
||||||
|
|
||||||
|
var body = JsonSerializer.Deserialize<Webhook>(rawBody, new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
||||||
|
if (body == null || !Guid.TryParse(body.Id, out var notificationId))
|
||||||
|
return BadRequest("Invalid webhook body");
|
||||||
|
|
||||||
|
if (await dbContext.Notifications.FirstOrDefaultAsync(notification => notification.Id == notificationId) != null)
|
||||||
|
return Ok();
|
||||||
|
|
||||||
|
var notify = new Notification
|
||||||
|
{
|
||||||
|
Id = notificationId,
|
||||||
|
ReceiverId = user.Id,
|
||||||
|
ReceiverName = body.Receiver.Username,
|
||||||
|
ReceiverNumber = body.Receiver.Number,
|
||||||
|
SenderName = body.Sender.Username,
|
||||||
|
SenderNumber = body.Sender.Number,
|
||||||
|
Comment = body.Comment,
|
||||||
|
Amount = body.Amount,
|
||||||
|
Type = body.Type,
|
||||||
|
IsRead = false,
|
||||||
|
CreatedAt = DateTime.UtcNow,
|
||||||
|
UpdatedAt = DateTime.UtcNow
|
||||||
|
};
|
||||||
|
|
||||||
|
await dbContext.Notifications.AddAsync(notify);
|
||||||
|
await dbContext.SaveChangesAsync();
|
||||||
|
return Ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("read")]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<ActionResult<List<Notification>>> ReadAllNotifications()
|
||||||
|
{
|
||||||
|
var user = HttpContext.Items["@me"] as User;
|
||||||
|
if (user == null) return Unauthorized();
|
||||||
|
|
||||||
|
var notifications = await dbContext.Notifications
|
||||||
|
.Where(notification => notification.ReceiverId == user.Id && !notification.IsRead)
|
||||||
|
.ToListAsync();
|
||||||
|
foreach (var notification in notifications)
|
||||||
|
{
|
||||||
|
notification.IsRead = true;
|
||||||
|
notification.UpdatedAt = DateTime.UtcNow;
|
||||||
|
}
|
||||||
|
if (notifications.Count > 0) await dbContext.SaveChangesAsync();
|
||||||
|
return Ok(notifications);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("all")]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<ActionResult<List<Notification>>> GetAllNotifications([FromQuery] int after, [FromQuery] int limit = 20)
|
||||||
|
{
|
||||||
|
var user = HttpContext.Items["@me"] as User;
|
||||||
|
if (user == null) return Unauthorized();
|
||||||
|
var notification = await dbContext.Notifications.Where(k => k.ReceiverId == user.Id).Skip(after).Take(limit).ToListAsync();
|
||||||
|
return Ok(notification);
|
||||||
|
}
|
||||||
|
|
||||||
|
[NonAction]
|
||||||
|
internal async Task<string> SendRequest(string endpoint, AuthenticationHeaderValue AuthHeader, HttpMethod method = null, object body = null)
|
||||||
|
{
|
||||||
|
method ??= body == null ? HttpMethod.Get : HttpMethod.Post;
|
||||||
|
|
||||||
|
HttpResponseMessage message;
|
||||||
|
var client = new System.Net.Http.HttpClient();
|
||||||
|
|
||||||
|
using (var requestMessage = new HttpRequestMessage(method, BASE_URL + endpoint))
|
||||||
|
{
|
||||||
|
requestMessage.Content = new StringContent(
|
||||||
|
JsonSerializer.Serialize(body),
|
||||||
|
Encoding.UTF8, "application/json"
|
||||||
|
);
|
||||||
|
|
||||||
|
requestMessage.Headers.Authorization = AuthHeader;
|
||||||
|
|
||||||
|
message = await client.SendAsync(requestMessage);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
client.Dispose();
|
||||||
|
|
||||||
|
return await message.Content.ReadAsStringAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Webhook(
|
||||||
|
string Id,
|
||||||
|
int Amount,
|
||||||
|
string Type,
|
||||||
|
WebhookUser Sender,
|
||||||
|
WebhookUser Receiver,
|
||||||
|
string Comment,
|
||||||
|
string CreatedAt
|
||||||
|
);
|
||||||
|
|
||||||
|
public record WebhookUser(string Username, string Number);
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
|
||||||
|
namespace SpMega.Backend.Middleware;
|
||||||
|
|
||||||
|
public class RequestTelemetryMiddleware(RequestDelegate next, ILogger<RequestTelemetryMiddleware> logger)
|
||||||
|
{
|
||||||
|
private static readonly ActivitySource Source = new("SpMega.RequestTelemetry");
|
||||||
|
private const string RequestIdHeader = "X-Request-Id";
|
||||||
|
|
||||||
|
public async Task InvokeAsync(HttpContext context)
|
||||||
|
{
|
||||||
|
var path = context.Request.Path.Value ?? string.Empty;
|
||||||
|
if (path.Equals("/api/v1/telemetry", StringComparison.OrdinalIgnoreCase)
|
||||||
|
&& context.Request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
await next(context);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var requestId = context.Request.Headers[RequestIdHeader].FirstOrDefault() ?? Guid.NewGuid().ToString("N");
|
||||||
|
context.Response.Headers[RequestIdHeader] = requestId;
|
||||||
|
|
||||||
|
using var activity = Source.StartActivity("http.request", ActivityKind.Server);
|
||||||
|
activity?.SetTag("request.id", requestId);
|
||||||
|
activity?.SetTag("http.method", context.Request.Method);
|
||||||
|
activity?.SetTag("http.path", path);
|
||||||
|
activity?.SetTag("http.scheme", context.Request.Scheme);
|
||||||
|
activity?.SetTag("http.host", context.Request.Host.Value ?? string.Empty);
|
||||||
|
activity?.SetTag("client.ip", context.Connection.RemoteIpAddress?.ToString());
|
||||||
|
activity?.SetTag("http.user_agent", context.Request.Headers.UserAgent.ToString());
|
||||||
|
activity?.SetTag("http.headers", string.Join(", ", context.Request.Headers.Select(h => $"{h.Key}: {h.Value}")));
|
||||||
|
|
||||||
|
var stopwatch = Stopwatch.StartNew();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await next(context);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
stopwatch.Stop();
|
||||||
|
activity?.SetTag("http.status_code", context.Response.StatusCode);
|
||||||
|
activity?.SetTag("http.duration_ms", stopwatch.ElapsedMilliseconds);
|
||||||
|
|
||||||
|
var userId = context.User?.Identity?.IsAuthenticated == true
|
||||||
|
? context.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value
|
||||||
|
: null;
|
||||||
|
if (userId is not null)
|
||||||
|
activity?.SetTag("user.id", userId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -418,8 +418,8 @@
|
|||||||
<div class="logo-text">SPMega</div>
|
<div class="logo-text">SPMega</div>
|
||||||
</a>
|
</a>
|
||||||
<div class="meta-info">
|
<div class="meta-info">
|
||||||
<div>Версия: <span class="badge">1.0.0-2026</span></div>
|
<div>Версия: <span class="badge">1.0.1-2026</span></div>
|
||||||
<div style="margin-top: 4px;">Обновлено: 28 июня 2026</div>
|
<div style="margin-top: 4px;">Обновлено: 12 июля 2026</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -487,9 +487,18 @@
|
|||||||
<p>Мы собираем и обрабатываем:</p>
|
<p>Мы собираем и обрабатываем:</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li>Ваш уникальный идентификатор Minecraft (<span class="badge">UUID</span>) и текущий никнейм.</li>
|
<li>Ваш уникальный идентификатор Minecraft (<span class="badge">UUID</span>) и текущий никнейм.</li>
|
||||||
<li>Сведения о версии игры, версии Java и используемой версии модификации.</li>
|
<li>Время первой и последующих авторизаций.</li>
|
||||||
<li>Ваш текущий IP-адрес для предотвращения мультиаккаунтинга и выявления попыток взлома API.</li>
|
<li>Ваш текущий IP-адрес для предотвращения и выявления попыток взлома API.</li>
|
||||||
<li>Техническую информацию о транзакциях (суммы, комментарии, номера виртуальных счетов/карт и идентификаторы).</li>
|
<li>Техническую информацию о транзакциях (суммы, комментарии, номера виртуальных счетов/карт и идентификаторы).</li>
|
||||||
|
<li>Технические характеристики устройства: процессор, видеокарту, объем оперативной памяти, операционную систему и название компьютера.</li>
|
||||||
|
<li>Показатели производительности мода, включая FPS и тайминги запросов.</li>
|
||||||
|
<li>Трассировочную информацию о запросах к серверной части SPMega для диагностики ошибок и улучшения качества мода.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Количество передаваемой телеметрии можно уменьшить в настройках модификации.</p>
|
||||||
|
<p>Мы не сохраняем:</p>
|
||||||
|
<ul>
|
||||||
|
<li>Токен карты «КАК ЕСТЬ», данные шифруются по протоколу AES-256-CBC, и только после этого сохраняются в базе данных.</li>
|
||||||
|
<li>Любые личные данные, кроме указанных выше</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -499,10 +508,11 @@
|
|||||||
<p>Мы высоко ценим доверие наших пользователей и гарантируем сохранность собираемой информации. Все личные данные передаются и обрабатываются по защищенным зашифрованным каналам связи (HTTPS/SSL).</p>
|
<p>Мы высоко ценим доверие наших пользователей и гарантируем сохранность собираемой информации. Все личные данные передаются и обрабатываются по защищенным зашифрованным каналам связи (HTTPS/SSL).</p>
|
||||||
<p>Администрация сайта строго обязуется:</p>
|
<p>Администрация сайта строго обязуется:</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li><strong>Не передавать, не продавать и не распространять</strong> ваши личные данные, IP-адреса и статистику третьим лицам.</li>
|
<li><strong>Не передавать, не продавать и не распространять</strong> ваши личные данные, IP-адреса, телеметрию и статистику третьим лицам.</li>
|
||||||
<li>Использовать собранную анонимизированную статистику исключительно во внутренних аналитических целях для улучшения производительности мода.</li>
|
<li>Использовать собранную анонимизированную статистику исключительно во внутренних аналитических целях для улучшения производительности мода.</li>
|
||||||
<li>Раскрывать информацию только в случаях, прямо предусмотренных действующим законодательством при наличии официальных судебных или правоохранительных запросов.</li>
|
<li>Раскрывать информацию только в случаях, прямо предусмотренных действующим законодательством государства Израиль при наличии официальных судебных или правоохранительных запросов.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
<p>По юридическим вопросам свяжитесь с нами по электронной почте <a href="mailto:yawaflua@outlook.co.il">yawaflua@outlook.co.il</a> или в Telegram: <a href="https://t.me/meharmen">@meharmen</a>.</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- Section 6 -->
|
<!-- Section 6 -->
|
||||||
@@ -517,11 +527,11 @@
|
|||||||
|
|
||||||
<footer>
|
<footer>
|
||||||
<div class="footer-links">
|
<div class="footer-links">
|
||||||
<a href="/v1/BillPage/00000000-0000-0000-0000-000000000000" class="footer-link">Проверить чек</a>
|
<a href="/00000000" class="footer-link">Проверить чек</a>
|
||||||
<span>•</span>
|
<span>•</span>
|
||||||
<a href="#" class="footer-link">Поддержка</a>
|
<a href="https://t.me/meharmen" class="footer-link">Поддержка</a>
|
||||||
</div>
|
</div>
|
||||||
<div>© 2026 SPMega. Все права защищены. Minecraft является торговой маркой Mojang Synergies AB.</div>
|
<div>© 2026 Dmitri Shimanski. Все права защищены. NOT AN OFFICIAL MINECRAFT SERVICE. NOT APPROVED BY OR ASSOCIATED WITH MOJANG OR MICROSOFT..</div>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
<!-- Scroll to Top Button -->
|
<!-- Scroll to Top Button -->
|
||||||
|
|||||||
@@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="meta-row">
|
<div class="meta-row">
|
||||||
<span class="meta-label">Отправитель:</span>
|
<span class="meta-label">Отправитель:</span>
|
||||||
<span class="meta-value bold">${escapeHtml(transaction.sender?.username || 'Клиент SPMega')}</span>
|
<span class="meta-value bold">${escapeHtml(transaction.senderMinecraftName || 'Клиент SPMega')}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="meta-row">
|
<div class="meta-row">
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using MongoDB.EntityFrameworkCore.Extensions;
|
using MongoDB.EntityFrameworkCore.Extensions;
|
||||||
|
using SpMega.Backend.Persistent.Models.Telemetry;
|
||||||
using SpMega.Backend.Persistent.Models.Transactions;
|
using SpMega.Backend.Persistent.Models.Transactions;
|
||||||
using SpMega.Backend.Persistent.Models.Users;
|
using SpMega.Backend.Persistent.Models.Users;
|
||||||
using SpMega.Backend.Services;
|
using SpMega.Backend.Services;
|
||||||
@@ -11,6 +12,7 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
|
|||||||
internal DbSet<Transaction> Transactions { get; set; }
|
internal DbSet<Transaction> Transactions { get; set; }
|
||||||
internal DbSet<User> Users { get; set; }
|
internal DbSet<User> Users { get; set; }
|
||||||
internal DbSet<UserSession> UserSessions { get; set; }
|
internal DbSet<UserSession> UserSessions { get; set; }
|
||||||
|
internal DbSet<Notification> Notifications { get; set; }
|
||||||
|
|
||||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace SpMega.Backend.Persistent.Models.DTO;
|
||||||
|
|
||||||
|
public record ModTelemetryEventDto(
|
||||||
|
string EventType,
|
||||||
|
DateTimeOffset Timestamp,
|
||||||
|
JsonElement Payload
|
||||||
|
);
|
||||||
|
|
||||||
|
public record ModTelemetryBatchDto(
|
||||||
|
string ClientVersion,
|
||||||
|
string SessionId,
|
||||||
|
DateTimeOffset SentAt,
|
||||||
|
List<ModTelemetryEventDto> Events
|
||||||
|
);
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
using MongoDB.Bson;
|
||||||
|
|
||||||
|
namespace SpMega.Backend.Persistent.Models.Telemetry;
|
||||||
|
|
||||||
|
public class BackendRequestTelemetryDocument
|
||||||
|
{
|
||||||
|
public ObjectId Id { get; set; }
|
||||||
|
public string RequestId { get; set; } = string.Empty;
|
||||||
|
public string Method { get; set; } = string.Empty;
|
||||||
|
public string Path { get; set; } = string.Empty;
|
||||||
|
public string Scheme { get; set; } = string.Empty;
|
||||||
|
public string Host { get; set; } = string.Empty;
|
||||||
|
public string? ClientIp { get; set; }
|
||||||
|
public string? UserAgent { get; set; }
|
||||||
|
public int StatusCode { get; set; }
|
||||||
|
public long DurationMs { get; set; }
|
||||||
|
public string? UserId { get; set; }
|
||||||
|
public DateTimeOffset Timestamp { get; set; } = DateTimeOffset.UtcNow;
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
using MongoDB.Bson;
|
||||||
|
|
||||||
|
namespace SpMega.Backend.Persistent.Models.Telemetry;
|
||||||
|
|
||||||
|
public class ModTelemetryDocument
|
||||||
|
{
|
||||||
|
public ObjectId Id { get; set; }
|
||||||
|
public string UserId { get; set; } = string.Empty;
|
||||||
|
public string SessionId { get; set; } = string.Empty;
|
||||||
|
public string ClientVersion { get; set; } = string.Empty;
|
||||||
|
public DateTimeOffset SentAt { get; set; }
|
||||||
|
public DateTimeOffset ReceivedAt { get; set; } = DateTimeOffset.UtcNow;
|
||||||
|
public List<ModTelemetryEventDocument> Events { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ModTelemetryEventDocument
|
||||||
|
{
|
||||||
|
public string EventType { get; set; } = string.Empty;
|
||||||
|
public DateTimeOffset Timestamp { get; set; }
|
||||||
|
public string PayloadJson { get; set; } = "{}";
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
using SpMega.Backend.Persistent.Models.Users;
|
||||||
|
|
||||||
|
namespace SpMega.Backend.Persistent.Models.Transactions;
|
||||||
|
|
||||||
|
public class Notification
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
public Guid ReceiverId { get; set; }
|
||||||
|
public string ReceiverName { get; set; }
|
||||||
|
public string ReceiverNumber { get; set; }
|
||||||
|
public string SenderName { get; set; }
|
||||||
|
public string SenderNumber { get; set; }
|
||||||
|
|
||||||
|
public string Comment { get; set; }
|
||||||
|
public int Amount { get; set; }
|
||||||
|
public string Type { get; set; }
|
||||||
|
|
||||||
|
public bool IsRead { get; set; } = false;
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using SpMega.Backend.Persistent.Models.Users;
|
using SpMega.Backend.Persistent.Models.Users;
|
||||||
|
|
||||||
@@ -7,13 +8,15 @@ public class Transaction
|
|||||||
{
|
{
|
||||||
public Guid Id { get; set; }
|
public Guid Id { get; set; }
|
||||||
public string ShortId { get; set; } = Program.GenerateRandomString(8);
|
public string ShortId { get; set; } = Program.GenerateRandomString(8);
|
||||||
public string ReceiverName { get; set; }
|
[MaxLength(2048)] public string ReceiverName { get; set; }
|
||||||
public string ReceiverCardNumber { get; set; }
|
[MaxLength(2048)] public string ReceiverCardNumber { get; set; }
|
||||||
[JsonIgnore] public User Sender { get; set; }
|
[JsonIgnore] public User Sender { get; set; }
|
||||||
public string SenderCardNumber { get; set; }
|
|
||||||
|
[MaxLength(2048)] public string SenderMinecraftName { get; set; }
|
||||||
|
[MaxLength(2048)] public string SenderCardNumber { get; set; }
|
||||||
|
|
||||||
public int Amount { get; set; } = 0;
|
public int Amount { get; set; } = 0;
|
||||||
public string Comment { get; set; } = "";
|
[MaxLength(2048)] public string Comment { get; set; } = "";
|
||||||
|
|
||||||
public DateTime TransactionDate { get; set; } = DateTime.UtcNow;
|
public DateTime TransactionDate { get; set; } = DateTime.UtcNow;
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,10 @@ public class Card
|
|||||||
public string Name { get; set; }
|
public string Name { get; set; }
|
||||||
public string SpworldsID { get; set; }
|
public string SpworldsID { get; set; }
|
||||||
public string Token { get; set; }
|
public string Token { get; set; }
|
||||||
|
public string? ShortId { get; set; } = "";
|
||||||
|
public bool? WebhookConnected { get; set; } = false;
|
||||||
|
|
||||||
|
public int? Balance { get; set; } = -1;
|
||||||
|
|
||||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||||
public DateTime UpdatedAt { get; set; }
|
public DateTime UpdatedAt { get; set; }
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
using SpMega.Backend.Persistent.Models.Transactions;
|
using SpMega.Backend.Persistent.Models.Transactions;
|
||||||
|
|
||||||
namespace SpMega.Backend.Persistent.Models.Users;
|
namespace SpMega.Backend.Persistent.Models.Users;
|
||||||
@@ -5,8 +6,10 @@ namespace SpMega.Backend.Persistent.Models.Users;
|
|||||||
public class User
|
public class User
|
||||||
{
|
{
|
||||||
public Guid Id { get; set; }
|
public Guid Id { get; set; }
|
||||||
public string Username { get; set; }
|
[MaxLength(2048)] public string Username { get; set; }
|
||||||
public string Token { get; set; }
|
[MaxLength(2048)] public string Token { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(2048)] public string? ShortId { get; set; }
|
||||||
|
|
||||||
public List<Card> Cards { get; set; } = [];
|
public List<Card> Cards { get; set; } = [];
|
||||||
public List<Transaction> Transactions { get; set; } = [];
|
public List<Transaction> Transactions { get; set; } = [];
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
namespace SpMega.Backend.Persistent.Models.Users;
|
namespace SpMega.Backend.Persistent.Models.Users;
|
||||||
|
|
||||||
public class UserSession
|
public class UserSession
|
||||||
{
|
{
|
||||||
public Guid Id { get; set; }
|
public Guid Id { get; set; }
|
||||||
public string Token { get; set; }
|
[MaxLength(2048)] public string Token { get; set; }
|
||||||
public User? User { get; set; } = null;
|
public User? User { get; set; } = null;
|
||||||
public Guid UserId { get; set; }
|
public Guid UserId { get; set; }
|
||||||
public string UserName { get; set; }
|
[MaxLength(2048)] public string UserName { get; set; }
|
||||||
|
|
||||||
public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
|
public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
|
||||||
public DateTime UpdatedAt { get; set; }
|
public DateTime UpdatedAt { get; set; }
|
||||||
|
|||||||
@@ -3,7 +3,12 @@ using System.Text;
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using MongoDB.Driver;
|
using MongoDB.Driver;
|
||||||
|
using OpenTelemetry.Exporter;
|
||||||
|
using OpenTelemetry.Metrics;
|
||||||
|
using OpenTelemetry.Resources;
|
||||||
|
using OpenTelemetry.Trace;
|
||||||
using SpMega.Backend.Authetication;
|
using SpMega.Backend.Authetication;
|
||||||
|
using SpMega.Backend.Middleware;
|
||||||
using SpMega.Backend.Persistent.Database;
|
using SpMega.Backend.Persistent.Database;
|
||||||
using SpMega.Backend.Services;
|
using SpMega.Backend.Services;
|
||||||
|
|
||||||
@@ -15,12 +20,14 @@ public class Program
|
|||||||
{
|
{
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
builder.Configuration
|
builder.Configuration
|
||||||
.AddJsonFile("appsettings.json", false)
|
.AddJsonFile("appsettings.json", true)
|
||||||
.AddJsonFile("appsettings.Development.json", false)
|
.AddJsonFile("appsettings.Development.json", true)
|
||||||
.AddEnvironmentVariables();
|
.AddEnvironmentVariables();
|
||||||
|
|
||||||
var encryptionKey = builder.Configuration["Encryption:Key"] ?? "a-default-fallback-only-for-dev-key-change-this!";
|
var conf = builder.Configuration;
|
||||||
|
var encryptionKey = conf["Encryption:Key"] ?? "a-default-fallback-only-for-dev-key-change-this!";
|
||||||
EncryptionHelper.Initialize(encryptionKey);
|
EncryptionHelper.Initialize(encryptionKey);
|
||||||
|
_ = conf["JWT:Secret"] ?? conf["JWT__Secret"] ?? throw new InvalidOperationException("JWT__Secret is not configured.");
|
||||||
|
|
||||||
builder.Services.AddAuthorization();
|
builder.Services.AddAuthorization();
|
||||||
builder.Services.AddLogging(logging =>
|
builder.Services.AddLogging(logging =>
|
||||||
@@ -54,18 +61,51 @@ public class Program
|
|||||||
.RequireAuthenticatedUser()
|
.RequireAuthenticatedUser()
|
||||||
.Build());
|
.Build());
|
||||||
|
|
||||||
var serviceCollection = new ServiceCollection();
|
|
||||||
var mongoClient =
|
var mongoClient =
|
||||||
new MongoClient(builder.Configuration.GetValue<string>("Mongo") ?? "mongodb://curiosity:27018");
|
new MongoClient(builder.Configuration.GetValue<string>("Mongo") ?? "mongodb://curiosity:27018");
|
||||||
serviceCollection.AddSingleton<IMongoClient>(mongoClient);
|
builder.Services.AddSingleton<IMongoClient>(mongoClient);
|
||||||
|
|
||||||
builder.Services.AddDbContext<AppDbContext>((_, options) =>
|
builder.Services.AddDbContext<AppDbContext>((_, options) =>
|
||||||
{
|
{
|
||||||
options.UseMongoDB(mongoClient, "spmega");
|
options.UseMongoDB(mongoClient, "spmega");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
var otlpEndpoint = (conf["Otlp:Endpoint"] ?? conf["Otlp__Endpoint"] ?? "http://curiosity:5080/api/default").TrimEnd('/');
|
||||||
|
var otlpHeaders = conf["Otlp:Headers"] ?? conf["Otlp__Headers"] ?? throw new InvalidOperationException("Otlp__Headers is not configured.");
|
||||||
|
var tracesEndpoint = new Uri($"{otlpEndpoint}/v1/traces");
|
||||||
|
var metricsEndpoint = new Uri($"{otlpEndpoint}/v1/metrics");
|
||||||
|
builder.Services.AddOpenTelemetry()
|
||||||
|
.ConfigureResource(res => res.AddService("SpMega.Backend"))
|
||||||
|
.WithTracing(tracing =>
|
||||||
|
{
|
||||||
|
tracing
|
||||||
|
.AddSource("SpMega.ModTelemetry")
|
||||||
|
.AddSource("SpMega.RequestTelemetry")
|
||||||
|
.AddAspNetCoreInstrumentation()
|
||||||
|
.AddOtlpExporter(opts =>
|
||||||
|
{
|
||||||
|
opts.Protocol = OtlpExportProtocol.HttpProtobuf;
|
||||||
|
opts.Endpoint = tracesEndpoint;
|
||||||
|
opts.Headers = otlpHeaders;
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.WithMetrics(metrics => metrics
|
||||||
|
.AddAspNetCoreInstrumentation()
|
||||||
|
.AddMeter(
|
||||||
|
"Microsoft.AspNetCore.Hosting",
|
||||||
|
"Microsoft.AspNetCore.Server.Kestrel",
|
||||||
|
"System.Net.Http",
|
||||||
|
"System.Runtime")
|
||||||
|
.AddOtlpExporter(opts =>
|
||||||
|
{
|
||||||
|
opts.Protocol = OtlpExportProtocol.HttpProtobuf;
|
||||||
|
opts.Endpoint = metricsEndpoint;
|
||||||
|
opts.Headers = otlpHeaders;
|
||||||
|
}));
|
||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|
||||||
|
app.UseMiddleware<RequestTelemetryMiddleware>();
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api"), appBuilder =>
|
app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api"), appBuilder =>
|
||||||
|
|||||||
@@ -47,7 +47,6 @@ public static class EncryptionHelper
|
|||||||
using var encryptor = aes.CreateEncryptor(aes.Key, iv);
|
using var encryptor = aes.CreateEncryptor(aes.Key, iv);
|
||||||
using var ms = new MemoryStream();
|
using var ms = new MemoryStream();
|
||||||
|
|
||||||
// Write the IV to the beginning of the stream so it is stored alongside the ciphertext
|
|
||||||
ms.Write(iv, 0, iv.Length);
|
ms.Write(iv, 0, iv.Length);
|
||||||
|
|
||||||
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
|
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ namespace SpMega.Backend.Services;
|
|||||||
public class TokenService(IConfiguration conf)
|
public class TokenService(IConfiguration conf)
|
||||||
{
|
{
|
||||||
private const int AccessTokenExpirationMinutes = 24;
|
private const int AccessTokenExpirationMinutes = 24;
|
||||||
private readonly string _issuer = conf["JWT__Issuer"] ?? "spmega.il.yawaflua.tech";
|
private readonly string _issuer = conf["JWT:Issuer"] ?? conf["JWT__Issuer"] ?? "spmega.il.yawaflua.tech";
|
||||||
private readonly string _secret = conf["JWT__Secret"] ?? throw new InvalidOperationException("JWT__Secret is not configured.");
|
private readonly string _secret = conf["JWT:Secret"] ?? conf["JWT__Secret"] ?? throw new InvalidOperationException("JWT__Secret is not configured.");
|
||||||
|
|
||||||
public string GenerateAccessToken(string userName, Guid uuid)
|
public string GenerateAccessToken(string userName, Guid uuid)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -22,6 +22,9 @@
|
|||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.9" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.9" />
|
||||||
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.19.1" />
|
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.19.1" />
|
||||||
<PackageReference Include="MongoDB.EntityFrameworkCore" Version="10.0.2" />
|
<PackageReference Include="MongoDB.EntityFrameworkCore" Version="10.0.2" />
|
||||||
|
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.12.0" />
|
||||||
|
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.12.0" />
|
||||||
|
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.12.0" />
|
||||||
<PackageReference Include="spworlds-api" Version="1.0.3" />
|
<PackageReference Include="spworlds-api" Version="1.0.3" />
|
||||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.19.1" />
|
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.19.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
|
||||||
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003APaymentWrapper_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FAppData_003FRoaming_003FJetBrains_003FRider2025_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F28d7b99649ed43d899c3d8518f41c1976400_003F94_003Fbc0e580e_003FPaymentWrapper_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||||
|
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ASPWorlds_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003FAppData_003FRoaming_003FJetBrains_003FRider2025_002E3_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F28d7b99649ed43d899c3d8518f41c1976400_003F64_003Fd3041423_003FSPWorlds_002Ecs/@EntryIndexedValue">ForceIncluded</s:String></wpf:ResourceDictionary>
|
||||||
+1
-1
@@ -6,7 +6,7 @@ minecraft_version=1.21.11
|
|||||||
yarn_mappings=1.21.11+build.4
|
yarn_mappings=1.21.11+build.4
|
||||||
loader_version=0.18.1
|
loader_version=0.18.1
|
||||||
# Mod Properties
|
# Mod Properties
|
||||||
mod_version=0.4-pre-alpha
|
mod_version=0.5-beta
|
||||||
maven_group=git.yawaflua.tech
|
maven_group=git.yawaflua.tech
|
||||||
archives_base_name=SPMega
|
archives_base_name=SPMega
|
||||||
# Dependencies
|
# Dependencies
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import net.minecraft.text.Text;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.CompletableFuture;
|
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
public class ChatListener {
|
public class ChatListener {
|
||||||
@@ -57,8 +56,7 @@ public class ChatListener {
|
|||||||
if (client.player != null) {
|
if (client.player != null) {
|
||||||
String playerUuid = client.player.getUuidAsString();
|
String playerUuid = client.player.getUuidAsString();
|
||||||
|
|
||||||
CompletableFuture
|
BankUiService.instance().addCardAsync(cardId, tokenId, playerUuid)
|
||||||
.supplyAsync(() -> BankUiService.instance().addCard(cardId, tokenId, playerUuid))
|
|
||||||
.thenAccept(msg -> {
|
.thenAccept(msg -> {
|
||||||
if (client == null) {
|
if (client == null) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -34,6 +34,10 @@ public class ModMenuIntegration implements ModMenuApi {
|
|||||||
final boolean[] allowBackend = {current.allowBackend()};
|
final boolean[] allowBackend = {current.allowBackend()};
|
||||||
final boolean[] signQuickPayEnabled = {current.signQuickPayEnabled()};
|
final boolean[] signQuickPayEnabled = {current.signQuickPayEnabled()};
|
||||||
final GpsHudPosition[] gpsPosition = {current.gpsPosition()};
|
final GpsHudPosition[] gpsPosition = {current.gpsPosition()};
|
||||||
|
final GpsHudPosition[] notificationPosition = {current.notificationPosition()};
|
||||||
|
|
||||||
|
final int[] telemetryIntervalSeconds = {current.telemetryIntervalSeconds()};
|
||||||
|
final boolean[] telemetryCollectSystemInfo = {current.telemetryCollectSystemInfo()};
|
||||||
|
|
||||||
general.addEntry(entryBuilder.startStrField(Text.translatable("option.spmega.api_domain"), current.apiDomain())
|
general.addEntry(entryBuilder.startStrField(Text.translatable("option.spmega.api_domain"), current.apiDomain())
|
||||||
.setDefaultValue(ModConfig.DEFAULT_API_DOMAIN)
|
.setDefaultValue(ModConfig.DEFAULT_API_DOMAIN)
|
||||||
@@ -55,10 +59,12 @@ public class ModMenuIntegration implements ModMenuApi {
|
|||||||
.setTooltip(Text.literal("Запустить процесс авторизации через Mojang и ваш бэкенд"))
|
.setTooltip(Text.literal("Запустить процесс авторизации через Mojang и ваш бэкенд"))
|
||||||
.setSaveConsumer(newValue -> {
|
.setSaveConsumer(newValue -> {
|
||||||
if (newValue) {
|
if (newValue) {
|
||||||
BackendAuthenticator.authenticate(MinecraftClient.getInstance());
|
BackendAuthenticator.authenticateAsync(MinecraftClient.getInstance())
|
||||||
if (SPMega.getConfig() != null) {
|
.thenAccept(authenticated -> {
|
||||||
|
if (authenticated && SPMega.getConfig() != null) {
|
||||||
apiToken[0] = SPMega.getConfig().apiToken();
|
apiToken[0] = SPMega.getConfig().apiToken();
|
||||||
}
|
}
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
apiToken[0] = ModConfig.DEFAULT_API_TOKEN;
|
apiToken[0] = ModConfig.DEFAULT_API_TOKEN;
|
||||||
}
|
}
|
||||||
@@ -80,6 +86,34 @@ public class ModMenuIntegration implements ModMenuApi {
|
|||||||
.setSaveConsumer(newValue -> gpsPosition[0] = newValue)
|
.setSaveConsumer(newValue -> gpsPosition[0] = newValue)
|
||||||
.build());
|
.build());
|
||||||
|
|
||||||
|
general.addEntry(entryBuilder.startEnumSelector(
|
||||||
|
Text.translatable("option.spmega.notification_position"),
|
||||||
|
GpsHudPosition.class,
|
||||||
|
current.notificationPosition()
|
||||||
|
)
|
||||||
|
.setDefaultValue(ModConfig.DEFAULT_NOTIFICATION_POSITION)
|
||||||
|
.setEnumNameProvider(position -> Text.translatable(
|
||||||
|
"option.spmega.notification_position." + position.name().toLowerCase()))
|
||||||
|
.setSaveConsumer(newValue -> notificationPosition[0] = newValue)
|
||||||
|
.build());
|
||||||
|
|
||||||
|
// Telemetry settings
|
||||||
|
ConfigCategory telemetry = builder.getOrCreateCategory(Text.translatable("category.spmega.telemetry"));
|
||||||
|
|
||||||
|
telemetry.addEntry(entryBuilder.startIntField(Text.translatable("option.spmega.telemetry_interval"), current.telemetryIntervalSeconds())
|
||||||
|
.setDefaultValue(ModConfig.DEFAULT_TELEMETRY_INTERVAL_SECONDS)
|
||||||
|
.setMin(10)
|
||||||
|
.setMax(600)
|
||||||
|
.setTooltip(Text.translatable("tooltip.spmega.telemetry_interval"))
|
||||||
|
.setSaveConsumer(newValue -> telemetryIntervalSeconds[0] = newValue)
|
||||||
|
.build());
|
||||||
|
|
||||||
|
telemetry.addEntry(entryBuilder.startBooleanToggle(Text.translatable("option.spmega.telemetry_system_info"), current.telemetryCollectSystemInfo())
|
||||||
|
.setDefaultValue(ModConfig.DEFAULT_TELEMETRY_COLLECT_SYSTEM_INFO)
|
||||||
|
.setTooltip(Text.translatable("tooltip.spmega.telemetry_system_info"))
|
||||||
|
.setSaveConsumer(newValue -> telemetryCollectSystemInfo[0] = newValue)
|
||||||
|
.build());
|
||||||
|
|
||||||
builder.setSavingRunnable(() -> {
|
builder.setSavingRunnable(() -> {
|
||||||
boolean gpsEnabledVal = true;
|
boolean gpsEnabledVal = true;
|
||||||
if (SPMega.getConfig() != null) {
|
if (SPMega.getConfig() != null) {
|
||||||
@@ -91,7 +125,10 @@ public class ModMenuIntegration implements ModMenuApi {
|
|||||||
allowBackend[0],
|
allowBackend[0],
|
||||||
signQuickPayEnabled[0],
|
signQuickPayEnabled[0],
|
||||||
gpsEnabledVal,
|
gpsEnabledVal,
|
||||||
gpsPosition[0]
|
gpsPosition[0],
|
||||||
|
notificationPosition[0],
|
||||||
|
telemetryIntervalSeconds[0],
|
||||||
|
telemetryCollectSystemInfo[0]
|
||||||
);
|
);
|
||||||
SPMega.setConfig(updated);
|
SPMega.setConfig(updated);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package git.yawaflua.tech.spmega.client;
|
|||||||
import git.yawaflua.tech.spmega.ModConfig;
|
import git.yawaflua.tech.spmega.ModConfig;
|
||||||
import git.yawaflua.tech.spmega.SPMega;
|
import git.yawaflua.tech.spmega.SPMega;
|
||||||
import git.yawaflua.tech.spmega.client.qr.QRCodeScanner;
|
import git.yawaflua.tech.spmega.client.qr.QRCodeScanner;
|
||||||
|
import git.yawaflua.tech.spmega.client.telemetry.*;
|
||||||
import git.yawaflua.tech.spmega.client.ui.GpsHudRenderer;
|
import git.yawaflua.tech.spmega.client.ui.GpsHudRenderer;
|
||||||
import git.yawaflua.tech.spmega.client.ui.UiNotifications;
|
import git.yawaflua.tech.spmega.client.ui.UiNotifications;
|
||||||
import git.yawaflua.tech.spmega.client.ui.UiOpeners;
|
import git.yawaflua.tech.spmega.client.ui.UiOpeners;
|
||||||
@@ -99,12 +100,13 @@ public class SPMegaClient implements ClientModInitializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ClientTickEvents.END_CLIENT_TICK.register(client -> {
|
ClientTickEvents.END_CLIENT_TICK.register(client -> {
|
||||||
|
PerformanceSampler.instance().tick();
|
||||||
UiNotifications.instance().tick();
|
UiNotifications.instance().tick();
|
||||||
while (openBankMenuKeyBinding.wasPressed()) {
|
while (openBankMenuKeyBinding.wasPressed()) {
|
||||||
UiOpeners.openMainMenu(client);
|
UiOpeners.openMainMenu(client);
|
||||||
}
|
}
|
||||||
while (scanQrKeyBinding.wasPressed()) {
|
while (scanQrKeyBinding.wasPressed()) {
|
||||||
QRCodeScanner.ScanQrCode(client);
|
QRCodeScanner.scanQrCode(client);
|
||||||
}
|
}
|
||||||
while (toggleGpsKeyBinding.wasPressed()) {
|
while (toggleGpsKeyBinding.wasPressed()) {
|
||||||
GpsHudRenderer.instance().toggle();
|
GpsHudRenderer.instance().toggle();
|
||||||
@@ -116,7 +118,10 @@ public class SPMegaClient implements ClientModInitializer {
|
|||||||
current.allowBackend(),
|
current.allowBackend(),
|
||||||
current.signQuickPayEnabled(),
|
current.signQuickPayEnabled(),
|
||||||
GpsHudRenderer.instance().isEnabled(),
|
GpsHudRenderer.instance().isEnabled(),
|
||||||
current.gpsPosition()
|
current.gpsPosition(),
|
||||||
|
current.notificationPosition(),
|
||||||
|
current.telemetryIntervalSeconds(),
|
||||||
|
current.telemetryCollectSystemInfo()
|
||||||
);
|
);
|
||||||
SPMega.setConfig(updated);
|
SPMega.setConfig(updated);
|
||||||
}
|
}
|
||||||
@@ -166,25 +171,13 @@ public class SPMegaClient implements ClientModInitializer {
|
|||||||
}
|
}
|
||||||
UiNotifications.instance().render(drawContext, client.textRenderer, scaledWidth, scaledHeight);
|
UiNotifications.instance().render(drawContext, client.textRenderer, scaledWidth, scaledHeight);
|
||||||
});
|
});
|
||||||
// CompletableFuture.supplyAsync(() -> BackendAuthenticator.authenticate(client))
|
|
||||||
// .thenAccept(authResult -> {
|
|
||||||
// if (authResult) {
|
|
||||||
// System.out.println("SPMega: Authenticated on backend successfully.");
|
|
||||||
// } else {
|
|
||||||
// System.err.println("SPMega: Authentication on backend failed");
|
|
||||||
// }
|
|
||||||
// })
|
|
||||||
// .exceptionally(ex -> {
|
|
||||||
// System.err.println("SPMega: Authentication error: " + ex.getMessage());
|
|
||||||
// return null;
|
|
||||||
// });
|
|
||||||
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> {
|
ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> {
|
||||||
if (client.player != null) {
|
if (client.player != null) {
|
||||||
BankUiService.instance().refreshOnServerJoin(client.player.getUuidAsString());
|
BankUiService.instance().refreshOnServerJoinAsync(client.player.getUuidAsString());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -238,8 +231,35 @@ public class SPMegaClient implements ClientModInitializer {
|
|||||||
});
|
});
|
||||||
|
|
||||||
new ChatListener().register();
|
new ChatListener().register();
|
||||||
BackendAuthenticator.authenticate(MinecraftClient.getInstance());
|
WebhookNotificationPoller.instance().start();
|
||||||
|
BackendAuthenticator.authenticateAsync(MinecraftClient.getInstance())
|
||||||
|
.exceptionally(throwable -> {
|
||||||
|
System.err.println("[SPMEGA] Error during async authenticate: " + throwable.getMessage());
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Telemetry init
|
||||||
|
long clientInitStart = System.nanoTime();
|
||||||
|
ModConfig cfg = SPMega.getConfig();
|
||||||
|
int interval = (cfg != null) ? cfg.telemetryIntervalSeconds() : ModConfig.DEFAULT_TELEMETRY_INTERVAL_SECONDS;
|
||||||
|
SystemInfoCollector.instance().init();
|
||||||
|
TelemetrySender.instance().start(interval);
|
||||||
|
long clientInitMs = (System.nanoTime() - clientInitStart) / 1_000_000L;
|
||||||
|
com.google.gson.JsonObject initPayload = new com.google.gson.JsonObject();
|
||||||
|
initPayload.addProperty("phase", "client_init");
|
||||||
|
initPayload.addProperty("durationMs", clientInitMs);
|
||||||
|
TelemetryCollector.instance().record(TelemetryEvent.now("lifecycle", initPayload));
|
||||||
|
|
||||||
|
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
||||||
|
com.google.gson.JsonObject deinitPayload = new com.google.gson.JsonObject();
|
||||||
|
deinitPayload.addProperty("phase", "client_deinit");
|
||||||
|
TelemetryCollector.instance().record(TelemetryEvent.now("lifecycle", deinitPayload));
|
||||||
|
TelemetrySender.instance().flush();
|
||||||
|
TelemetrySender.instance().stop();
|
||||||
|
}, "SPMega-Telemetry-Shutdown"));
|
||||||
|
|
||||||
System.out.println("Author of SPMega make it with 4 cans of monster");
|
System.out.println("Author of SPMega make it with 4 cans of monster");
|
||||||
|
System.out.println("If u want to see more updates - give me like 10 shekels for monster plzzz");
|
||||||
System.out.println("Initialized beshalom! Tieie tovim!");
|
System.out.println("Initialized beshalom! Tieie tovim!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package git.yawaflua.tech.spmega.client;
|
||||||
|
|
||||||
|
import git.yawaflua.tech.spmega.client.ui.UiNotifications;
|
||||||
|
import git.yawaflua.tech.spmega.client.ui.service.BackendAuthenticator;
|
||||||
|
import git.yawaflua.tech.spmega.client.ui.service.BankUiService;
|
||||||
|
import net.minecraft.client.MinecraftClient;
|
||||||
|
import net.minecraft.text.Text;
|
||||||
|
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
|
public final class WebhookNotificationPoller {
|
||||||
|
private static final WebhookNotificationPoller INSTANCE = new WebhookNotificationPoller();
|
||||||
|
private static final long POLL_INTERVAL_SECONDS = 15;
|
||||||
|
|
||||||
|
private final AtomicBoolean started = new AtomicBoolean();
|
||||||
|
private final AtomicBoolean requestInFlight = new AtomicBoolean();
|
||||||
|
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
|
||||||
|
Thread thread = new Thread(runnable, "SPMega-Webhook-Poller");
|
||||||
|
thread.setDaemon(true);
|
||||||
|
return thread;
|
||||||
|
});
|
||||||
|
|
||||||
|
private WebhookNotificationPoller() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static WebhookNotificationPoller instance() {
|
||||||
|
return INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String format(BackendAuthenticator.PaymentNotification notification) {
|
||||||
|
String sender = notification.senderName().isBlank()
|
||||||
|
? notification.senderNumber()
|
||||||
|
: notification.senderName();
|
||||||
|
String comment = notification.comment().isBlank() ? "" : " — " + notification.comment();
|
||||||
|
return "Получено " + notification.amount() + " АР от " + sender + comment;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void start() {
|
||||||
|
if (started.compareAndSet(false, true)) {
|
||||||
|
scheduler.scheduleAtFixedRate(this::poll, 0, POLL_INTERVAL_SECONDS, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void poll() {
|
||||||
|
try {
|
||||||
|
if (!BankUiService.instance().hasWebhookEnabledCards()
|
||||||
|
|| !requestInFlight.compareAndSet(false, true)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (Exception exception) {
|
||||||
|
System.err.println("[SPMEGA] Failed to read local webhook state: " + exception.getMessage());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
BackendAuthenticator.readNotificationsAsync().whenComplete((notifications, exception) -> {
|
||||||
|
requestInFlight.set(false);
|
||||||
|
if (exception != null) {
|
||||||
|
System.err.println("[SPMEGA] Failed to poll webhook notifications: " + exception.getMessage());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
MinecraftClient client = MinecraftClient.getInstance();
|
||||||
|
if (client == null || notifications.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
client.execute(() -> notifications.forEach(notification ->
|
||||||
|
UiNotifications.instance().showQueued(Text.literal(format(notification)))));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
package git.yawaflua.tech.spmega.client.api;
|
||||||
|
|
||||||
|
import com.google.gson.*;
|
||||||
|
import git.yawaflua.tech.spmega.client.telemetry.InstrumentedHttpClient;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.CompletionException;
|
||||||
|
|
||||||
|
public final class SPWorldsApiClient {
|
||||||
|
private final InstrumentedHttpClient httpClient;
|
||||||
|
private final Gson gson;
|
||||||
|
private final String baseUrl;
|
||||||
|
|
||||||
|
public SPWorldsApiClient(String baseUrl) {
|
||||||
|
this.httpClient = new InstrumentedHttpClient();
|
||||||
|
this.gson = new Gson();
|
||||||
|
this.baseUrl = normalizeBaseUrl(baseUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String encodeAuth(CardAuth auth) {
|
||||||
|
String raw = auth.cardId() + ":" + auth.cardToken();
|
||||||
|
return Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String normalizeBaseUrl(String rawBaseUrl) {
|
||||||
|
String fallback = "https://spworlds.ru";
|
||||||
|
if (rawBaseUrl == null || rawBaseUrl.trim().isEmpty()) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
String value = rawBaseUrl.trim();
|
||||||
|
if (value.endsWith("/")) {
|
||||||
|
return value.substring(0, value.length() - 1);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String getString(JsonObject json, String key) {
|
||||||
|
if (!json.has(key) || json.get(key).isJsonNull()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return json.get(key).getAsString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletableFuture<CardInfo> getCardInfoAsync(CardAuth auth) {
|
||||||
|
HttpRequest request = requestBuilder("/api/public/card", auth).GET().build();
|
||||||
|
return sendAsync(request).thenApply(body -> {
|
||||||
|
try {
|
||||||
|
JsonObject json = JsonParser.parseString(body).getAsJsonObject();
|
||||||
|
if (json.has("statusCode")) {
|
||||||
|
switch (json.get("statusCode").getAsInt()) {
|
||||||
|
case 403:
|
||||||
|
throw new IOException("Апи вернула ошибку: " + json.get("message").getAsString());
|
||||||
|
default:
|
||||||
|
System.out.println("Unhandled status code in card info response: " + json.get("statusCode").getAsInt());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
long balance = json.has("balance") ? json.get("balance").getAsLong() : 0L;
|
||||||
|
String webhook = json.has("webhook") && !json.get("webhook").isJsonNull()
|
||||||
|
? json.get("webhook").getAsString()
|
||||||
|
: "";
|
||||||
|
return new CardInfo(balance, webhook);
|
||||||
|
} catch (Exception exception) {
|
||||||
|
System.out.println("Failed to parse card info response: " + exception.getMessage());
|
||||||
|
System.out.println(body);
|
||||||
|
throw new CompletionException(new IOException("Failed to parse card info response", exception));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletableFuture<List<PlayerCard>> getPlayerCardsAsync(String username, CardAuth auth) {
|
||||||
|
HttpRequest request = requestBuilder("/api/public/accounts/" + username + "/cards", auth).GET().build();
|
||||||
|
return sendAsync(request).thenApply(body -> {
|
||||||
|
try {
|
||||||
|
JsonArray json = JsonParser.parseString(body).getAsJsonArray();
|
||||||
|
List<PlayerCard> cards = new ArrayList<>();
|
||||||
|
for (JsonElement element : json) {
|
||||||
|
JsonObject card = element.getAsJsonObject();
|
||||||
|
String name = card.has("name") ? card.get("name").getAsString() : "";
|
||||||
|
String number = card.has("number") ? card.get("number").getAsString() : "";
|
||||||
|
cards.add(new PlayerCard(name, number));
|
||||||
|
}
|
||||||
|
return cards;
|
||||||
|
} catch (Exception exception) {
|
||||||
|
System.out.println("Failed to parse player cards response: " + exception.getMessage());
|
||||||
|
System.out.println(body);
|
||||||
|
throw new CompletionException(new IOException("Failed to parse player cards response", exception));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletableFuture<AccountMe> getAccountMeAsync(CardAuth auth) {
|
||||||
|
HttpRequest request = requestBuilder("/api/public/accounts/me", auth).GET().build();
|
||||||
|
return sendAsync(request).thenApply(body -> {
|
||||||
|
try {
|
||||||
|
JsonObject json = JsonParser.parseString(body).getAsJsonObject();
|
||||||
|
|
||||||
|
String id = json.has("id") ? json.get("id").getAsString() : "";
|
||||||
|
String username = json.has("username") ? json.get("username").getAsString() : "";
|
||||||
|
String minecraftUuid = json.has("minecraftUUID") ? json.get("minecraftUUID").getAsString() : "";
|
||||||
|
|
||||||
|
List<AccountCard> cards = new ArrayList<>();
|
||||||
|
if (json.has("cards") && json.get("cards").isJsonArray()) {
|
||||||
|
for (JsonElement element : json.getAsJsonArray("cards")) {
|
||||||
|
JsonObject card = element.getAsJsonObject();
|
||||||
|
cards.add(new AccountCard(
|
||||||
|
getString(card, "id"),
|
||||||
|
getString(card, "name"),
|
||||||
|
getString(card, "number"),
|
||||||
|
card.has("color") && !card.get("color").isJsonNull() ? card.get("color").getAsInt() : 0
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new AccountMe(id, username, minecraftUuid, cards);
|
||||||
|
} catch (Exception exception) {
|
||||||
|
System.out.println("Failed to parse account info response: " + exception.getMessage());
|
||||||
|
System.out.println(body);
|
||||||
|
throw new CompletionException(new IOException("Failed to parse account info response", exception));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletableFuture<TransactionResult> createTransactionAsync(
|
||||||
|
CardAuth auth, String receiver, long amount, String comment) {
|
||||||
|
JsonObject payload = new JsonObject();
|
||||||
|
payload.addProperty("receiver", receiver);
|
||||||
|
payload.addProperty("amount", amount);
|
||||||
|
payload.addProperty("comment", comment.isEmpty() ? "Перевод через SPMega" : comment);
|
||||||
|
|
||||||
|
HttpRequest request = requestBuilder("/api/public/transactions", auth)
|
||||||
|
.POST(HttpRequest.BodyPublishers.ofString(gson.toJson(payload)))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return sendAsync(request).thenApply(body -> {
|
||||||
|
try {
|
||||||
|
JsonObject json = JsonParser.parseString(body).getAsJsonObject();
|
||||||
|
long balance = json.has("balance") ? json.get("balance").getAsLong() : 0L;
|
||||||
|
return new TransactionResult(balance);
|
||||||
|
} catch (Exception exception) {
|
||||||
|
System.out.println("Failed to parse transaction response: " + exception.getMessage());
|
||||||
|
System.out.println(body);
|
||||||
|
throw new CompletionException(new IOException("Failed to parse transaction response", exception));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpRequest.Builder requestBuilder(String path, CardAuth auth) {
|
||||||
|
return HttpRequest.newBuilder(URI.create(baseUrl + path))
|
||||||
|
.header("Authorization", "Bearer " + encodeAuth(auth))
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.header("Accept", "application/json");
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompletableFuture<String> sendAsync(HttpRequest request) {
|
||||||
|
return httpClient.sendAsync(request).thenApply(response -> {
|
||||||
|
int statusCode = response.statusCode();
|
||||||
|
if (statusCode < 200 || statusCode >= 300) {
|
||||||
|
System.out.println(response.body());
|
||||||
|
JsonElement parsed = JsonParser.parseString(response.body());
|
||||||
|
JsonObject object = parsed.isJsonArray()
|
||||||
|
? parsed.getAsJsonArray().get(0).getAsJsonObject()
|
||||||
|
: parsed.getAsJsonObject();
|
||||||
|
String message = "";
|
||||||
|
if (object.has("error") && !object.get("error").isJsonNull()) {
|
||||||
|
message = "Ошибка в запросе: " + object.get("error").getAsString();
|
||||||
|
} else if (object.has("message") && !object.get("message").isJsonNull()) {
|
||||||
|
message = object.get("message").getAsString();
|
||||||
|
}
|
||||||
|
throw new CompletionException(new IOException(statusCode + ": " + message));
|
||||||
|
}
|
||||||
|
return response.body();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public record CardAuth(String cardId, String cardToken) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record CardInfo(long balance, String webhook) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record PlayerCard(String name, String number) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record AccountMe(String id, String username, String minecraftUuid, List<AccountCard> cards) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record AccountCard(String id, String name, String number, int color) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record TransactionResult(long balance) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -4,21 +4,32 @@ import com.google.zxing.*;
|
|||||||
import com.google.zxing.common.GlobalHistogramBinarizer;
|
import com.google.zxing.common.GlobalHistogramBinarizer;
|
||||||
import com.google.zxing.common.HybridBinarizer;
|
import com.google.zxing.common.HybridBinarizer;
|
||||||
import com.google.zxing.multi.GenericMultipleBarcodeReader;
|
import com.google.zxing.multi.GenericMultipleBarcodeReader;
|
||||||
|
import git.yawaflua.tech.spmega.client.telemetry.TelemetryCollector;
|
||||||
|
import git.yawaflua.tech.spmega.client.telemetry.TelemetryEvent;
|
||||||
import git.yawaflua.tech.spmega.client.ui.QRcodeAcceptScreen;
|
import git.yawaflua.tech.spmega.client.ui.QRcodeAcceptScreen;
|
||||||
import git.yawaflua.tech.spmega.client.ui.UiNotifications;
|
import git.yawaflua.tech.spmega.client.ui.UiNotifications;
|
||||||
import net.minecraft.client.MinecraftClient;
|
import net.minecraft.client.MinecraftClient;
|
||||||
import net.minecraft.client.texture.NativeImage;
|
|
||||||
import net.minecraft.client.util.ScreenshotRecorder;
|
import net.minecraft.client.util.ScreenshotRecorder;
|
||||||
import net.minecraft.text.Text;
|
import net.minecraft.text.Text;
|
||||||
|
|
||||||
import java.awt.image.BufferedImage;
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.EnumMap;
|
import java.util.EnumMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
public class QRCodeScanner {
|
public final class QRCodeScanner {
|
||||||
|
private static final ExecutorService DECODER = Executors.newSingleThreadExecutor(runnable -> {
|
||||||
|
Thread thread = new Thread(runnable, "SPMega-QR-Decoder");
|
||||||
|
thread.setDaemon(true);
|
||||||
|
return thread;
|
||||||
|
});
|
||||||
|
|
||||||
public static void ScanQrCode(MinecraftClient client) {
|
private QRCodeScanner() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void scanQrCode(MinecraftClient client) {
|
||||||
if (client == null || client.player == null || client.getFramebuffer() == null) {
|
if (client == null || client.player == null || client.getFramebuffer() == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -30,6 +41,7 @@ public class QRCodeScanner {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
long startNs = System.nanoTime();
|
||||||
try {
|
try {
|
||||||
ScreenshotRecorder.takeScreenshot(client.getFramebuffer(), nativeImage -> {
|
ScreenshotRecorder.takeScreenshot(client.getFramebuffer(), nativeImage -> {
|
||||||
try {
|
try {
|
||||||
@@ -39,24 +51,28 @@ public class QRCodeScanner {
|
|||||||
notifications.show(Text.translatable("message.spmega.qr.capture_failed"));
|
notifications.show(Text.translatable("message.spmega.qr.capture_failed"));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
recordQrEvent(false, false, null, "capture_failed", startNs);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
String result = decodeQRCode(nativeImageToBufferedImage(nativeImage));
|
int width = nativeImage.getWidth();
|
||||||
client.execute(() -> {
|
int height = nativeImage.getHeight();
|
||||||
if (client.player == null) {
|
int[] pixels = nativeImage.copyPixelsArgb();
|
||||||
return;
|
CompletableFuture.supplyAsync(() -> decodeQrCode(width, height, pixels), DECODER)
|
||||||
}
|
.whenComplete((result, throwable) -> {
|
||||||
if (result == null) {
|
client.execute(() -> showResult(client, notifications, result, throwable));
|
||||||
notifications.show(Text.translatable("message.spmega.qr.not_found"));
|
recordQrEvent(
|
||||||
return;
|
throwable == null && result != null,
|
||||||
}
|
System.nanoTime() - startNs > 50_000_000L,
|
||||||
|
result,
|
||||||
Text clickableLink = Text.literal(result)
|
throwable == null ? null : throwable.getClass().getSimpleName() + ": " + throwable.getMessage(),
|
||||||
.styled(style -> style.withInsertion(result));
|
startNs
|
||||||
client.player.sendMessage(Text.translatable("message.spmega.qr.found_link", clickableLink), false);
|
);
|
||||||
client.setScreen(new QRcodeAcceptScreen(result, client.currentScreen));
|
|
||||||
});
|
});
|
||||||
|
} catch (Exception exception) {
|
||||||
|
client.execute(() -> notifications.show(Text.translatable("message.spmega.qr.error")));
|
||||||
|
recordQrEvent(false, false, null,
|
||||||
|
exception.getClass().getSimpleName() + ": " + exception.getMessage(), startNs);
|
||||||
} finally {
|
} finally {
|
||||||
if (nativeImage != null) {
|
if (nativeImage != null) {
|
||||||
nativeImage.close();
|
nativeImage.close();
|
||||||
@@ -65,34 +81,55 @@ public class QRCodeScanner {
|
|||||||
});
|
});
|
||||||
} catch (Exception ex) {
|
} catch (Exception ex) {
|
||||||
notifications.show(Text.translatable("message.spmega.qr.error"));
|
notifications.show(Text.translatable("message.spmega.qr.error"));
|
||||||
|
recordQrEvent(false, false, null, ex.getClass().getSimpleName() + ": " + ex.getMessage(), startNs);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static BufferedImage nativeImageToBufferedImage(NativeImage screenshot) {
|
private static void showResult(
|
||||||
BufferedImage bufferedImage = new BufferedImage(
|
MinecraftClient client,
|
||||||
screenshot.getWidth(),
|
UiNotifications notifications,
|
||||||
screenshot.getHeight(),
|
String result,
|
||||||
BufferedImage.TYPE_INT_RGB
|
Throwable throwable
|
||||||
);
|
) {
|
||||||
|
if (client.player == null) {
|
||||||
for (int y = 0; y < screenshot.getHeight(); y++) {
|
return;
|
||||||
for (int x = 0; x < screenshot.getWidth(); x++) {
|
|
||||||
int color = screenshot.getColorArgb(x, y);
|
|
||||||
bufferedImage.setRGB(x, y, color);
|
|
||||||
}
|
}
|
||||||
|
if (throwable != null) {
|
||||||
|
notifications.show(Text.translatable("message.spmega.qr.error"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (result == null) {
|
||||||
|
notifications.show(Text.translatable("message.spmega.qr.not_found"));
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
return bufferedImage;
|
Text clickableLink = Text.literal(result).styled(style -> style.withInsertion(result));
|
||||||
|
client.player.sendMessage(Text.translatable("message.spmega.qr.found_link", clickableLink), false);
|
||||||
|
client.setScreen(new QRcodeAcceptScreen(result, client.currentScreen));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String decodeQRCode(BufferedImage image) {
|
private static void recordQrEvent(boolean success, boolean didLag, String decodedUrl, String error, long startNs) {
|
||||||
|
com.google.gson.JsonObject payload = new com.google.gson.JsonObject();
|
||||||
|
payload.addProperty("success", success);
|
||||||
|
payload.addProperty("didLag", didLag);
|
||||||
|
payload.addProperty("durationMs", (System.nanoTime() - startNs) / 1_000_000L);
|
||||||
|
if (decodedUrl != null) {
|
||||||
|
payload.addProperty("decodedUrl", decodedUrl);
|
||||||
|
}
|
||||||
|
if (error != null) {
|
||||||
|
payload.addProperty("error", error);
|
||||||
|
}
|
||||||
|
TelemetryCollector.instance().record(TelemetryEvent.now("qr_scan", payload));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String decodeQrCode(int width, int height, int[] pixels) {
|
||||||
Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
|
Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
|
||||||
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
|
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
|
||||||
hints.put(DecodeHintType.POSSIBLE_FORMATS, Collections.singletonList(BarcodeFormat.QR_CODE));
|
hints.put(DecodeHintType.POSSIBLE_FORMATS, Collections.singletonList(BarcodeFormat.QR_CODE));
|
||||||
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
|
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
|
||||||
hints.put(DecodeHintType.ALSO_INVERTED, Boolean.TRUE);
|
hints.put(DecodeHintType.ALSO_INVERTED, Boolean.TRUE);
|
||||||
|
|
||||||
LuminanceSource source = new RGBLuminanceSource(image.getWidth(), image.getHeight(), image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth()));
|
LuminanceSource source = new RGBLuminanceSource(width, height, pixels);
|
||||||
|
|
||||||
String result = tryDecodeWithStrategies(source, hints);
|
String result = tryDecodeWithStrategies(source, hints);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package git.yawaflua.tech.spmega.client.telemetry;
|
||||||
|
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
|
public record InstrumentedHttpClient(HttpClient delegate) {
|
||||||
|
public InstrumentedHttpClient() {
|
||||||
|
this(HttpClient.newBuilder()
|
||||||
|
.connectTimeout(Duration.ofSeconds(15))
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void recordHttpEvent(URI uri, String method, int statusCode,
|
||||||
|
long durationMs, boolean success, String errorType,
|
||||||
|
int fpsBefore, int fpsAfter) {
|
||||||
|
JsonObject payload = new JsonObject();
|
||||||
|
payload.addProperty("target", TelemetryUriSanitizer.classifyTarget(uri));
|
||||||
|
payload.addProperty("method", method);
|
||||||
|
payload.addProperty("path", TelemetryUriSanitizer.sanitize(uri));
|
||||||
|
payload.addProperty("statusCode", statusCode);
|
||||||
|
payload.addProperty("durationMs", durationMs);
|
||||||
|
payload.addProperty("success", success);
|
||||||
|
if (errorType != null) {
|
||||||
|
payload.addProperty("errorType", errorType);
|
||||||
|
}
|
||||||
|
payload.addProperty("fpsBefore", fpsBefore);
|
||||||
|
payload.addProperty("fpsAfter", fpsAfter);
|
||||||
|
|
||||||
|
TelemetryCollector.instance().record(TelemetryEvent.now("http_request", payload));
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletableFuture<HttpResponse<String>> sendAsync(HttpRequest request) {
|
||||||
|
URI uri = request.uri();
|
||||||
|
String method = request.method();
|
||||||
|
|
||||||
|
int fpsBefore = PerformanceSampler.instance().currentFps();
|
||||||
|
long startNs = System.nanoTime();
|
||||||
|
|
||||||
|
return delegate.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||||
|
.whenComplete((response, throwable) -> {
|
||||||
|
long durationMs = (System.nanoTime() - startNs) / 1_000_000L;
|
||||||
|
int fpsAfter = PerformanceSampler.instance().currentFps();
|
||||||
|
|
||||||
|
if (throwable != null) {
|
||||||
|
recordHttpEvent(uri, method, -1, durationMs,
|
||||||
|
false, throwable.getClass().getSimpleName(), fpsBefore, fpsAfter);
|
||||||
|
} else {
|
||||||
|
recordHttpEvent(uri, method, response.statusCode(), durationMs,
|
||||||
|
true, null, fpsBefore, fpsAfter);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package git.yawaflua.tech.spmega.client.telemetry;
|
||||||
|
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import net.minecraft.client.MinecraftClient;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
|
||||||
|
public final class PerformanceSampler {
|
||||||
|
private static final PerformanceSampler INSTANCE = new PerformanceSampler();
|
||||||
|
|
||||||
|
private final AtomicInteger fpsSum = new AtomicInteger();
|
||||||
|
private final AtomicInteger fpsCount = new AtomicInteger();
|
||||||
|
private final AtomicInteger fpsMin = new AtomicInteger(Integer.MAX_VALUE);
|
||||||
|
private final AtomicInteger fpsMax = new AtomicInteger(0);
|
||||||
|
private final AtomicLong lastSnapshotMs = new AtomicLong(System.currentTimeMillis());
|
||||||
|
|
||||||
|
private PerformanceSampler() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static PerformanceSampler instance() {
|
||||||
|
return INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void tick() {
|
||||||
|
int fps = MinecraftClient.getInstance().getCurrentFps();
|
||||||
|
fpsSum.addAndGet(fps);
|
||||||
|
fpsCount.incrementAndGet();
|
||||||
|
fpsMin.updateAndGet(prev -> Math.min(prev, fps));
|
||||||
|
fpsMax.updateAndGet(prev -> Math.max(prev, fps));
|
||||||
|
}
|
||||||
|
|
||||||
|
public int currentFps() {
|
||||||
|
return MinecraftClient.getInstance().getCurrentFps();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void emitSnapshot() {
|
||||||
|
int count = fpsCount.getAndSet(0);
|
||||||
|
int sum = fpsSum.getAndSet(0);
|
||||||
|
int min = fpsMin.getAndSet(Integer.MAX_VALUE);
|
||||||
|
int max = fpsMax.getAndSet(0);
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
long periodMs = now - lastSnapshotMs.getAndSet(now);
|
||||||
|
|
||||||
|
if (count == 0) return;
|
||||||
|
|
||||||
|
JsonObject payload = new JsonObject();
|
||||||
|
payload.addProperty("fpsAvg", sum / count);
|
||||||
|
payload.addProperty("fpsMin", min == Integer.MAX_VALUE ? 0 : min);
|
||||||
|
payload.addProperty("fpsMax", max);
|
||||||
|
payload.addProperty("sampleCount", count);
|
||||||
|
payload.addProperty("periodMs", periodMs);
|
||||||
|
|
||||||
|
Runtime rt = Runtime.getRuntime();
|
||||||
|
payload.addProperty("usedMemoryMb", (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024));
|
||||||
|
payload.addProperty("totalMemoryMb", rt.totalMemory() / (1024 * 1024));
|
||||||
|
payload.addProperty("maxMemoryMb", rt.maxMemory() / (1024 * 1024));
|
||||||
|
|
||||||
|
TelemetryCollector.instance().record(TelemetryEvent.now("performance_snapshot", payload));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package git.yawaflua.tech.spmega.client.telemetry;
|
||||||
|
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import net.minecraft.client.MinecraftClient;
|
||||||
|
import org.lwjgl.opengl.GL11;
|
||||||
|
import oshi.SystemInfo;
|
||||||
|
import oshi.hardware.CentralProcessor;
|
||||||
|
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.nio.file.FileStore;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
|
public final class SystemInfoCollector {
|
||||||
|
private static final SystemInfoCollector INSTANCE = new SystemInfoCollector();
|
||||||
|
private static final long MB = 1024L * 1024L;
|
||||||
|
|
||||||
|
private final CentralProcessor cpu = new SystemInfo().getHardware().getProcessor();
|
||||||
|
private final AtomicReference<String> cachedIp = new AtomicReference<>("<unknown>");
|
||||||
|
private final AtomicReference<String> gpuRenderer = new AtomicReference<>("<pending>");
|
||||||
|
private final AtomicReference<String> gpuVendor = new AtomicReference<>("<pending>");
|
||||||
|
private volatile boolean gpuCollected = false;
|
||||||
|
|
||||||
|
private SystemInfoCollector() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static SystemInfoCollector instance() {
|
||||||
|
return INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void init() {
|
||||||
|
fetchIpAsync();
|
||||||
|
collectGpuOnRenderThread();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fetchIpAsync() {
|
||||||
|
HttpClient.newBuilder()
|
||||||
|
.connectTimeout(Duration.ofSeconds(5))
|
||||||
|
.build()
|
||||||
|
.sendAsync(HttpRequest.newBuilder()
|
||||||
|
.uri(URI.create("https://api.ipify.org?format=text"))
|
||||||
|
.timeout(Duration.ofSeconds(5))
|
||||||
|
.GET()
|
||||||
|
.build(),
|
||||||
|
java.net.http.HttpResponse.BodyHandlers.ofString())
|
||||||
|
.thenAccept(response -> {
|
||||||
|
if (response.statusCode() == 200) {
|
||||||
|
cachedIp.set(response.body().trim());
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.exceptionally(ignored -> null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void collectGpuOnRenderThread() {
|
||||||
|
MinecraftClient.getInstance().execute(() -> {
|
||||||
|
try {
|
||||||
|
gpuRenderer.set(GL11.glGetString(GL11.GL_RENDERER));
|
||||||
|
gpuVendor.set(GL11.glGetString(GL11.GL_VENDOR));
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
gpuCollected = true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public JsonObject collect() {
|
||||||
|
JsonObject info = new JsonObject();
|
||||||
|
|
||||||
|
Runtime rt = Runtime.getRuntime();
|
||||||
|
info.addProperty("cpuCores", rt.availableProcessors());
|
||||||
|
info.addProperty("cpuName", cpu.getProcessorIdentifier().getName());
|
||||||
|
info.addProperty("cpuCurrentFrequencyHz", Arrays.stream(cpu.getCurrentFreq()).max().orElse(0));
|
||||||
|
info.addProperty("cpuMaxFrequencyHz", cpu.getMaxFreq());
|
||||||
|
|
||||||
|
try {
|
||||||
|
var osBean = java.lang.management.ManagementFactory.getOperatingSystemMXBean();
|
||||||
|
if (osBean instanceof com.sun.management.OperatingSystemMXBean ext) {
|
||||||
|
double cpuLoad = ext.getProcessCpuLoad();
|
||||||
|
if (cpuLoad >= 0) {
|
||||||
|
info.addProperty("cpuLoad", Math.round(cpuLoad * 100.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
|
||||||
|
info.addProperty("gpuRenderer", gpuRenderer.get());
|
||||||
|
info.addProperty("gpuVendor", gpuVendor.get());
|
||||||
|
|
||||||
|
info.addProperty("ramTotalMb", rt.maxMemory() / MB);
|
||||||
|
info.addProperty("ramFreeMb", rt.freeMemory() / MB);
|
||||||
|
info.addProperty("ramUsedMb", (rt.totalMemory() - rt.freeMemory()) / MB);
|
||||||
|
|
||||||
|
try {
|
||||||
|
FileStore store = Files.getFileStore(Path.of("."));
|
||||||
|
info.addProperty("storageTotalMb", store.getTotalSpace() / MB);
|
||||||
|
info.addProperty("storageFreeMb", store.getUsableSpace() / MB);
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
|
||||||
|
info.addProperty("publicIp", cachedIp.get());
|
||||||
|
|
||||||
|
try {
|
||||||
|
info.addProperty("hostName", InetAddress.getLocalHost().getHostName());
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
info.addProperty("hostName", System.getenv("COMPUTERNAME"));
|
||||||
|
}
|
||||||
|
|
||||||
|
info.addProperty("javaVersion", System.getProperty("java.version"));
|
||||||
|
info.addProperty("osName", System.getProperty("os.name"));
|
||||||
|
info.addProperty("osArch", System.getProperty("os.arch"));
|
||||||
|
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package git.yawaflua.tech.spmega.client.telemetry;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||||
|
|
||||||
|
public final class TelemetryCollector {
|
||||||
|
private static final TelemetryCollector INSTANCE = new TelemetryCollector();
|
||||||
|
private static final int MAX_QUEUE_SIZE = 1000;
|
||||||
|
|
||||||
|
private final ConcurrentLinkedQueue<TelemetryEvent> queue = new ConcurrentLinkedQueue<>();
|
||||||
|
|
||||||
|
private TelemetryCollector() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TelemetryCollector instance() {
|
||||||
|
return INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void record(TelemetryEvent event) {
|
||||||
|
if (event == null) return;
|
||||||
|
if (queue.size() >= MAX_QUEUE_SIZE) {
|
||||||
|
queue.poll();
|
||||||
|
}
|
||||||
|
queue.add(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<TelemetryEvent> drain() {
|
||||||
|
List<TelemetryEvent> batch = new ArrayList<>();
|
||||||
|
TelemetryEvent event;
|
||||||
|
while ((event = queue.poll()) != null) {
|
||||||
|
batch.add(event);
|
||||||
|
}
|
||||||
|
return batch;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int size() {
|
||||||
|
return queue.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package git.yawaflua.tech.spmega.client.telemetry;
|
||||||
|
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
public record TelemetryEvent(String eventType, Instant timestamp, JsonObject payload) {
|
||||||
|
|
||||||
|
public static TelemetryEvent now(String eventType, JsonObject payload) {
|
||||||
|
return new TelemetryEvent(eventType, Instant.now(), payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TelemetryEvent now(String eventType) {
|
||||||
|
return now(eventType, new JsonObject());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
package git.yawaflua.tech.spmega.client.telemetry;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import git.yawaflua.tech.spmega.ModConfig;
|
||||||
|
import git.yawaflua.tech.spmega.SPMega;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
public final class TelemetrySender {
|
||||||
|
private static final TelemetrySender INSTANCE = new TelemetrySender();
|
||||||
|
private static final Gson GSON = new Gson();
|
||||||
|
|
||||||
|
private final String sessionId = UUID.randomUUID().toString();
|
||||||
|
private final HttpClient httpClient;
|
||||||
|
private ScheduledExecutorService scheduler;
|
||||||
|
|
||||||
|
private TelemetrySender() {
|
||||||
|
this.httpClient = HttpClient.newBuilder()
|
||||||
|
.connectTimeout(Duration.ofSeconds(10))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TelemetrySender instance() {
|
||||||
|
return INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String sessionId() {
|
||||||
|
return sessionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void start(int intervalSeconds) {
|
||||||
|
if (scheduler != null && !scheduler.isShutdown()) {
|
||||||
|
scheduler.shutdownNow();
|
||||||
|
}
|
||||||
|
scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||||
|
Thread t = new Thread(r, "SPMega-Telemetry-Sender");
|
||||||
|
t.setDaemon(true);
|
||||||
|
return t;
|
||||||
|
});
|
||||||
|
scheduler.scheduleAtFixedRate(this::flush, intervalSeconds, intervalSeconds, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void stop() {
|
||||||
|
if (scheduler != null) {
|
||||||
|
scheduler.shutdownNow();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void flush() {
|
||||||
|
try {
|
||||||
|
ModConfig config = SPMega.getConfig();
|
||||||
|
if (config == null) return;
|
||||||
|
|
||||||
|
// Performance snapshot при каждом flush
|
||||||
|
PerformanceSampler.instance().emitSnapshot();
|
||||||
|
|
||||||
|
// System info (only if telemetryCollectSystemInfo enabled)
|
||||||
|
if (config.telemetryCollectSystemInfo()) {
|
||||||
|
JsonObject sysInfo = SystemInfoCollector.instance().collect();
|
||||||
|
TelemetryCollector.instance().record(TelemetryEvent.now("system_info", sysInfo));
|
||||||
|
}
|
||||||
|
|
||||||
|
List<TelemetryEvent> events = TelemetryCollector.instance().drain();
|
||||||
|
if (events.isEmpty()) return;
|
||||||
|
|
||||||
|
JsonObject batch = new JsonObject();
|
||||||
|
batch.addProperty("clientVersion", getModVersion());
|
||||||
|
batch.addProperty("sessionId", sessionId);
|
||||||
|
batch.addProperty("sentAt", Instant.now().toString());
|
||||||
|
|
||||||
|
JsonArray eventsArray = new JsonArray();
|
||||||
|
for (TelemetryEvent event : events) {
|
||||||
|
JsonObject ev = new JsonObject();
|
||||||
|
ev.addProperty("eventType", event.eventType());
|
||||||
|
ev.addProperty("timestamp", event.timestamp().toString());
|
||||||
|
ev.add("payload", event.payload());
|
||||||
|
eventsArray.add(ev);
|
||||||
|
}
|
||||||
|
batch.add("events", eventsArray);
|
||||||
|
|
||||||
|
String body = GSON.toJson(batch);
|
||||||
|
String apiDomain = config.apiDomain();
|
||||||
|
if (apiDomain == null || apiDomain.isEmpty()) apiDomain = ModConfig.DEFAULT_API_DOMAIN;
|
||||||
|
|
||||||
|
String token = config.apiToken();
|
||||||
|
HttpRequest.Builder reqBuilder = HttpRequest.newBuilder()
|
||||||
|
.uri(URI.create(apiDomain + "/api/v1/telemetry"))
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.timeout(Duration.ofSeconds(10))
|
||||||
|
.POST(HttpRequest.BodyPublishers.ofString(body));
|
||||||
|
|
||||||
|
if (token != null && !token.equals(ModConfig.DEFAULT_API_TOKEN)) {
|
||||||
|
reqBuilder.header("Authorization", "Bearer " + token);
|
||||||
|
}
|
||||||
|
|
||||||
|
httpClient.sendAsync(reqBuilder.build(), HttpResponse.BodyHandlers.ofString());
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.err.println("[SPMEGA] Telemetry flush error: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getModVersion() {
|
||||||
|
try {
|
||||||
|
return net.fabricmc.loader.api.FabricLoader.getInstance()
|
||||||
|
.getModContainer("spmega")
|
||||||
|
.map(c -> c.getMetadata().getVersion().getFriendlyString())
|
||||||
|
.orElse("unknown");
|
||||||
|
} catch (Exception e) {
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package git.yawaflua.tech.spmega.client.telemetry;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
public final class TelemetryUriSanitizer {
|
||||||
|
private static final Pattern UUID_PATTERN = Pattern.compile(
|
||||||
|
"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}");
|
||||||
|
private static final Pattern TOKEN_PATTERN = Pattern.compile(
|
||||||
|
"(token|key|secret|password|auth|bearer)=[^&]+", Pattern.CASE_INSENSITIVE);
|
||||||
|
|
||||||
|
private TelemetryUriSanitizer() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String sanitize(URI uri) {
|
||||||
|
if (uri == null) return "<null>";
|
||||||
|
String path = uri.getPath() != null ? uri.getPath() : "";
|
||||||
|
path = UUID_PATTERN.matcher(path).replaceAll("<uuid>");
|
||||||
|
|
||||||
|
String query = uri.getQuery();
|
||||||
|
if (query != null) {
|
||||||
|
query = TOKEN_PATTERN.matcher(query).replaceAll("$1=<redacted>");
|
||||||
|
return uri.getHost() + path + "?" + query;
|
||||||
|
}
|
||||||
|
return uri.getHost() + path;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String sanitize(String url) {
|
||||||
|
try {
|
||||||
|
return sanitize(URI.create(url));
|
||||||
|
} catch (Exception e) {
|
||||||
|
return "<invalid-url>";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String classifyTarget(URI uri) {
|
||||||
|
if (uri == null) return "unknown";
|
||||||
|
String host = uri.getHost();
|
||||||
|
if (host == null) return "unknown";
|
||||||
|
if (host.contains("spworlds.ru")) return "spworlds";
|
||||||
|
if (host.contains("spmega") || host.contains("ywfl.dev") || host.contains("yawaflua")) return "spmega-backend";
|
||||||
|
if (host.contains("mojang.com") || host.contains("minecraft.net")) return "mojang";
|
||||||
|
if (host.contains("sp-mini.ru") || host.contains("spmap")) return "gps-map";
|
||||||
|
if (host.contains("ipify.org")) return "ipify";
|
||||||
|
return "other";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,6 @@ import net.minecraft.client.gui.widget.ButtonWidget;
|
|||||||
import net.minecraft.client.gui.widget.TextFieldWidget;
|
import net.minecraft.client.gui.widget.TextFieldWidget;
|
||||||
import net.minecraft.text.Text;
|
import net.minecraft.text.Text;
|
||||||
|
|
||||||
import java.util.concurrent.CompletableFuture;
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
public class AddCardScreen extends Screen {
|
public class AddCardScreen extends Screen {
|
||||||
@@ -85,8 +84,7 @@ public class AddCardScreen extends Screen {
|
|||||||
addButton.active = false;
|
addButton.active = false;
|
||||||
cancelButton.active = false;
|
cancelButton.active = false;
|
||||||
|
|
||||||
CompletableFuture
|
bankUiService.addCardAsync(cardId, cardToken, playerUuid)
|
||||||
.supplyAsync(() -> bankUiService.addCard(cardId, cardToken, playerUuid))
|
|
||||||
.thenAccept(message -> {
|
.thenAccept(message -> {
|
||||||
if (this.client == null) {
|
if (this.client == null) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -3,13 +3,13 @@ package git.yawaflua.tech.spmega.client.ui;
|
|||||||
import git.yawaflua.tech.spmega.client.ui.service.BankUiService;
|
import git.yawaflua.tech.spmega.client.ui.service.BankUiService;
|
||||||
import git.yawaflua.tech.spmega.client.ui.service.CardViewModel;
|
import git.yawaflua.tech.spmega.client.ui.service.CardViewModel;
|
||||||
import net.minecraft.client.gui.DrawContext;
|
import net.minecraft.client.gui.DrawContext;
|
||||||
|
import net.minecraft.client.gui.screen.ConfirmScreen;
|
||||||
import net.minecraft.client.gui.screen.Screen;
|
import net.minecraft.client.gui.screen.Screen;
|
||||||
import net.minecraft.client.gui.widget.ButtonWidget;
|
import net.minecraft.client.gui.widget.ButtonWidget;
|
||||||
import net.minecraft.text.Text;
|
import net.minecraft.text.Text;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.CompletableFuture;
|
|
||||||
|
|
||||||
public class CardScreen extends Screen {
|
public class CardScreen extends Screen {
|
||||||
private final Screen parent;
|
private final Screen parent;
|
||||||
@@ -17,6 +17,7 @@ public class CardScreen extends Screen {
|
|||||||
private final UiNotifications notifications = UiNotifications.instance();
|
private final UiNotifications notifications = UiNotifications.instance();
|
||||||
private final List<ButtonWidget> cardButtons = new ArrayList<>();
|
private final List<ButtonWidget> cardButtons = new ArrayList<>();
|
||||||
private ButtonWidget historyButton;
|
private ButtonWidget historyButton;
|
||||||
|
private ButtonWidget webhookButton;
|
||||||
|
|
||||||
public CardScreen(Screen parent) {
|
public CardScreen(Screen parent) {
|
||||||
super(Text.literal("Управление картами"));
|
super(Text.literal("Управление картами"));
|
||||||
@@ -46,25 +47,30 @@ public class CardScreen extends Screen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.addDrawableChild(ButtonWidget.builder(Text.literal("Удалить"), button -> {
|
this.addDrawableChild(ButtonWidget.builder(Text.literal("Удалить"), button -> {
|
||||||
CompletableFuture.supplyAsync(() -> {
|
bankUiService.removeSelectedCardAsync()
|
||||||
bankUiService.removeSelectedCard();
|
.thenAccept(message -> {
|
||||||
return true;
|
if (this.client != null) {
|
||||||
});
|
this.client.execute(() -> {
|
||||||
notifications.showMessage(bankUiService.getLastMessage());
|
notifications.showMessage(message);
|
||||||
this.clearAndInit();
|
this.clearAndInit();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
}).dimensions(rightX, startY, columnWidth, 20).build());
|
}).dimensions(rightX, startY, columnWidth, 20).build());
|
||||||
|
|
||||||
this.addDrawableChild(ButtonWidget.builder(Text.literal("Обновить"), button -> {
|
this.addDrawableChild(ButtonWidget.builder(Text.literal("Обновить"), button -> {
|
||||||
String playerUuid = this.client != null && this.client.player != null
|
String playerUuid = this.client != null && this.client.player != null
|
||||||
? this.client.player.getUuidAsString()
|
? this.client.player.getUuidAsString()
|
||||||
: "";
|
: "";
|
||||||
CompletableFuture.supplyAsync(() -> {
|
bankUiService.refreshSelectedCardAsync(playerUuid)
|
||||||
bankUiService.refreshSelectedCard(playerUuid);
|
.thenAccept(message -> {
|
||||||
return true;
|
if (this.client != null) {
|
||||||
});
|
this.client.execute(() -> {
|
||||||
String message = bankUiService.getLastMessage().isBlank() ? "Карта обновлена" : bankUiService.getLastMessage();
|
|
||||||
notifications.showMessage(message);
|
notifications.showMessage(message);
|
||||||
this.clearAndInit();
|
this.clearAndInit();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
}).dimensions(rightX, startY + 24, columnWidth, 20).build());
|
}).dimensions(rightX, startY + 24, columnWidth, 20).build());
|
||||||
|
|
||||||
this.addDrawableChild(ButtonWidget.builder(Text.literal("Добавить новую"), button -> {
|
this.addDrawableChild(ButtonWidget.builder(Text.literal("Добавить новую"), button -> {
|
||||||
@@ -89,8 +95,30 @@ public class CardScreen extends Screen {
|
|||||||
this.client.setScreen(new TransactionHistoryScreen(this, selected.id(), selected.title()));
|
this.client.setScreen(new TransactionHistoryScreen(this, selected.id(), selected.title()));
|
||||||
}).dimensions(rightX, startY + 72, columnWidth, 20).build());
|
}).dimensions(rightX, startY + 72, columnWidth, 20).build());
|
||||||
|
|
||||||
|
webhookButton = this.addDrawableChild(ButtonWidget.builder(Text.literal("Включить вебхуки"), button -> {
|
||||||
|
if (this.client == null || bankUiService.getSelectedCard() == null) {
|
||||||
|
notifications.show(Text.literal("Сначала выбери или добавь карту"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.client.setScreen(new ConfirmScreen(confirmed -> {
|
||||||
|
if (this.client == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.client.setScreen(this);
|
||||||
|
if (!confirmed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
bankUiService.registerSelectedWebhookAsync().thenAccept(message -> this.client.execute(() -> {
|
||||||
|
notifications.showMessage(message);
|
||||||
|
this.clearAndInit();
|
||||||
|
}));
|
||||||
|
}, Text.literal("Включить обработку вебхуков?"),
|
||||||
|
Text.literal("Если другой вебхук уже подключен к карте — он может затереться."),
|
||||||
|
Text.literal("Включить"), Text.literal("Отмена")));
|
||||||
|
}).dimensions(rightX, startY + 96, columnWidth, 20).build());
|
||||||
|
|
||||||
this.addDrawableChild(ButtonWidget.builder(Text.literal("Назад"), button -> this.close())
|
this.addDrawableChild(ButtonWidget.builder(Text.literal("Назад"), button -> this.close())
|
||||||
.dimensions(rightX, startY + 120, columnWidth, 20)
|
.dimensions(rightX, startY + 144, columnWidth, 20)
|
||||||
.build());
|
.build());
|
||||||
|
|
||||||
if (cards.isEmpty()) {
|
if (cards.isEmpty()) {
|
||||||
@@ -143,5 +171,11 @@ public class CardScreen extends Screen {
|
|||||||
if (historyButton != null) {
|
if (historyButton != null) {
|
||||||
historyButton.active = !cards.isEmpty();
|
historyButton.active = !cards.isEmpty();
|
||||||
}
|
}
|
||||||
|
if (webhookButton != null) {
|
||||||
|
CardViewModel selected = bankUiService.getSelectedCard();
|
||||||
|
boolean enabled = selected != null && selected.webhookEnabled();
|
||||||
|
webhookButton.active = selected != null && !enabled;
|
||||||
|
webhookButton.setMessage(Text.literal(enabled ? "Вебхуки включены" : "Включить вебхуки"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package git.yawaflua.tech.spmega.client.ui;
|
|||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import git.yawaflua.tech.spmega.GpsHudPosition;
|
import git.yawaflua.tech.spmega.GpsHudPosition;
|
||||||
import git.yawaflua.tech.spmega.SPMega;
|
import git.yawaflua.tech.spmega.SPMega;
|
||||||
|
import git.yawaflua.tech.spmega.client.telemetry.InstrumentedHttpClient;
|
||||||
import net.minecraft.client.MinecraftClient;
|
import net.minecraft.client.MinecraftClient;
|
||||||
import net.minecraft.client.font.TextRenderer;
|
import net.minecraft.client.font.TextRenderer;
|
||||||
import net.minecraft.client.gui.DrawContext;
|
import net.minecraft.client.gui.DrawContext;
|
||||||
@@ -10,9 +11,7 @@ import net.minecraft.text.Text;
|
|||||||
import net.minecraft.world.World;
|
import net.minecraft.world.World;
|
||||||
|
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.net.http.HttpClient;
|
|
||||||
import java.net.http.HttpRequest;
|
import java.net.http.HttpRequest;
|
||||||
import java.net.http.HttpResponse;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
@@ -21,9 +20,8 @@ import java.util.concurrent.TimeUnit;
|
|||||||
|
|
||||||
public final class GpsHudRenderer {
|
public final class GpsHudRenderer {
|
||||||
private static final GpsHudRenderer INSTANCE = new GpsHudRenderer();
|
private static final GpsHudRenderer INSTANCE = new GpsHudRenderer();
|
||||||
private final Object citiesLock = new Object();
|
|
||||||
private boolean enabled = true;
|
private boolean enabled = true;
|
||||||
private List<City> cities = new ArrayList<>();
|
private volatile List<City> cities = List.of();
|
||||||
|
|
||||||
private GpsHudRenderer() {
|
private GpsHudRenderer() {
|
||||||
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||||
@@ -51,33 +49,35 @@ public final class GpsHudRenderer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void fetchCities() {
|
private void fetchCities() {
|
||||||
try {
|
|
||||||
HttpClient client = HttpClient.newHttpClient();
|
|
||||||
HttpRequest request = HttpRequest.newBuilder()
|
HttpRequest request = HttpRequest.newBuilder()
|
||||||
.uri(URI.create("https://spm-map.tonyaleksandr.ru/api/map/territories"))
|
.uri(URI.create("https://map.sp-mini.ru/api/map/territories"))
|
||||||
.GET()
|
.GET()
|
||||||
.build();
|
.build();
|
||||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
|
||||||
if (response.statusCode() == 200) {
|
new InstrumentedHttpClient().sendAsync(request)
|
||||||
|
.thenAccept(response -> {
|
||||||
|
if (response.statusCode() != 200) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
TerritoryWrapper[] parsed = new Gson().fromJson(response.body(), TerritoryWrapper[].class);
|
TerritoryWrapper[] parsed = new Gson().fromJson(response.body(), TerritoryWrapper[].class);
|
||||||
if (parsed != null) {
|
if (parsed == null) {
|
||||||
List<City> list = new ArrayList<>();
|
return;
|
||||||
for (TerritoryWrapper w : parsed) {
|
}
|
||||||
if (w != null && w.territory != null && w.territory.nether_portal != null && w.territory.nether_portal.length >= 2) {
|
List<City> updatedCities = new ArrayList<>();
|
||||||
City c = new City();
|
for (TerritoryWrapper wrapper : parsed) {
|
||||||
c.name = w.territory.name;
|
if (wrapper != null && wrapper.territory != null
|
||||||
c.netherX = w.territory.nether_portal[0];
|
&& wrapper.territory.nether_portal != null
|
||||||
c.netherZ = w.territory.nether_portal[1];
|
&& wrapper.territory.nether_portal.length >= 2) {
|
||||||
list.add(c);
|
City city = new City();
|
||||||
|
city.name = wrapper.territory.name;
|
||||||
|
city.netherX = wrapper.territory.nether_portal[0];
|
||||||
|
city.netherZ = wrapper.territory.nether_portal[1];
|
||||||
|
updatedCities.add(city);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
synchronized (citiesLock) {
|
cities = List.copyOf(updatedCities);
|
||||||
cities = list;
|
})
|
||||||
}
|
.exceptionally(ignored -> null);
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void render(DrawContext context, TextRenderer textRenderer, int width, int height) {
|
public void render(DrawContext context, TextRenderer textRenderer, int width, int height) {
|
||||||
@@ -103,13 +103,13 @@ public final class GpsHudRenderer {
|
|||||||
String offsetText = "§7Смещение: §f" + (playerLane.offset == 0 ? "0" : (playerLane.offset > 0 ? "+" + playerLane.offset : playerLane.offset));
|
String offsetText = "§7Смещение: §f" + (playerLane.offset == 0 ? "0" : (playerLane.offset > 0 ? "+" + playerLane.offset : playerLane.offset));
|
||||||
|
|
||||||
City nearestCity = null;
|
City nearestCity = null;
|
||||||
double minDistanceSq = Double.MAX_VALUE;
|
double minDistanceSquared = Double.MAX_VALUE;
|
||||||
for (City city : cities) {
|
for (City city : cities) {
|
||||||
double dx = playerX - (city.netherX / 8);
|
double dx = playerX - (city.netherX / 8);
|
||||||
double dz = playerZ - (city.netherZ / 8);
|
double dz = playerZ - (city.netherZ / 8);
|
||||||
double distSq = Math.sqrt(dx * dx + dz * dz);
|
double distanceSquared = dx * dx + dz * dz;
|
||||||
if (distSq < minDistanceSq) {
|
if (distanceSquared < minDistanceSquared) {
|
||||||
minDistanceSq = distSq;
|
minDistanceSquared = distanceSquared;
|
||||||
nearestCity = city;
|
nearestCity = city;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ public class MainBankScreen extends Screen {
|
|||||||
|
|
||||||
this.addDrawableChild(ButtonWidget.builder(Text.translatable("button.spmega.scan_qr"), button -> {
|
this.addDrawableChild(ButtonWidget.builder(Text.translatable("button.spmega.scan_qr"), button -> {
|
||||||
this.client.setScreen(null);
|
this.client.setScreen(null);
|
||||||
QRCodeScanner.ScanQrCode(this.client);
|
QRCodeScanner.scanQrCode(this.client);
|
||||||
}).dimensions(centerX - 60, y + 28, 120, 20).build());
|
}).dimensions(centerX - 60, y + 28, 120, 20).build());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import net.minecraft.text.Text;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.CompletableFuture;
|
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@@ -382,8 +381,7 @@ public class PaymentScreen extends Screen {
|
|||||||
}
|
}
|
||||||
lastRecipientLookup = username;
|
lastRecipientLookup = username;
|
||||||
|
|
||||||
CompletableFuture
|
bankUiService.loadRecipientCardsAsync(username)
|
||||||
.supplyAsync(() -> bankUiService.loadRecipientCards(username))
|
|
||||||
.thenAccept(cards -> {
|
.thenAccept(cards -> {
|
||||||
if (this.client == null) {
|
if (this.client == null) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package git.yawaflua.tech.spmega.client.ui;
|
|||||||
import git.yawaflua.tech.spmega.client.ui.service.BackendAuthenticator;
|
import git.yawaflua.tech.spmega.client.ui.service.BackendAuthenticator;
|
||||||
import git.yawaflua.tech.spmega.client.ui.service.BankDatabase.LocalTransaction;
|
import git.yawaflua.tech.spmega.client.ui.service.BankDatabase.LocalTransaction;
|
||||||
import git.yawaflua.tech.spmega.client.ui.service.BankUiService;
|
import git.yawaflua.tech.spmega.client.ui.service.BankUiService;
|
||||||
|
import net.minecraft.client.MinecraftClient;
|
||||||
import net.minecraft.client.gui.DrawContext;
|
import net.minecraft.client.gui.DrawContext;
|
||||||
import net.minecraft.client.gui.screen.Screen;
|
import net.minecraft.client.gui.screen.Screen;
|
||||||
import net.minecraft.client.gui.widget.ButtonWidget;
|
import net.minecraft.client.gui.widget.ButtonWidget;
|
||||||
@@ -19,6 +20,8 @@ public class TransactionHistoryScreen extends Screen {
|
|||||||
private final List<LocalTransaction> transactions = new ArrayList<>();
|
private final List<LocalTransaction> transactions = new ArrayList<>();
|
||||||
private boolean loading = true;
|
private boolean loading = true;
|
||||||
private String errorMessage = "";
|
private String errorMessage = "";
|
||||||
|
private int scrollOffset = 0;
|
||||||
|
private int currentPage = 1;
|
||||||
|
|
||||||
public TransactionHistoryScreen(Screen parent, String cardId, String cardTitle) {
|
public TransactionHistoryScreen(Screen parent, String cardId, String cardTitle) {
|
||||||
super(Text.literal("История транзакций"));
|
super(Text.literal("История транзакций"));
|
||||||
@@ -36,45 +39,114 @@ public class TransactionHistoryScreen extends Screen {
|
|||||||
.dimensions(centerX - 60, startY + 10, 120, 20)
|
.dimensions(centerX - 60, startY + 10, 120, 20)
|
||||||
.build());
|
.build());
|
||||||
|
|
||||||
|
// Scroll Up/Down buttons
|
||||||
|
this.addDrawableChild(ButtonWidget.builder(Text.literal("▲"), button -> scrollUp())
|
||||||
|
.dimensions(centerX + 140, 65, 20, 20)
|
||||||
|
.build());
|
||||||
|
|
||||||
|
this.addDrawableChild(ButtonWidget.builder(Text.literal("▼"), button -> scrollDown())
|
||||||
|
.dimensions(centerX + 140, 155, 20, 20)
|
||||||
|
.build());
|
||||||
|
|
||||||
|
// Prev Page button
|
||||||
|
this.addDrawableChild(ButtonWidget.builder(Text.literal("<"), button -> {
|
||||||
|
if (currentPage > 1) {
|
||||||
|
currentPage--;
|
||||||
|
scrollOffset = 0;
|
||||||
loadTransactions();
|
loadTransactions();
|
||||||
}
|
}
|
||||||
|
}).dimensions(centerX - 100, startY - 15, 30, 20).build());
|
||||||
|
|
||||||
|
// Next Page button
|
||||||
|
this.addDrawableChild(ButtonWidget.builder(Text.literal(">"), button -> {
|
||||||
|
currentPage++;
|
||||||
|
scrollOffset = 0;
|
||||||
|
loadTransactions();
|
||||||
|
}).dimensions(centerX + 70, startY - 15, 30, 20).build());
|
||||||
|
|
||||||
|
loadTransactions();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void scrollUp() {
|
||||||
|
if (scrollOffset > 0) {
|
||||||
|
scrollOffset--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void scrollDown() {
|
||||||
|
if (scrollOffset < Math.max(0, transactions.size() - 6)) {
|
||||||
|
scrollOffset++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Support pre-1.20.2 mouse scroll
|
||||||
|
public boolean mouseScrolled(double mouseX, double mouseY, double amount) {
|
||||||
|
if (amount > 0) {
|
||||||
|
scrollUp();
|
||||||
|
} else if (amount < 0) {
|
||||||
|
scrollDown();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Support 1.20.2+ mouse scroll
|
||||||
|
@Override
|
||||||
|
public boolean mouseScrolled(double mouseX, double mouseY, double horizontalAmount, double verticalAmount) {
|
||||||
|
if (verticalAmount > 0) {
|
||||||
|
scrollUp();
|
||||||
|
} else if (verticalAmount < 0) {
|
||||||
|
scrollDown();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
private void loadTransactions() {
|
private void loadTransactions() {
|
||||||
loading = true;
|
loading = true;
|
||||||
errorMessage = "";
|
errorMessage = "";
|
||||||
transactions.clear();
|
transactions.clear();
|
||||||
|
|
||||||
CompletableFuture.runAsync(() -> {
|
UiNotifications.instance().show(Text.literal("Загрузка..."));
|
||||||
try {
|
|
||||||
List<LocalTransaction> list = null;
|
int page = currentPage;
|
||||||
|
System.out.println("[SPMEGA] Transaction history loading started for card: " + cardId + ", page: " + page);
|
||||||
git.yawaflua.tech.spmega.ModConfig config = git.yawaflua.tech.spmega.SPMega.getConfig();
|
git.yawaflua.tech.spmega.ModConfig config = git.yawaflua.tech.spmega.SPMega.getConfig();
|
||||||
if (config != null && config.allowBackend()) {
|
CompletableFuture<List<LocalTransaction>> remote = config != null && config.allowBackend()
|
||||||
try {
|
? BackendAuthenticator.fetchTransactionsFromBackendAsync(cardId, page)
|
||||||
list = BackendAuthenticator.fetchTransactionsFromBackend(cardId);
|
.whenComplete((list, exception) -> {
|
||||||
} catch (Exception e) {
|
if (exception == null) {
|
||||||
System.err.println("[SPMEGA] Failed to fetch transactions from server, falling back to DB: " + e.getMessage());
|
System.out.println("[SPMEGA] Fetched " + list.size() + " transactions from backend.");
|
||||||
}
|
} else {
|
||||||
|
System.err.println("[SPMEGA] Failed to fetch transactions from server, falling back to DB: "
|
||||||
|
+ exception.getMessage());
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
.exceptionally(exception -> null)
|
||||||
|
: CompletableFuture.completedFuture(null);
|
||||||
|
|
||||||
if (list == null) {
|
remote.thenApply(list -> {
|
||||||
list = BankUiService.instance().getDatabase().loadTransferHistory(cardId);
|
if (list != null) {
|
||||||
|
return list;
|
||||||
}
|
}
|
||||||
|
List<LocalTransaction> local = BankUiService.instance().getDatabase().loadTransferHistory(cardId);
|
||||||
List<LocalTransaction> finalList = list;
|
System.out.println("[SPMEGA] Loaded " + local.size() + " transactions from database.");
|
||||||
if (this.client != null) {
|
return local;
|
||||||
this.client.execute(() -> {
|
})
|
||||||
this.transactions.addAll(finalList);
|
.whenComplete((list, exception) -> {
|
||||||
this.loading = false;
|
MinecraftClient minecraftClient = MinecraftClient.getInstance();
|
||||||
|
if (minecraftClient == null) {
|
||||||
|
System.out.println("[SPMEGA] MinecraftClient.getInstance() is null in loadTransactions callback!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
minecraftClient.execute(() -> {
|
||||||
|
if (exception != null) {
|
||||||
|
errorMessage = exception.getMessage();
|
||||||
|
} else {
|
||||||
|
System.out.println("[SPMEGA] Setting transactions list on main thread. Count: " + list.size());
|
||||||
|
transactions.addAll(list);
|
||||||
|
scrollOffset = 0;
|
||||||
|
}
|
||||||
|
loading = false;
|
||||||
});
|
});
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
if (this.client != null) {
|
|
||||||
this.client.execute(() -> {
|
|
||||||
this.errorMessage = e.getMessage();
|
|
||||||
this.loading = false;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,30 +163,38 @@ public class TransactionHistoryScreen extends Screen {
|
|||||||
|
|
||||||
int centerX = this.width / 2;
|
int centerX = this.width / 2;
|
||||||
int startY = 50;
|
int startY = 50;
|
||||||
|
int bottomStartY = this.height / 2 + 50;
|
||||||
|
|
||||||
context.drawCenteredTextWithShadow(this.textRenderer, this.title, centerX, 20, 0xFFFFFF);
|
context.drawCenteredTextWithShadow(this.textRenderer, this.title, centerX, 20, 0xFFFFFFFF);
|
||||||
context.drawCenteredTextWithShadow(this.textRenderer, Text.literal("Карта: " + cardTitle), centerX, 35, 0xBFBFBF);
|
context.drawCenteredTextWithShadow(this.textRenderer, Text.literal("Карта: " + cardTitle), centerX, 35, 0xFFBFBFBF);
|
||||||
|
context.drawCenteredTextWithShadow(this.textRenderer, Text.literal("Стр. " + currentPage), centerX, bottomStartY - 9, 0xFFFFFFFF);
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
context.drawCenteredTextWithShadow(this.textRenderer, Text.literal("Загрузка транзакций..."), centerX, this.height / 2 - 10, 0xCCCCCC);
|
context.drawCenteredTextWithShadow(this.textRenderer, Text.literal("Загрузка транзакций..."), centerX, this.height / 2 - 10, 0xFFCCCCCC);
|
||||||
} else if (!errorMessage.isEmpty()) {
|
} else if (!errorMessage.isEmpty()) {
|
||||||
context.drawCenteredTextWithShadow(this.textRenderer, Text.literal("Ошибка: " + errorMessage), centerX, this.height / 2 - 10, 0xFF5555);
|
context.drawCenteredTextWithShadow(this.textRenderer, Text.literal("Ошибка: " + errorMessage), centerX, this.height / 2 - 10, 0xFFFF5555);
|
||||||
} else if (transactions.isEmpty()) {
|
} else if (transactions.isEmpty()) {
|
||||||
context.drawCenteredTextWithShadow(this.textRenderer, Text.literal("Транзакций не найдено"), centerX, this.height / 2 - 10, 0xCCCCCC);
|
context.drawCenteredTextWithShadow(this.textRenderer, Text.literal("Транзакций не найдено"), centerX, this.height / 2 - 10, 0xFFCCCCCC);
|
||||||
} else {
|
} else {
|
||||||
int y = startY + 15;
|
int y = startY + 15;
|
||||||
for (int i = 0; i < Math.min(6, transactions.size()); i++) {
|
int limit = Math.min(6, transactions.size() - scrollOffset);
|
||||||
LocalTransaction tx = transactions.get(i);
|
for (int i = 0; i < limit; i++) {
|
||||||
|
LocalTransaction tx = transactions.get(scrollOffset + i);
|
||||||
|
|
||||||
String amountText = tx.amount() + " АР";
|
String amountText = tx.amount() + " АР";
|
||||||
String dateText = tx.createdAt();
|
String dateText = tx.createdAt();
|
||||||
|
if (dateText == null) {
|
||||||
|
dateText = "";
|
||||||
|
}
|
||||||
if (dateText.length() > 19) {
|
if (dateText.length() > 19) {
|
||||||
dateText = dateText.substring(0, 19).replace("T", " ");
|
dateText = dateText.substring(0, 19).replace("T", " ");
|
||||||
}
|
}
|
||||||
String commentText = tx.comment().isEmpty() ? "" : " (" + tx.comment() + ")";
|
String commentText = tx.comment().isEmpty() ? "" : " (" + tx.comment() + ")";
|
||||||
|
|
||||||
String line = String.format("%s -> %s | %s%s", dateText, tx.receiver(), amountText, commentText);
|
String line = String.format("%s -> %s | %s%s", dateText, tx.receiver(), amountText, commentText);
|
||||||
int color = tx.status().equalsIgnoreCase("SUCCESS") ? 0x55FF55 : 0xFF5555;
|
|
||||||
|
String status = tx.status();
|
||||||
|
int color = (status != null && status.equalsIgnoreCase("SUCCESS")) ? 0xFF55FF55 : 0xFFFF5555;
|
||||||
|
|
||||||
context.drawCenteredTextWithShadow(this.textRenderer, Text.literal(line), centerX, y, color);
|
context.drawCenteredTextWithShadow(this.textRenderer, Text.literal(line), centerX, y, color);
|
||||||
y += 18;
|
y += 18;
|
||||||
|
|||||||
@@ -5,17 +5,22 @@ import com.google.gson.JsonObject;
|
|||||||
import com.google.gson.JsonParser;
|
import com.google.gson.JsonParser;
|
||||||
import com.google.gson.Strictness;
|
import com.google.gson.Strictness;
|
||||||
import com.google.gson.stream.JsonReader;
|
import com.google.gson.stream.JsonReader;
|
||||||
|
import git.yawaflua.tech.spmega.GpsHudPosition;
|
||||||
|
import git.yawaflua.tech.spmega.SPMega;
|
||||||
import net.minecraft.client.font.TextRenderer;
|
import net.minecraft.client.font.TextRenderer;
|
||||||
import net.minecraft.client.gui.DrawContext;
|
import net.minecraft.client.gui.DrawContext;
|
||||||
import net.minecraft.text.Text;
|
import net.minecraft.text.Text;
|
||||||
|
|
||||||
import java.awt.*;
|
import java.awt.*;
|
||||||
|
import java.util.ArrayDeque;
|
||||||
|
import java.util.Queue;
|
||||||
|
|
||||||
public final class UiNotifications {
|
public final class UiNotifications {
|
||||||
private static final int DEFAULT_DURATION_TICKS = 70;
|
private static final int DEFAULT_DURATION_TICKS = 70;
|
||||||
private static final UiNotifications INSTANCE = new UiNotifications();
|
private static final UiNotifications INSTANCE = new UiNotifications();
|
||||||
|
|
||||||
private Text currentText = Text.empty();
|
private Text currentText = Text.empty();
|
||||||
|
private final Queue<Text> queuedTexts = new ArrayDeque<>();
|
||||||
private int remainingTicks;
|
private int remainingTicks;
|
||||||
|
|
||||||
private UiNotifications() {
|
private UiNotifications() {
|
||||||
@@ -62,6 +67,17 @@ public final class UiNotifications {
|
|||||||
show(Text.literal(extractMessage(message)));
|
show(Text.literal(extractMessage(message)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public synchronized void showQueued(Text text) {
|
||||||
|
if (text == null || text.getString().isBlank()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!isVisible()) {
|
||||||
|
show(text);
|
||||||
|
} else {
|
||||||
|
queuedTexts.add(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public synchronized void render(DrawContext context, TextRenderer textRenderer, int width, int height) {
|
public synchronized void render(DrawContext context, TextRenderer textRenderer, int width, int height) {
|
||||||
if (!isVisible()) {
|
if (!isVisible()) {
|
||||||
return;
|
return;
|
||||||
@@ -72,8 +88,18 @@ public final class UiNotifications {
|
|||||||
int textWidth = textRenderer.getWidth(message);
|
int textWidth = textRenderer.getWidth(message);
|
||||||
int boxWidth = textWidth + padding * 2;
|
int boxWidth = textWidth + padding * 2;
|
||||||
int boxHeight = textRenderer.fontHeight + padding * 2;
|
int boxHeight = textRenderer.fontHeight + padding * 2;
|
||||||
int x = width - boxWidth - 10;
|
GpsHudPosition position = SPMega.getConfig() == null
|
||||||
int y = height - boxHeight - 10;
|
? GpsHudPosition.BOTTOM_RIGHT
|
||||||
|
: SPMega.getConfig().notificationPosition();
|
||||||
|
int x = switch (position) {
|
||||||
|
case TOP_LEFT, BOTTOM_LEFT -> 10;
|
||||||
|
case TOP_CENTER, BOTTOM_CENTER -> (width - boxWidth) / 2;
|
||||||
|
case TOP_RIGHT, BOTTOM_RIGHT -> width - boxWidth - 10;
|
||||||
|
};
|
||||||
|
int y = switch (position) {
|
||||||
|
case TOP_LEFT, TOP_CENTER, TOP_RIGHT -> 10;
|
||||||
|
case BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT -> height - boxHeight - 10;
|
||||||
|
};
|
||||||
|
|
||||||
context.fill(x, y, x + boxWidth, y + boxHeight, Color.DARK_GRAY.getRGB());
|
context.fill(x, y, x + boxWidth, y + boxHeight, Color.DARK_GRAY.getRGB());
|
||||||
context.drawTextWithShadow(textRenderer, currentText, x + padding, y + padding, Color.WHITE.getRGB());
|
context.drawTextWithShadow(textRenderer, currentText, x + padding, y + padding, Color.WHITE.getRGB());
|
||||||
@@ -85,8 +111,8 @@ public final class UiNotifications {
|
|||||||
}
|
}
|
||||||
remainingTicks--;
|
remainingTicks--;
|
||||||
if (remainingTicks <= 0) {
|
if (remainingTicks <= 0) {
|
||||||
currentText = Text.empty();
|
currentText = queuedTexts.isEmpty() ? Text.empty() : queuedTexts.remove();
|
||||||
remainingTicks = 0;
|
remainingTicks = currentText.getString().isBlank() ? 0 : DEFAULT_DURATION_TICKS;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+256
-105
@@ -1,59 +1,65 @@
|
|||||||
package git.yawaflua.tech.spmega.client.ui.service;
|
package git.yawaflua.tech.spmega.client.ui.service;
|
||||||
|
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
import com.google.gson.JsonParser;
|
import com.google.gson.JsonParser;
|
||||||
import com.mojang.authlib.exceptions.AuthenticationException;
|
import com.mojang.authlib.exceptions.AuthenticationException;
|
||||||
import com.mojang.authlib.minecraft.MinecraftSessionService;
|
import com.mojang.authlib.minecraft.MinecraftSessionService;
|
||||||
import git.yawaflua.tech.spmega.ModConfig;
|
import git.yawaflua.tech.spmega.ModConfig;
|
||||||
import git.yawaflua.tech.spmega.SPMega;
|
import git.yawaflua.tech.spmega.SPMega;
|
||||||
|
import git.yawaflua.tech.spmega.client.telemetry.InstrumentedHttpClient;
|
||||||
import net.minecraft.client.MinecraftClient;
|
import net.minecraft.client.MinecraftClient;
|
||||||
import net.minecraft.client.session.Session;
|
import net.minecraft.client.session.Session;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.net.http.HttpClient;
|
|
||||||
import java.net.http.HttpRequest;
|
import java.net.http.HttpRequest;
|
||||||
import java.net.http.HttpResponse;
|
import java.net.http.HttpResponse;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.CompletionException;
|
||||||
|
|
||||||
public class BackendAuthenticator {
|
public final class BackendAuthenticator {
|
||||||
|
|
||||||
public static boolean authenticate(MinecraftClient client) {
|
private BackendAuthenticator() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CompletableFuture<Boolean> authenticateAsync(MinecraftClient client) {
|
||||||
Session session = client.getSession();
|
Session session = client.getSession();
|
||||||
if (session == null || session.getUuidOrNull() == null) {
|
if (session == null || session.getUuidOrNull() == null) {
|
||||||
System.err.println("Cannot authenticate: Client has no valid session.");
|
System.err.println("Cannot authenticate: Client has no valid session.");
|
||||||
return false;
|
return CompletableFuture.completedFuture(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
MinecraftSessionService sessionService = client.getApiServices().sessionService();
|
MinecraftSessionService sessionService = client.getApiServices().sessionService();
|
||||||
|
return sendStartSessionRequestToBackendAsync(session.getUsername(), session.getUuidOrNull())
|
||||||
try {
|
.thenCompose(serverId -> CompletableFuture.runAsync(() -> {
|
||||||
var serverId = sendStartSessionRequestToBackend(session.getUsername(), session.getUuidOrNull());
|
|
||||||
System.out.println("[SPMEGA] Trying to auth in mojang with serverId: " + serverId);
|
System.out.println("[SPMEGA] Trying to auth in mojang with serverId: " + serverId);
|
||||||
sessionService.joinServer(
|
try {
|
||||||
session.getUuidOrNull(),
|
sessionService.joinServer(session.getUuidOrNull(), session.getAccessToken(), serverId);
|
||||||
session.getAccessToken(),
|
} catch (AuthenticationException exception) {
|
||||||
serverId
|
throw new CompletionException(exception);
|
||||||
);
|
}
|
||||||
|
})
|
||||||
|
.thenCompose(ignored -> {
|
||||||
System.out.println("[SPMEGA] Sending session submitter to backend");
|
System.out.println("[SPMEGA] Sending session submitter to backend");
|
||||||
|
return sendAuthRequestToBackendAsync(session.getUuidOrNull(), serverId);
|
||||||
return sendAuthRequestToBackend(session.getUuidOrNull(), serverId);
|
}))
|
||||||
|
.exceptionally(throwable -> {
|
||||||
} catch (AuthenticationException e) {
|
Throwable cause = throwable.getCause() == null ? throwable : throwable.getCause();
|
||||||
System.err.println("I cant auth by Mojang: " + e.getMessage());
|
if (cause instanceof AuthenticationException) {
|
||||||
|
System.err.println("I cant auth by Mojang: " + cause.getMessage());
|
||||||
System.err.println("Please check your credentials and try again.");
|
System.err.println("Please check your credentials and try again.");
|
||||||
return false;
|
} else {
|
||||||
|
System.err.println("Failed to authenticate with backend: " + cause.getMessage());
|
||||||
} catch (Exception e) {
|
|
||||||
System.err.println("Failed to authenticate with backend: " + e.getMessage());
|
|
||||||
return false;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String sendStartSessionRequestToBackend(String username, UUID uuid) throws IOException, InterruptedException {
|
private static CompletableFuture<String> sendStartSessionRequestToBackendAsync(String username, UUID uuid) {
|
||||||
ModConfig config = SPMega.getConfig();
|
ModConfig config = SPMega.getConfig();
|
||||||
String apiDomain = (config != null) ? config.apiDomain() : ModConfig.DEFAULT_API_DOMAIN;
|
String apiDomain = (config != null) ? config.apiDomain() : ModConfig.DEFAULT_API_DOMAIN;
|
||||||
if (apiDomain == null || apiDomain.isBlank()) {
|
if (apiDomain == null || apiDomain.isBlank()) {
|
||||||
@@ -70,29 +76,29 @@ public class BackendAuthenticator {
|
|||||||
|
|
||||||
String url = apiDomain + "/api/v1/auth/start";
|
String url = apiDomain + "/api/v1/auth/start";
|
||||||
|
|
||||||
HttpClient httpClient = HttpClient.newHttpClient();
|
InstrumentedHttpClient httpClient = new InstrumentedHttpClient();
|
||||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.header("Accept", "application/json")
|
.header("Accept", "application/json")
|
||||||
.method("POST", HttpRequest.BodyPublishers.ofString(requestBody))
|
.method("POST", HttpRequest.BodyPublishers.ofString(requestBody))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
return httpClient.sendAsync(request).thenApply(response -> {
|
||||||
if (response.statusCode() != 200) {
|
if (response.statusCode() != 200) {
|
||||||
System.err.println("[SPMEGA] Server returned status code " + response.statusCode() + " on start: " + response.body());
|
System.err.println("[SPMEGA] Server returned status code " + response.statusCode() + " on start: " + response.body());
|
||||||
throw new IOException("Server returned status code " + response.statusCode() + " on start: " + response.body());
|
throw new CompletionException(new IOException(
|
||||||
|
"Server returned status code " + response.statusCode() + " on start: " + response.body()));
|
||||||
}
|
}
|
||||||
|
|
||||||
JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject();
|
JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject();
|
||||||
if (json.has("sessionId")) {
|
if (!json.has("sessionId")) {
|
||||||
return json.get("sessionId").getAsString();
|
|
||||||
} else {
|
|
||||||
System.err.println("[SPMEGA] Invalid response from start endpoint: " + response.body());
|
System.err.println("[SPMEGA] Invalid response from start endpoint: " + response.body());
|
||||||
throw new IOException("Invalid response from start endpoint: " + response.body());
|
throw new CompletionException(new IOException("Invalid response from start endpoint: " + response.body()));
|
||||||
}
|
}
|
||||||
|
return json.get("sessionId").getAsString();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean sendAuthRequestToBackend(UUID uuid, String serverId) throws IOException, InterruptedException {
|
private static CompletableFuture<Boolean> sendAuthRequestToBackendAsync(UUID uuid, String serverId) {
|
||||||
ModConfig config = SPMega.getConfig();
|
ModConfig config = SPMega.getConfig();
|
||||||
String apiDomain = (config != null) ? config.apiDomain() : ModConfig.DEFAULT_API_DOMAIN;
|
String apiDomain = (config != null) ? config.apiDomain() : ModConfig.DEFAULT_API_DOMAIN;
|
||||||
if (apiDomain == null || apiDomain.isBlank()) {
|
if (apiDomain == null || apiDomain.isBlank()) {
|
||||||
@@ -109,42 +115,37 @@ public class BackendAuthenticator {
|
|||||||
|
|
||||||
String url = apiDomain + "/api/v1/auth/validate";
|
String url = apiDomain + "/api/v1/auth/validate";
|
||||||
|
|
||||||
HttpClient httpClient = HttpClient.newHttpClient();
|
InstrumentedHttpClient httpClient = new InstrumentedHttpClient();
|
||||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.header("Accept", "application/json")
|
.header("Accept", "application/json")
|
||||||
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
|
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
return httpClient.sendAsync(request).thenApply(response -> {
|
||||||
if (response.statusCode() != 200) {
|
if (response.statusCode() != 200) {
|
||||||
System.err.println("[SPMEGA] Server returned status code " + response.statusCode() + " on validate: " + response.body());
|
System.err.println("[SPMEGA] Server returned status code " + response.statusCode() + " on validate: " + response.body());
|
||||||
throw new IOException("Server returned status code " + response.statusCode() + " on validate: " + response.body());
|
throw new CompletionException(new IOException(
|
||||||
|
"Server returned status code " + response.statusCode() + " on validate: " + response.body()));
|
||||||
|
}
|
||||||
|
JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject();
|
||||||
|
if (!json.has("token")) {
|
||||||
|
System.err.println("[SPMEGA] Invalid response from validate endpoint: " + response.body());
|
||||||
|
throw new CompletionException(new IOException("Invalid response from validate endpoint: " + response.body()));
|
||||||
|
}
|
||||||
|
if (config == null) {
|
||||||
|
System.err.println("[SPMEGA] Config is null, cannot save token.");
|
||||||
|
throw new CompletionException(new IOException("Config is null, cannot save token."));
|
||||||
}
|
}
|
||||||
|
|
||||||
JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject();
|
|
||||||
if (json.has("token")) {
|
|
||||||
String token = json.get("token").getAsString();
|
String token = json.get("token").getAsString();
|
||||||
if (config != null) {
|
SPMega.setConfig(new ModConfig(
|
||||||
ModConfig updated = new ModConfig(
|
config.apiDomain(), token, config.allowBackend(), config.signQuickPayEnabled(),
|
||||||
config.apiDomain(),
|
config.gpsEnabled(), config.gpsPosition(), config.notificationPosition(),
|
||||||
token,
|
config.telemetryIntervalSeconds(), config.telemetryCollectSystemInfo()));
|
||||||
config.allowBackend(),
|
|
||||||
config.signQuickPayEnabled(),
|
|
||||||
config.gpsEnabled(),
|
|
||||||
config.gpsPosition()
|
|
||||||
);
|
|
||||||
SPMega.setConfig(updated);
|
|
||||||
System.out.println("[SPMEGA] Backend auth successful, saved token.");
|
System.out.println("[SPMEGA] Backend auth successful, saved token.");
|
||||||
return true;
|
return true;
|
||||||
} else {
|
});
|
||||||
System.err.println("[SPMEGA] Config is null, cannot save token.");
|
|
||||||
throw new IOException("Config is null, cannot save token.");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
System.err.println("[SPMEGA] Invalid response from validate endpoint: " + response.body());
|
|
||||||
throw new IOException("Invalid response from validate endpoint: " + response.body());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void sendCardToBackend(String cardId, String cardToken) {
|
public static void sendCardToBackend(String cardId, String cardToken) {
|
||||||
@@ -168,7 +169,7 @@ public class BackendAuthenticator {
|
|||||||
jsonPayload.addProperty("token", cardToken);
|
jsonPayload.addProperty("token", cardToken);
|
||||||
String requestBody = jsonPayload.toString();
|
String requestBody = jsonPayload.toString();
|
||||||
|
|
||||||
HttpClient httpClient = HttpClient.newHttpClient();
|
InstrumentedHttpClient httpClient = new InstrumentedHttpClient();
|
||||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.header("Accept", "application/json")
|
.header("Accept", "application/json")
|
||||||
@@ -176,7 +177,7 @@ public class BackendAuthenticator {
|
|||||||
.PUT(HttpRequest.BodyPublishers.ofString(requestBody))
|
.PUT(HttpRequest.BodyPublishers.ofString(requestBody))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
httpClient.sendAsync(request)
|
||||||
.thenAccept(response -> {
|
.thenAccept(response -> {
|
||||||
if (response.statusCode() != 200 && response.statusCode() != 204) {
|
if (response.statusCode() != 200 && response.statusCode() != 204) {
|
||||||
System.err.println("[SPMEGA] Failed to send card to backend: status code "
|
System.err.println("[SPMEGA] Failed to send card to backend: status code "
|
||||||
@@ -191,10 +192,10 @@ public class BackendAuthenticator {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<CardCredentials> fetchCardsFromBackend() throws IOException, InterruptedException {
|
public static CompletableFuture<List<CardCredentials>> fetchCardsFromBackendAsync() {
|
||||||
ModConfig config = SPMega.getConfig();
|
ModConfig config = SPMega.getConfig();
|
||||||
if (config == null || !config.allowBackend()) {
|
if (config == null || !config.allowBackend()) {
|
||||||
return List.of();
|
return CompletableFuture.completedFuture(List.of());
|
||||||
}
|
}
|
||||||
|
|
||||||
String apiDomain = config.apiDomain();
|
String apiDomain = config.apiDomain();
|
||||||
@@ -207,41 +208,36 @@ public class BackendAuthenticator {
|
|||||||
|
|
||||||
String url = apiDomain + "/api/v1/auth/cards";
|
String url = apiDomain + "/api/v1/auth/cards";
|
||||||
|
|
||||||
HttpClient httpClient = HttpClient.newHttpClient();
|
InstrumentedHttpClient httpClient = new InstrumentedHttpClient();
|
||||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||||
.header("Accept", "application/json")
|
.header("Accept", "application/json")
|
||||||
.header("Authorization", "Bearer " + config.apiToken())
|
.header("Authorization", "Bearer " + config.apiToken())
|
||||||
.GET()
|
.GET()
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
return httpClient.sendAsync(request).thenApply(response -> {
|
||||||
if (response.statusCode() != 200) {
|
if (response.statusCode() != 200) {
|
||||||
throw new IOException("Server returned status code " + response.statusCode() + " on fetch cards.");
|
throw new CompletionException(new IOException(
|
||||||
|
"Server returned status code " + response.statusCode() + " on fetch cards."));
|
||||||
}
|
}
|
||||||
|
|
||||||
com.google.gson.JsonArray cardsArray = JsonParser.parseString(response.body()).getAsJsonArray();
|
com.google.gson.JsonArray cardsArray = JsonParser.parseString(response.body()).getAsJsonArray();
|
||||||
List<CardCredentials> cards = new ArrayList<>();
|
List<CardCredentials> cards = new ArrayList<>();
|
||||||
for (com.google.gson.JsonElement el : cardsArray) {
|
for (com.google.gson.JsonElement element : cardsArray) {
|
||||||
JsonObject cardJson = el.getAsJsonObject();
|
JsonObject cardJson = element.getAsJsonObject();
|
||||||
String cardId = "";
|
String cardId = cardJson.has("cardId") && !cardJson.get("cardId").isJsonNull()
|
||||||
if (cardJson.has("cardId") && !cardJson.get("cardId").isJsonNull()) {
|
? cardJson.get("cardId").getAsString()
|
||||||
cardId = cardJson.get("cardId").getAsString();
|
: (cardJson.has("id") && !cardJson.get("id").isJsonNull() ? cardJson.get("id").getAsString() : "");
|
||||||
} else if (cardJson.has("id") && !cardJson.get("id").isJsonNull()) {
|
String cardToken = cardJson.has("cardToken") && !cardJson.get("cardToken").isJsonNull()
|
||||||
cardId = cardJson.get("id").getAsString();
|
? cardJson.get("cardToken").getAsString()
|
||||||
}
|
: (cardJson.has("token") && !cardJson.get("token").isJsonNull() ? cardJson.get("token").getAsString() : "");
|
||||||
|
boolean webhookEnabled = cardJson.has("webhookConnected")
|
||||||
String cardToken = "";
|
&& cardJson.get("webhookConnected").getAsBoolean();
|
||||||
if (cardJson.has("cardToken") && !cardJson.get("cardToken").isJsonNull()) {
|
|
||||||
cardToken = cardJson.get("cardToken").getAsString();
|
|
||||||
} else if (cardJson.has("token") && !cardJson.get("token").isJsonNull()) {
|
|
||||||
cardToken = cardJson.get("token").getAsString();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cardId.isEmpty() && !cardToken.isEmpty()) {
|
if (!cardId.isEmpty() && !cardToken.isEmpty()) {
|
||||||
cards.add(new CardCredentials(cardId, cardToken));
|
cards.add(new CardCredentials(cardId, cardToken, webhookEnabled));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return cards;
|
return cards;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void deleteCardOnBackend(String cardId) {
|
public static void deleteCardOnBackend(String cardId) {
|
||||||
@@ -260,14 +256,14 @@ public class BackendAuthenticator {
|
|||||||
|
|
||||||
String url = apiDomain + "/api/v1/auth/cards/" + cardId;
|
String url = apiDomain + "/api/v1/auth/cards/" + cardId;
|
||||||
|
|
||||||
HttpClient httpClient = HttpClient.newHttpClient();
|
InstrumentedHttpClient httpClient = new InstrumentedHttpClient();
|
||||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||||
.header("Accept", "application/json")
|
.header("Accept", "application/json")
|
||||||
.header("Authorization", "Bearer " + config.apiToken())
|
.header("Authorization", "Bearer " + config.apiToken())
|
||||||
.DELETE()
|
.DELETE()
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
httpClient.sendAsync(request)
|
||||||
.thenAccept(response -> {
|
.thenAccept(response -> {
|
||||||
if (response.statusCode() != 200 && response.statusCode() != 204) {
|
if (response.statusCode() != 200 && response.statusCode() != 204) {
|
||||||
System.err.println("[SPMEGA] Failed to delete card from backend: status code "
|
System.err.println("[SPMEGA] Failed to delete card from backend: status code "
|
||||||
@@ -282,10 +278,87 @@ public class BackendAuthenticator {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean createTransactionOnBackend(String senderCardId, String receiver, long amount, String comment) throws IOException, InterruptedException {
|
public static CompletableFuture<Void> registerWebhookForCardAsync(String cardId) {
|
||||||
|
ModConfig config = SPMega.getConfig();
|
||||||
|
if (config == null || !config.allowBackend()) {
|
||||||
|
return CompletableFuture.failedFuture(new IOException("Backend is disabled"));
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpRequest request = HttpRequest.newBuilder(URI.create(backendUrl(config, "/api/v1/webhook/" + cardId)))
|
||||||
|
.header("Accept", "application/json")
|
||||||
|
.header("Authorization", "Bearer " + config.apiToken())
|
||||||
|
.PUT(HttpRequest.BodyPublishers.noBody())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return new InstrumentedHttpClient().sendAsync(request).thenApply(response -> {
|
||||||
|
if (response.statusCode() != 200 && response.statusCode() != 204) {
|
||||||
|
throw new CompletionException(new IOException(
|
||||||
|
"Server returned status code " + response.statusCode() + ": " + response.body()));
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CompletableFuture<List<PaymentNotification>> readNotificationsAsync() {
|
||||||
|
ModConfig config = SPMega.getConfig();
|
||||||
|
if (config == null || !config.allowBackend()
|
||||||
|
|| config.apiToken() == null || config.apiToken().isBlank()
|
||||||
|
|| ModConfig.DEFAULT_API_TOKEN.equals(config.apiToken())) {
|
||||||
|
return CompletableFuture.completedFuture(List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpRequest request = HttpRequest.newBuilder(URI.create(backendUrl(config, "/api/v1/webhook/read")))
|
||||||
|
.header("Accept", "application/json")
|
||||||
|
.header("Authorization", "Bearer " + config.apiToken())
|
||||||
|
.GET()
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return new InstrumentedHttpClient().sendAsync(request).thenApply(response -> {
|
||||||
|
if (response.statusCode() != 200) {
|
||||||
|
throw new CompletionException(new IOException(
|
||||||
|
"Server returned status code " + response.statusCode() + " on notification read."));
|
||||||
|
}
|
||||||
|
JsonElement parsed = JsonParser.parseString(response.body());
|
||||||
|
com.google.gson.JsonArray array = parsed.isJsonArray()
|
||||||
|
? parsed.getAsJsonArray()
|
||||||
|
: parsed.getAsJsonObject().getAsJsonArray("$values");
|
||||||
|
if (array == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<PaymentNotification> notifications = new ArrayList<>();
|
||||||
|
for (JsonElement element : array) {
|
||||||
|
JsonObject json = element.getAsJsonObject();
|
||||||
|
notifications.add(new PaymentNotification(
|
||||||
|
stringValue(json, "id"),
|
||||||
|
stringValue(json, "senderName"),
|
||||||
|
stringValue(json, "senderNumber"),
|
||||||
|
stringValue(json, "comment"),
|
||||||
|
json.has("amount") ? json.get("amount").getAsInt() : 0,
|
||||||
|
stringValue(json, "type")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
return notifications;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String backendUrl(ModConfig config, String path) {
|
||||||
|
String domain = config.apiDomain();
|
||||||
|
if (domain == null || domain.isBlank()) {
|
||||||
|
domain = ModConfig.DEFAULT_API_DOMAIN;
|
||||||
|
}
|
||||||
|
return (domain.endsWith("/") ? domain.substring(0, domain.length() - 1) : domain) + path;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String stringValue(JsonObject json, String name) {
|
||||||
|
return json.has(name) && !json.get(name).isJsonNull() ? json.get(name).getAsString() : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CompletableFuture<Boolean> createTransactionOnBackendAsync(
|
||||||
|
String senderCardId, String receiver, long amount, String comment) {
|
||||||
ModConfig config = SPMega.getConfig();
|
ModConfig config = SPMega.getConfig();
|
||||||
if (config == null) {
|
if (config == null) {
|
||||||
throw new IOException("ModConfig is null");
|
return CompletableFuture.failedFuture(new IOException("ModConfig is null"));
|
||||||
}
|
}
|
||||||
|
|
||||||
String apiDomain = config.apiDomain();
|
String apiDomain = config.apiDomain();
|
||||||
@@ -299,15 +372,15 @@ public class BackendAuthenticator {
|
|||||||
String url = apiDomain + "/api/v1/transactions";
|
String url = apiDomain + "/api/v1/transactions";
|
||||||
|
|
||||||
JsonObject jsonPayload = new JsonObject();
|
JsonObject jsonPayload = new JsonObject();
|
||||||
jsonPayload.addProperty("senderCardId", senderCardId);
|
jsonPayload.addProperty("cardToUse", senderCardId);
|
||||||
jsonPayload.addProperty("cardId", senderCardId);
|
jsonPayload.addProperty("cardId", senderCardId);
|
||||||
jsonPayload.addProperty("receiver", receiver);
|
jsonPayload.addProperty("receiverCard", receiver);
|
||||||
jsonPayload.addProperty("recipient", receiver);
|
jsonPayload.addProperty("receiverName", receiver);
|
||||||
jsonPayload.addProperty("amount", amount);
|
jsonPayload.addProperty("amount", amount);
|
||||||
jsonPayload.addProperty("comment", comment);
|
jsonPayload.addProperty("comment", comment);
|
||||||
String requestBody = jsonPayload.toString();
|
String requestBody = jsonPayload.toString();
|
||||||
|
|
||||||
HttpClient httpClient = HttpClient.newHttpClient();
|
InstrumentedHttpClient httpClient = new InstrumentedHttpClient();
|
||||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.header("Accept", "application/json")
|
.header("Accept", "application/json")
|
||||||
@@ -315,18 +388,22 @@ public class BackendAuthenticator {
|
|||||||
.PUT(HttpRequest.BodyPublishers.ofString(requestBody))
|
.PUT(HttpRequest.BodyPublishers.ofString(requestBody))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
return httpClient.sendAsync(request).thenApply(response -> {
|
||||||
if (response.statusCode() == 200 || response.statusCode() == 201 || response.statusCode() == 204) {
|
if (response.statusCode() != 200 && response.statusCode() != 201 && response.statusCode() != 204) {
|
||||||
return true;
|
throw new CompletionException(new IOException(
|
||||||
} else {
|
"Server returned status code " + response.statusCode() + ": " + response.body()));
|
||||||
throw new IOException("Server returned status code " + response.statusCode() + ": " + response.body());
|
|
||||||
}
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<BankDatabase.LocalTransaction> fetchTransactionsFromBackend(String cardId) throws IOException, InterruptedException {
|
public static CompletableFuture<List<BankDatabase.LocalTransaction>> fetchTransactionsFromBackendAsync(
|
||||||
|
String cardId, int page) {
|
||||||
|
System.out.println("[SPMEGA] fetchTransactionsFromBackend called for cardId: " + cardId + ", page: " + page);
|
||||||
ModConfig config = SPMega.getConfig();
|
ModConfig config = SPMega.getConfig();
|
||||||
if (config == null || !config.allowBackend()) {
|
if (config == null || !config.allowBackend()) {
|
||||||
return List.of();
|
System.out.println("[SPMEGA] fetchTransactionsFromBackend aborted: config is null or backend not allowed.");
|
||||||
|
return CompletableFuture.completedFuture(List.of());
|
||||||
}
|
}
|
||||||
|
|
||||||
String apiDomain = config.apiDomain();
|
String apiDomain = config.apiDomain();
|
||||||
@@ -337,32 +414,106 @@ public class BackendAuthenticator {
|
|||||||
apiDomain = apiDomain.substring(0, apiDomain.length() - 1);
|
apiDomain = apiDomain.substring(0, apiDomain.length() - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
String url = apiDomain + "/api/v1/transactions?cardId=" + cardId;
|
String url = apiDomain + "/api/v1/transactions?p=" + page;
|
||||||
|
System.out.println("[SPMEGA] Requesting transactions from URL: " + url);
|
||||||
|
|
||||||
HttpClient httpClient = HttpClient.newHttpClient();
|
InstrumentedHttpClient httpClient = new InstrumentedHttpClient();
|
||||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||||
.header("Accept", "application/json")
|
.header("Accept", "application/json")
|
||||||
.header("Authorization", "Bearer " + config.apiToken())
|
.header("Authorization", "Bearer " + config.apiToken())
|
||||||
.GET()
|
.GET()
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
return httpClient.sendAsync(request)
|
||||||
if (response.statusCode() != 200) {
|
.thenApply(response -> parseTransactionsResponse(response, cardId));
|
||||||
throw new IOException("Server returned status code " + response.statusCode() + " on fetch transactions.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
com.google.gson.JsonArray transactionsArray = JsonParser.parseString(response.body()).getAsJsonArray();
|
private static List<BankDatabase.LocalTransaction> parseTransactionsResponse(
|
||||||
|
HttpResponse<String> response, String cardId) {
|
||||||
|
System.out.println("[SPMEGA] Response status code: " + response.statusCode());
|
||||||
|
if (response.statusCode() != 200) {
|
||||||
|
System.err.println("[SPMEGA] Failed response body: " + response.body());
|
||||||
|
throw new CompletionException(new IOException(
|
||||||
|
"Server returned status code " + response.statusCode() + " on fetch transactions."));
|
||||||
|
}
|
||||||
|
|
||||||
|
String body = response.body();
|
||||||
|
System.out.println("[SPMEGA] Response body: " + (body.length() > 500 ? body.substring(0, 500) + "..." : body));
|
||||||
|
|
||||||
|
JsonElement parsed = JsonParser.parseString(body);
|
||||||
|
com.google.gson.JsonArray transactionsArray = null;
|
||||||
|
|
||||||
|
if (parsed.isJsonArray()) {
|
||||||
|
transactionsArray = parsed.getAsJsonArray();
|
||||||
|
} else if (parsed.isJsonObject()) {
|
||||||
|
JsonObject obj = parsed.getAsJsonObject();
|
||||||
|
if (obj.has("$values") && obj.get("$values").isJsonArray()) {
|
||||||
|
transactionsArray = obj.getAsJsonArray("$values");
|
||||||
|
} else if (obj.has("transactions") && obj.get("transactions").isJsonArray()) {
|
||||||
|
transactionsArray = obj.getAsJsonArray("transactions");
|
||||||
|
} else if (obj.has("values") && obj.get("values").isJsonArray()) {
|
||||||
|
transactionsArray = obj.getAsJsonArray("values");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (transactionsArray == null) {
|
||||||
|
System.err.println("[SPMEGA] Response body is not a JSON array or wrapped array: " + body);
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("[SPMEGA] Total transactions returned from server: " + transactionsArray.size());
|
||||||
List<BankDatabase.LocalTransaction> list = new ArrayList<>();
|
List<BankDatabase.LocalTransaction> list = new ArrayList<>();
|
||||||
for (com.google.gson.JsonElement el : transactionsArray) {
|
for (com.google.gson.JsonElement el : transactionsArray) {
|
||||||
|
try {
|
||||||
JsonObject json = el.getAsJsonObject();
|
JsonObject json = el.getAsJsonObject();
|
||||||
String receiver = json.has("receiver") ? json.get("receiver").getAsString() : (json.has("recipient") ? json.get("recipient").getAsString() : "unknown");
|
|
||||||
|
// Check cardId filter
|
||||||
|
String senderCardNumber = "";
|
||||||
|
if (json.has("senderCardNumber") && !json.get("senderCardNumber").isJsonNull()) {
|
||||||
|
senderCardNumber = json.get("senderCardNumber").getAsString();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!senderCardNumber.equalsIgnoreCase(cardId)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String receiver = "unknown";
|
||||||
|
if (json.has("receiver") && !json.get("receiver").isJsonNull()) {
|
||||||
|
receiver = json.get("receiver").getAsString();
|
||||||
|
} else if (json.has("receiverName") && !json.get("receiverName").isJsonNull()) {
|
||||||
|
receiver = json.get("receiverName").getAsString();
|
||||||
|
} else if (json.has("receiverCardNumber") && !json.get("receiverCardNumber").isJsonNull()) {
|
||||||
|
receiver = json.get("receiverCardNumber").getAsString();
|
||||||
|
} else if (json.has("recipient") && !json.get("recipient").isJsonNull()) {
|
||||||
|
receiver = json.get("recipient").getAsString();
|
||||||
|
}
|
||||||
|
|
||||||
long amount = json.has("amount") ? json.get("amount").getAsLong() : 0L;
|
long amount = json.has("amount") ? json.get("amount").getAsLong() : 0L;
|
||||||
String comment = json.has("comment") && !json.get("comment").isJsonNull() ? json.get("comment").getAsString() : "";
|
String comment = json.has("comment") && !json.get("comment").isJsonNull() ? json.get("comment").getAsString() : "";
|
||||||
String status = json.has("status") ? json.get("status").getAsString() : "SUCCESS";
|
String status = json.has("status") && !json.get("status").isJsonNull() ? json.get("status").getAsString() : "SUCCESS";
|
||||||
String createdAt = json.has("createdAt") ? json.get("createdAt").getAsString() : (json.has("created_at") ? json.get("created_at").getAsString() : "");
|
|
||||||
|
String createdAt = "";
|
||||||
|
if (json.has("transactionDate") && !json.get("transactionDate").isJsonNull()) {
|
||||||
|
createdAt = json.get("transactionDate").getAsString();
|
||||||
|
} else if (json.has("createdAt") && !json.get("createdAt").isJsonNull()) {
|
||||||
|
createdAt = json.get("createdAt").getAsString();
|
||||||
|
} else if (json.has("created_at") && !json.get("created_at").isJsonNull()) {
|
||||||
|
createdAt = json.get("created_at").getAsString();
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.printf("[SPMEGA] Parsed transaction: %s -> %s, amount=%d, comment=%s, status=%s%n",
|
||||||
|
createdAt, receiver, amount, comment, status);
|
||||||
|
|
||||||
list.add(new BankDatabase.LocalTransaction(receiver, amount, comment, status, createdAt));
|
list.add(new BankDatabase.LocalTransaction(receiver, amount, comment, status, createdAt));
|
||||||
|
} catch (Exception parseEx) {
|
||||||
|
System.err.println("[SPMEGA] Error parsing transaction element: " + parseEx.getMessage());
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
System.out.println("[SPMEGA] Returning " + list.size() + " filtered transactions for card " + cardId);
|
||||||
return list;
|
return list;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public record PaymentNotification(
|
||||||
|
String id, String senderName, String senderNumber, String comment, int amount, String type) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,9 +23,23 @@ public final class BankDatabase {
|
|||||||
card_number TEXT,
|
card_number TEXT,
|
||||||
balance INTEGER NOT NULL DEFAULT 0,
|
balance INTEGER NOT NULL DEFAULT 0,
|
||||||
owner_uuid TEXT,
|
owner_uuid TEXT,
|
||||||
|
webhook_enabled INTEGER NOT NULL DEFAULT 0,
|
||||||
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
|
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
|
||||||
)
|
)
|
||||||
""");
|
""");
|
||||||
|
boolean hasWebhookColumn = false;
|
||||||
|
try (ResultSet columns = statement.executeQuery("PRAGMA table_info(cards)")) {
|
||||||
|
while (columns.next()) {
|
||||||
|
if ("webhook_enabled".equals(columns.getString("name"))) {
|
||||||
|
hasWebhookColumn = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasWebhookColumn) {
|
||||||
|
statement.executeUpdate(
|
||||||
|
"ALTER TABLE cards ADD COLUMN webhook_enabled INTEGER NOT NULL DEFAULT 0");
|
||||||
|
}
|
||||||
statement.executeUpdate("""
|
statement.executeUpdate("""
|
||||||
CREATE TABLE IF NOT EXISTS transfer_history (
|
CREATE TABLE IF NOT EXISTS transfer_history (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
@@ -100,8 +114,31 @@ public final class BankDatabase {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public synchronized void setWebhookEnabled(String cardId, boolean enabled) {
|
||||||
|
String sql = "UPDATE cards SET webhook_enabled = ?, updated_at = CURRENT_TIMESTAMP WHERE card_id = ?";
|
||||||
|
try (Connection connection = open(); PreparedStatement statement = connection.prepareStatement(sql)) {
|
||||||
|
statement.setBoolean(1, enabled);
|
||||||
|
statement.setString(2, cardId);
|
||||||
|
statement.executeUpdate();
|
||||||
|
} catch (SQLException exception) {
|
||||||
|
throw new RuntimeException("Failed to update webhook state", exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized boolean hasWebhookEnabledCards() {
|
||||||
|
try (Connection connection = open();
|
||||||
|
PreparedStatement statement = connection.prepareStatement(
|
||||||
|
"SELECT 1 FROM cards WHERE webhook_enabled = 1 LIMIT 1");
|
||||||
|
ResultSet result = statement.executeQuery()) {
|
||||||
|
return result.next();
|
||||||
|
} catch (SQLException exception) {
|
||||||
|
throw new RuntimeException("Failed to read webhook state", exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public synchronized List<StoredCard> loadCards() {
|
public synchronized List<StoredCard> loadCards() {
|
||||||
String sql = "SELECT card_id, card_token, card_name, card_number, balance, owner_uuid FROM cards ORDER BY updated_at DESC";
|
String sql = "SELECT card_id, card_token, card_name, card_number, balance, owner_uuid, webhook_enabled "
|
||||||
|
+ "FROM cards ORDER BY updated_at DESC";
|
||||||
List<StoredCard> result = new ArrayList<>();
|
List<StoredCard> result = new ArrayList<>();
|
||||||
try (Connection connection = open();
|
try (Connection connection = open();
|
||||||
PreparedStatement statement = connection.prepareStatement(sql);
|
PreparedStatement statement = connection.prepareStatement(sql);
|
||||||
@@ -113,7 +150,8 @@ public final class BankDatabase {
|
|||||||
rs.getString("card_name"),
|
rs.getString("card_name"),
|
||||||
rs.getString("card_number"),
|
rs.getString("card_number"),
|
||||||
rs.getLong("balance"),
|
rs.getLong("balance"),
|
||||||
rs.getString("owner_uuid")
|
rs.getString("owner_uuid"),
|
||||||
|
rs.getBoolean("webhook_enabled")
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
|
|||||||
@@ -2,9 +2,13 @@ package git.yawaflua.tech.spmega.client.ui.service;
|
|||||||
|
|
||||||
import git.yawaflua.tech.spmega.ModConfig;
|
import git.yawaflua.tech.spmega.ModConfig;
|
||||||
import git.yawaflua.tech.spmega.SPMega;
|
import git.yawaflua.tech.spmega.SPMega;
|
||||||
import git.yawaflua.tech.spmega.api.SPWorldsApiClient;
|
import git.yawaflua.tech.spmega.client.api.SPWorldsApiClient;
|
||||||
|
import git.yawaflua.tech.spmega.client.telemetry.TelemetryCollector;
|
||||||
|
import git.yawaflua.tech.spmega.client.telemetry.TelemetryEvent;
|
||||||
import net.fabricmc.loader.api.FabricLoader;
|
import net.fabricmc.loader.api.FabricLoader;
|
||||||
|
|
||||||
|
import net.minecraft.client.MinecraftClient;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
|
||||||
@@ -17,7 +21,7 @@ public final class BankUiService {
|
|||||||
private final String apiDomain = "https://spworlds.ru";
|
private final String apiDomain = "https://spworlds.ru";
|
||||||
|
|
||||||
private int selectedCardIndex;
|
private int selectedCardIndex;
|
||||||
private String lastMessage = "";
|
private volatile String lastMessage = "";
|
||||||
|
|
||||||
private BankUiService() {
|
private BankUiService() {
|
||||||
this.database = new BankDatabase(FabricLoader.getInstance().getConfigDir().resolve("spmega.db"));
|
this.database = new BankDatabase(FabricLoader.getInstance().getConfigDir().resolve("spmega.db"));
|
||||||
@@ -54,11 +58,20 @@ public final class BankUiService {
|
|||||||
return normalized.substring(normalized.length() - 5);
|
return normalized.substring(normalized.length() - 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized List<CardViewModel> getCards() {
|
private void runOnMainThread(Runnable runnable) {
|
||||||
|
MinecraftClient client = MinecraftClient.getInstance();
|
||||||
|
if (client == null || client.isOnThread()) {
|
||||||
|
runnable.run();
|
||||||
|
} else {
|
||||||
|
client.execute(runnable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<CardViewModel> getCards() {
|
||||||
return Collections.unmodifiableList(cards);
|
return Collections.unmodifiableList(cards);
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized CardViewModel getSelectedCard() {
|
public CardViewModel getSelectedCard() {
|
||||||
if (cards.isEmpty()) {
|
if (cards.isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -66,7 +79,7 @@ public final class BankUiService {
|
|||||||
return cards.get(selectedCardIndex);
|
return cards.get(selectedCardIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized int getSelectedCardIndex() {
|
public int getSelectedCardIndex() {
|
||||||
if (cards.isEmpty()) {
|
if (cards.isEmpty()) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -74,7 +87,7 @@ public final class BankUiService {
|
|||||||
return selectedCardIndex;
|
return selectedCardIndex;
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void setSelectedCardIndex(int index) {
|
public void setSelectedCardIndex(int index) {
|
||||||
if (cards.isEmpty()) {
|
if (cards.isEmpty()) {
|
||||||
selectedCardIndex = 0;
|
selectedCardIndex = 0;
|
||||||
return;
|
return;
|
||||||
@@ -82,7 +95,7 @@ public final class BankUiService {
|
|||||||
selectedCardIndex = Math.floorMod(index, cards.size());
|
selectedCardIndex = Math.floorMod(index, cards.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized CardViewModel cycleSelectedCard(int direction) {
|
public CardViewModel cycleSelectedCard(int direction) {
|
||||||
if (cards.isEmpty()) {
|
if (cards.isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -90,47 +103,51 @@ public final class BankUiService {
|
|||||||
return cards.get(selectedCardIndex);
|
return cards.get(selectedCardIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized String getLastMessage() {
|
public String getLastMessage() {
|
||||||
return lastMessage;
|
return lastMessage;
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void syncCardsWithBackend(String playerUuid) {
|
private static String rootMessage(Throwable throwable) {
|
||||||
try {
|
Throwable cause = throwable;
|
||||||
List<CardCredentials> backendCards = BackendAuthenticator.fetchCardsFromBackend();
|
while (cause.getCause() != null) {
|
||||||
boolean changed = false;
|
cause = cause.getCause();
|
||||||
for (CardCredentials creds : backendCards) {
|
|
||||||
if (database.getCredentials(creds.cardId()) == null) {
|
|
||||||
database.upsertCardCredentials(creds.cardId(), creds.cardToken());
|
|
||||||
refreshCard(creds.cardId(), creds.cardToken(), playerUuid, false, false);
|
|
||||||
changed = true;
|
|
||||||
}
|
}
|
||||||
|
return cause.getMessage();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public CompletableFuture<Void> syncCardsWithBackendAsync(String playerUuid) {
|
||||||
|
return BackendAuthenticator.fetchCardsFromBackendAsync()
|
||||||
|
.thenCompose(cards -> syncMissingCardsAsync(cards, playerUuid))
|
||||||
|
.thenAccept(changed -> {
|
||||||
if (changed) {
|
if (changed) {
|
||||||
reloadCardsFromDb();
|
reloadCardsFromDb();
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
})
|
||||||
System.err.println("[SPMEGA] Failed to sync cards with backend: " + e.getMessage());
|
.exceptionally(exception -> {
|
||||||
}
|
System.err.println("[SPMEGA] Failed to sync cards with backend: " + exception.getMessage());
|
||||||
|
return null;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void refreshOnServerJoin(String playerUuid) {
|
public CompletableFuture<Void> refreshOnServerJoinAsync(String playerUuid) {
|
||||||
syncCardsWithBackend(playerUuid);
|
return BackendAuthenticator.fetchCardsFromBackendAsync()
|
||||||
|
.exceptionally(exception -> {
|
||||||
List<StoredCard> storedCards = database.loadCards();
|
System.err.println("[SPMEGA] Failed to sync cards with backend: " + exception.getMessage());
|
||||||
for (StoredCard card : storedCards) {
|
return List.of();
|
||||||
refreshCard(card.cardId(), card.cardToken(), playerUuid, false, false);
|
})
|
||||||
}
|
.thenCompose(cards -> syncMissingCardsAsync(cards, playerUuid))
|
||||||
reloadCardsFromDb();
|
.thenCompose(ignored -> refreshStoredCardsAsync(playerUuid))
|
||||||
|
.thenRun(this::reloadCardsFromDb);
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized List<String> loadRecipientCards(String username) {
|
public CompletableFuture<List<String>> loadRecipientCardsAsync(String username) {
|
||||||
CardCredentials credentials = getSelectedCredentials();
|
CardCredentials credentials = getSelectedCredentials();
|
||||||
if (credentials == null || username == null || username.isBlank()) {
|
if (credentials == null || username == null || username.isBlank()) {
|
||||||
return List.of();
|
return CompletableFuture.completedFuture(List.of());
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
return apiClient.getPlayerCardsAsync(username, toApiAuth(credentials))
|
||||||
List<SPWorldsApiClient.PlayerCard> apiCards = apiClient.getPlayerCards(username, toApiAuth(credentials));
|
.thenApply(apiCards -> {
|
||||||
List<String> numbers = new ArrayList<>();
|
List<String> numbers = new ArrayList<>();
|
||||||
for (SPWorldsApiClient.PlayerCard apiCard : apiCards) {
|
for (SPWorldsApiClient.PlayerCard apiCard : apiCards) {
|
||||||
if (apiCard.number() != null && !apiCard.number().isBlank()) {
|
if (apiCard.number() != null && !apiCard.number().isBlank()) {
|
||||||
@@ -139,161 +156,167 @@ public final class BankUiService {
|
|||||||
}
|
}
|
||||||
lastMessage = "";
|
lastMessage = "";
|
||||||
return numbers;
|
return numbers;
|
||||||
} catch (Exception exception) {
|
})
|
||||||
|
.exceptionally(exception -> {
|
||||||
lastMessage = "Не удалось получить карты игрока: " + exception.getMessage();
|
lastMessage = "Не удалось получить карты игрока: " + exception.getMessage();
|
||||||
return List.of();
|
return List.of();
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized String addCard(String cardIdRaw, String cardTokenRaw, String playerUuid) {
|
public CompletableFuture<String> removeSelectedCardAsync() {
|
||||||
|
CardViewModel selected = getSelectedCard();
|
||||||
|
if (selected == null) {
|
||||||
|
return CompletableFuture.completedFuture("Нет карты для удаления");
|
||||||
|
}
|
||||||
|
|
||||||
|
String cardId = selected.id();
|
||||||
|
return CompletableFuture.supplyAsync(() -> {
|
||||||
|
database.deleteCard(cardId);
|
||||||
|
ModConfig config = SPMega.getConfig();
|
||||||
|
if (config != null && config.allowBackend()) {
|
||||||
|
BackendAuthenticator.deleteCardOnBackend(cardId);
|
||||||
|
}
|
||||||
|
|
||||||
|
reloadCardsFromDb();
|
||||||
|
runOnMainThread(() -> {
|
||||||
|
if (selectedCardIndex >= cards.size()) {
|
||||||
|
selectedCardIndex = Math.max(0, cards.size() - 1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return "Карта удалена";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletableFuture<String> addCardAsync(String cardIdRaw, String cardTokenRaw, String playerUuid) {
|
||||||
String cardId = cardIdRaw == null ? "" : cardIdRaw.trim();
|
String cardId = cardIdRaw == null ? "" : cardIdRaw.trim();
|
||||||
String cardToken = cardTokenRaw == null ? "" : cardTokenRaw.trim();
|
String cardToken = cardTokenRaw == null ? "" : cardTokenRaw.trim();
|
||||||
|
|
||||||
if (cardId.isEmpty() || cardToken.isEmpty()) {
|
if (cardId.isEmpty() || cardToken.isEmpty()) {
|
||||||
lastMessage = "Укажи cardId и cardToken";
|
return CompletableFuture.completedFuture("Укажи cardId и cardToken");
|
||||||
return lastMessage;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
UUID.fromString(cardId);
|
UUID.fromString(cardId);
|
||||||
} catch (IllegalArgumentException exception) {
|
} catch (IllegalArgumentException exception) {
|
||||||
lastMessage = "cardId должен быть UUID";
|
return CompletableFuture.completedFuture("cardId должен быть UUID");
|
||||||
return lastMessage;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
database.upsertCardCredentials(cardId, cardToken);
|
return CompletableFuture.runAsync(() -> database.upsertCardCredentials(cardId, cardToken))
|
||||||
boolean refreshed = refreshCard(cardId, cardToken, playerUuid, true, true);
|
.thenCompose(ignored -> refreshCardAsync(cardId, cardToken, playerUuid, true, true))
|
||||||
|
.thenApply(refreshed -> {
|
||||||
if (!refreshed) {
|
if (!refreshed) {
|
||||||
database.deleteCard(cardId);
|
database.deleteCard(cardId);
|
||||||
}
|
}
|
||||||
reloadCardsFromDb();
|
reloadCardsFromDb();
|
||||||
|
return refreshed && lastMessage.isBlank() ? "Карта добавлена" : lastMessage;
|
||||||
if (refreshed && lastMessage.isBlank()) {
|
});
|
||||||
lastMessage = "Карта добавлена";
|
|
||||||
}
|
|
||||||
return lastMessage;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void removeSelectedCard() {
|
public CompletableFuture<String> refreshSelectedCardAsync(String playerUuid) {
|
||||||
CardViewModel selected = getSelectedCard();
|
CardViewModel selected = getSelectedCard();
|
||||||
if (selected == null) {
|
if (selected == null) {
|
||||||
lastMessage = "Нет карты для удаления";
|
return CompletableFuture.completedFuture("Нет карты для обновления");
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
String cardId = selected.id();
|
return CompletableFuture.supplyAsync(() -> database.getCredentials(selected.id()))
|
||||||
database.deleteCard(cardId);
|
.thenCompose(credentials -> {
|
||||||
ModConfig config = SPMega.getConfig();
|
|
||||||
if (config.allowBackend())
|
|
||||||
BackendAuthenticator.deleteCardOnBackend(cardId);
|
|
||||||
|
|
||||||
reloadCardsFromDb();
|
|
||||||
if (selectedCardIndex >= cards.size()) {
|
|
||||||
selectedCardIndex = Math.max(0, cards.size() - 1);
|
|
||||||
}
|
|
||||||
lastMessage = "Карта удалена";
|
|
||||||
}
|
|
||||||
|
|
||||||
public synchronized void refreshSelectedCard(String playerUuid) {
|
|
||||||
CardViewModel selected = getSelectedCard();
|
|
||||||
if (selected == null) {
|
|
||||||
lastMessage = "Нет карты для обновления";
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
CardCredentials credentials = database.getCredentials(selected.id());
|
|
||||||
if (credentials == null) {
|
if (credentials == null) {
|
||||||
lastMessage = "Не найдены креды карты";
|
return CompletableFuture.completedFuture("Не найдены креды карты");
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
return refreshCardAsync(credentials.cardId(), credentials.cardToken(), playerUuid, false, false)
|
||||||
refreshCard(credentials.cardId(), credentials.cardToken(), playerUuid, false, false);
|
.thenApply(ignored -> {
|
||||||
reloadCardsFromDb();
|
reloadCardsFromDb();
|
||||||
|
return lastMessage.isBlank() ? "Карта обновлена" : lastMessage;
|
||||||
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized boolean submitPayment(PaymentDraft draft) {
|
private void recordPaymentEvent(PaymentDraft draft, boolean success, String mode, String destination, long durationMs, String senderLast4) {
|
||||||
CardCredentials credentials = database.getCredentials(draft.senderCardId());
|
recordPaymentEvent(draft, success, mode, destination, durationMs, senderLast4, null);
|
||||||
if (credentials == null) {
|
|
||||||
lastMessage = "Не найдены креды карты отправителя";
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
git.yawaflua.tech.spmega.ModConfig config = git.yawaflua.tech.spmega.SPMega.getConfig();
|
private void recordPaymentEvent(PaymentDraft draft, boolean success, String mode, String destination, long durationMs, String senderLast4, String error) {
|
||||||
boolean useBackend = config != null && config.allowBackend();
|
com.google.gson.JsonObject payload = new com.google.gson.JsonObject();
|
||||||
|
payload.addProperty("success", success);
|
||||||
try {
|
payload.addProperty("mode", mode);
|
||||||
long newBalance = 0;
|
payload.addProperty("destination", destination);
|
||||||
if (useBackend) {
|
payload.addProperty("durationMs", durationMs);
|
||||||
BackendAuthenticator.createTransactionOnBackend(
|
payload.addProperty("senderCardLast4", senderLast4 != null ? senderLast4 : "unknown");
|
||||||
draft.senderCardId(),
|
payload.addProperty("amount", draft.amount());
|
||||||
draft.recipient(),
|
payload.addProperty("receiver", draft.recipient());
|
||||||
draft.amount(),
|
if (error != null) {
|
||||||
draft.comment()
|
payload.addProperty("error", trimMessage(error));
|
||||||
);
|
|
||||||
try {
|
|
||||||
refreshCard(credentials.cardId(), credentials.cardToken(), "", false, false);
|
|
||||||
StoredCard updatedCard = database.loadCards().stream()
|
|
||||||
.filter(c -> c.cardId().equals(credentials.cardId()))
|
|
||||||
.findFirst()
|
|
||||||
.orElse(null);
|
|
||||||
if (updatedCard != null) {
|
|
||||||
newBalance = updatedCard.balance();
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.err.println("[SPMEGA] Failed to refresh card balance after transaction: " + e.getMessage());
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
SPWorldsApiClient.TransactionResult result = apiClient.createTransaction(
|
|
||||||
toApiAuth(credentials),
|
|
||||||
draft.recipient(),
|
|
||||||
draft.amount(),
|
|
||||||
draft.comment()
|
|
||||||
);
|
|
||||||
newBalance = result.balance();
|
|
||||||
database.updateCardBalance(credentials.cardId(), newBalance);
|
|
||||||
}
|
|
||||||
|
|
||||||
database.insertTransferHistory(
|
|
||||||
credentials.cardId(),
|
|
||||||
draft.recipient(),
|
|
||||||
draft.amount(),
|
|
||||||
draft.comment(),
|
|
||||||
newBalance,
|
|
||||||
"SUCCESS"
|
|
||||||
);
|
|
||||||
|
|
||||||
reloadCardsFromDb();
|
|
||||||
lastMessage = "Перевод выполнен";
|
|
||||||
return true;
|
|
||||||
} catch (Exception exception) {
|
|
||||||
database.insertTransferHistory(
|
|
||||||
credentials.cardId(),
|
|
||||||
draft.recipient(),
|
|
||||||
draft.amount(),
|
|
||||||
draft.comment(),
|
|
||||||
null,
|
|
||||||
"FAILED: " + trimMessage(exception.getMessage())
|
|
||||||
);
|
|
||||||
lastMessage = "Ошибка перевода: " + exception.getMessage();
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
TelemetryCollector.instance().record(TelemetryEvent.now("payment", payload));
|
||||||
}
|
}
|
||||||
|
|
||||||
public CompletableFuture<Boolean> submitPaymentAsync(PaymentDraft draft) {
|
public CompletableFuture<Boolean> submitPaymentAsync(PaymentDraft draft) {
|
||||||
return CompletableFuture.supplyAsync(() -> submitPayment(draft));
|
return CompletableFuture.supplyAsync(() -> database.getCredentials(draft.senderCardId()))
|
||||||
|
.thenCompose(credentials -> {
|
||||||
|
if (credentials == null) {
|
||||||
|
lastMessage = "Не найдены креды карты отправителя";
|
||||||
|
recordPaymentEvent(draft, false, "local", "no_credentials", 0, null);
|
||||||
|
return CompletableFuture.completedFuture(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean refreshCard(
|
ModConfig config = SPMega.getConfig();
|
||||||
|
boolean useBackend = config != null && config.allowBackend();
|
||||||
|
String mode = useBackend ? "backend" : "spworlds-direct";
|
||||||
|
String destination = useBackend ? "backend" : "local-db";
|
||||||
|
String senderLast4 = extractLastDigits(credentials.cardId());
|
||||||
|
long startNs = System.nanoTime();
|
||||||
|
|
||||||
|
CompletableFuture<Long> transaction = useBackend
|
||||||
|
? BackendAuthenticator.createTransactionOnBackendAsync(
|
||||||
|
draft.senderCardId(), draft.recipient(), draft.amount(), draft.comment())
|
||||||
|
.thenCompose(ignored -> refreshCardAsync(
|
||||||
|
credentials.cardId(), credentials.cardToken(), "", false, false))
|
||||||
|
.thenApply(ignored -> database.loadCards().stream()
|
||||||
|
.filter(card -> card.cardId().equals(credentials.cardId()))
|
||||||
|
.findFirst()
|
||||||
|
.map(StoredCard::balance)
|
||||||
|
.orElse(0L))
|
||||||
|
: apiClient.createTransactionAsync(
|
||||||
|
toApiAuth(credentials), draft.recipient(), draft.amount(), draft.comment())
|
||||||
|
.thenApply(result -> {
|
||||||
|
database.updateCardBalance(credentials.cardId(), result.balance());
|
||||||
|
return result.balance();
|
||||||
|
});
|
||||||
|
|
||||||
|
return transaction
|
||||||
|
.thenApply(newBalance -> {
|
||||||
|
database.insertTransferHistory(
|
||||||
|
credentials.cardId(), draft.recipient(), draft.amount(), draft.comment(),
|
||||||
|
newBalance, "SUCCESS");
|
||||||
|
reloadCardsFromDb();
|
||||||
|
lastMessage = "Перевод выполнен";
|
||||||
|
recordPaymentEvent(draft, true, mode, destination,
|
||||||
|
(System.nanoTime() - startNs) / 1_000_000L, senderLast4);
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
.exceptionally(exception -> {
|
||||||
|
String error = rootMessage(exception);
|
||||||
|
database.insertTransferHistory(
|
||||||
|
credentials.cardId(), draft.recipient(), draft.amount(), draft.comment(),
|
||||||
|
null, "FAILED: " + trimMessage(error));
|
||||||
|
lastMessage = "Ошибка перевода: " + error;
|
||||||
|
recordPaymentEvent(draft, false, mode, destination,
|
||||||
|
(System.nanoTime() - startNs) / 1_000_000L, senderLast4, error);
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompletableFuture<Boolean> refreshCardAsync(
|
||||||
String cardId,
|
String cardId,
|
||||||
String cardToken,
|
String cardToken,
|
||||||
String playerUuid,
|
String playerUuid,
|
||||||
boolean reportOwnerWarning,
|
boolean reportOwnerWarning,
|
||||||
boolean requireCardInAccount
|
boolean requireCardInAccount
|
||||||
) {
|
) {
|
||||||
try {
|
|
||||||
SPWorldsApiClient.CardAuth auth = new SPWorldsApiClient.CardAuth(cardId, cardToken);
|
SPWorldsApiClient.CardAuth auth = new SPWorldsApiClient.CardAuth(cardId, cardToken);
|
||||||
SPWorldsApiClient.AccountMe me = apiClient.getAccountMe(auth);
|
return apiClient.getAccountMeAsync(auth)
|
||||||
SPWorldsApiClient.CardInfo cardInfo = apiClient.getCardInfo(auth);
|
.thenCompose(me -> apiClient.getCardInfoAsync(auth).thenApply(cardInfo -> {
|
||||||
|
|
||||||
SPWorldsApiClient.AccountCard currentCard = me.cards().stream()
|
SPWorldsApiClient.AccountCard currentCard = me.cards().stream()
|
||||||
.filter(card -> Objects.equals(card.id(), cardId))
|
.filter(card -> Objects.equals(card.id(), cardId))
|
||||||
@@ -318,33 +341,81 @@ public final class BankUiService {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
git.yawaflua.tech.spmega.ModConfig config = git.yawaflua.tech.spmega.SPMega.getConfig();
|
ModConfig config = SPMega.getConfig();
|
||||||
if (config.allowBackend())
|
if (config != null && config.allowBackend()) {
|
||||||
CompletableFuture.supplyAsync(() -> {
|
|
||||||
BackendAuthenticator.sendCardToBackend(cardId, cardToken);
|
BackendAuthenticator.sendCardToBackend(cardId, cardToken);
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
);
|
|
||||||
|
|
||||||
lastMessage = "";
|
lastMessage = "";
|
||||||
return true;
|
return true;
|
||||||
} catch (Exception exception) {
|
}))
|
||||||
lastMessage = "Не удалось обновить карту: " + exception.getMessage();
|
.exceptionally(exception -> {
|
||||||
|
lastMessage = "Не удалось обновить карту: " + rootMessage(exception);
|
||||||
return false;
|
return false;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public CompletableFuture<String> registerSelectedWebhookAsync() {
|
||||||
|
CardViewModel selected = getSelectedCard();
|
||||||
|
if (selected == null) {
|
||||||
|
return CompletableFuture.completedFuture("Сначала выбери или добавь карту");
|
||||||
|
}
|
||||||
|
if (selected.webhookEnabled()) {
|
||||||
|
return CompletableFuture.completedFuture("Вебхук для этой карты уже включён");
|
||||||
|
}
|
||||||
|
|
||||||
|
return BackendAuthenticator.registerWebhookForCardAsync(selected.id())
|
||||||
|
.thenApply(ignored -> {
|
||||||
|
database.setWebhookEnabled(selected.id(), true);
|
||||||
|
reloadCardsFromDb();
|
||||||
|
return "Обработка вебхуков включена";
|
||||||
|
})
|
||||||
|
.exceptionally(exception -> "Не удалось включить вебхук: " + rootMessage(exception));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasWebhookEnabledCards() {
|
||||||
|
return database.hasWebhookEnabledCards();
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompletableFuture<Boolean> syncMissingCardsAsync(List<CardCredentials> backendCards, String playerUuid) {
|
||||||
|
CompletableFuture<Boolean> result = CompletableFuture.completedFuture(false);
|
||||||
|
for (CardCredentials credentials : backendCards) {
|
||||||
|
result = result.thenCompose(changed -> {
|
||||||
|
if (database.getCredentials(credentials.cardId()) != null) {
|
||||||
|
database.setWebhookEnabled(credentials.cardId(), credentials.webhookEnabled());
|
||||||
|
return CompletableFuture.completedFuture(changed);
|
||||||
|
}
|
||||||
|
database.upsertCardCredentials(credentials.cardId(), credentials.cardToken());
|
||||||
|
database.setWebhookEnabled(credentials.cardId(), credentials.webhookEnabled());
|
||||||
|
return refreshCardAsync(
|
||||||
|
credentials.cardId(), credentials.cardToken(), playerUuid, false, false)
|
||||||
|
.thenApply(ignored -> true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompletableFuture<Void> refreshStoredCardsAsync(String playerUuid) {
|
||||||
|
CompletableFuture<Void> result = CompletableFuture.completedFuture(null);
|
||||||
|
for (StoredCard card : database.loadCards()) {
|
||||||
|
result = result.thenCompose(ignored -> refreshCardAsync(
|
||||||
|
card.cardId(), card.cardToken(), playerUuid, false, false).thenApply(refreshed -> null));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void reloadCardsFromDb() {
|
private void reloadCardsFromDb() {
|
||||||
List<StoredCard> storedCards = database.loadCards();
|
List<StoredCard> storedCards = database.loadCards();
|
||||||
|
runOnMainThread(() -> {
|
||||||
cards.clear();
|
cards.clear();
|
||||||
|
|
||||||
for (StoredCard stored : storedCards) {
|
for (StoredCard stored : storedCards) {
|
||||||
String cardNumber = stored.cardNumber() == null || stored.cardNumber().isBlank()
|
String cardNumber = stored.cardNumber() == null || stored.cardNumber().isBlank()
|
||||||
? extractLastDigits(stored.cardId())
|
? extractLastDigits(stored.cardId())
|
||||||
: stored.cardNumber();
|
: stored.cardNumber();
|
||||||
String cardName = stored.cardName() == null || stored.cardName().isBlank() ? "Карта" : stored.cardName();
|
String cardName = stored.cardName() == null || stored.cardName().isBlank() ? "Карта" : stored.cardName();
|
||||||
String title = cardNumber + ": " + cardName;
|
String title = cardNumber + ": " + cardName;
|
||||||
cards.add(new CardViewModel(stored.cardId(), title, stored.balance()));
|
cards.add(new CardViewModel(
|
||||||
|
stored.cardId(), title, stored.balance(), stored.webhookEnabled()));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cards.isEmpty()) {
|
if (cards.isEmpty()) {
|
||||||
@@ -352,6 +423,7 @@ public final class BankUiService {
|
|||||||
} else {
|
} else {
|
||||||
selectedCardIndex = Math.floorMod(selectedCardIndex, cards.size());
|
selectedCardIndex = Math.floorMod(selectedCardIndex, cards.size());
|
||||||
}
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private CardCredentials getSelectedCredentials() {
|
private CardCredentials getSelectedCredentials() {
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
package git.yawaflua.tech.spmega.client.ui.service;
|
package git.yawaflua.tech.spmega.client.ui.service;
|
||||||
|
|
||||||
public record CardCredentials(String cardId, String cardToken) {
|
public record CardCredentials(String cardId, String cardToken, boolean webhookEnabled) {
|
||||||
|
public CardCredentials(String cardId, String cardToken) {
|
||||||
|
this(cardId, cardToken, false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
package git.yawaflua.tech.spmega.client.ui.service;
|
package git.yawaflua.tech.spmega.client.ui.service;
|
||||||
|
|
||||||
public record CardViewModel(String id, String title, long balance) {
|
public record CardViewModel(String id, String title, long balance, boolean webhookEnabled) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package git.yawaflua.tech.spmega.client.ui.service;
|
package git.yawaflua.tech.spmega.client.ui.service;
|
||||||
|
|
||||||
public record StoredCard(String cardId, String cardToken, String cardName, String cardNumber, long balance,
|
public record StoredCard(String cardId, String cardToken, String cardName, String cardNumber, long balance,
|
||||||
String ownerUuid) {
|
String ownerUuid, boolean webhookEnabled) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,21 @@
|
|||||||
"option.spmega.gps_position.bottom_left": "Bottom-Left",
|
"option.spmega.gps_position.bottom_left": "Bottom-Left",
|
||||||
"option.spmega.gps_position.bottom_right": "Bottom-Right",
|
"option.spmega.gps_position.bottom_right": "Bottom-Right",
|
||||||
"option.spmega.gps_position.bottom_center": "Bottom-center",
|
"option.spmega.gps_position.bottom_center": "Bottom-center",
|
||||||
"option.spmega.gps_position.top_center": "Top-center"
|
"option.spmega.gps_position.top_center": "Top-center",
|
||||||
|
"option.spmega.notification_position": "Notification position",
|
||||||
|
"option.spmega.notification_position.top_left": "Top-left",
|
||||||
|
"option.spmega.notification_position.top_right": "Top-right",
|
||||||
|
"option.spmega.notification_position.bottom_left": "Bottom-left",
|
||||||
|
"option.spmega.notification_position.bottom_right": "Bottom-right",
|
||||||
|
"option.spmega.notification_position.bottom_center": "Bottom-center",
|
||||||
|
"option.spmega.notification_position.top_center": "Top-center",
|
||||||
|
"category.spmega.telemetry": "Telemetry",
|
||||||
|
"option.spmega.telemetry_enabled": "Collect system information",
|
||||||
|
"tooltip.spmega.telemetry_enabled": "Disabling hides hardware data (CPU, GPU, RAM, IP). Performance and request stats keep sending.",
|
||||||
|
"option.spmega.telemetry_interval": "Send interval (sec)",
|
||||||
|
"tooltip.spmega.telemetry_interval": "How often telemetry batches are sent to the server (10-600 sec)",
|
||||||
|
"option.spmega.telemetry_system_info": "Send system information",
|
||||||
|
"tooltip.spmega.telemetry_system_info": "CPU, GPU, RAM, storage, IP, device name, Java version"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,19 @@
|
|||||||
"option.spmega.gps_position.bottom_left": "Слева внизу",
|
"option.spmega.gps_position.bottom_left": "Слева внизу",
|
||||||
"option.spmega.gps_position.bottom_center": "Снизу по-центру",
|
"option.spmega.gps_position.bottom_center": "Снизу по-центру",
|
||||||
"option.spmega.gps_position.top_center": "Сверху по-центру",
|
"option.spmega.gps_position.top_center": "Сверху по-центру",
|
||||||
"option.spmega.gps_position.bottom_right": "Снизу справа"
|
"option.spmega.gps_position.bottom_right": "Снизу справа",
|
||||||
|
"option.spmega.notification_position": "Положение уведомлений",
|
||||||
|
"option.spmega.notification_position.top_left": "Слева вверху",
|
||||||
|
"option.spmega.notification_position.top_right": "Справа вверху",
|
||||||
|
"option.spmega.notification_position.bottom_left": "Слева внизу",
|
||||||
|
"option.spmega.notification_position.bottom_center": "Снизу по центру",
|
||||||
|
"option.spmega.notification_position.top_center": "Сверху по центру",
|
||||||
|
"option.spmega.notification_position.bottom_right": "Снизу справа",
|
||||||
|
"category.spmega.telemetry": "Телеметрия",
|
||||||
|
"option.spmega.telemetry_enabled": "Сбор системной информации",
|
||||||
|
"tooltip.spmega.telemetry_enabled": "Отключение скрывает данные компьютера (CPU, GPU, RAM, IP). Статистика производительности и запросов продолжает отправляться.",
|
||||||
|
"option.spmega.telemetry_interval": "Интервал отправки (сек)",
|
||||||
|
"tooltip.spmega.telemetry_interval": "Как часто батч телеметрии отправляется на сервер (от 10 до 600 сек)",
|
||||||
|
"option.spmega.telemetry_system_info": "Отправлять информацию о системе",
|
||||||
|
"tooltip.spmega.telemetry_system_info": "CPU, GPU, RAM, диск, IP, имя устройства, версия Java"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ public final class ConfigManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
boolean allowAccess = readBoolean(properties, "allow.backend", defaults.allowBackend());
|
boolean allowAccess = readBoolean(properties, "allow.backend", defaults.allowBackend());
|
||||||
String rawAllowAccess = properties.getProperty("sign.quickPay.enabled");
|
String rawAllowAccess = properties.getProperty("allow.backend");
|
||||||
if (rawAllowAccess == null || !Boolean.toString(allowAccess).equalsIgnoreCase(rawAllowAccess.trim())) {
|
if (rawAllowAccess == null || !Boolean.toString(allowAccess).equalsIgnoreCase(rawAllowAccess.trim())) {
|
||||||
shouldSave = true;
|
shouldSave = true;
|
||||||
}
|
}
|
||||||
@@ -66,7 +66,28 @@ public final class ConfigManager {
|
|||||||
shouldSave = true;
|
shouldSave = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
ModConfig config = new ModConfig(apiDomain, apiToken, allowAccess, signQuickPayEnabled, gpsEnabled, gpsPosition);
|
GpsHudPosition notificationPosition = readEnum(
|
||||||
|
properties, "notifications.position", GpsHudPosition.class, defaults.notificationPosition());
|
||||||
|
String rawNotificationPosition = properties.getProperty("notifications.position");
|
||||||
|
if (rawNotificationPosition == null
|
||||||
|
|| !notificationPosition.name().equalsIgnoreCase(rawNotificationPosition.trim())) {
|
||||||
|
shouldSave = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
int telemetryIntervalSeconds = readInt(properties, "telemetry.intervalSeconds", defaults.telemetryIntervalSeconds());
|
||||||
|
String rawInterval = properties.getProperty("telemetry.intervalSeconds");
|
||||||
|
if (rawInterval == null || !Integer.toString(telemetryIntervalSeconds).equals(rawInterval.trim())) {
|
||||||
|
shouldSave = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean telemetryCollectSystemInfo = readBoolean(properties, "telemetry.collectSystemInfo", defaults.telemetryCollectSystemInfo());
|
||||||
|
String rawSysInfo = properties.getProperty("telemetry.collectSystemInfo");
|
||||||
|
if (rawSysInfo == null || !Boolean.toString(telemetryCollectSystemInfo).equalsIgnoreCase(rawSysInfo.trim())) {
|
||||||
|
shouldSave = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
ModConfig config = new ModConfig(apiDomain, apiToken, allowAccess, signQuickPayEnabled, gpsEnabled, gpsPosition,
|
||||||
|
notificationPosition, telemetryIntervalSeconds, telemetryCollectSystemInfo);
|
||||||
|
|
||||||
|
|
||||||
if (shouldSave) {
|
if (shouldSave) {
|
||||||
@@ -126,9 +147,13 @@ public final class ConfigManager {
|
|||||||
Properties properties = new Properties();
|
Properties properties = new Properties();
|
||||||
properties.setProperty("api.domain", config.apiDomain());
|
properties.setProperty("api.domain", config.apiDomain());
|
||||||
properties.setProperty("api.token", config.apiToken());
|
properties.setProperty("api.token", config.apiToken());
|
||||||
|
properties.setProperty("allow.backend", Boolean.toString(config.allowBackend()));
|
||||||
properties.setProperty("sign.quickPay.enabled", Boolean.toString(config.signQuickPayEnabled()));
|
properties.setProperty("sign.quickPay.enabled", Boolean.toString(config.signQuickPayEnabled()));
|
||||||
properties.setProperty("gps.enabled", Boolean.toString(config.gpsEnabled()));
|
properties.setProperty("gps.enabled", Boolean.toString(config.gpsEnabled()));
|
||||||
properties.setProperty("gps.position", config.gpsPosition().name());
|
properties.setProperty("gps.position", config.gpsPosition().name());
|
||||||
|
properties.setProperty("notifications.position", config.notificationPosition().name());
|
||||||
|
properties.setProperty("telemetry.intervalSeconds", Integer.toString(config.telemetryIntervalSeconds()));
|
||||||
|
properties.setProperty("telemetry.collectSystemInfo", Boolean.toString(config.telemetryCollectSystemInfo()));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Files.createDirectories(configPath.getParent());
|
Files.createDirectories(configPath.getParent());
|
||||||
@@ -140,6 +165,18 @@ public final class ConfigManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static int readInt(Properties properties, String key, int fallback) {
|
||||||
|
String value = properties.getProperty(key);
|
||||||
|
if (value == null || value.trim().isEmpty()) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(value.trim());
|
||||||
|
} catch (NumberFormatException exception) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static <E extends Enum<E>> E readEnum(Properties properties, String key, Class<E> enumClass, E fallback) {
|
private static <E extends Enum<E>> E readEnum(Properties properties, String key, Class<E> enumClass, E fallback) {
|
||||||
String value = properties.getProperty(key);
|
String value = properties.getProperty(key);
|
||||||
if (value == null || value.trim().isEmpty()) {
|
if (value == null || value.trim().isEmpty()) {
|
||||||
|
|||||||
@@ -1,13 +1,19 @@
|
|||||||
package git.yawaflua.tech.spmega;
|
package git.yawaflua.tech.spmega;
|
||||||
|
|
||||||
public record ModConfig(String apiDomain, String apiToken, boolean allowBackend, boolean signQuickPayEnabled,
|
public record ModConfig(String apiDomain, String apiToken, boolean allowBackend, boolean signQuickPayEnabled,
|
||||||
boolean gpsEnabled, GpsHudPosition gpsPosition) {
|
boolean gpsEnabled, GpsHudPosition gpsPosition,
|
||||||
public static final String DEFAULT_API_DOMAIN = "http://localhost:5129";
|
GpsHudPosition notificationPosition, int telemetryIntervalSeconds,
|
||||||
public static final boolean ALLOW_BACKEND = false;
|
boolean telemetryCollectSystemInfo) {
|
||||||
public static final String DEFAULT_API_TOKEN = "ulBKE9MWEtIGiPAhXV69I28W9BRiSrV3";
|
public static final String DEFAULT_API_DOMAIN = "https://spmega.yawaflua.tech";
|
||||||
|
public static final boolean ALLOW_BACKEND = true;
|
||||||
|
public static final String DEFAULT_API_TOKEN = "-";
|
||||||
public static final boolean DEFAULT_SIGN_QUICK_PAY_ENABLED = true;
|
public static final boolean DEFAULT_SIGN_QUICK_PAY_ENABLED = true;
|
||||||
public static final boolean DEFAULT_GPS_ENABLED = true;
|
public static final boolean DEFAULT_GPS_ENABLED = true;
|
||||||
public static final GpsHudPosition DEFAULT_GPS_POSITION = GpsHudPosition.TOP_LEFT;
|
public static final GpsHudPosition DEFAULT_GPS_POSITION = GpsHudPosition.TOP_CENTER;
|
||||||
|
public static final GpsHudPosition DEFAULT_NOTIFICATION_POSITION = GpsHudPosition.BOTTOM_RIGHT;
|
||||||
|
public static final boolean DEFAULT_TELEMETRY_ENABLED = true;
|
||||||
|
public static final int DEFAULT_TELEMETRY_INTERVAL_SECONDS = 60;
|
||||||
|
public static final boolean DEFAULT_TELEMETRY_COLLECT_SYSTEM_INFO = true;
|
||||||
|
|
||||||
public static ModConfig createDefault() {
|
public static ModConfig createDefault() {
|
||||||
return new ModConfig(
|
return new ModConfig(
|
||||||
@@ -16,9 +22,10 @@ public record ModConfig(String apiDomain, String apiToken, boolean allowBackend,
|
|||||||
ALLOW_BACKEND,
|
ALLOW_BACKEND,
|
||||||
DEFAULT_SIGN_QUICK_PAY_ENABLED,
|
DEFAULT_SIGN_QUICK_PAY_ENABLED,
|
||||||
DEFAULT_GPS_ENABLED,
|
DEFAULT_GPS_ENABLED,
|
||||||
DEFAULT_GPS_POSITION
|
DEFAULT_GPS_POSITION,
|
||||||
|
DEFAULT_NOTIFICATION_POSITION,
|
||||||
|
DEFAULT_TELEMETRY_INTERVAL_SECONDS,
|
||||||
|
DEFAULT_TELEMETRY_COLLECT_SYSTEM_INFO
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,9 @@ public class SPMega implements ModInitializer {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onInitialize() {
|
public void onInitialize() {
|
||||||
|
long startNs = System.nanoTime();
|
||||||
config = ConfigManager.loadOrCreate();
|
config = ConfigManager.loadOrCreate();
|
||||||
|
long durationMs = (System.nanoTime() - startNs) / 1_000_000L;
|
||||||
|
System.out.println("[SPMEGA] Main init took " + durationMs + "ms");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,199 +0,0 @@
|
|||||||
package git.yawaflua.tech.spmega.api;
|
|
||||||
|
|
||||||
import com.google.gson.*;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.URI;
|
|
||||||
import java.net.http.HttpClient;
|
|
||||||
import java.net.http.HttpRequest;
|
|
||||||
import java.net.http.HttpResponse;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public final class SPWorldsApiClient {
|
|
||||||
private final HttpClient httpClient;
|
|
||||||
private final Gson gson;
|
|
||||||
private final String baseUrl;
|
|
||||||
|
|
||||||
public SPWorldsApiClient(String baseUrl) {
|
|
||||||
this.httpClient = HttpClient.newHttpClient();
|
|
||||||
this.gson = new Gson();
|
|
||||||
this.baseUrl = normalizeBaseUrl(baseUrl);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String encodeAuth(CardAuth auth) {
|
|
||||||
String raw = auth.cardId() + ":" + auth.cardToken();
|
|
||||||
return Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String normalizeBaseUrl(String rawBaseUrl) {
|
|
||||||
String fallback = "https://spworlds.ru";
|
|
||||||
if (rawBaseUrl == null || rawBaseUrl.trim().isEmpty()) {
|
|
||||||
return fallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
String value = rawBaseUrl.trim();
|
|
||||||
if (value.endsWith("/")) {
|
|
||||||
return value.substring(0, value.length() - 1);
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String getString(JsonObject json, String key) {
|
|
||||||
if (!json.has(key) || json.get(key).isJsonNull()) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
return json.get(key).getAsString();
|
|
||||||
}
|
|
||||||
|
|
||||||
public CardInfo getCardInfo(CardAuth auth) throws IOException, InterruptedException {
|
|
||||||
HttpRequest request = requestBuilder("/api/public/card", auth).GET().build();
|
|
||||||
String body = send(request);
|
|
||||||
try {
|
|
||||||
JsonObject json = JsonParser.parseString(body).getAsJsonObject();
|
|
||||||
if (json.has("statusCode")) {
|
|
||||||
switch (json.get("statusCode").getAsInt()) {
|
|
||||||
case 403:
|
|
||||||
throw new IOException("Апи вернула ошибку: " + json.get("message").getAsString());
|
|
||||||
default:
|
|
||||||
System.out.println("Unhandled status code in card info response: " + json.get("statusCode").getAsInt());
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
long balance = json.has("balance") ? json.get("balance").getAsLong() : 0L;
|
|
||||||
String webhook = json.has("webhook") && !json.get("webhook").isJsonNull()
|
|
||||||
? json.get("webhook").getAsString()
|
|
||||||
: "";
|
|
||||||
return new CardInfo(balance, webhook);
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.out.println("Failed to parse card info response: " + e.getMessage());
|
|
||||||
System.out.println(body);
|
|
||||||
|
|
||||||
throw new IOException("Failed to parse card info response", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<PlayerCard> getPlayerCards(String username, CardAuth auth) throws IOException, InterruptedException {
|
|
||||||
HttpRequest request = requestBuilder("/api/public/accounts/" + username + "/cards", auth).GET().build();
|
|
||||||
String body = send(request);
|
|
||||||
try {
|
|
||||||
JsonArray json = JsonParser.parseString(body).getAsJsonArray();
|
|
||||||
|
|
||||||
List<PlayerCard> cards = new ArrayList<>();
|
|
||||||
for (JsonElement element : json) {
|
|
||||||
JsonObject card = element.getAsJsonObject();
|
|
||||||
String name = card.has("name") ? card.get("name").getAsString() : "";
|
|
||||||
String number = card.has("number") ? card.get("number").getAsString() : "";
|
|
||||||
cards.add(new PlayerCard(name, number));
|
|
||||||
}
|
|
||||||
return cards;
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.out.println("Failed to parse player cards response: " + e.getMessage());
|
|
||||||
System.out.println(body);
|
|
||||||
throw new IOException("Failed to parse player cards response", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public AccountMe getAccountMe(CardAuth auth) throws IOException, InterruptedException {
|
|
||||||
HttpRequest request = requestBuilder("/api/public/accounts/me", auth).GET().build();
|
|
||||||
String body = send(request);
|
|
||||||
try {
|
|
||||||
JsonObject json = JsonParser.parseString(body).getAsJsonObject();
|
|
||||||
|
|
||||||
String id = json.has("id") ? json.get("id").getAsString() : "";
|
|
||||||
String username = json.has("username") ? json.get("username").getAsString() : "";
|
|
||||||
String minecraftUuid = json.has("minecraftUUID") ? json.get("minecraftUUID").getAsString() : "";
|
|
||||||
|
|
||||||
List<AccountCard> cards = new ArrayList<>();
|
|
||||||
if (json.has("cards") && json.get("cards").isJsonArray()) {
|
|
||||||
for (JsonElement element : json.getAsJsonArray("cards")) {
|
|
||||||
JsonObject card = element.getAsJsonObject();
|
|
||||||
cards.add(new AccountCard(
|
|
||||||
getString(card, "id"),
|
|
||||||
getString(card, "name"),
|
|
||||||
getString(card, "number"),
|
|
||||||
card.has("color") && !card.get("color").isJsonNull() ? card.get("color").getAsInt() : 0
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return new AccountMe(id, username, minecraftUuid, cards);
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.out.println("Failed to parse account info response: " + e.getMessage());
|
|
||||||
System.out.println(body);
|
|
||||||
|
|
||||||
throw new IOException("Failed to parse account info response", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public TransactionResult createTransaction(CardAuth auth, String receiver, long amount, String comment)
|
|
||||||
throws IOException, InterruptedException {
|
|
||||||
JsonObject payload = new JsonObject();
|
|
||||||
payload.addProperty("receiver", receiver);
|
|
||||||
payload.addProperty("amount", amount);
|
|
||||||
payload.addProperty("comment", comment.isEmpty() ? "Перевод через SPMega" : comment);
|
|
||||||
|
|
||||||
HttpRequest request = requestBuilder("/api/public/transactions", auth)
|
|
||||||
.POST(HttpRequest.BodyPublishers.ofString(gson.toJson(payload)))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
String body = send(request);
|
|
||||||
try {
|
|
||||||
JsonObject json = JsonParser.parseString(body).getAsJsonObject();
|
|
||||||
|
|
||||||
long balance = json.has("balance") ? json.get("balance").getAsLong() : 0L;
|
|
||||||
return new TransactionResult(balance);
|
|
||||||
} catch (Exception exception) {
|
|
||||||
System.out.println("Failed to parse transaction response: " + exception.getMessage());
|
|
||||||
System.out.println(body);
|
|
||||||
|
|
||||||
throw new IOException("Failed to parse transaction response", exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private HttpRequest.Builder requestBuilder(String path, CardAuth auth) {
|
|
||||||
return HttpRequest.newBuilder(URI.create(baseUrl + path))
|
|
||||||
.header("Authorization", "Bearer " + encodeAuth(auth))
|
|
||||||
.header("Content-Type", "application/json")
|
|
||||||
.header("Accept", "application/json");
|
|
||||||
}
|
|
||||||
|
|
||||||
private String send(HttpRequest request) throws IOException, InterruptedException {
|
|
||||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
|
||||||
int statusCode = response.statusCode();
|
|
||||||
if (statusCode < 200 || statusCode >= 300) {
|
|
||||||
System.out.println(response.body());
|
|
||||||
JsonElement parsed = JsonParser.parseString(response.body());
|
|
||||||
JsonObject object = parsed.isJsonArray() ? parsed.getAsJsonArray().get(0).getAsJsonObject() : parsed.getAsJsonObject();
|
|
||||||
var message = "";
|
|
||||||
if (object.has("error") && !object.get("error").isJsonNull()) {
|
|
||||||
message = "Ошибка в запросе: " + object.get("error").getAsString();
|
|
||||||
} else if (object.has("message") && !object.get("message").isJsonNull()) {
|
|
||||||
message = object.get("message").getAsString();
|
|
||||||
}
|
|
||||||
throw new IOException(statusCode + ": " + message);
|
|
||||||
}
|
|
||||||
return response.body();
|
|
||||||
}
|
|
||||||
|
|
||||||
public record CardAuth(String cardId, String cardToken) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public record CardInfo(long balance, String webhook) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public record PlayerCard(String name, String number) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public record AccountMe(String id, String username, String minecraftUuid, List<AccountCard> cards) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public record AccountCard(String id, String name, String number, int color) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public record TransactionResult(long balance) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -3,12 +3,20 @@
|
|||||||
"id": "spmega",
|
"id": "spmega",
|
||||||
"version": "${version}",
|
"version": "${version}",
|
||||||
"name": "SPMega",
|
"name": "SPMega",
|
||||||
"description": "yawaflua`s SPRadar+SPMHelper mod, thats make a lot!",
|
"description": "yawaflua's SPRadar+SPMHelper mod, that's make a lot!",
|
||||||
"authors": [
|
"authors": [
|
||||||
"Dmitri 'yawaflua' Shimanski aka DOLBAYEB"
|
{
|
||||||
|
"name": "Dmitri 'yawaflua' Shimanski aka DOLBAYEB",
|
||||||
|
"contact": {
|
||||||
|
"homepage": "https://yawaflua.tech",
|
||||||
|
"email": "spmega@yawaflua.tech"
|
||||||
|
}
|
||||||
|
}
|
||||||
],
|
],
|
||||||
"contact": {
|
"contact": {
|
||||||
|
"homepage": "https://yawaflua.tech",
|
||||||
|
"issues": "https://git.yawaflua.tech/spmega",
|
||||||
|
"sources": "https://git.yawaflua.tech/spmega"
|
||||||
},
|
},
|
||||||
"license": "CC BY-NC-ND 4.0",
|
"license": "CC BY-NC-ND 4.0",
|
||||||
"icon": "icon.png",
|
"icon": "icon.png",
|
||||||
@@ -37,7 +45,9 @@
|
|||||||
"depends": {
|
"depends": {
|
||||||
"fabricloader": ">=${loader_version}",
|
"fabricloader": ">=${loader_version}",
|
||||||
"fabric-api": "*",
|
"fabric-api": "*",
|
||||||
"minecraft": "${minecraft_version}",
|
"minecraft": "${minecraft_version}"
|
||||||
|
},
|
||||||
|
"suggests": {
|
||||||
"cloth-config2": ">=${cloth_config_version}"
|
"cloth-config2": ">=${cloth_config_version}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user