Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1bc688d83 | ||
|
|
efe19edaf4 | ||
|
|
d12890f8eb | ||
|
|
69244ef832 | ||
|
|
d04afe2968 | ||
|
|
f19a5d3586 | ||
|
|
0e53d7dd8c | ||
|
|
f3a2a5d463 | ||
|
|
d065c6897e |
+2
-1
@@ -20,7 +20,8 @@ hs_err_pid*
|
||||
# Common working directory
|
||||
run
|
||||
|
||||
backend/SpMega.Backend/src/*
|
||||
backend/SpMega.Backend/bin/*
|
||||
backend/SpMega.Backend/obj/*
|
||||
backend/SpMega.Backend/appsettings.json
|
||||
backend/SpMega.Backend/appsettings.Development.json
|
||||
backend/SpMega.Backend/SpMega.Backend.http
|
||||
@@ -1,3 +1,4 @@
|
||||

|
||||
# SPMega
|
||||
|
||||
SPMega - клиентский Fabric-мод с банковым UI для работы с картами и переводами через API `spworlds.ru`.
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
@@ -19,6 +20,7 @@ namespace SpMega.Backend.Controllers.v1;
|
||||
|
||||
public record GetSessionIdBody(string userName, Guid userUUID);
|
||||
public record ValidateSessionBody(string sessionId, Guid userUUID);
|
||||
|
||||
[Route("api/v1/auth")]
|
||||
[ApiController]
|
||||
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);
|
||||
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>();
|
||||
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 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)
|
||||
{
|
||||
user.Token = token;
|
||||
user.Username = session.UserName;
|
||||
user.UpdatedAt = DateTime.UtcNow;
|
||||
user.ShortId ??= shortId;
|
||||
|
||||
dbContext.Update(user);
|
||||
}
|
||||
else
|
||||
@@ -83,6 +110,8 @@ public class AuthController(AppDbContext dbContext, TokenService tokenService, I
|
||||
Id = body.userUUID,
|
||||
Username = session.UserName,
|
||||
Token = token,
|
||||
UpdatedAt = DateTime.UtcNow,
|
||||
ShortId = shortId,
|
||||
};
|
||||
await dbContext.AddAsync(user);
|
||||
}
|
||||
@@ -109,15 +138,17 @@ public class AuthController(AppDbContext dbContext, TokenService tokenService, I
|
||||
string Base64BearerToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(BearerToken));
|
||||
var resp = await SendRequest("/accounts/me", new("Bearer", Base64BearerToken));
|
||||
var me = JsonSerializer.Deserialize<UserAccountDTO>(resp);
|
||||
Console.WriteLine(resp);
|
||||
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))
|
||||
{
|
||||
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 existingCard = user.Cards.FirstOrDefault(k => k.Id.ToString() == card.id);
|
||||
@@ -126,6 +157,7 @@ public class AuthController(AppDbContext dbContext, TokenService tokenService, I
|
||||
{
|
||||
Id = Guid.Parse(card.id),
|
||||
Name = card.name,
|
||||
Balance = balance ?? -1,
|
||||
SpworldsID = card.number,
|
||||
Token = Base64BearerToken,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
@@ -136,6 +168,7 @@ public class AuthController(AppDbContext dbContext, TokenService tokenService, I
|
||||
existingCard.Name = card.name;
|
||||
existingCard.SpworldsID = card.number;
|
||||
existingCard.Token = Base64BearerToken;
|
||||
existingCard.Balance = balance ?? -1;
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -37,12 +37,7 @@ public class TransactionsController(AppDbContext context, ILogger<TransactionsCo
|
||||
ShortId = "00000000",
|
||||
ReceiverName = "yawaflua",
|
||||
ReceiverCardNumber = "00000",
|
||||
Sender = new User
|
||||
{
|
||||
Id = default,
|
||||
Username = "yawaflua",
|
||||
Token = "123",
|
||||
},
|
||||
SenderMinecraftName = "yawaflua",
|
||||
SenderCardNumber = "010101",
|
||||
Amount = 42,
|
||||
Comment = "API FIRST",
|
||||
@@ -70,14 +65,19 @@ public class TransactionsController(AppDbContext context, ILogger<TransactionsCo
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
shortId = Program.GenerateRandomString(5);
|
||||
shortId = Program.GenerateRandomString(2);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -87,31 +87,31 @@ public class TransactionsController(AppDbContext context, ILogger<TransactionsCo
|
||||
var transaction = new Transaction
|
||||
{
|
||||
ReceiverName = body.receiverName,
|
||||
ShortId = shortId,
|
||||
ShortId = $"{user.ShortId}{shortId}",
|
||||
ReceiverCardNumber = body.receiverCard,
|
||||
Sender = user,
|
||||
SenderCardNumber = body.cardId,
|
||||
SenderCardNumber = cardToUse.SpworldsID,
|
||||
SenderMinecraftName = user.Username,
|
||||
Amount = body.amount,
|
||||
Comment = body.comment,
|
||||
Comment = body.comment
|
||||
};
|
||||
try
|
||||
{
|
||||
var uri = "s.ywfl.dev" + "/" + shortId;
|
||||
var uri = "ywfl.dev" + "/s" + shortId;
|
||||
var transitionInfo = new Dictionary<string, object>
|
||||
{
|
||||
{ "receiver", body.receiverCard },
|
||||
{ "amount", body.amount },
|
||||
{ "comment", body.comment + ";Чек:"+ uri }
|
||||
{ "comment", (body.comment)[10..] + "..;Чек:"+ uri }
|
||||
};
|
||||
Console.WriteLine((body.comment + ";Чек: "+ uri).Length);
|
||||
Console.WriteLine((body.comment + ";Чек: "+ uri));
|
||||
var resp = await SendRequest(endpoint: "transactions", body: transitionInfo,
|
||||
AuthHeader: new("Bearer", cardToUse.Token));
|
||||
var resp = await SendRequest(endpoint: "transactions", body: transitionInfo, AuthHeader: new("Bearer", cardToUse.Token));
|
||||
var balance = (int?)JsonNode.Parse(resp)?["balance"];
|
||||
if (balance == null)
|
||||
{
|
||||
throw new Exception("Failed to create transaction: " + resp);
|
||||
}
|
||||
cardToUse.Balance = balance.Value;
|
||||
|
||||
|
||||
} catch (Exception exception)
|
||||
{
|
||||
@@ -125,6 +125,12 @@ public class TransactionsController(AppDbContext context, ILogger<TransactionsCo
|
||||
{
|
||||
Id = transaction.Id,
|
||||
ReceiverName = transaction.ReceiverName,
|
||||
ReceiverCardNumber = transaction.ReceiverCardNumber,
|
||||
SenderMinecraftName = transaction.SenderMinecraftName,
|
||||
SenderCardNumber = transaction.SenderCardNumber,
|
||||
Amount = transaction.Amount,
|
||||
Comment = transaction.Comment,
|
||||
TransactionDate = transaction.TransactionDate
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
</a>
|
||||
<div class="meta-info">
|
||||
<div>Версия: <span class="badge">1.0.0-2026</span></div>
|
||||
<div style="margin-top: 4px;">Обновлено: 28 июня 2026</div>
|
||||
<div>Версия: <span class="badge">1.0.1-2026</span></div>
|
||||
<div style="margin-top: 4px;">Обновлено: 12 июля 2026</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -490,7 +490,11 @@
|
||||
<li>Время первой и последующих авторизаций.</li>
|
||||
<li>Ваш текущий IP-адрес для предотвращения и выявления попыток взлома API.</li>
|
||||
<li>Техническую информацию о транзакциях (суммы, комментарии, номера виртуальных счетов/карт и идентификаторы).</li>
|
||||
<li>Технические характеристики устройства: процессор, видеокарту, объем оперативной памяти, операционную систему и название компьютера.</li>
|
||||
<li>Показатели производительности мода, включая FPS и тайминги запросов.</li>
|
||||
<li>Трассировочную информацию о запросах к серверной части SPMega для диагностики ошибок и улучшения качества мода.</li>
|
||||
</ul>
|
||||
<p>Количество передаваемой телеметрии можно уменьшить в настройках модификации.</p>
|
||||
<p>Мы не сохраняем:</p>
|
||||
<ul>
|
||||
<li>Токен карты «КАК ЕСТЬ», данные шифруются по протоколу AES-256-CBC, и только после этого сохраняются в базе данных.</li>
|
||||
@@ -504,10 +508,11 @@
|
||||
<p>Мы высоко ценим доверие наших пользователей и гарантируем сохранность собираемой информации. Все личные данные передаются и обрабатываются по защищенным зашифрованным каналам связи (HTTPS/SSL).</p>
|
||||
<p>Администрация сайта строго обязуется:</p>
|
||||
<ul>
|
||||
<li><strong>Не передавать, не продавать и не распространять</strong> ваши личные данные, IP-адреса и статистику третьим лицам.</li>
|
||||
<li><strong>Не передавать, не продавать и не распространять</strong> ваши личные данные, IP-адреса, телеметрию и статистику третьим лицам.</li>
|
||||
<li>Использовать собранную анонимизированную статистику исключительно во внутренних аналитических целях для улучшения производительности мода.</li>
|
||||
<li>Раскрывать информацию только в случаях, прямо предусмотренных действующим законодательством государства Израиль при наличии официальных судебных или правоохранительных запросов.</li>
|
||||
</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 6 -->
|
||||
|
||||
@@ -587,7 +587,7 @@
|
||||
|
||||
<div class="meta-row">
|
||||
<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 class="meta-row">
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MongoDB.EntityFrameworkCore.Extensions;
|
||||
using SpMega.Backend.Persistent.Models.Telemetry;
|
||||
using SpMega.Backend.Persistent.Models.Transactions;
|
||||
using SpMega.Backend.Persistent.Models.Users;
|
||||
using SpMega.Backend.Services;
|
||||
@@ -11,6 +12,7 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
|
||||
internal DbSet<Transaction> Transactions { get; set; }
|
||||
internal DbSet<User> Users { get; set; }
|
||||
internal DbSet<UserSession> UserSessions { get; set; }
|
||||
internal DbSet<Notification> Notifications { get; set; }
|
||||
|
||||
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 SpMega.Backend.Persistent.Models.Users;
|
||||
|
||||
@@ -7,13 +8,15 @@ public class Transaction
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string ShortId { get; set; } = Program.GenerateRandomString(8);
|
||||
public string ReceiverName { get; set; }
|
||||
public string ReceiverCardNumber { get; set; }
|
||||
[MaxLength(2048)] public string ReceiverName { get; set; }
|
||||
[MaxLength(2048)] public string ReceiverCardNumber { 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 string Comment { get; set; } = "";
|
||||
[MaxLength(2048)] public string Comment { get; set; } = "";
|
||||
|
||||
public DateTime TransactionDate { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
@@ -9,6 +9,10 @@ public class Card
|
||||
public string Name { get; set; }
|
||||
public string SpworldsID { 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 UpdatedAt { get; set; }
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using SpMega.Backend.Persistent.Models.Transactions;
|
||||
|
||||
namespace SpMega.Backend.Persistent.Models.Users;
|
||||
@@ -5,8 +6,10 @@ namespace SpMega.Backend.Persistent.Models.Users;
|
||||
public class User
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Username { get; set; }
|
||||
public string Token { get; set; }
|
||||
[MaxLength(2048)] public string Username { get; set; }
|
||||
[MaxLength(2048)] public string Token { get; set; }
|
||||
|
||||
[MaxLength(2048)] public string? ShortId { get; set; }
|
||||
|
||||
public List<Card> Cards { get; set; } = [];
|
||||
public List<Transaction> Transactions { get; set; } = [];
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SpMega.Backend.Persistent.Models.Users;
|
||||
|
||||
public class UserSession
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Token { get; set; }
|
||||
[MaxLength(2048)] public string Token { get; set; }
|
||||
public User? User { get; set; } = null;
|
||||
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 UpdatedAt { get; set; }
|
||||
|
||||
@@ -3,7 +3,12 @@ using System.Text;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MongoDB.Driver;
|
||||
using OpenTelemetry.Exporter;
|
||||
using OpenTelemetry.Metrics;
|
||||
using OpenTelemetry.Resources;
|
||||
using OpenTelemetry.Trace;
|
||||
using SpMega.Backend.Authetication;
|
||||
using SpMega.Backend.Middleware;
|
||||
using SpMega.Backend.Persistent.Database;
|
||||
using SpMega.Backend.Services;
|
||||
|
||||
@@ -56,18 +61,51 @@ public class Program
|
||||
.RequireAuthenticatedUser()
|
||||
.Build());
|
||||
|
||||
var serviceCollection = new ServiceCollection();
|
||||
var mongoClient =
|
||||
new MongoClient(builder.Configuration.GetValue<string>("Mongo") ?? "mongodb://curiosity:27018");
|
||||
serviceCollection.AddSingleton<IMongoClient>(mongoClient);
|
||||
|
||||
builder.Services.AddSingleton<IMongoClient>(mongoClient);
|
||||
|
||||
builder.Services.AddDbContext<AppDbContext>((_, options) =>
|
||||
{
|
||||
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();
|
||||
|
||||
app.UseMiddleware<RequestTelemetryMiddleware>();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api"), appBuilder =>
|
||||
@@ -95,4 +133,4 @@ public class Program
|
||||
|
||||
return result.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,9 @@
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.19.1" />
|
||||
<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="System.IdentityModel.Tokens.Jwt" Version="8.19.1" />
|
||||
</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
|
||||
loader_version=0.18.1
|
||||
# Mod Properties
|
||||
mod_version=0.4-pre-alpha
|
||||
mod_version=0.5-beta
|
||||
maven_group=git.yawaflua.tech
|
||||
archives_base_name=SPMega
|
||||
# Dependencies
|
||||
|
||||
@@ -34,6 +34,10 @@ public class ModMenuIntegration implements ModMenuApi {
|
||||
final boolean[] allowBackend = {current.allowBackend()};
|
||||
final boolean[] signQuickPayEnabled = {current.signQuickPayEnabled()};
|
||||
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())
|
||||
.setDefaultValue(ModConfig.DEFAULT_API_DOMAIN)
|
||||
@@ -55,10 +59,12 @@ public class ModMenuIntegration implements ModMenuApi {
|
||||
.setTooltip(Text.literal("Запустить процесс авторизации через Mojang и ваш бэкенд"))
|
||||
.setSaveConsumer(newValue -> {
|
||||
if (newValue) {
|
||||
BackendAuthenticator.authenticate(MinecraftClient.getInstance());
|
||||
if (SPMega.getConfig() != null) {
|
||||
apiToken[0] = SPMega.getConfig().apiToken();
|
||||
}
|
||||
BackendAuthenticator.authenticateAsync(MinecraftClient.getInstance())
|
||||
.thenAccept(authenticated -> {
|
||||
if (authenticated && SPMega.getConfig() != null) {
|
||||
apiToken[0] = SPMega.getConfig().apiToken();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
apiToken[0] = ModConfig.DEFAULT_API_TOKEN;
|
||||
}
|
||||
@@ -80,6 +86,34 @@ public class ModMenuIntegration implements ModMenuApi {
|
||||
.setSaveConsumer(newValue -> gpsPosition[0] = newValue)
|
||||
.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(() -> {
|
||||
boolean gpsEnabledVal = true;
|
||||
if (SPMega.getConfig() != null) {
|
||||
@@ -91,7 +125,10 @@ public class ModMenuIntegration implements ModMenuApi {
|
||||
allowBackend[0],
|
||||
signQuickPayEnabled[0],
|
||||
gpsEnabledVal,
|
||||
gpsPosition[0]
|
||||
gpsPosition[0],
|
||||
notificationPosition[0],
|
||||
telemetryIntervalSeconds[0],
|
||||
telemetryCollectSystemInfo[0]
|
||||
);
|
||||
SPMega.setConfig(updated);
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ package git.yawaflua.tech.spmega.client;
|
||||
import git.yawaflua.tech.spmega.ModConfig;
|
||||
import git.yawaflua.tech.spmega.SPMega;
|
||||
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.UiNotifications;
|
||||
import git.yawaflua.tech.spmega.client.ui.UiOpeners;
|
||||
@@ -26,7 +27,6 @@ import net.minecraft.text.Text;
|
||||
import net.minecraft.util.ActionResult;
|
||||
import org.lwjgl.glfw.GLFW;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -100,12 +100,13 @@ public class SPMegaClient implements ClientModInitializer {
|
||||
}
|
||||
|
||||
ClientTickEvents.END_CLIENT_TICK.register(client -> {
|
||||
PerformanceSampler.instance().tick();
|
||||
UiNotifications.instance().tick();
|
||||
while (openBankMenuKeyBinding.wasPressed()) {
|
||||
UiOpeners.openMainMenu(client);
|
||||
}
|
||||
while (scanQrKeyBinding.wasPressed()) {
|
||||
QRCodeScanner.ScanQrCode(client);
|
||||
QRCodeScanner.scanQrCode(client);
|
||||
}
|
||||
while (toggleGpsKeyBinding.wasPressed()) {
|
||||
GpsHudRenderer.instance().toggle();
|
||||
@@ -117,7 +118,10 @@ public class SPMegaClient implements ClientModInitializer {
|
||||
current.allowBackend(),
|
||||
current.signQuickPayEnabled(),
|
||||
GpsHudRenderer.instance().isEnabled(),
|
||||
current.gpsPosition()
|
||||
current.gpsPosition(),
|
||||
current.notificationPosition(),
|
||||
current.telemetryIntervalSeconds(),
|
||||
current.telemetryCollectSystemInfo()
|
||||
);
|
||||
SPMega.setConfig(updated);
|
||||
}
|
||||
@@ -227,11 +231,33 @@ public class SPMegaClient implements ClientModInitializer {
|
||||
});
|
||||
|
||||
new ChatListener().register();
|
||||
CompletableFuture.runAsync(() -> 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("If u want to see more updates - give me like 10 shekels for monster plzzz");
|
||||
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.HybridBinarizer;
|
||||
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.UiNotifications;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.client.texture.NativeImage;
|
||||
import net.minecraft.client.util.ScreenshotRecorder;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumMap;
|
||||
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) {
|
||||
return;
|
||||
}
|
||||
@@ -30,6 +41,7 @@ public class QRCodeScanner {
|
||||
return;
|
||||
}
|
||||
|
||||
long startNs = System.nanoTime();
|
||||
try {
|
||||
ScreenshotRecorder.takeScreenshot(client.getFramebuffer(), nativeImage -> {
|
||||
try {
|
||||
@@ -39,24 +51,28 @@ public class QRCodeScanner {
|
||||
notifications.show(Text.translatable("message.spmega.qr.capture_failed"));
|
||||
}
|
||||
});
|
||||
recordQrEvent(false, false, null, "capture_failed", startNs);
|
||||
return;
|
||||
}
|
||||
|
||||
String result = decodeQRCode(nativeImageToBufferedImage(nativeImage));
|
||||
client.execute(() -> {
|
||||
if (client.player == null) {
|
||||
return;
|
||||
}
|
||||
if (result == null) {
|
||||
notifications.show(Text.translatable("message.spmega.qr.not_found"));
|
||||
return;
|
||||
}
|
||||
|
||||
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));
|
||||
});
|
||||
int width = nativeImage.getWidth();
|
||||
int height = nativeImage.getHeight();
|
||||
int[] pixels = nativeImage.copyPixelsArgb();
|
||||
CompletableFuture.supplyAsync(() -> decodeQrCode(width, height, pixels), DECODER)
|
||||
.whenComplete((result, throwable) -> {
|
||||
client.execute(() -> showResult(client, notifications, result, throwable));
|
||||
recordQrEvent(
|
||||
throwable == null && result != null,
|
||||
System.nanoTime() - startNs > 50_000_000L,
|
||||
result,
|
||||
throwable == null ? null : throwable.getClass().getSimpleName() + ": " + throwable.getMessage(),
|
||||
startNs
|
||||
);
|
||||
});
|
||||
} catch (Exception exception) {
|
||||
client.execute(() -> notifications.show(Text.translatable("message.spmega.qr.error")));
|
||||
recordQrEvent(false, false, null,
|
||||
exception.getClass().getSimpleName() + ": " + exception.getMessage(), startNs);
|
||||
} finally {
|
||||
if (nativeImage != null) {
|
||||
nativeImage.close();
|
||||
@@ -65,34 +81,55 @@ public class QRCodeScanner {
|
||||
});
|
||||
} catch (Exception ex) {
|
||||
notifications.show(Text.translatable("message.spmega.qr.error"));
|
||||
recordQrEvent(false, false, null, ex.getClass().getSimpleName() + ": " + ex.getMessage(), startNs);
|
||||
}
|
||||
}
|
||||
|
||||
private static BufferedImage nativeImageToBufferedImage(NativeImage screenshot) {
|
||||
BufferedImage bufferedImage = new BufferedImage(
|
||||
screenshot.getWidth(),
|
||||
screenshot.getHeight(),
|
||||
BufferedImage.TYPE_INT_RGB
|
||||
);
|
||||
|
||||
for (int y = 0; y < screenshot.getHeight(); y++) {
|
||||
for (int x = 0; x < screenshot.getWidth(); x++) {
|
||||
int color = screenshot.getColorArgb(x, y);
|
||||
bufferedImage.setRGB(x, y, color);
|
||||
}
|
||||
private static void showResult(
|
||||
MinecraftClient client,
|
||||
UiNotifications notifications,
|
||||
String result,
|
||||
Throwable throwable
|
||||
) {
|
||||
if (client.player == null) {
|
||||
return;
|
||||
}
|
||||
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);
|
||||
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
|
||||
hints.put(DecodeHintType.POSSIBLE_FORMATS, Collections.singletonList(BarcodeFormat.QR_CODE));
|
||||
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
|
||||
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);
|
||||
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package git.yawaflua.tech.spmega.client.ui;
|
||||
import git.yawaflua.tech.spmega.client.ui.service.BankUiService;
|
||||
import git.yawaflua.tech.spmega.client.ui.service.CardViewModel;
|
||||
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.widget.ButtonWidget;
|
||||
import net.minecraft.text.Text;
|
||||
@@ -16,6 +17,7 @@ public class CardScreen extends Screen {
|
||||
private final UiNotifications notifications = UiNotifications.instance();
|
||||
private final List<ButtonWidget> cardButtons = new ArrayList<>();
|
||||
private ButtonWidget historyButton;
|
||||
private ButtonWidget webhookButton;
|
||||
|
||||
public CardScreen(Screen parent) {
|
||||
super(Text.literal("Управление картами"));
|
||||
@@ -93,8 +95,30 @@ public class CardScreen extends Screen {
|
||||
this.client.setScreen(new TransactionHistoryScreen(this, selected.id(), selected.title()));
|
||||
}).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())
|
||||
.dimensions(rightX, startY + 120, columnWidth, 20)
|
||||
.dimensions(rightX, startY + 144, columnWidth, 20)
|
||||
.build());
|
||||
|
||||
if (cards.isEmpty()) {
|
||||
@@ -147,5 +171,11 @@ public class CardScreen extends Screen {
|
||||
if (historyButton != null) {
|
||||
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 git.yawaflua.tech.spmega.GpsHudPosition;
|
||||
import git.yawaflua.tech.spmega.SPMega;
|
||||
import git.yawaflua.tech.spmega.client.telemetry.InstrumentedHttpClient;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.client.font.TextRenderer;
|
||||
import net.minecraft.client.gui.DrawContext;
|
||||
@@ -10,9 +11,7 @@ import net.minecraft.text.Text;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -21,9 +20,8 @@ import java.util.concurrent.TimeUnit;
|
||||
|
||||
public final class GpsHudRenderer {
|
||||
private static final GpsHudRenderer INSTANCE = new GpsHudRenderer();
|
||||
private final Object citiesLock = new Object();
|
||||
private boolean enabled = true;
|
||||
private List<City> cities = new ArrayList<>();
|
||||
private volatile List<City> cities = List.of();
|
||||
|
||||
private GpsHudRenderer() {
|
||||
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
@@ -51,33 +49,35 @@ public final class GpsHudRenderer {
|
||||
}
|
||||
|
||||
private void fetchCities() {
|
||||
try {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("https://spm-map.tonyaleksandr.ru/api/map/territories"))
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() == 200) {
|
||||
TerritoryWrapper[] parsed = new Gson().fromJson(response.body(), TerritoryWrapper[].class);
|
||||
if (parsed != null) {
|
||||
List<City> list = new ArrayList<>();
|
||||
for (TerritoryWrapper w : parsed) {
|
||||
if (w != null && w.territory != null && w.territory.nether_portal != null && w.territory.nether_portal.length >= 2) {
|
||||
City c = new City();
|
||||
c.name = w.territory.name;
|
||||
c.netherX = w.territory.nether_portal[0];
|
||||
c.netherZ = w.territory.nether_portal[1];
|
||||
list.add(c);
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("https://map.sp-mini.ru/api/map/territories"))
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
new InstrumentedHttpClient().sendAsync(request)
|
||||
.thenAccept(response -> {
|
||||
if (response.statusCode() != 200) {
|
||||
return;
|
||||
}
|
||||
TerritoryWrapper[] parsed = new Gson().fromJson(response.body(), TerritoryWrapper[].class);
|
||||
if (parsed == null) {
|
||||
return;
|
||||
}
|
||||
List<City> updatedCities = new ArrayList<>();
|
||||
for (TerritoryWrapper wrapper : parsed) {
|
||||
if (wrapper != null && wrapper.territory != null
|
||||
&& wrapper.territory.nether_portal != null
|
||||
&& wrapper.territory.nether_portal.length >= 2) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
cities = List.copyOf(updatedCities);
|
||||
})
|
||||
.exceptionally(ignored -> null);
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
City nearestCity = null;
|
||||
double minDistanceSq = Double.MAX_VALUE;
|
||||
double minDistanceSquared = Double.MAX_VALUE;
|
||||
for (City city : cities) {
|
||||
double dx = playerX - (city.netherX / 8);
|
||||
double dz = playerZ - (city.netherZ / 8);
|
||||
double distSq = Math.sqrt(dx * dx + dz * dz);
|
||||
if (distSq < minDistanceSq) {
|
||||
minDistanceSq = distSq;
|
||||
double distanceSquared = dx * dx + dz * dz;
|
||||
if (distanceSquared < minDistanceSquared) {
|
||||
minDistanceSquared = distanceSquared;
|
||||
nearestCity = city;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ public class MainBankScreen extends Screen {
|
||||
|
||||
this.addDrawableChild(ButtonWidget.builder(Text.translatable("button.spmega.scan_qr"), button -> {
|
||||
this.client.setScreen(null);
|
||||
QRCodeScanner.ScanQrCode(this.client);
|
||||
QRCodeScanner.scanQrCode(this.client);
|
||||
}).dimensions(centerX - 60, y + 28, 120, 20).build());
|
||||
}
|
||||
|
||||
|
||||
@@ -107,50 +107,47 @@ public class TransactionHistoryScreen extends Screen {
|
||||
|
||||
UiNotifications.instance().show(Text.literal("Загрузка..."));
|
||||
|
||||
CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
System.out.println("[SPMEGA] Transaction history loading started for card: " + cardId + ", page: " + currentPage);
|
||||
List<LocalTransaction> list = null;
|
||||
git.yawaflua.tech.spmega.ModConfig config = git.yawaflua.tech.spmega.SPMega.getConfig();
|
||||
if (config != null && config.allowBackend()) {
|
||||
try {
|
||||
list = BackendAuthenticator.fetchTransactionsFromBackend(cardId, currentPage);
|
||||
System.out.println("[SPMEGA] Fetched " + (list != null ? list.size() : "null") + " transactions from backend.");
|
||||
} catch (Exception e) {
|
||||
System.err.println("[SPMEGA] Failed to fetch transactions from server, falling back to DB: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
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();
|
||||
CompletableFuture<List<LocalTransaction>> remote = config != null && config.allowBackend()
|
||||
? BackendAuthenticator.fetchTransactionsFromBackendAsync(cardId, page)
|
||||
.whenComplete((list, exception) -> {
|
||||
if (exception == null) {
|
||||
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);
|
||||
|
||||
remote.thenApply(list -> {
|
||||
if (list != null) {
|
||||
return list;
|
||||
}
|
||||
List<LocalTransaction> local = BankUiService.instance().getDatabase().loadTransferHistory(cardId);
|
||||
System.out.println("[SPMEGA] Loaded " + local.size() + " transactions from database.");
|
||||
return local;
|
||||
})
|
||||
.whenComplete((list, exception) -> {
|
||||
MinecraftClient minecraftClient = MinecraftClient.getInstance();
|
||||
if (minecraftClient == null) {
|
||||
System.out.println("[SPMEGA] MinecraftClient.getInstance() is null in loadTransactions callback!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (list == null) {
|
||||
list = BankUiService.instance().getDatabase().loadTransferHistory(cardId);
|
||||
System.out.println("[SPMEGA] Loaded " + (list != null ? list.size() : "null") + " transactions from database.");
|
||||
}
|
||||
|
||||
List<LocalTransaction> finalList = list != null ? list : new ArrayList<>();
|
||||
MinecraftClient minecraftClient = MinecraftClient.getInstance();
|
||||
if (minecraftClient != null) {
|
||||
minecraftClient.execute(() -> {
|
||||
System.out.println("[SPMEGA] Setting transactions list on main thread. Count: " + finalList.size());
|
||||
this.transactions.addAll(finalList);
|
||||
this.scrollOffset = 0;
|
||||
this.loading = false;
|
||||
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;
|
||||
});
|
||||
} else {
|
||||
System.out.println("[SPMEGA] MinecraftClient.getInstance() is null in loadTransactions callback!");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("[SPMEGA] Outer exception in loadTransactions: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
MinecraftClient minecraftClient = MinecraftClient.getInstance();
|
||||
if (minecraftClient != null) {
|
||||
minecraftClient.execute(() -> {
|
||||
this.errorMessage = e.getMessage();
|
||||
this.loading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -5,17 +5,22 @@ import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.google.gson.Strictness;
|
||||
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.gui.DrawContext;
|
||||
import net.minecraft.text.Text;
|
||||
|
||||
import java.awt.*;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Queue;
|
||||
|
||||
public final class UiNotifications {
|
||||
private static final int DEFAULT_DURATION_TICKS = 70;
|
||||
private static final UiNotifications INSTANCE = new UiNotifications();
|
||||
|
||||
private Text currentText = Text.empty();
|
||||
private final Queue<Text> queuedTexts = new ArrayDeque<>();
|
||||
private int remainingTicks;
|
||||
|
||||
private UiNotifications() {
|
||||
@@ -62,6 +67,17 @@ public final class UiNotifications {
|
||||
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) {
|
||||
if (!isVisible()) {
|
||||
return;
|
||||
@@ -72,8 +88,18 @@ public final class UiNotifications {
|
||||
int textWidth = textRenderer.getWidth(message);
|
||||
int boxWidth = textWidth + padding * 2;
|
||||
int boxHeight = textRenderer.fontHeight + padding * 2;
|
||||
int x = width - boxWidth - 10;
|
||||
int y = height - boxHeight - 10;
|
||||
GpsHudPosition position = SPMega.getConfig() == null
|
||||
? 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.drawTextWithShadow(textRenderer, currentText, x + padding, y + padding, Color.WHITE.getRGB());
|
||||
@@ -85,8 +111,8 @@ public final class UiNotifications {
|
||||
}
|
||||
remainingTicks--;
|
||||
if (remainingTicks <= 0) {
|
||||
currentText = Text.empty();
|
||||
remainingTicks = 0;
|
||||
currentText = queuedTexts.isEmpty() ? Text.empty() : queuedTexts.remove();
|
||||
remainingTicks = currentText.getString().isBlank() ? 0 : DEFAULT_DURATION_TICKS;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+204
-111
@@ -7,54 +7,59 @@ import com.mojang.authlib.exceptions.AuthenticationException;
|
||||
import com.mojang.authlib.minecraft.MinecraftSessionService;
|
||||
import git.yawaflua.tech.spmega.ModConfig;
|
||||
import git.yawaflua.tech.spmega.SPMega;
|
||||
import git.yawaflua.tech.spmega.client.telemetry.InstrumentedHttpClient;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.client.session.Session;
|
||||
|
||||
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.util.ArrayList;
|
||||
import java.util.List;
|
||||
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();
|
||||
if (session == null || session.getUuidOrNull() == null) {
|
||||
System.err.println("Cannot authenticate: Client has no valid session.");
|
||||
return false;
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}
|
||||
|
||||
MinecraftSessionService sessionService = client.getApiServices().sessionService();
|
||||
|
||||
try {
|
||||
var serverId = sendStartSessionRequestToBackend(session.getUsername(), session.getUuidOrNull());
|
||||
System.out.println("[SPMEGA] Trying to auth in mojang with serverId: " + serverId);
|
||||
sessionService.joinServer(
|
||||
session.getUuidOrNull(),
|
||||
session.getAccessToken(),
|
||||
serverId
|
||||
);
|
||||
System.out.println("[SPMEGA] Sending session submitter to backend");
|
||||
|
||||
return sendAuthRequestToBackend(session.getUuidOrNull(), serverId);
|
||||
|
||||
} catch (AuthenticationException e) {
|
||||
System.err.println("I cant auth by Mojang: " + e.getMessage());
|
||||
System.err.println("Please check your credentials and try again.");
|
||||
return false;
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("Failed to authenticate with backend: " + e.getMessage());
|
||||
return false;
|
||||
|
||||
}
|
||||
return sendStartSessionRequestToBackendAsync(session.getUsername(), session.getUuidOrNull())
|
||||
.thenCompose(serverId -> CompletableFuture.runAsync(() -> {
|
||||
System.out.println("[SPMEGA] Trying to auth in mojang with serverId: " + serverId);
|
||||
try {
|
||||
sessionService.joinServer(session.getUuidOrNull(), session.getAccessToken(), serverId);
|
||||
} catch (AuthenticationException exception) {
|
||||
throw new CompletionException(exception);
|
||||
}
|
||||
})
|
||||
.thenCompose(ignored -> {
|
||||
System.out.println("[SPMEGA] Sending session submitter to backend");
|
||||
return sendAuthRequestToBackendAsync(session.getUuidOrNull(), serverId);
|
||||
}))
|
||||
.exceptionally(throwable -> {
|
||||
Throwable cause = throwable.getCause() == null ? throwable : throwable.getCause();
|
||||
if (cause instanceof AuthenticationException) {
|
||||
System.err.println("I cant auth by Mojang: " + cause.getMessage());
|
||||
System.err.println("Please check your credentials and try again.");
|
||||
} else {
|
||||
System.err.println("Failed to authenticate with backend: " + cause.getMessage());
|
||||
}
|
||||
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();
|
||||
String apiDomain = (config != null) ? config.apiDomain() : ModConfig.DEFAULT_API_DOMAIN;
|
||||
if (apiDomain == null || apiDomain.isBlank()) {
|
||||
@@ -71,28 +76,29 @@ public class BackendAuthenticator {
|
||||
|
||||
String url = apiDomain + "/api/v1/auth/start";
|
||||
|
||||
HttpClient httpClient = HttpClient.newHttpClient();
|
||||
InstrumentedHttpClient httpClient = new InstrumentedHttpClient();
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json")
|
||||
.method("POST", HttpRequest.BodyPublishers.ofString(requestBody))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() != 200) {
|
||||
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());
|
||||
}
|
||||
|
||||
JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject();
|
||||
if (!json.has("sessionId")) {
|
||||
System.err.println("[SPMEGA] Invalid response from start endpoint: " + response.body());
|
||||
throw new IOException("Invalid response from start endpoint: " + response.body());
|
||||
}
|
||||
return json.get("sessionId").getAsString();
|
||||
return httpClient.sendAsync(request).thenApply(response -> {
|
||||
if (response.statusCode() != 200) {
|
||||
System.err.println("[SPMEGA] 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();
|
||||
if (!json.has("sessionId")) {
|
||||
System.err.println("[SPMEGA] 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();
|
||||
String apiDomain = (config != null) ? config.apiDomain() : ModConfig.DEFAULT_API_DOMAIN;
|
||||
if (apiDomain == null || apiDomain.isBlank()) {
|
||||
@@ -109,41 +115,37 @@ public class BackendAuthenticator {
|
||||
|
||||
String url = apiDomain + "/api/v1/auth/validate";
|
||||
|
||||
HttpClient httpClient = HttpClient.newHttpClient();
|
||||
InstrumentedHttpClient httpClient = new InstrumentedHttpClient();
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() != 200) {
|
||||
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());
|
||||
}
|
||||
return httpClient.sendAsync(request).thenApply(response -> {
|
||||
if (response.statusCode() != 200) {
|
||||
System.err.println("[SPMEGA] 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")) {
|
||||
System.err.println("[SPMEGA] Invalid response from validate endpoint: " + response.body());
|
||||
throw new IOException("Invalid response from validate endpoint: " + response.body());
|
||||
}
|
||||
if (config == null) {
|
||||
System.err.println("[SPMEGA] Config is null, cannot save token.");
|
||||
throw new IOException("Config is null, cannot save token.");
|
||||
}
|
||||
|
||||
String token = json.get("token").getAsString();
|
||||
ModConfig updated = new ModConfig(
|
||||
config.apiDomain(),
|
||||
token,
|
||||
config.allowBackend(),
|
||||
config.signQuickPayEnabled(),
|
||||
config.gpsEnabled(),
|
||||
config.gpsPosition()
|
||||
);
|
||||
SPMega.setConfig(updated);
|
||||
System.out.println("[SPMEGA] Backend auth successful, saved token.");
|
||||
return true;
|
||||
String token = json.get("token").getAsString();
|
||||
SPMega.setConfig(new ModConfig(
|
||||
config.apiDomain(), token, config.allowBackend(), config.signQuickPayEnabled(),
|
||||
config.gpsEnabled(), config.gpsPosition(), config.notificationPosition(),
|
||||
config.telemetryIntervalSeconds(), config.telemetryCollectSystemInfo()));
|
||||
System.out.println("[SPMEGA] Backend auth successful, saved token.");
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public static void sendCardToBackend(String cardId, String cardToken) {
|
||||
@@ -167,7 +169,7 @@ public class BackendAuthenticator {
|
||||
jsonPayload.addProperty("token", cardToken);
|
||||
String requestBody = jsonPayload.toString();
|
||||
|
||||
HttpClient httpClient = HttpClient.newHttpClient();
|
||||
InstrumentedHttpClient httpClient = new InstrumentedHttpClient();
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json")
|
||||
@@ -175,7 +177,7 @@ public class BackendAuthenticator {
|
||||
.PUT(HttpRequest.BodyPublishers.ofString(requestBody))
|
||||
.build();
|
||||
|
||||
httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
httpClient.sendAsync(request)
|
||||
.thenAccept(response -> {
|
||||
if (response.statusCode() != 200 && response.statusCode() != 204) {
|
||||
System.err.println("[SPMEGA] Failed to send card to backend: status code "
|
||||
@@ -190,10 +192,10 @@ public class BackendAuthenticator {
|
||||
});
|
||||
}
|
||||
|
||||
public static List<CardCredentials> fetchCardsFromBackend() throws IOException, InterruptedException {
|
||||
public static CompletableFuture<List<CardCredentials>> fetchCardsFromBackendAsync() {
|
||||
ModConfig config = SPMega.getConfig();
|
||||
if (config == null || !config.allowBackend()) {
|
||||
return List.of();
|
||||
return CompletableFuture.completedFuture(List.of());
|
||||
}
|
||||
|
||||
String apiDomain = config.apiDomain();
|
||||
@@ -206,35 +208,36 @@ public class BackendAuthenticator {
|
||||
|
||||
String url = apiDomain + "/api/v1/auth/cards";
|
||||
|
||||
HttpClient httpClient = HttpClient.newHttpClient();
|
||||
InstrumentedHttpClient httpClient = new InstrumentedHttpClient();
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||
.header("Accept", "application/json")
|
||||
.header("Authorization", "Bearer " + config.apiToken())
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() != 200) {
|
||||
throw new IOException("Server returned status code " + response.statusCode() + " on fetch cards.");
|
||||
}
|
||||
|
||||
com.google.gson.JsonArray cardsArray = JsonParser.parseString(response.body()).getAsJsonArray();
|
||||
List<CardCredentials> cards = new ArrayList<>();
|
||||
for (com.google.gson.JsonElement el : cardsArray) {
|
||||
JsonObject cardJson = el.getAsJsonObject();
|
||||
String cardId = cardJson.has("cardId") && !cardJson.get("cardId").isJsonNull()
|
||||
? cardJson.get("cardId").getAsString()
|
||||
: (cardJson.has("id") && !cardJson.get("id").isJsonNull() ? cardJson.get("id").getAsString() : "");
|
||||
|
||||
String cardToken = cardJson.has("cardToken") && !cardJson.get("cardToken").isJsonNull()
|
||||
? cardJson.get("cardToken").getAsString()
|
||||
: (cardJson.has("token") && !cardJson.get("token").isJsonNull() ? cardJson.get("token").getAsString() : "");
|
||||
|
||||
if (!cardId.isEmpty() && !cardToken.isEmpty()) {
|
||||
cards.add(new CardCredentials(cardId, cardToken));
|
||||
return httpClient.sendAsync(request).thenApply(response -> {
|
||||
if (response.statusCode() != 200) {
|
||||
throw new CompletionException(new IOException(
|
||||
"Server returned status code " + response.statusCode() + " on fetch cards."));
|
||||
}
|
||||
}
|
||||
return cards;
|
||||
com.google.gson.JsonArray cardsArray = JsonParser.parseString(response.body()).getAsJsonArray();
|
||||
List<CardCredentials> cards = new ArrayList<>();
|
||||
for (com.google.gson.JsonElement element : cardsArray) {
|
||||
JsonObject cardJson = element.getAsJsonObject();
|
||||
String cardId = cardJson.has("cardId") && !cardJson.get("cardId").isJsonNull()
|
||||
? cardJson.get("cardId").getAsString()
|
||||
: (cardJson.has("id") && !cardJson.get("id").isJsonNull() ? cardJson.get("id").getAsString() : "");
|
||||
String cardToken = cardJson.has("cardToken") && !cardJson.get("cardToken").isJsonNull()
|
||||
? cardJson.get("cardToken").getAsString()
|
||||
: (cardJson.has("token") && !cardJson.get("token").isJsonNull() ? cardJson.get("token").getAsString() : "");
|
||||
boolean webhookEnabled = cardJson.has("webhookConnected")
|
||||
&& cardJson.get("webhookConnected").getAsBoolean();
|
||||
if (!cardId.isEmpty() && !cardToken.isEmpty()) {
|
||||
cards.add(new CardCredentials(cardId, cardToken, webhookEnabled));
|
||||
}
|
||||
}
|
||||
return cards;
|
||||
});
|
||||
}
|
||||
|
||||
public static void deleteCardOnBackend(String cardId) {
|
||||
@@ -253,14 +256,14 @@ public class BackendAuthenticator {
|
||||
|
||||
String url = apiDomain + "/api/v1/auth/cards/" + cardId;
|
||||
|
||||
HttpClient httpClient = HttpClient.newHttpClient();
|
||||
InstrumentedHttpClient httpClient = new InstrumentedHttpClient();
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||
.header("Accept", "application/json")
|
||||
.header("Authorization", "Bearer " + config.apiToken())
|
||||
.DELETE()
|
||||
.build();
|
||||
|
||||
httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
httpClient.sendAsync(request)
|
||||
.thenAccept(response -> {
|
||||
if (response.statusCode() != 200 && response.statusCode() != 204) {
|
||||
System.err.println("[SPMEGA] Failed to delete card from backend: status code "
|
||||
@@ -275,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();
|
||||
if (config == null) {
|
||||
throw new IOException("ModConfig is null");
|
||||
return CompletableFuture.failedFuture(new IOException("ModConfig is null"));
|
||||
}
|
||||
|
||||
String apiDomain = config.apiDomain();
|
||||
@@ -300,7 +380,7 @@ public class BackendAuthenticator {
|
||||
jsonPayload.addProperty("comment", comment);
|
||||
String requestBody = jsonPayload.toString();
|
||||
|
||||
HttpClient httpClient = HttpClient.newHttpClient();
|
||||
InstrumentedHttpClient httpClient = new InstrumentedHttpClient();
|
||||
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json")
|
||||
@@ -308,19 +388,22 @@ public class BackendAuthenticator {
|
||||
.PUT(HttpRequest.BodyPublishers.ofString(requestBody))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() != 200 && response.statusCode() != 201 && response.statusCode() != 204) {
|
||||
throw new IOException("Server returned status code " + response.statusCode() + ": " + response.body());
|
||||
}
|
||||
return true;
|
||||
return httpClient.sendAsync(request).thenApply(response -> {
|
||||
if (response.statusCode() != 200 && response.statusCode() != 201 && response.statusCode() != 204) {
|
||||
throw new CompletionException(new IOException(
|
||||
"Server returned status code " + response.statusCode() + ": " + response.body()));
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public static List<BankDatabase.LocalTransaction> fetchTransactionsFromBackend(String cardId, int page) 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();
|
||||
if (config == null || !config.allowBackend()) {
|
||||
System.out.println("[SPMEGA] fetchTransactionsFromBackend aborted: config is null or backend not allowed.");
|
||||
return List.of();
|
||||
return CompletableFuture.completedFuture(List.of());
|
||||
}
|
||||
|
||||
String apiDomain = config.apiDomain();
|
||||
@@ -334,18 +417,24 @@ public class BackendAuthenticator {
|
||||
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))
|
||||
.header("Accept", "application/json")
|
||||
.header("Authorization", "Bearer " + config.apiToken())
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
return httpClient.sendAsync(request)
|
||||
.thenApply(response -> parseTransactionsResponse(response, cardId));
|
||||
}
|
||||
|
||||
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 IOException("Server returned status code " + response.statusCode() + " on fetch transactions.");
|
||||
throw new CompletionException(new IOException(
|
||||
"Server returned status code " + response.statusCode() + " on fetch transactions."));
|
||||
}
|
||||
|
||||
String body = response.body();
|
||||
@@ -423,4 +512,8 @@ public class BackendAuthenticator {
|
||||
System.out.println("[SPMEGA] Returning " + list.size() + " filtered transactions for card " + cardId);
|
||||
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,
|
||||
balance INTEGER NOT NULL DEFAULT 0,
|
||||
owner_uuid TEXT,
|
||||
webhook_enabled INTEGER NOT NULL DEFAULT 0,
|
||||
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("""
|
||||
CREATE TABLE IF NOT EXISTS transfer_history (
|
||||
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() {
|
||||
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<>();
|
||||
try (Connection connection = open();
|
||||
PreparedStatement statement = connection.prepareStatement(sql);
|
||||
@@ -113,7 +150,8 @@ public final class BankDatabase {
|
||||
rs.getString("card_name"),
|
||||
rs.getString("card_number"),
|
||||
rs.getLong("balance"),
|
||||
rs.getString("owner_uuid")
|
||||
rs.getString("owner_uuid"),
|
||||
rs.getBoolean("webhook_enabled")
|
||||
));
|
||||
}
|
||||
return result;
|
||||
|
||||
@@ -2,7 +2,9 @@ package git.yawaflua.tech.spmega.client.ui.service;
|
||||
|
||||
import git.yawaflua.tech.spmega.ModConfig;
|
||||
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.minecraft.client.MinecraftClient;
|
||||
@@ -105,47 +107,37 @@ public final class BankUiService {
|
||||
return lastMessage;
|
||||
}
|
||||
|
||||
private static String rootMessage(Throwable throwable) {
|
||||
Throwable cause = throwable;
|
||||
while (cause.getCause() != null) {
|
||||
cause = cause.getCause();
|
||||
}
|
||||
return cause.getMessage();
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> syncCardsWithBackendAsync(String playerUuid) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
List<CardCredentials> backendCards = BackendAuthenticator.fetchCardsFromBackend();
|
||||
boolean changed = false;
|
||||
for (CardCredentials creds : backendCards) {
|
||||
if (database.getCredentials(creds.cardId()) == null) {
|
||||
database.upsertCardCredentials(creds.cardId(), creds.cardToken());
|
||||
refreshCardSync(creds.cardId(), creds.cardToken(), playerUuid, false, false);
|
||||
changed = true;
|
||||
return BackendAuthenticator.fetchCardsFromBackendAsync()
|
||||
.thenCompose(cards -> syncMissingCardsAsync(cards, playerUuid))
|
||||
.thenAccept(changed -> {
|
||||
if (changed) {
|
||||
reloadCardsFromDb();
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
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 CompletableFuture<Void> refreshOnServerJoinAsync(String playerUuid) {
|
||||
return CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
List<CardCredentials> backendCards = BackendAuthenticator.fetchCardsFromBackend();
|
||||
for (CardCredentials creds : backendCards) {
|
||||
if (database.getCredentials(creds.cardId()) == null) {
|
||||
database.upsertCardCredentials(creds.cardId(), creds.cardToken());
|
||||
refreshCardSync(creds.cardId(), creds.cardToken(), playerUuid, false, false);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("[SPMEGA] Failed to sync cards with backend: " + e.getMessage());
|
||||
}
|
||||
|
||||
List<StoredCard> storedCards = database.loadCards();
|
||||
for (StoredCard card : storedCards) {
|
||||
refreshCardSync(card.cardId(), card.cardToken(), playerUuid, false, false);
|
||||
}
|
||||
reloadCardsFromDb();
|
||||
});
|
||||
return BackendAuthenticator.fetchCardsFromBackendAsync()
|
||||
.exceptionally(exception -> {
|
||||
System.err.println("[SPMEGA] Failed to sync cards with backend: " + exception.getMessage());
|
||||
return List.of();
|
||||
})
|
||||
.thenCompose(cards -> syncMissingCardsAsync(cards, playerUuid))
|
||||
.thenCompose(ignored -> refreshStoredCardsAsync(playerUuid))
|
||||
.thenRun(this::reloadCardsFromDb);
|
||||
}
|
||||
|
||||
public CompletableFuture<List<String>> loadRecipientCardsAsync(String username) {
|
||||
@@ -154,9 +146,8 @@ public final class BankUiService {
|
||||
return CompletableFuture.completedFuture(List.of());
|
||||
}
|
||||
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
List<SPWorldsApiClient.PlayerCard> apiCards = apiClient.getPlayerCards(username, toApiAuth(credentials));
|
||||
return apiClient.getPlayerCardsAsync(username, toApiAuth(credentials))
|
||||
.thenApply(apiCards -> {
|
||||
List<String> numbers = new ArrayList<>();
|
||||
for (SPWorldsApiClient.PlayerCard apiCard : apiCards) {
|
||||
if (apiCard.number() != null && !apiCard.number().isBlank()) {
|
||||
@@ -165,40 +156,11 @@ public final class BankUiService {
|
||||
}
|
||||
lastMessage = "";
|
||||
return numbers;
|
||||
} catch (Exception exception) {
|
||||
})
|
||||
.exceptionally(exception -> {
|
||||
lastMessage = "Не удалось получить карты игрока: " + exception.getMessage();
|
||||
return List.of();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<String> addCardAsync(String cardIdRaw, String cardTokenRaw, String playerUuid) {
|
||||
String cardId = cardIdRaw == null ? "" : cardIdRaw.trim();
|
||||
String cardToken = cardTokenRaw == null ? "" : cardTokenRaw.trim();
|
||||
|
||||
if (cardId.isEmpty() || cardToken.isEmpty()) {
|
||||
return CompletableFuture.completedFuture("Укажи cardId и cardToken");
|
||||
}
|
||||
|
||||
try {
|
||||
UUID.fromString(cardId);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
return CompletableFuture.completedFuture("cardId должен быть UUID");
|
||||
}
|
||||
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
database.upsertCardCredentials(cardId, cardToken);
|
||||
boolean refreshed = refreshCardSync(cardId, cardToken, playerUuid, true, true);
|
||||
if (!refreshed) {
|
||||
database.deleteCard(cardId);
|
||||
}
|
||||
reloadCardsFromDb();
|
||||
|
||||
if (refreshed && lastMessage.isBlank()) {
|
||||
return "Карта добавлена";
|
||||
}
|
||||
return lastMessage;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<String> removeSelectedCardAsync() {
|
||||
@@ -225,105 +187,136 @@ public final class BankUiService {
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<String> addCardAsync(String cardIdRaw, String cardTokenRaw, String playerUuid) {
|
||||
String cardId = cardIdRaw == null ? "" : cardIdRaw.trim();
|
||||
String cardToken = cardTokenRaw == null ? "" : cardTokenRaw.trim();
|
||||
|
||||
if (cardId.isEmpty() || cardToken.isEmpty()) {
|
||||
return CompletableFuture.completedFuture("Укажи cardId и cardToken");
|
||||
}
|
||||
|
||||
try {
|
||||
UUID.fromString(cardId);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
return CompletableFuture.completedFuture("cardId должен быть UUID");
|
||||
}
|
||||
|
||||
return CompletableFuture.runAsync(() -> database.upsertCardCredentials(cardId, cardToken))
|
||||
.thenCompose(ignored -> refreshCardAsync(cardId, cardToken, playerUuid, true, true))
|
||||
.thenApply(refreshed -> {
|
||||
if (!refreshed) {
|
||||
database.deleteCard(cardId);
|
||||
}
|
||||
reloadCardsFromDb();
|
||||
return refreshed && lastMessage.isBlank() ? "Карта добавлена" : lastMessage;
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<String> refreshSelectedCardAsync(String playerUuid) {
|
||||
CardViewModel selected = getSelectedCard();
|
||||
if (selected == null) {
|
||||
return CompletableFuture.completedFuture("Нет карты для обновления");
|
||||
}
|
||||
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
CardCredentials credentials = database.getCredentials(selected.id());
|
||||
return CompletableFuture.supplyAsync(() -> database.getCredentials(selected.id()))
|
||||
.thenCompose(credentials -> {
|
||||
if (credentials == null) {
|
||||
return "Не найдены креды карты";
|
||||
return CompletableFuture.completedFuture("Не найдены креды карты");
|
||||
}
|
||||
return refreshCardAsync(credentials.cardId(), credentials.cardToken(), playerUuid, false, false)
|
||||
.thenApply(ignored -> {
|
||||
reloadCardsFromDb();
|
||||
return lastMessage.isBlank() ? "Карта обновлена" : lastMessage;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
refreshCardSync(credentials.cardId(), credentials.cardToken(), playerUuid, false, false);
|
||||
reloadCardsFromDb();
|
||||
return lastMessage.isBlank() ? "Карта обновлена" : lastMessage;
|
||||
});
|
||||
private void recordPaymentEvent(PaymentDraft draft, boolean success, String mode, String destination, long durationMs, String senderLast4) {
|
||||
recordPaymentEvent(draft, success, mode, destination, durationMs, senderLast4, null);
|
||||
}
|
||||
|
||||
private void recordPaymentEvent(PaymentDraft draft, boolean success, String mode, String destination, long durationMs, String senderLast4, String error) {
|
||||
com.google.gson.JsonObject payload = new com.google.gson.JsonObject();
|
||||
payload.addProperty("success", success);
|
||||
payload.addProperty("mode", mode);
|
||||
payload.addProperty("destination", destination);
|
||||
payload.addProperty("durationMs", durationMs);
|
||||
payload.addProperty("senderCardLast4", senderLast4 != null ? senderLast4 : "unknown");
|
||||
payload.addProperty("amount", draft.amount());
|
||||
payload.addProperty("receiver", draft.recipient());
|
||||
if (error != null) {
|
||||
payload.addProperty("error", trimMessage(error));
|
||||
}
|
||||
TelemetryCollector.instance().record(TelemetryEvent.now("payment", payload));
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> submitPaymentAsync(PaymentDraft draft) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
CardCredentials credentials = database.getCredentials(draft.senderCardId());
|
||||
return CompletableFuture.supplyAsync(() -> database.getCredentials(draft.senderCardId()))
|
||||
.thenCompose(credentials -> {
|
||||
if (credentials == null) {
|
||||
lastMessage = "Не найдены креды карты отправителя";
|
||||
return false;
|
||||
recordPaymentEvent(draft, false, "local", "no_credentials", 0, null);
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}
|
||||
|
||||
git.yawaflua.tech.spmega.ModConfig config = git.yawaflua.tech.spmega.SPMega.getConfig();
|
||||
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();
|
||||
|
||||
try {
|
||||
long newBalance = 0;
|
||||
if (useBackend) {
|
||||
BackendAuthenticator.createTransactionOnBackend(
|
||||
draft.senderCardId(),
|
||||
draft.recipient(),
|
||||
draft.amount(),
|
||||
draft.comment()
|
||||
);
|
||||
try {
|
||||
refreshCardSync(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);
|
||||
}
|
||||
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();
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
});
|
||||
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 boolean refreshCardSync(
|
||||
private CompletableFuture<Boolean> refreshCardAsync(
|
||||
String cardId,
|
||||
String cardToken,
|
||||
String playerUuid,
|
||||
boolean reportOwnerWarning,
|
||||
boolean requireCardInAccount
|
||||
) {
|
||||
try {
|
||||
SPWorldsApiClient.CardAuth auth = new SPWorldsApiClient.CardAuth(cardId, cardToken);
|
||||
SPWorldsApiClient.AccountMe me = apiClient.getAccountMe(auth);
|
||||
SPWorldsApiClient.CardInfo cardInfo = apiClient.getCardInfo(auth);
|
||||
SPWorldsApiClient.CardAuth auth = new SPWorldsApiClient.CardAuth(cardId, cardToken);
|
||||
return apiClient.getAccountMeAsync(auth)
|
||||
.thenCompose(me -> apiClient.getCardInfoAsync(auth).thenApply(cardInfo -> {
|
||||
|
||||
SPWorldsApiClient.AccountCard currentCard = me.cards().stream()
|
||||
.filter(card -> Objects.equals(card.id(), cardId))
|
||||
@@ -348,17 +341,67 @@ public final class BankUiService {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
git.yawaflua.tech.spmega.ModConfig config = git.yawaflua.tech.spmega.SPMega.getConfig();
|
||||
ModConfig config = SPMega.getConfig();
|
||||
if (config != null && config.allowBackend()) {
|
||||
BackendAuthenticator.sendCardToBackend(cardId, cardToken);
|
||||
}
|
||||
|
||||
lastMessage = "";
|
||||
return true;
|
||||
} catch (Exception exception) {
|
||||
lastMessage = "Не удалось обновить карту: " + exception.getMessage();
|
||||
return false;
|
||||
}))
|
||||
.exceptionally(exception -> {
|
||||
lastMessage = "Не удалось обновить карту: " + rootMessage(exception);
|
||||
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() {
|
||||
@@ -371,7 +414,8 @@ public final class BankUiService {
|
||||
: stored.cardNumber();
|
||||
String cardName = stored.cardName() == null || stored.cardName().isBlank() ? "Карта" : stored.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()) {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
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;
|
||||
|
||||
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;
|
||||
|
||||
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_right": "Bottom-Right",
|
||||
"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_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());
|
||||
String rawAllowAccess = properties.getProperty("sign.quickPay.enabled");
|
||||
String rawAllowAccess = properties.getProperty("allow.backend");
|
||||
if (rawAllowAccess == null || !Boolean.toString(allowAccess).equalsIgnoreCase(rawAllowAccess.trim())) {
|
||||
shouldSave = true;
|
||||
}
|
||||
@@ -66,7 +66,28 @@ public final class ConfigManager {
|
||||
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) {
|
||||
@@ -126,9 +147,13 @@ public final class ConfigManager {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("api.domain", config.apiDomain());
|
||||
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("gps.enabled", Boolean.toString(config.gpsEnabled()));
|
||||
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 {
|
||||
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) {
|
||||
String value = properties.getProperty(key);
|
||||
if (value == null || value.trim().isEmpty()) {
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
package git.yawaflua.tech.spmega;
|
||||
|
||||
public record ModConfig(String apiDomain, String apiToken, boolean allowBackend, boolean signQuickPayEnabled,
|
||||
boolean gpsEnabled, GpsHudPosition gpsPosition) {
|
||||
boolean gpsEnabled, GpsHudPosition gpsPosition,
|
||||
GpsHudPosition notificationPosition, int telemetryIntervalSeconds,
|
||||
boolean telemetryCollectSystemInfo) {
|
||||
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_GPS_ENABLED = true;
|
||||
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() {
|
||||
return new ModConfig(
|
||||
@@ -16,9 +22,10 @@ public record ModConfig(String apiDomain, String apiToken, boolean allowBackend,
|
||||
ALLOW_BACKEND,
|
||||
DEFAULT_SIGN_QUICK_PAY_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
|
||||
public void onInitialize() {
|
||||
long startNs = System.nanoTime();
|
||||
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) {
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user