Cnass commited on
Commit
a2c6f6c
·
verified ·
1 Parent(s): 4d5cc3a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -78
app.py CHANGED
@@ -12,7 +12,7 @@ from fastapi.responses import FileResponse, JSONResponse
12
  from fastapi.middleware.cors import CORSMiddleware
13
 
14
  # ==========================================
15
- # C# SCRIPT FABRİKASI (X-RAY YANSIMA İLE YENİLMEZ SÜRÜM)
16
  # ==========================================
17
  def generate_csx_scripts():
18
  extract_code = """using System.IO;
@@ -22,16 +22,16 @@ using System.Linq;
22
  using System.Reflection;
23
  using UndertaleModLib;
24
 
25
- // X-RAY ALGORİTMASI: Değişken ismi ne olursa olsun PNG verisini (byte array) bulur
26
- byte[] GetImg(object td) {
27
- if (td == null) return null;
 
 
28
  var t = td.GetType();
29
- var p = t.GetProperty("TextureBlob") ?? t.GetProperty("TextureBuffer") ?? t.GetProperty("Data");
30
  if (p != null) return p.GetValue(td) as byte[];
31
- var fp = t.GetProperties().FirstOrDefault(x => x.PropertyType == typeof(byte[]));
32
- if (fp != null) return fp.GetValue(td) as byte[];
33
- var ff = t.GetFields().FirstOrDefault(x => x.FieldType == typeof(byte[]));
34
- if (ff != null) return ff.GetValue(td) as byte[];
35
  return null;
36
  }
37
 
@@ -49,15 +49,16 @@ Directory.CreateDirectory("Fonts");
49
  var fontData = new Dictionary<string, object>();
50
  foreach (var font in Data.Fonts) {
51
  if (font.Texture != null && font.Texture.TexturePage != null) {
52
- string texName = font.Texture.TexturePage.Name.Content;
 
 
 
 
53
  string texPath = "Fonts/" + texName + ".png";
54
  if (!File.Exists(texPath)) {
55
- var tex = Data.EmbeddedTextures.FirstOrDefault(t => t.Name.Content == texName);
56
- if (tex != null && tex.TextureData != null) {
57
- byte[] img = GetImg(tex.TextureData);
58
- if (img != null) {
59
- File.WriteAllBytes(texPath, img);
60
- }
61
  }
62
  }
63
  var glyphs = new Dictionary<string, object>();
@@ -78,16 +79,21 @@ using System.Linq;
78
  using System.Reflection;
79
  using UndertaleModLib;
80
 
81
- // X-RAY ALGORİTMASI: Düzenlenmiş PNG resmini isme bakmaksızın motora geri zorlar
82
- void SetImg(object td, byte[] d) {
83
- if (td == null) return;
 
 
 
 
 
 
 
84
  var t = td.GetType();
85
- var p = t.GetProperty("TextureBlob") ?? t.GetProperty("TextureBuffer") ?? t.GetProperty("Data");
86
- if (p != null && p.CanWrite) { p.SetValue(td, d); return; }
87
- var fp = t.GetProperties().FirstOrDefault(x => x.PropertyType == typeof(byte[]) && x.CanWrite);
88
- if (fp != null) { fp.SetValue(td, d); return; }
89
- var ff = t.GetFields().FirstOrDefault(x => x.FieldType == typeof(byte[]));
90
- if (ff != null) { ff.SetValue(td, d); return; }
91
  }
92
 
93
  string json = File.ReadAllText("strings.json");
@@ -101,19 +107,23 @@ foreach (var str in Data.Strings) {
101
 
102
  // FONT RESİMLERİNİ VE KOORDİNAT HARİTASINI GERİ YÜKLE
103
  if (Directory.Exists("Fonts")) {
104
- foreach (var texFile in Directory.GetFiles("Fonts", "*.png")) {
105
- string texName = Path.GetFileNameWithoutExtension(texFile);
106
- var tex = Data.EmbeddedTextures.FirstOrDefault(t => t.Name.Content == texName);
107
- if (tex != null && tex.TextureData != null) {
108
- SetImg(tex.TextureData, File.ReadAllBytes(texFile));
109
- }
110
- }
111
  string fontJsonPath = "Fonts/font_data.json";
112
  if (File.Exists(fontJsonPath)) {
113
  string fJson = File.ReadAllText(fontJsonPath);
114
  var fDict = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(fJson);
 
115
  foreach (var font in Data.Fonts) {
116
  if (fDict.TryGetValue(font.Name.Content, out JsonElement fData)) {
 
 
 
 
 
 
 
 
 
 
117
  if (fData.TryGetProperty("Glyphs", out JsonElement glyphsJson)) {
118
  foreach (var glyphProp in glyphsJson.EnumerateObject()) {
119
  ushort charCode;
@@ -137,7 +147,7 @@ if (Directory.Exists("Fonts")) {
137
  }
138
  }
139
 
140
- // Reflection ile Dinamik Kaydetme (Tüm UMT sürümleriyle uyumlu)
141
  using (var stream = new FileStream("repacked_game.droid", FileMode.Create, FileAccess.Write)) {
142
  var m2 = typeof(UndertaleIO).GetMethod("Write", new[] { typeof(Stream), typeof(UndertaleData) });
143
  if (m2 != null) m2.Invoke(null, new object[] { stream, Data });
@@ -154,12 +164,8 @@ using (var stream = new FileStream("repacked_game.droid", FileMode.Create, FileA
154
  with open("/app/extract.csx", "w", encoding="utf-8") as f: f.write(extract_code)
155
  with open("/app/repack.csx", "w", encoding="utf-8") as f: f.write(repack_code)
156
 
157
- # Sunucu başlarken CSX dosyalarını her zaman hatasız haliyle yeniden oluştur.
158
  generate_csx_scripts()
159
 
160
- # ==========================================
161
- # ANA SUNUCU (FASTAPI)
162
- # ==========================================
163
  app = FastAPI()
164
  app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
165
 
@@ -175,39 +181,26 @@ def get_cli_command():
175
 
176
  def deep_heal_droid(filepath):
177
  try:
178
- with open(filepath, "rb") as f:
179
- data = bytearray(f.read())
180
-
181
  original_header = data[0:4]
182
- if original_header != b'FORM':
183
- data[0:4] = b'FORM'
184
-
185
  offset = 8
186
  file_len = len(data)
187
  log = []
188
-
189
  while offset < file_len:
190
  if offset + 8 > file_len:
191
  data = data[:offset]
192
  break
193
-
194
  chunk_name = data[offset:offset+4]
195
  chunk_size = struct.unpack("<I", data[offset+4:offset+8])[0]
196
-
197
  is_valid = all(32 <= b <= 126 for b in chunk_name)
198
-
199
  if not is_valid or chunk_size > file_len:
200
  log.append(f"TUZAK KESİLDİ: Bozuk Blok '{chunk_name}' | Konum: {offset}")
201
  data = data[:offset]
202
  break
203
-
204
  offset += 8 + chunk_size
205
-
206
  data[4:8] = struct.pack("<I", len(data) - 8)
207
-
208
- with open(filepath, "wb") as f:
209
- f.write(data)
210
-
211
  return original_header, "\n".join(log)
212
  except Exception as e:
213
  return None, f"İyileştirme Hatası: {str(e)}"
@@ -224,11 +217,9 @@ def revert_header(filepath, original_header):
224
  async def extract_dialogues(file: UploadFile = File(...)):
225
  temp_dir = tempfile.mkdtemp()
226
  asset_path = os.path.join(temp_dir, file.filename)
227
-
228
  with open(asset_path, "wb") as f: f.write(await file.read())
229
 
230
  fake_header, heal_log = deep_heal_droid(asset_path)
231
-
232
  cmd = get_cli_command() + ["load", file.filename, "-s", "/app/extract.csx"]
233
  process = subprocess.run(cmd, cwd=temp_dir, capture_output=True, text=True)
234
 
@@ -239,7 +230,7 @@ async def extract_dialogues(file: UploadFile = File(...)):
239
  if os.path.exists(json_path):
240
  zipf.write(json_path, arcname="strings.json")
241
 
242
- # FONT KLASÖRÜNÜ ZİPE EKLE
243
  font_dir = os.path.join(temp_dir, "Fonts")
244
  if os.path.exists(font_dir):
245
  for root, dirs, files in os.walk(font_dir):
@@ -248,10 +239,9 @@ async def extract_dialogues(file: UploadFile = File(...)):
248
  arcname = os.path.relpath(file_path, temp_dir)
249
  zipf.write(file_path, arcname=arcname)
250
 
251
- if heal_log:
252
- zipf.writestr("IYILESME_RAPORU.txt", f"--- OTO-SIFACI RAPORU ---\n\n{heal_log}".encode('utf-8'))
253
  else:
254
- log_msg = f"=== UMT MOTORU ÇÖKME LOGU ===\nBASLIK: {fake_header}\nIYILESME LOGU:\n{heal_log}\n\nSTDOUT:\n{process.stdout}\n\nSTDERR:\n{process.stderr}\n"
255
  zipf.writestr("UMT_Hata_Logu.txt", log_msg.encode('utf-8'))
256
 
257
  return FileResponse(zip_filename, media_type="application/zip", filename=f"{file.filename}_dialogues.zip")
@@ -259,30 +249,20 @@ async def extract_dialogues(file: UploadFile = File(...)):
259
  def process_repack(job_id: str, asset_path: str, zip_path: str, original_filename: str):
260
  try:
261
  temp_dir = os.path.dirname(asset_path)
262
- jobs[job_id] = {"status": "processing", "progress": 20, "message": "Oyun korumaları analiz edilip kırılıyor..."}
263
-
264
  original_header, heal_log = deep_heal_droid(asset_path)
265
 
266
  with zipfile.ZipFile(zip_path, 'r') as zipf:
267
- zipf.extractall(temp_dir) # JSON ve Font resimlerini tamamen çıkar
268
 
269
  jobs[job_id].update({"progress": 50, "message": "UMT C# Motoru çalıştırılıyor... Lütfen bekleyin."})
270
-
271
  cmd = get_cli_command() + ["load", original_filename, "-s", "/app/repack.csx"]
272
  process = subprocess.run(cmd, cwd=temp_dir, capture_output=True, text=True)
273
 
274
  output_path = os.path.join(temp_dir, "repacked_game.droid")
275
-
276
  if os.path.exists(output_path):
277
  revert_header(output_path, original_header)
278
-
279
- jobs[job_id].update({
280
- "status": "completed",
281
- "progress": 100,
282
- "message": "UMT İşlemi Başarılı! Droid Dosyası İndiriliyor...",
283
- "file_path": output_path,
284
- "filename": original_filename
285
- })
286
  else:
287
  jobs[job_id].update({"status": "error", "message": f"Paketleme başarısız! Log: {process.stderr}\n{process.stdout}"})
288
  except Exception as e:
@@ -294,18 +274,14 @@ async def repack_async(background_tasks: BackgroundTasks, asset_file: UploadFile
294
  temp_dir = tempfile.mkdtemp()
295
  asset_path = os.path.join(temp_dir, asset_file.filename)
296
  zip_path = os.path.join(temp_dir, mod_zip.filename)
297
-
298
  with open(asset_path, "wb") as f: f.write(await asset_file.read())
299
  with open(zip_path, "wb") as f: f.write(await mod_zip.read())
300
-
301
  background_tasks.add_task(process_repack, job_id, asset_path, zip_path, asset_file.filename)
302
  jobs[job_id] = {"status": "queued", "progress": 0, "message": "GameMaker işleme sırasına alındı..."}
303
  return {"job_id": job_id}
304
 
305
  @app.get("/status/{job_id}")
306
- async def get_status(job_id: str):
307
- return jobs.get(job_id, JSONResponse(status_code=404, content={"error": "Bulunamadı"}))
308
 
309
  @app.get("/download/{job_id}")
310
- async def download_file(job_id: str):
311
- return FileResponse(jobs[job_id]["file_path"], media_type="application/octet-stream", filename=jobs[job_id]["filename"])
 
12
  from fastapi.middleware.cors import CORSMiddleware
13
 
14
  # ==========================================
15
+ # C# SCRIPT FABRİKASI (KUSURSUZ X-RAY GÖRSEL ÇIKARICI)
16
  # ==========================================
17
  def generate_csx_scripts():
18
  extract_code = """using System.IO;
 
