Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files- src/handlers.rs +174 -0
- src/main.rs +48 -0
- src/models.rs +29 -0
- src/processor.rs +164 -0
src/handlers.rs
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use axum::{
|
| 2 |
+
Json,
|
| 3 |
+
body::Body,
|
| 4 |
+
extract::{Path, State},
|
| 5 |
+
http::{StatusCode, header},
|
| 6 |
+
response::{IntoResponse, Response},
|
| 7 |
+
};
|
| 8 |
+
use flate2::read::GzDecoder;
|
| 9 |
+
use futures::StreamExt;
|
| 10 |
+
use sha2::{Digest, Sha256};
|
| 11 |
+
use std::{io::Cursor, sync::Arc};
|
| 12 |
+
|
| 13 |
+
use crate::AppState;
|
| 14 |
+
use crate::models::{SchematicData, UploadRequest, UploadResponse};
|
| 15 |
+
use crate::processor::{chunk_json_to_b64, compress_and_encode, extract_litematic_data};
|
| 16 |
+
|
| 17 |
+
pub async fn upload_litematic(
|
| 18 |
+
State(state): State<AppState>,
|
| 19 |
+
body_bytes: axum::body::Bytes,
|
| 20 |
+
) -> Result<Json<UploadResponse>, (StatusCode, String)> {
|
| 21 |
+
let payload: UploadRequest = serde_json::from_slice(&body_bytes)
|
| 22 |
+
.map_err(|e| (StatusCode::BAD_REQUEST, format!("Ошибка JSON: {}", e)))?;
|
| 23 |
+
|
| 24 |
+
println!("[API] Запрос на загрузку схематики: {}", payload.url);
|
| 25 |
+
|
| 26 |
+
let resp = state
|
| 27 |
+
.client
|
| 28 |
+
.get(&payload.url)
|
| 29 |
+
.send()
|
| 30 |
+
.await
|
| 31 |
+
.map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
|
| 32 |
+
|
| 33 |
+
let mut bytes = Vec::new();
|
| 34 |
+
let mut stream = resp.bytes_stream();
|
| 35 |
+
while let Some(chunk) = stream.next().await {
|
| 36 |
+
let chunk = chunk.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
| 37 |
+
bytes.extend_from_slice(&chunk);
|
| 38 |
+
if bytes.len() > 5 * 1024 * 1024 {
|
| 39 |
+
return Err((StatusCode::PAYLOAD_TOO_LARGE, "Лимит 5 МБ".into()));
|
| 40 |
+
}
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
// Хэшируем сразу после скачивания
|
| 44 |
+
let sha256 = format!("{:x}", Sha256::digest(&bytes));
|
| 45 |
+
|
| 46 |
+
// Проверка кэша (Требование 1)
|
| 47 |
+
if let Some(cached) = state.db.read().await.get(&sha256) {
|
| 48 |
+
println!("[API] Файл {} уже обработан, возвращаем из кэша.", sha256);
|
| 49 |
+
return Ok(Json(UploadResponse {
|
| 50 |
+
sha256,
|
| 51 |
+
size: cached.size.clone(),
|
| 52 |
+
chunks_count: cached.state_chunks.len(),
|
| 53 |
+
chunks_palette_count: cached.palette_chunks.len(),
|
| 54 |
+
chunks_entities_count: cached.entity_chunks.len(),
|
| 55 |
+
}));
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
// Обработка новой схематики
|
| 59 |
+
let sha_clone = sha256.clone();
|
| 60 |
+
let result = tokio::task::spawn_blocking(move || {
|
| 61 |
+
let mut decoder = GzDecoder::new(Cursor::new(bytes));
|
| 62 |
+
let nbt = fastnbt::from_reader(&mut decoder).map_err(|e| format!("NBT ошибка: {}", e))?;
|
| 63 |
+
|
| 64 |
+
let (palette_vec, size, entities_vec, states) = extract_litematic_data(nbt)?;
|
| 65 |
+
|
| 66 |
+
// Чанкинг и сжатие палитры и энтити (~20к символов)
|
| 67 |
+
let palette_chunks = chunk_json_to_b64(palette_vec, 20_000)?;
|
| 68 |
+
let entity_chunks = chunk_json_to_b64(entities_vec, 20_000)?;
|
| 69 |
+
|
| 70 |
+
// Чанкинг BlockStates (по 1800 Longs)
|
| 71 |
+
let sub_chunk_size = 1800;
|
| 72 |
+
let mut state_chunks =
|
| 73 |
+
Vec::with_capacity((states.len() + sub_chunk_size - 1) / sub_chunk_size);
|
| 74 |
+
let mut i = 0;
|
| 75 |
+
while i < states.len() {
|
| 76 |
+
let end = std::cmp::min(i + sub_chunk_size, states.len());
|
| 77 |
+
let slice = &states[i..end];
|
| 78 |
+
|
| 79 |
+
let mut raw_bytes = Vec::with_capacity(slice.len() * 8);
|
| 80 |
+
for &val in slice {
|
| 81 |
+
raw_bytes.extend_from_slice(&val.to_be_bytes());
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
state_chunks.push(compress_and_encode(&raw_bytes)?);
|
| 85 |
+
i = end;
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
Ok::<SchematicData, String>(SchematicData {
|
| 89 |
+
size,
|
| 90 |
+
state_chunks,
|
| 91 |
+
palette_chunks,
|
| 92 |
+
entity_chunks,
|
| 93 |
+
})
|
| 94 |
+
})
|
| 95 |
+
.await
|
| 96 |
+
.unwrap()
|
| 97 |
+
.map_err(|e| (StatusCode::BAD_REQUEST, e))?;
|
| 98 |
+
|
| 99 |
+
let chunks_count = result.state_chunks.len();
|
| 100 |
+
let chunks_palette_count = result.palette_chunks.len();
|
| 101 |
+
let chunks_entities_count = result.entity_chunks.len();
|
| 102 |
+
let size = result.size.clone();
|
| 103 |
+
|
| 104 |
+
// Записываем результат через Arc, чтобы минимизировать клонирование при GET-запросах
|
| 105 |
+
state
|
| 106 |
+
.db
|
| 107 |
+
.write()
|
| 108 |
+
.await
|
| 109 |
+
.insert(sha256.clone(), Arc::new(result));
|
| 110 |
+
|
| 111 |
+
println!(
|
| 112 |
+
"[API] Успешно обработано: {} | BlockStates: {}, Palettes: {}, Entities: {}",
|
| 113 |
+
sha256, chunks_count, chunks_palette_count, chunks_entities_count
|
| 114 |
+
);
|
| 115 |
+
|
| 116 |
+
Ok(Json(UploadResponse {
|
| 117 |
+
sha256,
|
| 118 |
+
size,
|
| 119 |
+
chunks_count,
|
| 120 |
+
chunks_palette_count,
|
| 121 |
+
chunks_entities_count,
|
| 122 |
+
}))
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
// Универсальная функция для выдачи чанка
|
| 126 |
+
async fn get_chunk(
|
| 127 |
+
state: &AppState,
|
| 128 |
+
sha256: &str,
|
| 129 |
+
chunk_index: usize,
|
| 130 |
+
extractor: fn(&SchematicData) -> &Vec<String>,
|
| 131 |
+
) -> Result<Response<Body>, (StatusCode, String)> {
|
| 132 |
+
let map_lock = state.db.read().await;
|
| 133 |
+
let schematic = map_lock
|
| 134 |
+
.get(sha256)
|
| 135 |
+
.ok_or((StatusCode::NOT_FOUND, "Схематика не найдена".to_string()))?;
|
| 136 |
+
|
| 137 |
+
let target_vec = extractor(schematic);
|
| 138 |
+
let chunk = target_vec.get(chunk_index).ok_or((
|
| 139 |
+
StatusCode::BAD_REQUEST,
|
| 140 |
+
format!(
|
| 141 |
+
"Индекс чанка {} выходит за границы ({})",
|
| 142 |
+
chunk_index,
|
| 143 |
+
target_vec.len()
|
| 144 |
+
),
|
| 145 |
+
))?;
|
| 146 |
+
|
| 147 |
+
Response::builder()
|
| 148 |
+
.status(StatusCode::OK)
|
| 149 |
+
.header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
|
| 150 |
+
.header(header::CACHE_CONTROL, "public, max-age=31536000, immutable")
|
| 151 |
+
.body(Body::from(chunk.clone()))
|
| 152 |
+
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
pub async fn get_blockstate(
|
| 156 |
+
State(state): State<AppState>,
|
| 157 |
+
Path((sha256, chunk_index)): Path<(String, usize)>,
|
| 158 |
+
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
| 159 |
+
get_chunk(&state, &sha256, chunk_index, |s| &s.state_chunks).await
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
pub async fn get_palette(
|
| 163 |
+
State(state): State<AppState>,
|
| 164 |
+
Path((sha256, chunk_index)): Path<(String, usize)>,
|
| 165 |
+
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
| 166 |
+
get_chunk(&state, &sha256, chunk_index, |s| &s.palette_chunks).await
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
pub async fn get_entity(
|
| 170 |
+
State(state): State<AppState>,
|
| 171 |
+
Path((sha256, chunk_index)): Path<(String, usize)>,
|
| 172 |
+
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
| 173 |
+
get_chunk(&state, &sha256, chunk_index, |s| &s.entity_chunks).await
|
| 174 |
+
}
|
src/main.rs
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
mod handlers;
|
| 2 |
+
mod models;
|
| 3 |
+
mod processor;
|
| 4 |
+
|
| 5 |
+
use axum::{
|
| 6 |
+
Router,
|
| 7 |
+
routing::{get, post},
|
| 8 |
+
};
|
| 9 |
+
use std::{collections::HashMap, sync::Arc};
|
| 10 |
+
use tokio::sync::RwLock;
|
| 11 |
+
|
| 12 |
+
use handlers::{get_blockstate, get_entity, get_palette, upload_litematic};
|
| 13 |
+
use models::SchematicData;
|
| 14 |
+
|
| 15 |
+
pub struct ServerContext {
|
| 16 |
+
pub db: RwLock<HashMap<String, Arc<SchematicData>>>,
|
| 17 |
+
pub client: reqwest::Client,
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
pub type AppState = Arc<ServerContext>;
|
| 21 |
+
|
| 22 |
+
#[tokio::main]
|
| 23 |
+
async fn main() {
|
| 24 |
+
let client = reqwest::Client::builder()
|
| 25 |
+
.timeout(std::time::Duration::from_secs(30))
|
| 26 |
+
.build()
|
| 27 |
+
.unwrap();
|
| 28 |
+
|
| 29 |
+
let context = Arc::new(ServerContext {
|
| 30 |
+
db: RwLock::new(HashMap::new()),
|
| 31 |
+
client,
|
| 32 |
+
});
|
| 33 |
+
|
| 34 |
+
let app = Router::new()
|
| 35 |
+
.route("/upload", post(upload_litematic))
|
| 36 |
+
.route("/get/state/:sha256/:chunk_index", get(get_blockstate))
|
| 37 |
+
.route("/get/palette/:sha256/:chunk_index", get(get_palette))
|
| 38 |
+
.route("/get/entity/:sha256/:chunk_index", get(get_entity))
|
| 39 |
+
.with_state(context);
|
| 40 |
+
|
| 41 |
+
let addr = format!(
|
| 42 |
+
"0.0.0.0:{}",
|
| 43 |
+
std::env::var("PORT").unwrap_or_else(|_| "7860".into())
|
| 44 |
+
);
|
| 45 |
+
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
|
| 46 |
+
println!("Сервер запущен на {}", addr);
|
| 47 |
+
axum::serve(listener, app).await.unwrap();
|
| 48 |
+
}
|
src/models.rs
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use serde::{Deserialize, Serialize};
|
| 2 |
+
use serde_json::Value as JsonValue;
|
| 3 |
+
|
| 4 |
+
#[derive(Deserialize)]
|
| 5 |
+
pub struct UploadRequest {
|
| 6 |
+
pub url: String,
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
#[derive(Serialize)]
|
| 10 |
+
pub struct UploadResponse {
|
| 11 |
+
#[serde(rename = "SHA256")]
|
| 12 |
+
pub sha256: String,
|
| 13 |
+
#[serde(rename = "Size")]
|
| 14 |
+
pub size: JsonValue,
|
| 15 |
+
#[serde(rename = "ChunksCount")]
|
| 16 |
+
pub chunks_count: usize,
|
| 17 |
+
#[serde(rename = "ChunksPaletteCount")]
|
| 18 |
+
pub chunks_palette_count: usize,
|
| 19 |
+
#[serde(rename = "ChunksEntitiesCount")]
|
| 20 |
+
pub chunks_entities_count: usize,
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
/// Структура для хранения обработанной схематики в памяти
|
| 24 |
+
pub struct SchematicData {
|
| 25 |
+
pub size: JsonValue,
|
| 26 |
+
pub state_chunks: Vec<String>,
|
| 27 |
+
pub palette_chunks: Vec<String>,
|
| 28 |
+
pub entity_chunks: Vec<String>,
|
| 29 |
+
}
|
src/processor.rs
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
|
| 2 |
+
use flate2::{Compression, write::ZlibEncoder};
|
| 3 |
+
use serde::Serialize;
|
| 4 |
+
use serde_json::{Value as JsonValue, json};
|
| 5 |
+
use std::{collections::HashMap, io::Write};
|
| 6 |
+
|
| 7 |
+
pub fn nbt_to_json(value: fastnbt::Value) -> JsonValue {
|
| 8 |
+
match value {
|
| 9 |
+
fastnbt::Value::Compound(map) => {
|
| 10 |
+
let json_map = map
|
| 11 |
+
.into_iter()
|
| 12 |
+
.map(|(k, v)| (k, nbt_to_json(v)))
|
| 13 |
+
.collect::<serde_json::Map<_, _>>();
|
| 14 |
+
JsonValue::Object(json_map)
|
| 15 |
+
}
|
| 16 |
+
fastnbt::Value::List(list) => JsonValue::Array(list.into_iter().map(nbt_to_json).collect()),
|
| 17 |
+
fastnbt::Value::ByteArray(arr) => {
|
| 18 |
+
JsonValue::Array(arr.into_iter().map(|x| json!(x)).collect())
|
| 19 |
+
}
|
| 20 |
+
fastnbt::Value::IntArray(arr) => {
|
| 21 |
+
JsonValue::Array(arr.into_iter().map(|x| json!(x)).collect())
|
| 22 |
+
}
|
| 23 |
+
fastnbt::Value::LongArray(arr) => {
|
| 24 |
+
JsonValue::Array(arr.to_vec().into_iter().map(|x| json!(x)).collect())
|
| 25 |
+
}
|
| 26 |
+
fastnbt::Value::Byte(x) => json!(x),
|
| 27 |
+
fastnbt::Value::Short(x) => json!(x),
|
| 28 |
+
fastnbt::Value::Int(x) => json!(x),
|
| 29 |
+
fastnbt::Value::Long(x) => json!(x),
|
| 30 |
+
fastnbt::Value::Float(x) => json!(x),
|
| 31 |
+
fastnbt::Value::Double(x) => json!(x),
|
| 32 |
+
fastnbt::Value::String(x) => json!(x),
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
/// Сжатие массива байт в zlib и кодирование в Base64
|
| 37 |
+
pub fn compress_and_encode(data: &[u8]) -> Result<String, String> {
|
| 38 |
+
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
|
| 39 |
+
encoder.write_all(data).map_err(|e| e.to_string())?;
|
| 40 |
+
encoder.flush().map_err(|e| e.to_string())?;
|
| 41 |
+
let compressed = encoder.finish().map_err(|e| e.to_string())?;
|
| 42 |
+
Ok(BASE64.encode(&compressed))
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
/// Универсальная функция для нарезки JSON-данных (палитры, энтити)
|
| 46 |
+
/// limit_chars — приблизительный лимит символов JSON-строки в одном чанке
|
| 47 |
+
pub fn chunk_json_to_b64<T: Serialize>(
|
| 48 |
+
items: Vec<T>,
|
| 49 |
+
limit_chars: usize,
|
| 50 |
+
) -> Result<Vec<String>, String> {
|
| 51 |
+
let mut chunks = Vec::new();
|
| 52 |
+
let mut current_chunk = Vec::new();
|
| 53 |
+
let mut current_len = 0;
|
| 54 |
+
|
| 55 |
+
for item in items {
|
| 56 |
+
let json_str = serde_json::to_string(&item).map_err(|e| e.to_string())?;
|
| 57 |
+
|
| 58 |
+
// Если добавление элемента превысит лимит и чанк не пустой, закрываем текущий чанк
|
| 59 |
+
if current_len + json_str.len() > limit_chars && !current_chunk.is_empty() {
|
| 60 |
+
let chunk_bytes = serde_json::to_vec(¤t_chunk).map_err(|e| e.to_string())?;
|
| 61 |
+
chunks.push(compress_and_encode(&chunk_bytes)?);
|
| 62 |
+
current_chunk.clear();
|
| 63 |
+
current_len = 0;
|
| 64 |
+
}
|
| 65 |
+
current_len += json_str.len();
|
| 66 |
+
current_chunk.push(item);
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
// Записываем остаток
|
| 70 |
+
if !current_chunk.is_empty() {
|
| 71 |
+
let chunk_bytes = serde_json::to_vec(¤t_chunk).map_err(|e| e.to_string())?;
|
| 72 |
+
chunks.push(compress_and_encode(&chunk_bytes)?);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
Ok(chunks)
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
pub fn extract_litematic_data(
|
| 79 |
+
nbt_value: fastnbt::Value,
|
| 80 |
+
) -> Result<(Vec<JsonValue>, JsonValue, Vec<(String, String)>, Vec<i64>), String> {
|
| 81 |
+
let mut root_map = match nbt_value {
|
| 82 |
+
fastnbt::Value::Compound(map) => map,
|
| 83 |
+
_ => return Err("Корень NBT не является Compound".into()),
|
| 84 |
+
};
|
| 85 |
+
|
| 86 |
+
let mut regions_map = match root_map.remove("Regions") {
|
| 87 |
+
Some(fastnbt::Value::Compound(map)) => map,
|
| 88 |
+
_ => return Err("Не найдена секция Regions".into()),
|
| 89 |
+
};
|
| 90 |
+
|
| 91 |
+
let (_, first_region) = regions_map
|
| 92 |
+
.into_iter()
|
| 93 |
+
.next()
|
| 94 |
+
.ok_or("Секция Regions пуста")?;
|
| 95 |
+
let mut region_map = match first_region {
|
| 96 |
+
fastnbt::Value::Compound(map) => map,
|
| 97 |
+
_ => return Err("Регион не является Compound".into()),
|
| 98 |
+
};
|
| 99 |
+
|
| 100 |
+
let palette_val = region_map
|
| 101 |
+
.remove("BlockStatePalette")
|
| 102 |
+
.ok_or("Нет BlockStatePalette")?;
|
| 103 |
+
let palette_vec = match palette_val {
|
| 104 |
+
fastnbt::Value::List(list) => {
|
| 105 |
+
let mut cleaned = Vec::with_capacity(list.len());
|
| 106 |
+
for item in list {
|
| 107 |
+
if let fastnbt::Value::Compound(mut cmap) = item {
|
| 108 |
+
if let Some(fastnbt::Value::String(name)) = cmap.remove("Name") {
|
| 109 |
+
let mut clean_name =
|
| 110 |
+
name.strip_prefix("minecraft:").unwrap_or(&name).to_string();
|
| 111 |
+
if let Some(fastnbt::Value::Compound(props)) = cmap.remove("Properties") {
|
| 112 |
+
let mut prop_list: Vec<String> = props
|
| 113 |
+
.into_iter()
|
| 114 |
+
.filter_map(|(k, v)| {
|
| 115 |
+
if let fastnbt::Value::String(s) = v {
|
| 116 |
+
Some(format!("{}={}", k, s))
|
| 117 |
+
} else {
|
| 118 |
+
None
|
| 119 |
+
}
|
| 120 |
+
})
|
| 121 |
+
.collect();
|
| 122 |
+
if !prop_list.is_empty() {
|
| 123 |
+
prop_list.sort();
|
| 124 |
+
clean_name = format!("{}[{}]", clean_name, prop_list.join(","));
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
cleaned.push(json!(clean_name));
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
}
|
| 131 |
+
cleaned
|
| 132 |
+
}
|
| 133 |
+
_ => return Err("BlockStatePalette не является списком".into()),
|
| 134 |
+
};
|
| 135 |
+
|
| 136 |
+
let size_json = nbt_to_json(region_map.remove("Size").ok_or("Нет Size")?);
|
| 137 |
+
|
| 138 |
+
let mut entities_vec = Vec::new();
|
| 139 |
+
if let Some(entities_val) = region_map
|
| 140 |
+
.remove("TileEntities")
|
| 141 |
+
.or_else(|| region_map.remove("BlockEntities"))
|
| 142 |
+
{
|
| 143 |
+
if let fastnbt::Value::List(list) = entities_val {
|
| 144 |
+
for item in list {
|
| 145 |
+
if let fastnbt::Value::Compound(map) = item {
|
| 146 |
+
let x = map.get("x").and_then(|v| v.as_i64()).unwrap_or(0);
|
| 147 |
+
let y = map.get("y").and_then(|v| v.as_i64()).unwrap_or(0);
|
| 148 |
+
let z = map.get("z").and_then(|v| v.as_i64()).unwrap_or(0);
|
| 149 |
+
let json_str = nbt_to_json(fastnbt::Value::Compound(map)).to_string();
|
| 150 |
+
entities_vec.push((format!("{},{},{}", x, y, z), json_str));
|
| 151 |
+
}
|
| 152 |
+
}
|
| 153 |
+
}
|
| 154 |
+
}
|
| 155 |
+
// Сортируем энтити по координатам для консистентного чанкинга
|
| 156 |
+
entities_vec.sort_by(|a, b| a.0.cmp(&b.0));
|
| 157 |
+
|
| 158 |
+
let block_states = match region_map.remove("BlockStates").ok_or("Нет BlockStates")? {
|
| 159 |
+
fastnbt::Value::LongArray(arr) => arr.to_vec(),
|
| 160 |
+
_ => return Err("BlockStates не является LongArray".into()),
|
| 161 |
+
};
|
| 162 |
+
|
| 163 |
+
Ok((palette_vec, size_json, entities_vec, block_states))
|
| 164 |
+
}
|