Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
2167 lines (1931 loc) · 85.5 KB
/
Copy pathmain.py
File metadata and controls
2167 lines (1931 loc) · 85.5 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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Author: Hydrooxzgen
# Github: https://github.com/Hydrooxzgen
# This project uses the GPL-3.0 license, you can modify/distribute this project according to the GPL-3.0 license
# The EBC config format version is b0.3.6
import asyncio
import json
import os
import re
import subprocess
import sys
import threading
import time
from uuid import uuid4
# ===== 常量定义区=====
# --- 路径常量 ---
ROOT = os.path.dirname(os.path.abspath(__file__))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
# 挂载核心配置与系统文件安全防护卫士 (PEP 578: 严防第三方 Mod 篡改或删除核心配置)
try:
from lib.security_guard import install_security_guard
install_security_guard()
except Exception:
pass
CONFIG_DIR = os.path.join(ROOT, "config")
CONFIG_PY = os.path.join(CONFIG_DIR, "config.py")
CONFIG_JSON = os.path.join(CONFIG_DIR, "config.json")
CONFIG_EXAMPLE_JSON = os.path.join(CONFIG_DIR, "config.example.json")
PERMISSION_JSON = os.path.join(CONFIG_DIR, "permission.json")
PERMISSION_EXAMPLE = os.path.join(CONFIG_DIR, "permission.example.json")
USERS_JSON = os.path.join(CONFIG_DIR, "users.json")
UPDATE_MARKER = os.path.join(ROOT, ".update_pending")
# --- 版本常量 ---
VERSION = "v1.1.3"
# ↓仅当不为None时从Github拉取更新日志, 反之则直接显示该变量内容。
DESCRIPTION = None
"""
feat1: 世界存档自动定时备份与快照
feat2: feat1 接入 webui
"""
MINIMIUM_ALLOWED_VERSION = "v1.1.0.1" # 因为v1.1.0.1版本新增了重要安全改进,再次降低了被第三方恶意mod入侵的风险,所以限制了降级
# 但是如果你需要降级低于v1.1.0.1的版本,请更改这里的值为0.0.0以删除限制
GITHUB_REPO = "Hydrooxzgen/EnderBridge" # You can edit this to your own repository if you fork it :)
# --- 命令行开关常量 ---
IS_TESTING = "pytest" in sys.modules or any("pytest" in str(a).lower() for a in sys.argv)
WANT_RESET = ("--reset-all" in sys.argv) or ("--reset" in sys.argv)
WANT_EXPORT = "export" in sys.argv
WANT_EXPORT_CLEAR = WANT_EXPORT and "-clear" in sys.argv
WANT_LOAD_WITHOUT_CONFIG = "--load-without-config" in sys.argv
WANT_VIEW_VERSION = not IS_TESTING and ("--version" in sys.argv or "-v" in sys.argv)
WANT_SYSTEM_MODE = "--system" in sys.argv
WANT_SAFE_MODE = "--safe-mode" in sys.argv
WANT_HELP = not IS_TESTING and ("--help" in sys.argv or "-h" in sys.argv)
WANT_VIEW_DESCRIPTION = "--description" in sys.argv
WANT_GOTO_OOBE = "--goto-oobe" in sys.argv
WANT_UPDATE = "update" in sys.argv
WANT_ROLLBACK = "--rollback" in sys.argv
WANT_PREVIEW = "preview" in sys.argv
ARGV_NOT_EXIST = not IS_TESTING and not WANT_RESET\
and not WANT_VIEW_VERSION and not WANT_EXPORT \
and not WANT_VIEW_DESCRIPTION and not WANT_HELP \
and not WANT_ROLLBACK and not WANT_PREVIEW
# --- 终端提示符常量 ---
CONSOLE_PROMPT = "EnderBridge> "
RESTART_EXIT_CODE = 42
ENV_SUPERVISED = "_EB_SUPERVISED"
def _is_oneshot_command() -> bool:
"""判断当前命令行是否为单次执行即退出的工具指令(无需启动主控 Supervisor 守护)"""
return bool(
WANT_RESET
or WANT_VIEW_VERSION
or WANT_EXPORT
or WANT_VIEW_DESCRIPTION
or WANT_HELP
or WANT_UPDATE
or WANT_ROLLBACK
or WANT_PREVIEW
or ("--no-supervisor" in sys.argv)
or (os.environ.get("EB_NO_SUPERVISOR") == "1")
)
# ===== 自动迁移:将根目录下的旧配置文件安全移动到 config/ 目录 =====
os.makedirs(CONFIG_DIR, exist_ok=True)
import shutil as _shutil_migrate
for _fname in [
"config.py", "config.py.bak", "config.json", "config.json.bak",
"config.example.json",
"permission.json", "permission.json.bak", "permission.example.json",
"users.json", "users.example.json",
"banlist.json",
]:
_old = os.path.join(ROOT, _fname)
_target = os.path.join(CONFIG_DIR, _fname)
if os.path.exists(_old):
# 若 config/ 目录下尚无该配置文件,优先安全迁移而非直接删除!
if not os.path.exists(_target):
try:
_shutil_migrate.move(_old, _target)
except Exception:
pass
else:
try:
os.remove(_old)
except OSError:
pass
def _parse_version(v: str) -> tuple:
"""解析版本号字符串(如 'b0.4.1 dev', 'b0.4.1')为可比较的元组 (0, 4, 1)"""
v = v.strip().split()[0] # 去掉 ' dev' 等后缀
v = v.lstrip('bBvV') # 去掉前缀 b/B/v/V
parts = v.split('.')
result = []
for p in parts:
try:
result.append(int(p))
except ValueError:
break
return tuple(result)
def _check_minimum_version(new_version: str) -> None:
"""检查新版本是否低于最低允许版本,是则中止升级"""
if not new_version or not MINIMIUM_ALLOWED_VERSION:
return
try:
new_ver = _parse_version(new_version)
min_ver = _parse_version(MINIMIUM_ALLOWED_VERSION)
if new_ver < min_ver:
_update_err(
f"目标版本 {new_version} 低于最低允许版本 {MINIMIUM_ALLOWED_VERSION},\n"
f"操作终止"
)
except Exception:
pass # 版本格式异常时跳过检查,不阻塞升级
# ===== 依赖检测(必须早于任何第三方mod使用) =====
# 自动发现虚拟环境并检测核心依赖 (websockets, bcrypt)
def _ensure_venv_path() -> None:
if IS_TESTING:
return
for _v in (".venv", "venv", "env"):
_sp = os.path.join(ROOT, _v, "Lib", "site-packages")
if not os.path.isdir(_sp):
_lib = os.path.join(ROOT, _v, "lib")
if os.path.isdir(_lib):
for _pv in os.listdir(_lib):
_p = os.path.join(_lib, _pv, "site-packages")
if os.path.isdir(_p):
_sp = _p
break
if os.path.isdir(_sp) and _sp not in sys.path:
sys.path.insert(0, _sp)
_ensure_venv_path()
def _dependencies_ok() -> bool:
try:
import websockets # noqa: F401
import bcrypt # noqa: F401
return True
except ImportError:
return False
def _run_setup() -> None:
print("========================================")
print(" 检测到缺少依赖, 正在安装依赖...")
print("========================================")
res = subprocess.run([sys.executable, "setup.py"], cwd=ROOT)
if res.returncode != 0:
print("依赖安装失败, 请手动运行 python setup.py 排查")
sys.exit(1)
# 安装成功后重启进程, 使新安装的包生效
print("依赖安装完成, 重启进程...")
os.execv(sys.executable, [sys.executable] + sys.argv)
if not WANT_RESET and not WANT_EXPORT and not _dependencies_ok():
_run_setup()
# ===== 引导阶段(必须早于任何依赖 config.py 的模块加载) =====
# 依赖 config.json 的模块(lib/logger.py、lib/utils.py、lib/mods.py 等)均为延迟加载,
# 因此 config.json 缺失时(如 --reset-all 之后)可先在此根据模板自动补全,保证程序可启动。
# 此阶段判断启动参数并执行对应操作(ARGV_NOT_EXIST 见顶部常量区)
if not os.path.exists(CONFIG_PY) and not os.path.exists(CONFIG_JSON) and ARGV_NOT_EXIST:
# 从模板初始化全新配置
if os.path.exists(CONFIG_EXAMPLE_JSON):
import shutil as _shutil_cfg
_shutil_cfg.copy2(CONFIG_EXAMPLE_JSON, CONFIG_JSON)
# 清理可能残留的旧备份, 保证重置彻底
_bak = CONFIG_JSON + ".bak"
if os.path.exists(_bak):
try:
os.remove(_bak)
except OSError:
pass
# --load-without-config 跳过向导,必须清除 is_first_run,
# 否则下次正常启动会误触发向导
if WANT_LOAD_WITHOUT_CONFIG:
try:
with open(CONFIG_JSON, "r", encoding="utf-8") as _f:
_j = json.load(_f)
if _j.get("is_first_run", False):
_j["is_first_run"] = False
with open(CONFIG_JSON, "w", encoding="utf-8") as _f:
json.dump(_j, _f, ensure_ascii=False, indent=2)
except Exception:
pass
print("未找到 config.json, 已根据模板自动生成默认配置(可在向导中修改)")
# permission.json 缺失时从模板复制
if not os.path.exists(PERMISSION_JSON) and ARGV_NOT_EXIST:
if os.path.exists(PERMISSION_EXAMPLE):
with open(PERMISSION_EXAMPLE, "r", encoding="utf-8") as f:
content = f.read()
with open(PERMISSION_JSON, "w", encoding="utf-8") as f:
f.write(content)
_bak_perm = PERMISSION_JSON + ".bak"
if os.path.exists(_bak_perm):
try:
os.remove(_bak_perm)
except OSError:
pass
print("未找到 permission.json, 已根据模板自动生成默认权限配置")
# ===== 一键重置:python main.py --reset-all =====
# 清除所有配置文件(不启动服务器),并将模板 config.example.json 的 is_first_run 复位为 True
if WANT_RESET:
files = ["config.py", "config.py.bak", "config.json", "config.json.bak", "permission.json", "permission.json.bak", "users.json", "banlist.json"]
removed = []
# 同时清理 config/ 子目录和根目录的旧配置文件,防止启动时自动迁移将旧文件恢复
for name in files:
for base in (CONFIG_DIR, ROOT):
p = os.path.join(base, name)
if os.path.exists(p):
try:
os.remove(p)
except OSError:
pass
removed.append(name)
try:
import glob
for f in glob.glob(os.path.join(CONFIG_DIR, "*.bak_reset_*")):
try:
os.remove(f)
except OSError:
pass
except Exception:
pass
# 复位模板标记,下次启动自动进入向导重新配置
try:
if os.path.exists(CONFIG_EXAMPLE_JSON):
with open(CONFIG_EXAMPLE_JSON, "r", encoding="utf-8") as f:
tpl = json.load(f)
if not tpl.get("is_first_run", False):
tpl["is_first_run"] = True
with open(CONFIG_EXAMPLE_JSON, "w", encoding="utf-8") as f:
json.dump(tpl, f, ensure_ascii=False, indent=2)
except Exception:
pass
print("========================================")
print(" 配置已重置")
print("========================================")
sys.exit(0)
# 查看版本并退出
if WANT_VIEW_VERSION:
print(f"EnderBridge {VERSION}")
sys.exit(0)
# 显示描述并退出
if WANT_VIEW_DESCRIPTION:
if DESCRIPTION is not None:
print(DESCRIPTION)
else:
print(f"No description available. Please check the GitHub repository for more information.")
sys.exit(0)
# 显示帮助并退出
if WANT_HELP:
print(f"EnderBridge {VERSION}")
print(f"{DESCRIPTION}")
print()
print("用法: python main.py [命令] [选项]")
print()
print("命令:")
print(" (无参数) 正常启动服务器")
print(" preview [蓝图文件] 离线本地 3D 预览蓝图(无需启动MC或客户端)")
print(" update <压缩包> 一键升级(保留配置,默认自动备份)")
print(" export [输出路径] 一键导出为zip")
print(" --rollback [备份包] 回滚到指定备份(默认最新)")
print()
print("选项:")
print(" --help, -h 显示此帮助信息")
print(" --version, -v 显示当前版本")
print(" --safe-mode 安全模式启动: 跳过第三方 Mod 加载,仅保留核心通信与 WebUI")
print(" --reset-all 一键重置所有配置")
print(" --load-without-config 跳过配置直接启动(调试用)")
print(" --system 启用系统保留账户模式")
print(" --goto-oobe 重新进入配置向导(保留当前配置)")
print(" --bypass-backup 配合 update 命令使用,跳过更新前自动备份")
print()
print("示例:")
print(" python main.py 启动服务器")
print(" python main.py preview 樱花塔.litematic 在本地浏览器 3D 预览蓝图")
print(" python main.py preview 樱花塔 --export out.html 导出独立离线 HTML 预览网页")
print(" python main.py update update.zip 从压缩包升级")
print(" python main.py update update.zip --bypass-backup 跳过备份直接升级")
print(" python main.py export 导出为zip")
print(" python main.py export D:/backup/eb.zip 导出到指定路径")
print(" python main.py --reset-all 重置所有配置")
print(" python main.py --version 查看版本")
sys.exit(0)
# ===== 回滚:python main.py --rollback [备份包] =====
# 用更新前自动生成的备份覆盖当前项目(默认用最新备份),完成后退出不启动服务器。
# (WANT_ROLLBACK 开关常量见顶部)
if WANT_ROLLBACK:
from version_manager.package import rollback, PackageError
idx = sys.argv.index("--rollback")
backup_arg = sys.argv[idx + 1] if len(sys.argv) > idx + 1 and not sys.argv[idx + 1].startswith("-") else None
print("========================================")
print(" 正在回滚 EnderBridge ...")
print(f" 当前版本: {VERSION}")
if backup_arg:
print(f" 指定备份: {backup_arg}")
print("========================================")
try:
used = rollback(ROOT, backup_arg)
except PackageError as e:
print("========================================")
print(f" 回滚失败: {e}")
print("========================================")
sys.exit(1)
print("========================================")
print(f" 回滚完成: {used}")
print(" 请重新启动: py -B main.py")
print("========================================")
sys.exit(0)
# ===== 一键升级:python main.py update <新版本压缩包> =====
# 从压缩包(zip / tar.gz)升级当前版本,保留 config.py / permission.json
# 等设置与 resources / structures / logs 等用户数据,完成后退出不启动服务器。
# 更新前自动备份到上级目录(保留最近 3 个),可用 --rollback 回滚。
# (WANT_UPDATE 开关常量见顶部)
if WANT_UPDATE:
import shutil
import tempfile
from version_manager.package import (
apply_archive,
backup_dir,
iter_archive_members,
PackageError,
)
def _load_github_token() -> str:
"""从 config.py 读取 GitHub API Token"""
try:
import importlib.util
spec = importlib.util.spec_from_file_location("_cfg_token", CONFIG_PY)
if spec and spec.loader:
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return getattr(mod, "githubToken", "") or ""
return ""
except Exception:
return ""
def _github_headers() -> dict:
"""返回 GitHub API 请求头,附带 Token 认证(若有)"""
headers = {"Accept": "application/vnd.github.v3+json"}
token = _load_github_token()
if token:
headers["Authorization"] = f"token {token}"
return headers
def _update_err(msg):
print("========================================")
print(f" 失败: {msg}")
print(" 当前版本未做任何改动,可继续正常启动")
print("========================================")
sys.exit(1)
# 兼容别名:旧内部函数名统一指向 version_manager.package
def _update_archive_members(archive):
"""迭代压缩包成员,产出 (相对路径, 文件对象)"""
try:
yield from iter_archive_members(archive)
except PackageError as e:
_update_err(str(e))
def _do_update(archive, new_version=None, auto_backup=True):
if not os.path.isfile(archive):
_update_err(f"找不到压缩包: {archive}")
print("========================================")
print(f" 正在升级 EnderBridge ...")
print(f" 当前版本: {VERSION}")
if new_version:
print(f" 目标版本: {new_version}")
print(f" 压缩包: {archive}")
print("========================================")
# 1. 先探测压缩包内容,校验为 EnderBridge 项目
members = []
try:
for rel, _f in _update_archive_members(archive):
members.append(rel)
except Exception as e:
_update_err(f"读取压缩包失败: {e}")
if "main.py" not in members:
_update_err("无法识别此更新包, 请确保你选择的是EnderBridge压缩包")
# 1.5 版本降级检查:从压缩包中读取新版本号并与最低允许版本比较
_check_minimum_version(new_version or "")
# 如果 new_version 未提供,尝试从压缩包的 main.py 中提取
if not new_version:
try:
for rel, fobj in _update_archive_members(archive):
if rel == "main.py" and fobj is not None:
_src = fobj.read().decode("utf-8", errors="replace")
_m = re.search(r'^VERSION\s*=\s*"([^"]+)"', _src, re.MULTILINE)
if _m:
_check_minimum_version(_m.group(1))
break
except Exception:
pass
# 1.6 更新前自动备份(失败则中止,不动现有文件)
if auto_backup:
try:
backup_path = backup_dir(ROOT)
except PackageError as e:
_update_err(str(e))
print(f" 已备份当前版本: {backup_path}")
else:
print(" [提示] 已跳过更新前自动备份")
# 2-4. 解压到临时目录(跳过数据区,模板放行) → 校验 → 覆盖到项目根目录
try:
copied = apply_archive(archive, ROOT)
except PackageError as e:
_update_err(str(e))
else:
print(f" 已覆盖 {copied} 个文件")
# 5. 更新版本号
if new_version:
main_path = os.path.join(ROOT, "main.py")
try:
with open(main_path, "r", encoding="utf-8") as f:
src = f.read()
new_src = re.sub(
r'^VERSION\s*=\s*"[^"]*"',
f'VERSION = "{new_version}"',
src,
count=1,
flags=re.MULTILINE,
)
if new_src != src:
with open(main_path, "w", encoding="utf-8") as f:
f.write(new_src)
print(f" 版本号已更新: {VERSION} → {new_version}")
except Exception as e:
print(f" 警告: 版本号更新失败 ({e}),请手动修改 VERSION")
# 6. 重新生成 requirements.txt 缺失依赖的自动安装由下次启动完成
print("========================================")
print(" 升级完成!")
print(" 已保留: config/ 目录等设置与用户数据")
print(" 请重新启动: py -B main.py")
print("========================================")
sys.exit(0)
def _download_release(tag=None):
"""从 GitHub Releases 下载压缩包,返回本地临时文件路径
Args:
tag: 版本标签(如 "b0.1.0"),None 表示最新版本
"""
import urllib.parse
import urllib.request
import urllib.error
if tag:
api_url = f"https://api.github.com/repos/{GITHUB_REPO}/releases/tags/{urllib.parse.quote(tag)}"
else:
# releases/latest 只返回正式版;仓库最新版本为预览版(prerelease)时会返回 404,
# 改用列表接口取最新一条(含预览版),与 WebUI 检查更新保持一致。
api_url = f"https://api.github.com/repos/{GITHUB_REPO}/releases?per_page=1"
print(f" 正在查询 GitHub Releases ...")
print(f" API: {api_url}")
# 1. 查询 release 信息
data: dict = {}
try:
req = urllib.request.Request(api_url, headers=_github_headers())
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode("utf-8"))
if isinstance(data, list):
# 列表接口返回数组,取最新一条
if not data:
_update_err(f"GitHub 上未找到版本 latest\n 仓库: {GITHUB_REPO}")
data = data[0]
except urllib.error.HTTPError as e:
if e.code == 404:
ver = tag or "latest"
_update_err(f"GitHub 上未找到版本 {ver}\n 仓库: {GITHUB_REPO}")
_update_err(f"查询 GitHub Releases 失败: {e}")
except Exception as e:
_update_err(f"网络请求失败: {e}")
if not isinstance(data, dict):
_update_err("GitHub API 返回格式异常")
release_tag = data.get("tag_name", "unknown")
release_name = data.get("name") or release_tag
print(f" 版本: {release_name} ({release_tag})")
# 2. 查找 zip 或 tar.gz 资源
assets = data.get("assets", [])
asset = None
for a in assets:
name = a.get("name", "").lower()
if name.endswith(".zip") or name.endswith((".tar.gz", ".tgz")):
asset = a
break
if not asset:
_update_err(f"版本 {release_tag} 中未找到 zip/tar.gz 压缩包资源")
assert asset is not None
download_url = asset["browser_download_url"]
asset_name = asset["name"]
print(f" 资源: {asset_name}")
print(f" 下载: {download_url}")
# 3. 下载到临时文件
tmp_fd, tmp_path = tempfile.mkstemp(suffix=os.path.splitext(asset_name)[1], prefix="enderbridge_dl_")
try:
print(f" 正在下载 ...")
req = urllib.request.Request(download_url, headers=_github_headers())
with urllib.request.urlopen(req, timeout=120) as resp:
total = int(resp.headers.get("Content-Length", 0))
downloaded = 0
with os.fdopen(tmp_fd, "wb") as f:
tmp_fd = -1 # fdopen 会接管关闭
while True:
chunk = resp.read(8192)
if not chunk:
break
f.write(chunk)
downloaded += len(chunk)
if total:
pct = downloaded * 100 // total
sys.stdout.write(f"\r 下载进度: {pct}% ({downloaded}/{total})")
sys.stdout.flush()
if total:
print() # 换行
print(f" 下载完成: {tmp_path}")
return tmp_path
except Exception as e:
if tmp_fd >= 0:
os.close(tmp_fd)
try:
os.unlink(tmp_path)
except Exception:
pass
_update_err(f"下载失败: {e}")
def _download_commit(ref=None):
"""从 GitHub 下载指定 commit 的源码压缩包
Args:
ref: commit SHA 或分支名(如 "abc1234","HEAD","main"),None 表示默认分支最新
Returns:
(本地临时文件路径, 版本号字符串)
"""
import urllib.parse
import urllib.request
import urllib.error
ref = ref or "HEAD"
# 1. 解析 ref → 获取 commit 信息
if ref.upper() == "HEAD" or ref == "":
# 获取默认分支最新 commit
api_url = f"https://api.github.com/repos/{GITHUB_REPO}/commits/HEAD"
else:
api_url = f"https://api.github.com/repos/{GITHUB_REPO}/commits/{urllib.parse.quote(ref)}"
print(f" 正在查询 GitHub Commits ...")
print(f" API: {api_url}")
commit_data = None
try:
req = urllib.request.Request(api_url, headers=_github_headers())
with urllib.request.urlopen(req, timeout=30) as resp:
commit_data = json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as e:
if e.code == 404:
_update_err(f"GitHub 上未找到 commit: {ref}\n 仓库: {GITHUB_REPO}")
_update_err(f"查询 GitHub Commits 失败: {e}")
except Exception as e:
_update_err(f"网络请求失败: {e}")
if not isinstance(commit_data, dict):
_update_err("GitHub API 返回格式异常")
assert isinstance(commit_data, dict)
sha = commit_data["sha"]
short_sha = sha[:7]
commit_msg = commit_data.get("commit", {}).get("message", "").split("\n")[0]
print(f" Commit: {short_sha} - {commit_msg}")
# 2. 检查此 commit 是否有 tag
version = None
try:
tags_url = f"https://api.github.com/repos/{GITHUB_REPO}/tags"
req = urllib.request.Request(tags_url, headers=_github_headers())
with urllib.request.urlopen(req, timeout=30) as resp:
tags = json.loads(resp.read().decode("utf-8"))
for tag in tags:
tag_sha = tag.get("commit", {}).get("sha", "")
if tag_sha == sha:
version = tag["name"]
print(f" 已关联 Tag: {version}")
break
except Exception:
pass
if not version:
version = short_sha
print(f" 无关联 Tag,使用 Commit ID: {version}")
# 3. 下载源码压缩包(zipball)
download_url = f"https://api.github.com/repos/{GITHUB_REPO}/zipball/{sha}"
print(f" 下载: {download_url}")
tmp_fd, tmp_path = tempfile.mkstemp(suffix=".zip", prefix="enderbridge_commit_")
try:
print(f" 正在下载 ...")
req = urllib.request.Request(download_url, headers=_github_headers())
with urllib.request.urlopen(req, timeout=120) as resp:
total = int(resp.headers.get("Content-Length", 0))
downloaded = 0
with os.fdopen(tmp_fd, "wb") as f:
tmp_fd = -1
while True:
chunk = resp.read(8192)
if not chunk:
break
f.write(chunk)
downloaded += len(chunk)
if total:
pct = downloaded * 100 // total
sys.stdout.write(f"\r 下载进度: {pct}% ({downloaded}/{total})")
sys.stdout.flush()
if total:
print()
print(f" 下载完成: {tmp_path}")
return tmp_path, version
except Exception as e:
if tmp_fd >= 0:
os.close(tmp_fd)
try:
os.unlink(tmp_path)
except Exception:
pass
_update_err(f"下载失败: {e}")
# update 命令解析
bypass_backup = "--bypass-backup" in sys.argv
cfg_auto_backup = True
try:
if os.path.exists(CONFIG_JSON):
with open(CONFIG_JSON, "r", encoding="utf-8") as f:
_c = json.load(f)
cfg_auto_backup = bool((_c.get("updateConfig") or {}).get("autoBackup", True))
except Exception:
pass
should_backup = (not bypass_backup) and cfg_auto_backup
upd_pos = sys.argv.index("update")
pos_args = [a for a in sys.argv[upd_pos + 1:] if not a.startswith("--")]
if "--local" in sys.argv:
# 本地更新:py main.py update --local <压缩包> [--bypass-backup]
idx = sys.argv.index("--local")
local_args = [a for a in sys.argv[idx + 1:] if not a.startswith("--")]
if local_args:
_do_update(local_args[0], auto_backup=should_backup)
else:
_update_err("用法: python main.py update --local <新版本压缩包路径> [--bypass-backup]")
elif "--online" in sys.argv:
idx = sys.argv.index("--online")
rest = [a for a in sys.argv[idx + 1:] if not a.startswith("--")]
if rest and rest[0].lower() == "commit":
# commit 模式:py main.py update --online commit [HEAD|commitID] [--bypass-backup]
ref = rest[1] if len(rest) > 1 else None
dl_path, new_ver = _download_commit(ref) # type: ignore[misc]
try:
_do_update(dl_path, new_version=new_ver, auto_backup=should_backup)
finally:
try:
if dl_path:
os.unlink(dl_path)
except Exception:
pass
else:
# release 模式:py main.py update --online [release] [版本号] [--bypass-backup]
tag = None
if rest:
if rest[0].lower() == "release":
if len(rest) > 1:
tag = rest[1]
else:
tag = rest[0]
dl_path = _download_release(tag)
try:
_do_update(dl_path, new_version=tag, auto_backup=should_backup)
finally:
try:
if dl_path:
os.unlink(dl_path)
except Exception:
pass
elif pos_args:
# 无标志但有参数:py main.py update <压缩包> [--bypass-backup] → 当作 --local
_do_update(pos_args[0], auto_backup=should_backup)
else:
# 无参数:默认从 GitHub 下载最新 release
dl_path = _download_release()
try:
_do_update(dl_path, auto_backup=should_backup)
finally:
try:
if dl_path:
os.unlink(dl_path)
except Exception:
pass
# ===== 离线本地蓝图 3D 预览: python main.py preview <蓝图文件/路径> =====
# 无需启动 Minecraft 服务器或连接客户端,秒级在本地浏览器呈现三维体素投影
if WANT_PREVIEW:
import argparse
from lib.studio import preview_blueprint_locally
idx = sys.argv.index("preview")
sub_args = sys.argv[idx + 1:]
parser = argparse.ArgumentParser(prog="python main.py preview", description="EnderBridge 离线 3D 蓝图本地预览")
parser.add_argument("file", nargs="?", default="", help="蓝图文件名 (如 樱花塔.litematic) 或完整物理路径")
parser.add_argument("--export", "-o", default=None, help="导出独立的单文件离线 HTML 路径 (不指定则默认保存在 logs/ 并自动唤起浏览器)")
parser.add_argument("--no-browser", action="store_true", help="仅生成本地 HTML 预览文件,不自动唤起默认浏览器")
parsed = parser.parse_args(sub_args)
target_file = parsed.file.strip()
try:
out_path = preview_blueprint_locally(
target=target_file,
export_path=parsed.export,
open_browser=not parsed.no_browser
)
print("========================================")
print(" EnderBridge 蓝图离线 3D 本地预览")
print("========================================")
print(f" 已成功生成本地 3D 预览文件:")
print(f" {out_path}")
if not parsed.no_browser:
print(" 已在默认浏览器打开 3D 视轨交互界面")
print("========================================")
sys.exit(0)
except Exception as e:
print("========================================")
print(f" 本地预览失败: {e}")
print("========================================")
sys.exit(1)
# ===== WebUI 触发的更新:检测 .update_pending 标记文件(路径常量见顶部) =====
if os.path.isfile(UPDATE_MARKER) and not WANT_UPDATE:
# WebUI 写入了待更新的压缩包路径,立即执行更新
try:
with open(UPDATE_MARKER, "r", encoding="utf-8") as f:
pending_path = f.read().strip()
except Exception:
pending_path = ""
finally:
try:
os.remove(UPDATE_MARKER)
except Exception:
pass
if pending_path and os.path.isfile(pending_path):
from version_manager.package import apply_archive, backup_dir, PackageError, get_archive_version
# 检查是否低于最低允许版本, 防止降级到危险版本
pending_ver = get_archive_version(pending_path)
if pending_ver and MINIMIUM_ALLOWED_VERSION:
try:
if _parse_version(pending_ver) < _parse_version(MINIMIUM_ALLOWED_VERSION):
print("========================================")
print(f" [安全拦截] 目标版本 {pending_ver} 低于最低允许版本 {MINIMIUM_ALLOWED_VERSION}")
print(" 更新操作已终止,当前版本未受影响")
print("========================================")
pending_path = None
except Exception:
pass
if pending_path and os.path.isfile(pending_path):
print("========================================")
print(f" WebUI 触发更新: {pending_path}")
print(f" 当前版本: {VERSION}")
if pending_ver:
print(f" 目标版本: {pending_ver}")
print("========================================")
try:
try:
# 检查配置判断是否自动备份
do_backup = True
try:
if os.path.exists(CONFIG_JSON):
with open(CONFIG_JSON, "r", encoding="utf-8") as f:
_cfg = json.load(f)
do_backup = bool((_cfg.get("updateConfig") or {}).get("autoBackup", True))
except Exception:
pass
if do_backup:
backup_path = backup_dir(ROOT)
print(f" 已备份当前版本: {backup_path}")
else:
print(" [提示] 根据配置已跳过更新前自动备份 (updateConfig.autoBackup = false)")
copied = apply_archive(pending_path, ROOT)
except PackageError as e:
print(f" 更新失败: {e}")
sys.exit(1)
print(f" 已覆盖 {copied} 个文件")
print(" 文件已覆盖,正在重启以加载新版本...")
# 覆盖完成后磁盘上已是新版本代码,但内存中仍是旧代码
# 需要再启动一次新进程,让新代码正确加载并显示版本号
# (.update_pending 已在上方删除,新进程不会重复执行更新)
# 等待端口释放:旧进程的 destroy() 已关闭服务器,但 Windows 上
# TCP 端口可能仍在 TIME_WAIT 状态,需等待 OS 回收后新进程才能绑端口
print(" 等待端口释放...")
if os.environ.get(ENV_SUPERVISED) == "1":
os._exit(RESTART_EXIT_CODE)
else:
try:
import subprocess
subprocess.Popen([sys.executable] + sys.argv, cwd=ROOT)
except Exception as e:
print(f" 重启失败: {e},请手动重启服务器")
os._exit(0)
except Exception as e:
print(f" 更新失败: {e}")
else:
tmp = ""
# ===== WebUI 触发的回滚:检测 .rollback_pending 标记文件 =====
ROLLBACK_MARKER = os.path.join(ROOT, ".rollback_pending")
if os.path.isfile(ROLLBACK_MARKER) and not WANT_ROLLBACK:
try:
with open(ROLLBACK_MARKER, "r", encoding="utf-8") as f:
rollback_path = f.read().strip()
except Exception:
rollback_path = ""
finally:
try:
os.remove(ROLLBACK_MARKER)
except Exception:
pass
if rollback_path and os.path.isfile(rollback_path):
from version_manager.package import rollback as do_rollback, PackageError
print("========================================")
print(f" WebUI 触发回滚: {rollback_path}")
print(f" 当前版本: {VERSION}")
print("========================================")
try:
used = do_rollback(ROOT, rollback_path)
print(f" 已回滚到: {used}")
print(" 正在重启以加载回滚后的版本...")
print(" 等待端口释放...")
if os.environ.get(ENV_SUPERVISED) == "1":
os._exit(RESTART_EXIT_CODE)
else:
try:
import subprocess
subprocess.Popen([sys.executable] + sys.argv, cwd=ROOT)
except Exception as e:
print(f" 重启失败: {e},请手动重启服务器")
os._exit(0)
except PackageError as e:
print(f" 回滚失败: {e}")
# 将项目代码打包为 zip(排除用户数据/设置,与 update 命令的保留规则对称),
# 生成的压缩包可直接用于:python main.py update <压缩包> 升级其他实例。
if WANT_EXPORT:
from datetime import datetime
from version_manager.package import collect_export_files, create_export_zip, PackageError
def _export_err(msg):
print("======================================")
print(f" 导出失败: {msg}")
print("======================================")
sys.exit(1)
# 输出路径:默认当前工作目录 EnderBridge_export_<时间戳>.zip
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
default_name = f"EnderBridge_export_{stamp}.zip"
if len(sys.argv) > sys.argv.index("export") + 1:
out = os.path.abspath(sys.argv[sys.argv.index("export") + 1])
# 若路径是目录或不以 .zip 结尾,自动在其下生成默认文件名
if os.path.isdir(out) or not out.lower().endswith(".zip"):
out = os.path.join(out, default_name)
else:
out = os.path.abspath(os.path.join(os.getcwd(), default_name))
# 输出文件不能位于项目目录内,否则会把自己打进压缩包
if out == ROOT or out.startswith(ROOT + os.sep):
_export_err("输出路径不能位于项目目录内,请放到上级目录或指定其他位置")
export_ignore_path = os.path.join(ROOT, ".exportignore")
ignore_spec = None
if os.path.isfile(export_ignore_path):
from version_manager.package import ExportIgnore
ignore_spec = ExportIgnore.from_file(export_ignore_path)
try:
files = collect_export_files(ROOT, export_ignore=ignore_spec)
except PackageError as e:
_export_err(str(e))
print("======================================")
print(f" 正在导出 EnderBridge ...")
if ignore_spec and ignore_spec.rules:
# print(f" 已加载忽略规则: .exportignore ({len(ignore_spec.rules)} 条规则)")
pass
print(f" 文件数量: {len(files)}")
print(f" 输出路径: {out}")
print("======================================")
try:
create_export_zip(ROOT, out, export_ignore=ignore_spec)
except PackageError as e:
_export_err(str(e))
size_kb = os.path.getsize(out) / 1024.0
print("======================================")
print(f" 导出完成: {out} ({size_kb:.1f} KB)")
print(f" 使用方法: python main.py update {out}")
print("======================================")
# export -clear:导出后自动执行 reset-all
if WANT_EXPORT_CLEAR:
print(" 正在执行 --reset-all ...")
for name in ["config.py", "config.py.bak", "config.json", "config.json.bak", "permission.json", "permission.json.bak", "users.json", "banlist.json"]:
p = os.path.join(CONFIG_DIR, name)
if os.path.exists(p):
os.remove(p)
# 复位 JSON 模板标记
try:
if os.path.exists(CONFIG_EXAMPLE_JSON):
with open(CONFIG_EXAMPLE_JSON, "r", encoding="utf-8") as f:
data = json.load(f)
if data.get("is_first_run", False):
data["is_first_run"] = True
with open(CONFIG_EXAMPLE_JSON, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception:
pass
print(" 配置已重置")
sys.exit(0)
# 确保项目根目录可导入
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
# ===== 资源目录自愈:确保默认资源目录存在 =====
# basePath(music/mcfunc/ezmatic/image)与 ezmatic 导出目录 structures
# 缺失时自动创建,避免首次运行找不到目录(如投影目录 resources/ezmatic)。