22
  using System.Reflection;
23
  using UndertaleModLib;
24
 
25
+ // YENİLENMİŞ X-RAY: Hem obje içindeki hem de doğrudan çıplak (byte[]) olan resmi bulur.
26
+ byte[] GetImg(UndertaleEmbeddedTexture emb) {
27
+ if (emb == null || emb.TextureData == null) return null;
28
+ object td = emb.TextureData;
29
+ if (td is byte[] b) return b; // Eğer resim doğrudan çıplak haldeyse direkt al!
30
  var t = td.GetType();
31
+ var p = t.GetProperties().FirstOrDefault(x => x.PropertyType == typeof(byte[]));
32
  if (p != null) return p.GetValue(td) as byte[];
33
+ var f = t.GetFields().FirstOrDefault(x => x.FieldType == typeof(byte[]));
34
+ if (f != null) return f.GetValue(td) as byte[];
 
 
35
  return null;
36
  }
37
 
 
49
  var fontData = new Dictionary<string, object>();
50
  foreach (var font in Data.Fonts) {
51
  if (font.Texture != null && font.Texture.TexturePage != null) {
52
+ var emb = font.Texture.TexturePage;
53
+ // İsmi yoksa bile özel isim uydurarak o PNG'yi zorla kaydeder
54
+ string texName = emb.Name?.Content;
55
+ if (string.IsNullOrEmpty(texName)) texName = "Texture_" + font.Name.Content;
56
+
57
  string texPath = "Fonts/" + texName + ".png";
58
  if (!File.Exists(texPath)) {
59
+ byte[] img = GetImg(emb);
60
+ if (img != null) {
61
+ File.WriteAllBytes(texPath, img);
 
 
 
62
  }
63
  }
64
  var glyphs = new Dictionary<string, object>();
 
79
  using System.Reflection;
80
  using UndertaleModLib;
81
 
82
+ // YENİLENMİŞ X-RAY: Değiştirilen PNG resmini oyun dosyasına kusursuzca gömer
83
+ void SetImg(UndertaleEmbeddedTexture emb, byte[] d) {
84
+ if (emb == null || emb.TextureData == null) return;
85
+ object td = emb.TextureData;
86
+ if (td is byte[]) {
87
+ // Bazı UMT sürümlerinde TextureData sadece bir byte dizisidir
88
+ var prop = emb.GetType().GetProperty("TextureData");
89
+ if (prop != null && prop.CanWrite) prop.SetValue(emb, d);
90
+ return;
91
+ }
92
  var t = td.GetType();
93
+ var p = t.GetProperties().FirstOrDefault(x => x.PropertyType == typeof(byte[]) && x.CanWrite);
94
+ if (p != null) { p.SetValue(td, d); return; }
95
+ var f = t.GetFields().FirstOrDefault(x => x.FieldType == typeof(byte[]));
96
+ if (f != null) { f.SetValue(td, d); return; }
 
 
97
  }
98
 
99
  string json = File.ReadAllText("strings.json");
 
107
 
108
  // FONT RESİMLERİNİ VE KOORDİNAT HARİTASINI GERİ YÜKLE
109
  if (Directory.Exists("Fonts")) {
 
 
 
 
 
 
 
110
  string fontJsonPath = "Fonts/font_data.json";
111
  if (File.Exists(fontJsonPath)) {
112
  string fJson = File.ReadAllText(fontJsonPath);
113
  var fDict = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(fJson);
114
+
115
  foreach (var font in Data.Fonts) {
116
  if (fDict.TryGetValue(font.Name.Content, out JsonElement fData)) {
117
+ // Görseli Güncelle
118
+ if (fData.TryGetProperty("Texture", out JsonElement texElement)) {
119
+ string texName = texElement.GetString();
120
+ string texPath = "Fonts/" + texName + ".png";
121
+ if (File.Exists(texPath) && font.Texture != null && font.Texture.TexturePage != null) {
122
+ SetImg(font.Texture.TexturePage, File.ReadAllBytes(texPath));
123
+ }
124
+ }
125
+
126
+ // Koordinatları Güncelle
127
  if (fData.TryGetProperty("Glyphs", out JsonElement glyphsJson)) {
128
  foreach (var glyphProp in glyphsJson.EnumerateObject()) {
129
  ushort charCode;
 
147
  }
148
  }
149
 
150
+ // Reflection ile Dinamik Kaydetme
151
  using (var stream = new FileStream("repacked_game.droid", FileMode.Create, FileAccess.Write)) {
152
  var m2 = typeof(UndertaleIO).GetMethod("Write", new[] { typeof(Stream), typeof(UndertaleData) });
153
  if (m2 != null) m2.Invoke(null, new object[] { stream, Data });
 
164
  with open("/app/extract.csx", "w", encoding="utf-8") as f: f.write(extract_code)
165
  with open("/app/repack.csx", "w", encoding="utf-8") as f: f.write(repack_code)
166
 
 
167
  generate_csx_scripts()
168
 
 
 
 
169
  app = FastAPI()
170
  app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
171
 
 
181
 
182
  def deep_heal_droid(filepath):
183
  try:
184
+ with open(filepath, "rb") as f: data = bytearray(f.read())
 
 
185
  original_header = data[0:4]
186
+ if original_header != b'FORM': data[0:4] = b'FORM'
 
 
187
  offset = 8
188
  file_len = len(data)
189
  log = []
 
190
  while offset < file_len:
191
  if offset + 8 > file_len:
192
  data = data[:offset]
193
  break
 
194
  chunk_name = data[offset:offset+4]
195
  chunk_size = struct.unpack("<I", data[offset+4:offset+8])[0]
 
196
  is_valid = all(32 <= b <= 126 for b in chunk_name)
 
197
  if not is_valid or chunk_size > file_len:
198
  log.append(f"TUZAK KESİLDİ: Bozuk Blok '{chunk_name}' | Konum: {offset}")
199
  data = data[:offset]
200
  break
 
201
  offset += 8 + chunk_size
 
202
  data[4:8] = struct.pack("<I", len(data) - 8)
203
+ with open(filepath, "wb") as f: f.write(data)
 
 
 
204
  return original_header, "\n".join(log)
205
  except Exception as e:
206
  return None, f"İyileştirme Hatası: {str(e)}"
 
217
  async def extract_dialogues(file: UploadFile = File(...)):
218
  temp_dir = tempfile.mkdtemp()
219
  asset_path = os.path.join(temp_dir, file.filename)
 
220
  with open(asset_path, "wb") as f: f.write(await file.read())
221
 
222
  fake_header, heal_log = deep_heal_droid(asset_path)
 
223
  cmd = get_cli_command() + ["load", file.filename, "-s", "/app/extract.csx"]
224
  process = subprocess.run(cmd, cwd=temp_dir, capture_output=True, text=True)
225
 
 
230
  if os.path.exists(json_path):
231
  zipf.write(json_path, arcname="strings.json")
232
 
233
+ # FONT KLASÖRÜNÜ ZİPE EKLE (GARANTİLİ)
234
  font_dir = os.path.join(temp_dir, "Fonts")
235
  if os.path.exists(font_dir):
236
  for root, dirs, files in os.walk(font_dir):
 
239
  arcname = os.path.relpath(file_path, temp_dir)
240
  zipf.write(file_path, arcname=arcname)
241
 
242
+ if heal_log: zipf.writestr("IYILESME_RAPORU.txt", f"--- OTO-SIFACI RAPORU ---\n\n{heal_log}".encode('utf-8'))
 
243
  else:
244
+ log_msg = f"=== UMT MOTORU ÇÖKME LOGU ===\nBASLIK: {fake_header}\nSTDOUT:\n{process.stdout}\nSTDERR:\n{process.stderr}\n"
245
  zipf.writestr("UMT_Hata_Logu.txt", log_msg.encode('utf-8'))
246
 
247
  return FileResponse(zip_filename, media_type="application/zip", filename=f"{file.filename}_dialogues.zip")
 
249
  def process_repack(job_id: str, asset_path: str, zip_path: str, original_filename: str):
250
  try:
251
  temp_dir = os.path.dirname(asset_path)
252
+ jobs[job_id] = {"status": "processing", "progress": 20, "message": "Oyun korumaları kırılıyor..."}
 
253
  original_header, heal_log = deep_heal_droid(asset_path)
254
 
255
  with zipfile.ZipFile(zip_path, 'r') as zipf:
256
+ zipf.extractall(temp_dir)
257
 
258
  jobs[job_id].update({"progress": 50, "message": "UMT C# Motoru çalıştırılıyor... Lütfen bekleyin."})
 
259
  cmd = get_cli_command() + ["load", original_filename, "-s", "/app/repack.csx"]
260
  process = subprocess.run(cmd, cwd=temp_dir, capture_output=True, text=True)
261
 
262
  output_path = os.path.join(temp_dir, "repacked_game.droid")
 
263
  if os.path.exists(output_path):
264
  revert_header(output_path, original_header)
265
+ jobs[job_id].update({"status": "completed", "progress": 100, "message": "UMT İşlemi Başarılı! İndiriliyor...", "file_path": output_path, "filename": original_filename})
 
 
 
 
 
 
 
266
  else:
267
  jobs[job_id].update({"status": "error", "message": f"Paketleme başarısız! Log: {process.stderr}\n{process.stdout}"})
268
  except Exception as e:
 
274
  temp_dir = tempfile.mkdtemp()
275
  asset_path = os.path.join(temp_dir, asset_file.filename)
276
  zip_path = os.path.join(temp_dir, mod_zip.filename)
 
277
  with open(asset_path, "wb") as f: f.write(await asset_file.read())
278
  with open(zip_path, "wb") as f: f.write(await mod_zip.read())
 
279
  background_tasks.add_task(process_repack, job_id, asset_path, zip_path, asset_file.filename)
280
  jobs[job_id] = {"status": "queued", "progress": 0, "message": "GameMaker işleme sırasına alındı..."}
281
  return {"job_id": job_id}
282
 
283
  @app.get("/status/{job_id}")
284
+ async def get_status(job_id: str): return jobs.get(job_id, JSONResponse(status_code=404, content={"error": "Bulunamadı"}))
 
285
 
286
  @app.get("/download/{job_id}")
287
+ async def download_file(job_id: str): return FileResponse(jobs[job_id]["file_path"], media_type="application/octet-stream", filename=jobs[job_id]["filename"])