-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
668 lines (557 loc) · 26.4 KB
/
Copy pathserver.py
File metadata and controls
668 lines (557 loc) · 26.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
from fastapi import FastAPI, Request, Response, HTTPException, BackgroundTasks
from fastapi.responses import HTMLResponse, RedirectResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import uvicorn
import os
import json
import requests
import time
import shutil
from pathlib import Path
from typing import Optional, Dict, Any
from contextlib import asynccontextmanager
import html
import main
import get_info_state
# ===== Map Settings =====
MAP_BASE_URL = "https://act-webstatic.hoyoverse.com/map_manage/map/2/0f333192efeebcdfc400f2c49f5128bb"
MAP_CACHE_DIR = Path("static/map_cache")
MAX_ROW = 31
MAX_COL = 52
MAP_TIMEOUT = 10
MAP_REQUEST_DELAY = 0.05
map_session = requests.Session()
map_session.headers.update({
"User-Agent": "Mozilla/5.0",
"Referer": "https://act.hoyolab.com/"
})
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup: Clear map cache
if MAP_CACHE_DIR.exists():
#shutil.rmtree(MAP_CACHE_DIR)
pass
#MAP_CACHE_DIR.mkdir(parents=True, exist_ok=True)
#print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Map cache cleared and recreated.")
print("map cache werent cleared.")
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Server is now running and ready for requests.")
yield
# Shutdown logic (if any) can go here
app = FastAPI(lifespan=lifespan)
# Mount static files
app.mount("/static", StaticFiles(directory="static"), name="static")
# Templates
templates = Jinja2Templates(directory="templates")
class GlobalTextMap:
_data: Dict[str, Dict[str, str]] = {}
_base_dir = os.path.dirname(os.path.abspath(__file__))
_path = os.path.join(_base_dir, '.enka_py', 'assets', 'text_map.json')
@classmethod
def get(cls, lang: str, key: str) -> str:
if lang not in cls._data:
if os.path.exists(cls._path):
try:
with open(cls._path, 'r', encoding='utf-8') as f:
all_data = json.load(f)
cls._data = all_data
except Exception as e:
print(f"Error loading text_map.json: {e}")
return key
else:
return key
# Enka uses 'jp' but text_map uses 'ja' sometimes, or vice versa
# Check support
lang_key = lang
if lang == 'ja' and 'ja' not in cls._data and 'jp' in cls._data: lang_key = 'jp'
elif lang == 'jp' and 'jp' not in cls._data and 'ja' in cls._data: lang_key = 'ja'
if lang_key in cls._data:
return cls._data[lang_key].get(str(key), key)
return key
SUPPORTED_LANGUAGES = ["en", "ja"]
@app.middleware("http")
async def language_middleware(request: Request, call_next):
# 1. Static files skip
if request.url.path.startswith("/static"):
return await call_next(request)
# 2. Query param ?lang=xx redirect logic
lang_query = request.query_params.get("lang")
if lang_query in SUPPORTED_LANGUAGES:
path = request.url.path
path_parts = path.strip('/').split('/')
if path_parts and path_parts[0] in SUPPORTED_LANGUAGES:
path_parts[0] = lang_query
else:
path_parts.insert(0, lang_query)
new_path = "/" + "/".join(path_parts)
# Reconstruct query params without lang
new_query_params = dict(request.query_params)
del new_query_params['lang']
import urllib.parse
query_string = "?" + urllib.parse.urlencode(new_query_params) if new_query_params else ""
return RedirectResponse(url=new_path + query_string, status_code=301)
response = await call_next(request)
return response
def get_preferred_language(request: Request):
# Check cookie
cookie_lang = request.cookies.get("lang")
if cookie_lang in SUPPORTED_LANGUAGES:
return cookie_lang
# Default
return "en"
# Helper to set lang cookie
def response_with_cookie(response: Response, lang: str):
response.set_cookie(key="lang", value=lang, max_age=30*24*60*60)
return response
# Root Redirect
@app.get("/", response_class=RedirectResponse)
async def root(request: Request):
lang = get_preferred_language(request)
return RedirectResponse(url=f"/{lang}/home", status_code=302)
# Routes without lang prefix (Catch-all for known pages to redirect)
@app.get("/home", response_class=RedirectResponse)
@app.get("/characters", response_class=RedirectResponse)
@app.get("/changelog", response_class=RedirectResponse)
@app.get("/artifacter", response_class=RedirectResponse)
async def direct_access_redirect(request: Request):
lang = get_preferred_language(request)
path = request.url.path
return RedirectResponse(url=f"/{lang}{path}", status_code=302)
# Main Routes
@app.get("/{lang}/", response_class=RedirectResponse)
async def home_slash(request: Request, lang: str):
if lang not in SUPPORTED_LANGUAGES:
return RedirectResponse(url=f"/en/")
return RedirectResponse(url=f"/{lang}/home")
@app.get("/{lang}/home", response_class=HTMLResponse)
async def home(request: Request, lang: str):
if lang not in SUPPORTED_LANGUAGES:
return RedirectResponse(url=f"/en/home")
target_time = "2026-04-08T11:30:00+12:00"
response = templates.TemplateResponse("home.html", {"request": request, "lang": lang, "target_time": target_time})
return response_with_cookie(response, lang)
@app.get("/{lang}/characters", response_class=HTMLResponse)
async def characters(request: Request, lang: str):
if lang not in SUPPORTED_LANGUAGES:
return RedirectResponse(url=f"/en/characters")
chars = main.get_chars(lang)
response = templates.TemplateResponse("charslist.html", {"request": request, "lang": lang, "characters": chars})
return response_with_cookie(response, lang)
@app.get("/{lang}/character/{char_id}", response_class=HTMLResponse)
async def character(request: Request, lang: str, char_id: str):
if lang not in SUPPORTED_LANGUAGES:
return RedirectResponse(url=f"/en/character/{char_id}")
# Path construction (using relative paths for portability, assuming running from root)
base_dir = os.path.dirname(os.path.abspath(__file__))
json_path = os.path.join(base_dir, 'static', 'datas', 'chars_info', f'{char_id}.json')
if not os.path.exists(json_path):
json_path = os.path.join(base_dir, 'static', 'datas', 'json', f'{char_id}.json')
if os.path.exists(json_path):
with open(json_path, 'r', encoding='utf-8') as f:
char_info = json.load(f)
skill_jp = None
if lang == 'ja':
jp_path = os.path.join(base_dir, 'static', 'datas', 'skill_jp', f'{char_id}.json')
if os.path.exists(jp_path):
with open(jp_path, 'r', encoding='utf-8') as f:
skill_jp = json.load(f).get(char_id, {})
# Materials Name
m_name_path = os.path.join(base_dir, 'static', 'datas', f'materials_name_{lang}.json')
materials_name = {}
if os.path.exists(m_name_path):
with open(m_name_path, 'r', encoding='utf-8') as f:
materials_name = json.load(f)
# Materials Rate
m_rate_path = os.path.join(base_dir, 'static', 'datas', 'char_materials_rate.json')
char_materials_rate = {}
if os.path.exists(m_rate_path):
with open(m_rate_path, 'r', encoding='utf-8') as f:
char_materials_rate = json.load(f)
# Translate Rate (Overrides)
t_rate_path = os.path.join(base_dir, 'static', 'datas', 'translate_rate.json')
translate_rate = {}
if os.path.exists(t_rate_path):
with open(t_rate_path, 'r', encoding='utf-8') as f:
try:
translate_rate = json.load(f)
except:
translate_rate = {}
# Manual serialization to preserve order (Essential for the key fix)
char_info_json = json.dumps(char_info, ensure_ascii=False)
skill_jp_json = json.dumps(skill_jp, ensure_ascii=False) if skill_jp else 'null'
materials_name_json = json.dumps(materials_name, ensure_ascii=False)
char_materials_rate_json = json.dumps(char_materials_rate, ensure_ascii=False)
translate_rate_json = json.dumps(translate_rate, ensure_ascii=False)
context = {
"request": request,
"lang": lang,
"char_id": char_id,
"char_info": char_info,
"skill_jp": skill_jp,
"char_info_json": char_info_json,
"skill_jp_json": skill_jp_json,
"materials_name_json": materials_name_json,
"materials_name": materials_name,
"char_materials_rate_json": char_materials_rate_json,
"char_materials_rate": char_materials_rate,
"translate_rate_json": translate_rate_json
}
response = templates.TemplateResponse("charsinfo.html", context)
return response_with_cookie(response, lang)
else:
return HTMLResponse(content=f"Character data not found for ID: {char_id}", status_code=404)
@app.get("/{lang}/changelog", response_class=HTMLResponse)
async def changelog(request: Request, lang: str):
if lang not in SUPPORTED_LANGUAGES:
return RedirectResponse(url=f"/en/changelog")
base_dir = os.path.dirname(os.path.abspath(__file__))
json_path = os.path.join(base_dir, 'static', 'datas', f'changelog_{lang}.json')
changelog_data = []
if os.path.exists(json_path):
with open(json_path, 'r', encoding='utf-8') as f:
changelog_data = json.load(f)
response = templates.TemplateResponse("changelog.html", {"request": request, "lang": lang, "changelog": changelog_data})
return response_with_cookie(response, lang)
@app.get("/{lang}/weapons", response_class=HTMLResponse)
async def weapons(request: Request, lang: str):
if lang not in SUPPORTED_LANGUAGES:
return RedirectResponse(url=f"/en/weapons")
weapons_data = main.get_weapons(lang)
response = templates.TemplateResponse("weaponslist.html", {"request": request, "lang": lang, "weapons": weapons_data})
return response_with_cookie(response, lang)
@app.get("/{lang}/weapon/{weapon_id}", response_class=HTMLResponse)
async def weapon_detail(request: Request, lang: str, weapon_id: str):
if lang not in SUPPORTED_LANGUAGES:
return RedirectResponse(url=f"/en/weapon/{weapon_id}")
weapon_data = main.get_weapon_detail(weapon_id, lang)
if not weapon_data:
return RedirectResponse(url=f"/{lang}/weapons")
import json
weapon_json = json.dumps(weapon_data, ensure_ascii=False)
# Weapon Materials Rate
base_dir = os.path.dirname(os.path.abspath(__file__))
w_rate_path = os.path.join(base_dir, 'static', 'datas', 'weapon_materials_rate.json')
weapon_materials_rate = {}
if os.path.exists(w_rate_path):
with open(w_rate_path, 'r', encoding='utf-8') as f:
weapon_materials_rate = json.load(f)
weapon_materials_rate_json = json.dumps(weapon_materials_rate, ensure_ascii=False)
# Materials Name
m_name_path = os.path.join(base_dir, 'static', 'datas', f'materials_name_{lang}.json')
materials_name = {}
if os.path.exists(m_name_path):
with open(m_name_path, 'r', encoding='utf-8') as f:
materials_name = json.load(f)
materials_name_json = json.dumps(materials_name, ensure_ascii=False)
response = templates.TemplateResponse("weaponinfo.html", {
"request": request,
"lang": lang,
"weapon_id": weapon_id,
"weapon": weapon_data,
"weapon_json": weapon_json,
"weapon_materials_rate_json": weapon_materials_rate_json,
"materials_name_json": materials_name_json
})
return response_with_cookie(response, lang)
@app.get("/{lang}/artifacts", response_class=HTMLResponse)
async def artifacts(request: Request, lang: str):
if lang not in SUPPORTED_LANGUAGES:
return RedirectResponse(url=f"/en/artifacts")
base_dir = os.path.dirname(os.path.abspath(__file__))
file_suffix = "_en" if lang == "en" else ""
json_path = os.path.join(base_dir, f'static/datas/artifacts_data{file_suffix}.json')
artifacts_data = []
if os.path.exists(json_path):
with open(json_path, 'r', encoding='utf-8') as f:
artifacts_data = json.load(f)
# Sort by ID descending
artifacts_data.sort(key=lambda x: int(x['id']), reverse=True)
response = templates.TemplateResponse("artifacts.html", {"request": request, "lang": lang, "artifacts": artifacts_data})
return response_with_cookie(response, lang)
@app.get("/{lang}/card/{uid}/{char_id}", response_class=HTMLResponse)
async def build_card(request: Request, lang: str, uid: str, char_id: int):
if lang not in SUPPORTED_LANGUAGES:
return RedirectResponse(url=f"/en/card/{uid}/{char_id}")
base_dir = os.path.dirname(os.path.abspath(__file__))
json_path = os.path.join(base_dir, 'static', 'datas', 'cache', f'showcase_{uid}.json')
if not os.path.exists(json_path):
json_path = os.path.join(base_dir, 'static', 'datas', 'chars_info', f'showcase_{uid}.json')
if os.path.exists(json_path):
with open(json_path, 'r', encoding='utf-8') as f:
showcase_data = json.load(f)
# Find the character in avatarInfoList
char_data = None
if "avatarInfoList" in showcase_data:
for avatar in showcase_data["avatarInfoList"]:
if avatar.get("avatarId") == char_id:
char_data = avatar
break
if not char_data:
return HTMLResponse(content=f"Character {char_id} not found in showcase for UID {uid}", status_code=404)
# Get general character info (name, etc.)
char_info_path = os.path.join(base_dir, 'static', 'datas', 'chars_info', f'{char_id}.json')
if not os.path.exists(char_info_path):
char_info_path = os.path.join(base_dir, 'static', 'datas', 'json', f'{char_id}.json')
char_general_info = {}
if os.path.exists(char_info_path):
with open(char_info_path, 'r', encoding='utf-8') as f:
char_general_info = json.load(f)
# Materials Name for tooltips/labels
m_name_path = os.path.join(base_dir, 'static', 'datas', f'materials_name_{lang}.json')
materials_name = {}
if os.path.exists(m_name_path):
with open(m_name_path, 'r', encoding='utf-8') as f:
materials_name = json.load(f)
# Get Display Names from character.json and weapon.json
character_db_path = os.path.join(base_dir, 'static', 'datas', 'character.json')
weapon_db_path = os.path.join(base_dir, 'static', 'datas', 'weapon.json')
# Get Display Names
display_name = char_general_info.get("info", {}).get("name", str(char_id))
weapon_name = "Unknown Weapon"
if os.path.exists(character_db_path):
with open(character_db_path, 'r', encoding='utf-8') as f:
char_db = json.load(f)
for entry in char_db:
if str(char_id) in entry:
char_lang_key = f"{lang}Name" if lang != 'ja' else "jpName"
display_name = entry[str(char_id)].get(char_lang_key, display_name)
break
splash_id = str(char_id % 1000).zfill(3)
weapon_id = None
for equip in char_data.get("equipList", []):
if equip.get("flat", {}).get("itemType") == "ITEM_WEAPON":
weapon_id = str(equip.get("itemId"))
break
if weapon_id and os.path.exists(weapon_db_path):
with open(weapon_db_path, 'r', encoding='utf-8') as f:
weapon_db = json.load(f)
if weapon_id in weapon_db:
weapon_name = weapon_db[weapon_id].get(f"{lang}Name", weapon_name)
print(f"Rendering card for {uid}, char {char_id}, name: {display_name}")
# Create a mini text map for props
prop_keys = [
"FIGHT_PROP_ATTACK", "FIGHT_PROP_ATTACK_PERCENT", "FIGHT_PROP_BASE_ATTACK",
"FIGHT_PROP_DEFENSE", "FIGHT_PROP_DEFENSE_PERCENT", "FIGHT_PROP_BASE_DEFENSE",
"FIGHT_PROP_HP", "FIGHT_PROP_HP_PERCENT", "FIGHT_PROP_BASE_HP",
"FIGHT_PROP_CRITICAL", "FIGHT_PROP_CRITICAL_HURT", "FIGHT_PROP_CHARGE_EFFICIENCY",
"FIGHT_PROP_ELEMENT_MASTERY", "FIGHT_PROP_PHYSICAL_ADD_HURT",
"FIGHT_PROP_FIRE_ADD_HURT", "FIGHT_PROP_ELEC_ADD_HURT", "FIGHT_PROP_WATER_ADD_HURT",
"FIGHT_PROP_GRASS_ADD_HURT", "FIGHT_PROP_WIND_ADD_HURT", "FIGHT_PROP_ROCK_ADD_HURT",
"FIGHT_PROP_ICE_ADD_HURT", "FIGHT_PROP_HEAL_ADD"
]
prop_map = {k: GlobalTextMap.get(lang, k) for k in prop_keys}
# Get character list for navigation
char_list = []
if "avatarInfoList" in showcase_data:
# Load character.json for names
chars_db = {}
if os.path.exists(character_db_path):
with open(character_db_path, 'r', encoding='utf-8') as f:
chars_db_list = json.load(f)
if chars_db_list:
chars_db = chars_db_list[0]
for avatar in showcase_data["avatarInfoList"]:
avatar_id = avatar.get("avatarId")
cid = str(avatar_id)
cname = str(cid)
if cid in chars_db:
cname = chars_db[cid].get(f"{lang}Name" if lang != 'ja' else "jpName", cname)
# Calculate splash_id (last 3 digits of avatarId)
s_id = str(avatar_id % 1000).zfill(3)
char_list.append({"id": cid, "name": cname, "splash_id": s_id})
# Load artifact set name map
artifacts_file = 'artifacts_data_en.json' if lang == 'en' else 'artifacts_data.json'
artifacts_data_path = os.path.join(base_dir, 'static', 'datas', artifacts_file)
artifacts_name_map = {}
if os.path.exists(artifacts_data_path):
with open(artifacts_data_path, 'r', encoding='utf-8') as f:
artifacts_data_list = json.load(f)
for item in artifacts_data_list:
artifacts_name_map[item['id']] = item.get('name', '')
if str(char_id) == "039" or str(char_id) == "048":
pass
context = {
"request": request,
"lang": lang,
"uid": uid,
"char_id": char_id,
"display_name": display_name,
"weapon_name": weapon_name,
"prop_map": prop_map,
"char_data": char_data,
"showcase_data": showcase_data,
"char_general_info": char_general_info,
"splash_id": splash_id,
"materials_name": materials_name,
"char_list": char_list,
"char_list_json": json.dumps(char_list, ensure_ascii=False),
"char_data_json": json.dumps(char_data, ensure_ascii=False),
"showcase_data_json": json.dumps(showcase_data, ensure_ascii=False),
"char_general_info_json": json.dumps(char_general_info, ensure_ascii=False),
"artifacts_name_map_json": json.dumps(artifacts_name_map, ensure_ascii=False)
}
return templates.TemplateResponse("build_card.html", context)
else:
return HTMLResponse(content=f"Showcase data for UID {uid} not found. Please update via Artifacter page first.", status_code=404)
@app.get("/{lang}/artifacter", response_class=HTMLResponse)
async def artifacter(request: Request, lang: str):
if lang not in SUPPORTED_LANGUAGES:
return RedirectResponse(url=f"/en/artifacter")
base_dir = os.path.dirname(os.path.abspath(__file__))
char_path = os.path.join(base_dir, 'static', 'datas', 'character.json')
chars = {}
if os.path.exists(char_path):
with open(char_path, 'r', encoding='utf-8') as f:
chars_list = json.load(f)
if chars_list:
chars = chars_list[0]
response = templates.TemplateResponse("artifacter.html", {
"request": request,
"lang": lang,
"charslist": json.dumps(chars, ensure_ascii=False)
})
return response_with_cookie(response, lang)
@app.post("/api/update_uid")
async def update_uid(request: Request):
try:
data = await request.json()
uid = data.get("uid")
if not uid:
raise HTTPException(status_code=400, detail="UID is required")
success, message = await get_info_state.update_uid_data(int(uid))
# Get character list if success
characters = []
if success:
base_dir = os.path.dirname(os.path.abspath(__file__))
cache_path = os.path.join(base_dir, 'static', 'datas', 'cache', f'showcase_{uid}.json')
if os.path.exists(cache_path):
with open(cache_path, 'r', encoding='utf-8') as f:
showcase_data = json.load(f)
if "avatarInfoList" in showcase_data:
for avatar in showcase_data["avatarInfoList"]:
characters.append({
"id": avatar.get("avatarId"),
"level": avatar.get("propMap", {}).get("4001", {}).get("val", "0")
})
if success:
return {"status": "success", "message": message, "characters": characters}
else:
return {"status": "error", "message": message}
except Exception as e:
return {"status": "error", "message": str(e)}
@app.get("/{lang}/banners", response_class=HTMLResponse)
async def banners(request: Request, lang: str):
if lang not in SUPPORTED_LANGUAGES:
return RedirectResponse(url=f"/en/banners")
base_dir = os.path.dirname(os.path.abspath(__file__))
# Load kigan_history.json
history_path = os.path.join(base_dir, 'static', 'datas', 'kigan_history.json')
history = []
if os.path.exists(history_path):
with open(history_path, 'r', encoding='utf-8') as f:
history = json.load(f)
# Load character.json
char_path = os.path.join(base_dir, 'static', 'datas', 'character.json')
chars = {}
if os.path.exists(char_path):
with open(char_path, 'r', encoding='utf-8') as f:
chars_list = json.load(f)
if chars_list:
chars = chars_list[0]
# Filter out standard banners
filtered_history = [b for b in history if b.get("type") not in ["first_standerd", "standerd"]]
# Group by version
import re
grouped_data = {}
for entry in filtered_history:
ver = entry.get("version", "Unknown")
if ver not in grouped_data:
grouped_data[ver] = []
grouped_data[ver].append(entry)
# Sort versions descending
def ver_key(v):
parts = re.findall(r'\d+', v)
return [int(p) for p in parts] if parts else [-1]
sorted_versions = sorted(grouped_data.keys(), key=ver_key, reverse=True)
# Process grouping within each version
processed_history = []
for v in sorted_versions:
version_banners = grouped_data[v]
# 1. Separate Chronicled
chronicled = [b for b in version_banners if b.get("type") == "Chronicled"]
# 2. Group characters by 4-star pick-ups
char_banners = [b for b in version_banners if b.get("type") == "characters"]
groups = []
seen_4star_groups = [] # List of tuples (4star_tuple, group_index)
for b in char_banners:
p4 = tuple(sorted(b.get("pickup_4star", [])))
found_group = False
for group_p4, idx in seen_4star_groups:
if p4 == group_p4:
# Add to existing group
groups[idx]["five_stars"].extend(b.get("pickup_5star", []))
found_group = True
break
if not found_group:
# Create new group
new_group = {
"five_stars": list(b.get("pickup_5star", [])),
"four_stars": b.get("pickup_4star", []) # Keep original order if possible
}
seen_4star_groups.append((p4, len(groups)))
groups.append(new_group)
processed_history.append({
"version": v,
"banner_groups": groups,
"chronicled": chronicled
})
response = templates.TemplateResponse("banner.html", {
"request": request,
"lang": lang,
"history": processed_history,
"chars": chars
})
return response_with_cookie(response, lang)
@app.get("/serverup", response_class=HTMLResponse)
@app.post("/serverup", response_class=HTMLResponse)
@app.head("/serverup", response_class=HTMLResponse)
async def serverup(request: Request):
return HTMLResponse(content="Success to access")
# ===== Map Logic & Routes =====
def fetch_tile(row: int, col: int):
filename = f"{col}_{row}_N1.webp"
local_path = MAP_CACHE_DIR / filename
if local_path.exists():
return local_path
url = f"{MAP_BASE_URL}/{filename}"
try:
time.sleep(MAP_REQUEST_DELAY)
r = map_session.get(url, timeout=MAP_TIMEOUT)
r.raise_for_status()
with open(local_path, "wb") as f:
f.write(r.content)
return local_path
except Exception as e:
print(f"Failed to fetch {filename}: {e}")
return None
@app.get("/{lang}/map", response_class=HTMLResponse)
async def map(request: Request, lang: str):
if lang not in SUPPORTED_LANGUAGES:
return RedirectResponse(url=f"/en/map")
response = templates.TemplateResponse("map.html", {
"request": request,
"lang": lang,
"max_row": MAX_ROW,
"max_col": MAX_COL
})
return response_with_cookie(response, lang)
@app.get("/tile/{row}/{col}")
async def get_tile(row: int, col: int):
if not (0 <= row <= MAX_ROW and 0 <= col <= MAX_COL):
raise HTTPException(status_code=404, detail="Tile out of range")
path = fetch_tile(row, col)
if path and path.exists():
return FileResponse(path, media_type="image/webp")
raise HTTPException(status_code=404, detail="Tile not found")
if __name__ == "__main__":
uvicorn.run("server:app", host="0.0.0.0", port=8000, reload=True)