-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_ui.py
More file actions
2354 lines (2091 loc) · 109 KB
/
Copy pathweb_ui.py
File metadata and controls
2354 lines (2091 loc) · 109 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
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
Web UI 模块
提供 Web 管理界面,用于配置端口、渠道、DND 等。
使用 Flask + Bootstrap 5 实现。
"""
import json
import threading
import log
import db
import media
import port_manager as pm_module
from version import __version__
from flask import Flask, render_template, request, jsonify, redirect, url_for
app = Flask(__name__)
port_manager = None # Will be set by main.py
# Custom Jinja2 filter for parsing JSON
@app.template_filter('fromjson')
def fromjson_filter(value):
if isinstance(value, str):
try:
return json.loads(value)
except:
return []
return value if value else []
# ──────────────────────────────────────────────
# Page Routes
# ──────────────────────────────────────────────
@app.route("/")
def index():
"""仪表盘页面"""
stats = db.get_dashboard_stats()
ports = db.get_all_ports()
from flask import render_template_string
content_rendered = render_template_string(INDEX_CONTENT, stats=stats, ports=ports)
html = BASE_TEMPLATE.replace("{title}", "仪表盘") \
.replace("{dashboard_active}", "active") \
.replace("{ports_active}", "") \
.replace("{dnd_active}", "") \
.replace("{queue_active}", "") \
.replace("{logs_active}", "") \
.replace("{channels_active}", "") \
.replace("{templates_active}", "") \
.replace("{settings_active}", "") \
.replace("{content}", content_rendered) \
.replace("{extra_js}", INDEX_JS)
return html
@app.route("/ports")
def ports_page():
"""端口管理页面"""
ports = db.get_all_ports()
for p in ports:
p["channels"] = db.get_channels(p["id"])
wechat_configs = db.get_all_wechat_configs()
all_channels = db.get_all_channels()
from flask import render_template_string
all_templates = db.get_templates()
template_names = {t["id"]: t["name"] for t in all_templates}
templates = [t for t in all_templates if not t.get("is_fallback")]
content_rendered = render_template_string(PORTS_CONTENT, ports=ports, wechat_configs=wechat_configs, templates=templates, template_names=template_names, all_channels=all_channels)
html = BASE_TEMPLATE.replace("{title}", "端口管理") \
.replace("{dashboard_active}", "") \
.replace("{ports_active}", "active") \
.replace("{dnd_active}", "") \
.replace("{queue_active}", "") \
.replace("{logs_active}", "") \
.replace("{channels_active}", "") \
.replace("{templates_active}", "") \
.replace("{settings_active}", "") \
.replace("{content}", content_rendered) \
.replace("{extra_js}", PORTS_JS)
return html
@app.route("/dnd")
def dnd_page():
"""勿扰设置页面"""
dnd = db.get_dnd_settings()
from flask import render_template_string
content_rendered = render_template_string(DND_CONTENT, dnd=dnd)
html = BASE_TEMPLATE.replace("{title}", "勿扰设置") \
.replace("{dashboard_active}", "") \
.replace("{ports_active}", "") \
.replace("{dnd_active}", "active") \
.replace("{queue_active}", "") \
.replace("{logs_active}", "") \
.replace("{channels_active}", "") \
.replace("{templates_active}", "") \
.replace("{settings_active}", "") \
.replace("{content}", content_rendered) \
.replace("{extra_js}", DND_JS)
return html
@app.route("/queue")
def queue_page():
"""消息队列页面"""
from flask import render_template_string
content_rendered = render_template_string(QUEUE_CONTENT)
html = BASE_TEMPLATE.replace("{title}", "消息队列") \
.replace("{dashboard_active}", "") \
.replace("{ports_active}", "") \
.replace("{dnd_active}", "") \
.replace("{queue_active}", "active") \
.replace("{logs_active}", "") \
.replace("{channels_active}", "") \
.replace("{templates_active}", "") \
.replace("{settings_active}", "") \
.replace("{content}", content_rendered) \
.replace("{extra_js}", QUEUE_JS)
return html
@app.route("/wechat")
def wechat_page():
"""企业微信配置页面"""
wechat_configs = db.get_all_wechat_configs()
from flask import render_template_string
import json as _json
wechat_configs_json = _json.dumps(wechat_configs, default=str)
content_rendered = render_template_string(WECHAT_CONTENT, wechat_configs=wechat_configs, wechat_configs_json=wechat_configs_json)
html = BASE_TEMPLATE.replace("{title}", "企业微信配置") \
.replace("{dashboard_active}", "") \
.replace("{ports_active}", "") \
.replace("{dnd_active}", "") \
.replace("{queue_active}", "") \
.replace("{logs_active}", "") \
.replace("{channels_active}", "active") \
.replace("{templates_active}", "") \
.replace("{settings_active}", "") \
.replace("{content}", content_rendered) \
.replace("{extra_js}", WECHAT_JS.replace("{{ wechat_configs_json|safe }}", wechat_configs_json))
return html
@app.route("/channels")
def channels_page():
"""通道管理页面"""
channels = db.get_all_channels()
from flask import render_template_string
import json as _json
channels_json = _json.dumps(channels, default=str)
content_rendered = render_template_string(CHANNELS_CONTENT, channels=channels, channels_json=channels_json)
html = BASE_TEMPLATE.replace("{title}", "推送通道") \
.replace("{dashboard_active}", "") \
.replace("{ports_active}", "") \
.replace("{dnd_active}", "") \
.replace("{queue_active}", "") \
.replace("{logs_active}", "") \
.replace("{channels_active}", "") \
.replace("{channels_active}", "active") \
.replace("{templates_active}", "") \
.replace("{settings_active}", "") \
.replace("{content}", content_rendered) \
.replace("{extra_js}", CHANNELS_JS.replace("{{ channels_json|safe }}", channels_json))
return html
@app.route("/logs")
def logs_page():
"""系统日志页面"""
from flask import render_template_string
content_rendered = render_template_string(LOGS_CONTENT)
html = BASE_TEMPLATE.replace("{title}", "系统日志") \
.replace("{dashboard_active}", "") \
.replace("{ports_active}", "") \
.replace("{dnd_active}", "") \
.replace("{queue_active}", "") \
.replace("{logs_active}", "active") \
.replace("{channels_active}", "") \
.replace("{templates_active}", "") \
.replace("{settings_active}", "") \
.replace("{content}", content_rendered) \
.replace("{extra_js}", LOGS_JS)
return html
@app.route("/templates")
def templates_page():
"""推送模板页面"""
from flask import render_template_string
templates = db.get_templates()
content_rendered = render_template_string(TEMPLATES_CONTENT, templates=templates)
html = BASE_TEMPLATE.replace("{title}", "推送模板") \
.replace("{dashboard_active}", "") \
.replace("{ports_active}", "") \
.replace("{dnd_active}", "") \
.replace("{queue_active}", "") \
.replace("{logs_active}", "") \
.replace("{channels_active}", "") \
.replace("{templates_active}", "active") \
.replace("{settings_active}", "") \
.replace("{content}", content_rendered) \
.replace("{extra_js}", TEMPLATES_JS)
return html
@app.route("/settings")
def settings():
"""系统设置页面"""
import os as _os
config = db.get_all_system_config()
ports = db.get_all_ports()
from flask import render_template_string
content_rendered = render_template_string(
SETTINGS_CONTENT,
config=config,
version=__version__,
port_count=len(ports),
db_path=_os.getenv("DB_PATH", "emby_notifier.db"),
)
html = BASE_TEMPLATE.replace("{title}", "系统设置") \
.replace("{dashboard_active}", "") \
.replace("{ports_active}", "") \
.replace("{dnd_active}", "") \
.replace("{queue_active}", "") \
.replace("{logs_active}", "") \
.replace("{channels_active}", "") \
.replace("{templates_active}", "") \
.replace("{settings_active}", "active") \
.replace("{content}", content_rendered) \
.replace("{extra_js}", SETTINGS_JS)
return html
# ──────────────────────────────────────────────
# Port API
# ──────────────────────────────────────────────
@app.route("/api/ports", methods=["GET"])
def api_get_ports():
ports = db.get_all_ports()
for p in ports:
p["channels"] = db.get_channels(p["id"])
p["running"] = port_manager.is_running(p["id"]) if port_manager else False
return jsonify(ports)
@app.route("/api/ports", methods=["POST"])
def api_create_port():
data = request.json
port_number = data["port"]
# 检查端口是否被占用
ok, err = pm_module.check_port_available(port_number)
if not ok:
return jsonify({"error": err}), 400
port_id = db.create_port(
port_number=port_number,
server_name=data.get("server_name", ""),
server_url=data.get("server_url", ""),
template_id=data.get("template_id", 1),
channel_ids=data.get("channel_ids", []),
)
if port_id is None:
return jsonify({"error": "端口号已存在"}), 400
# Auto-start if enabled
if data.get("enabled", True) and port_manager:
port_manager.start_port(port_id)
return jsonify({"id": port_id, "status": "created"})
@app.route("/api/ports/<int:port_id>", methods=["PUT"])
def api_update_port(port_id):
data = request.json
old_port = db.get_port(port_id)
if not old_port:
return jsonify({"error": "Port not found"}), 404
# 如果端口号变更,检查新端口是否可用
new_port = data.get("port", old_port["port"])
if new_port != old_port["port"]:
ok, err = pm_module.check_port_available(new_port)
if not ok:
return jsonify({"error": err}), 400
was_running = port_manager.is_running(port_id) if port_manager else False
if was_running:
port_manager.stop_port(port_id)
db.update_port(port_id, **data)
# Restart if needed
new_enabled = data.get("enabled", old_port["enabled"])
if new_enabled and port_manager:
port_manager.start_port(port_id)
return jsonify({"status": "updated"})
@app.route("/api/ports/<int:port_id>", methods=["DELETE"])
def api_delete_port(port_id):
if port_manager:
port_manager.stop_port(port_id)
db.delete_port(port_id)
return jsonify({"status": "deleted"})
@app.route("/api/ports/<int:port_id>/toggle", methods=["POST"])
def api_toggle_port(port_id):
port = db.get_port(port_id)
if not port:
return jsonify({"error": "Port not found"}), 404
new_enabled = 0 if port["enabled"] else 1
db.update_port(port_id, enabled=new_enabled)
if port_manager:
if new_enabled:
port_manager.start_port(port_id)
else:
port_manager.stop_port(port_id)
return jsonify({"enabled": new_enabled})
# ──────────────────────────────────────────────
# WeChat Config API
# ──────────────────────────────────────────────
@app.route("/api/wechat-configs", methods=["GET"])
def api_get_wechat_configs():
configs = db.get_all_wechat_configs()
return jsonify(configs)
@app.route("/api/wechat-configs", methods=["POST"])
def api_create_wechat_config():
data = request.json
config_id = db.create_wechat_config(
name=data.get("name", ""),
corp_id=data.get("corp_id", ""),
corp_secret=data.get("corp_secret", ""),
agent_id=data.get("agent_id", 0),
enabled=data.get("enabled", 1)
)
return jsonify({"id": config_id, "status": "created"})
@app.route("/api/wechat-configs/<int:config_id>", methods=["PUT"])
def api_update_wechat_config(config_id):
data = request.json
db.update_wechat_config(
config_id=config_id,
name=data.get("name", ""),
corp_id=data.get("corp_id", ""),
corp_secret=data.get("corp_secret", ""),
agent_id=data.get("agent_id", 0),
enabled=data.get("enabled", 1)
)
return jsonify({"status": "updated"})
@app.route("/api/wechat-configs/<int:config_id>", methods=["DELETE"])
def api_delete_wechat_config(config_id):
db.delete_wechat_config(config_id)
return jsonify({"status": "deleted"})
# ──────────────────────────────────────────────
# Channel API (多通道管理)
# ──────────────────────────────────────────────
@app.route("/api/channels", methods=["GET"])
def api_get_all_channels():
channels = db.get_all_channels()
return jsonify(channels)
@app.route("/api/channels", methods=["POST"])
def api_create_channel():
data = request.json
channel_id = db.create_channel(
name=data.get("name", ""),
channel_type=data.get("type", ""),
config=json.dumps(data.get("config", {})),
enabled=data.get("enabled", 1),
)
return jsonify({"id": channel_id})
@app.route("/api/channels/<int:channel_id>", methods=["PUT"])
def api_update_channel(channel_id):
data = request.json
db.update_channel(
channel_id,
name=data.get("name"),
channel_type=data.get("type"),
config=json.dumps(data["config"]) if "config" in data else None,
enabled=data.get("enabled"),
)
return jsonify({"status": "updated"})
@app.route("/api/channels/<int:channel_id>", methods=["DELETE"])
def api_delete_channel(channel_id):
db.delete_channel(channel_id)
return jsonify({"status": "deleted"})
@app.route("/api/channels/<int:channel_id>/duplicate", methods=["POST"])
def api_duplicate_channel(channel_id):
"""复制通道"""
ch = db.get_channel(channel_id)
if not ch:
return jsonify({"error": "Channel not found"}), 404
new_id = db.create_channel(
name=ch["name"] + " (副本)",
channel_type=ch["type"],
config=ch["config"],
enabled=0, # 复制后默认禁用,避免重复推送
)
return jsonify({"id": new_id})
@app.route("/api/channels/<int:channel_id>/test", methods=["POST"])
def api_test_channel(channel_id):
"""测试通道连通性"""
ch = db.get_channel(channel_id)
if not ch:
return jsonify({"error": "Channel not found"}), 404
try:
config = json.loads(ch["config"]) if isinstance(ch["config"], str) else ch["config"]
from channels import create_channel
channel = create_channel(ch["type"], config)
ok = channel.test()
if ok:
log.logger.debug(f"Channel test successful: {ch['name']} ({ch['type']})")
return jsonify({"success": True, "message": "测试成功"})
else:
log.logger.error(f"Channel test failed: {ch['name']} ({ch['type']})")
return jsonify({"success": False, "message": "测试失败,请检查配置"})
except Exception as e:
log.logger.error(f"Channel test error: {ch['name']} - {e}")
return jsonify({"success": False, "error": str(e)})
# ──────────────────────────────────────────────
# DND API
# ──────────────────────────────────────────────
@app.route("/api/dnd", methods=["GET"])
def api_get_dnd():
return jsonify(db.get_dnd_settings())
@app.route("/api/dnd", methods=["POST"])
def api_save_dnd():
data = request.json
db.update_dnd(
enabled=data.get("enabled"),
start_time=data.get("start_time"),
end_time=data.get("end_time")
)
return jsonify({"status": "saved"})
# ──────────────────────────────────────────────
# Queue API
# ──────────────────────────────────────────────
@app.route("/api/queue", methods=["GET"])
def api_get_queue():
messages = db.get_all_messages()
for m in messages:
port = db.get_port(m["port_id"])
if port:
m["server_name"] = port["server_name"]
m["port"] = port["port"]
return jsonify({"messages": messages})
@app.route("/api/queue/flush", methods=["POST"])
def api_flush_queue():
"""Flush pending/failed messages (trigger send)"""
count = 0
for p in db.get_all_ports():
if p["enabled"]:
try:
n = media.flush_queue_for_port(p["id"])
count += n
except Exception as e:
log.logger.error(f"[Port {p['port']}] Flush error: {e}")
return jsonify({"count": count})
@app.route("/api/queue/<int:msg_id>", methods=["DELETE"])
def api_delete_queue_msg(msg_id):
db.delete_message(msg_id)
return jsonify({"status": "deleted"})
# ──────────────────────────────────────────────
# Test Push API
# ──────────────────────────────────────────────
@app.route("/api/ports/<int:port_id>/test", methods=["POST"])
def api_test_push(port_id):
"""Send test notification"""
port = db.get_port(port_id)
if not port:
return jsonify({"error": "Port not found"}), 404
channel_ids = json.loads(port.get("channel_ids", "[]")) if port else []
if not channel_ids:
return jsonify({"error": "没有配置推送通道"}), 400
try:
results = media.send_test_notification(port_id)
# 检查实际结果
errors = [v for k, v in results.items() if k.endswith("_error")]
success_count = len([v for k, v in results.items() if v == "success"])
failed_count = len(errors)
if failed_count > 0:
return jsonify({
"success": success_count,
"failed": failed_count,
"total": success_count + failed_count,
"errors": errors
}), 200
return jsonify({"success": success_count, "failed": 0, "total": success_count})
except Exception as e:
log.logger.error(f"Test push failed: {e}")
return jsonify({"error": str(e), "success": 0, "failed": 1, "total": 1}), 500
# ──────────────────────────────────────────────
# Stats API
# ──────────────────────────────────────────────
@app.route("/api/stats", methods=["GET"])
def api_stats():
stats = db.get_dashboard_stats()
if port_manager:
stats["ports_status"] = port_manager.get_status()
return jsonify(stats)
# ──────────────────────────────────────────────
# System Config API
# ──────────────────────────────────────────────
@app.route("/api/config", methods=["GET"])
def api_get_config():
return jsonify(db.get_all_system_config())
@app.route("/api/config", methods=["POST"])
def api_save_config():
data = request.json
for key, value in data.items():
db.set_system_config(key, value)
# 验证 TMDB Token(如果提供了)
if "TMDB_API_TOKEN" in data and data["TMDB_API_TOKEN"]:
import tmdb_api
success = tmdb_api.login()
if success:
return jsonify({"status": "saved", "tmdb_valid": True})
else:
return jsonify({"status": "saved", "tmdb_valid": False, "message": "TMDB Token 验证失败"})
return jsonify({"status": "saved"})
@app.route("/api/config/test_tmdb", methods=["POST"])
def api_test_tmdb():
data = request.json
token = data.get("token", "")
if not token:
return jsonify({"success": False, "error": "Token 不能为空"})
# 临时设置 token 进行测试
db.set_system_config("TMDB_API_TOKEN", token)
import tmdb_api
success = tmdb_api.login()
if success:
return jsonify({"success": True})
else:
return jsonify({"success": False, "error": "TMDB API 连接失败,请检查 Token 是否正确"})
@app.route("/api/logs", methods=["GET"])
def api_get_logs():
level = request.args.get("level")
limit = request.args.get("limit", 100, type=int)
logs = db.get_logs(level=level, limit=limit)
return jsonify(logs)
@app.route("/api/logs", methods=["DELETE"])
def api_clear_logs():
db.clear_logs()
return jsonify({"status": "cleared"})
@app.route("/api/logs/export")
def api_export_logs():
"""导出完整日志为文本文件"""
from flask import Response
from datetime import datetime
logs = db.get_logs(limit=10000)
lines = []
for log in logs:
timestamp = log.get("timestamp", "")
level = log.get("level", "")
module = log.get("module", "")
message = log.get("message", "")
lines.append(f"[{timestamp}] [{level}] [{module}] {message}")
content = "\n".join(lines)
filename = f"emby_notifier_logs_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
return Response(
content,
mimetype="text/plain",
headers={"Content-disposition": f"attachment; filename={filename}"}
)
@app.route("/api/templates", methods=["GET"])
def api_get_templates():
return jsonify(db.get_templates())
@app.route("/api/templates", methods=["POST"])
def api_create_template():
data = request.json
tid = db.create_template(
name=data.get("name", ""),
title=data.get("title", ""),
description=data.get("description", ""),
picurl_movie=data.get("picurl_movie", "media_backdrop"),
picurl_episode=data.get("picurl_episode", "media_still"),
enable_image=data.get("enable_image", 1),
)
return jsonify({"id": tid})
@app.route("/api/templates/<int:template_id>", methods=["PUT"])
def api_update_template(template_id):
data = request.json
t = db.get_template(template_id)
# 回退模板强制关闭图片
if t and t.get("is_fallback"):
data["enable_image"] = 0
db.update_template(template_id, **data)
return jsonify({"status": "updated"})
@app.route("/api/templates/<int:template_id>", methods=["DELETE"])
def api_delete_template(template_id):
t = db.get_template(template_id)
if t and t.get("is_fallback"):
return jsonify({"error": "回退模板不可删除"}), 400
db.delete_template(template_id)
return jsonify({"status": "deleted"})
def create_app(pm=None):
"""Create and return Flask app, optionally with port manager reference."""
global port_manager
port_manager = pm
return app
def run_web_ui(web_port=5000, pm=None):
"""Run the Web UI server."""
global port_manager
port_manager = pm
log.logger.info(f"Web UI starting on http://0.0.0.0:{web_port}")
app.run(host="0.0.0.0", port=web_port, debug=False, use_reloader=False)
# ──────────────────────────────────────────────
# HTML Templates
# ──────────────────────────────────────────────
BASE_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{title} - Emby Notifier</title>
<link href="/static/bootstrap.min.css" rel="stylesheet">
<link href="/static/bootstrap-icons.css" rel="stylesheet">
<style>
:root {
--sidebar-width: 240px;
--sidebar-bg: #1a1d23;
--sidebar-hover: #2d3139;
--sidebar-active: #3b82f6;
}
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f0f2f5; }
.sidebar {
position: fixed; top: 0; left: 0; width: var(--sidebar-width);
height: 100vh; background: var(--sidebar-bg); color: #fff;
padding-top: 0; z-index: 1000; overflow-y: auto;
}
.sidebar .brand {
padding: 1.2rem 1rem; border-bottom: 1px solid rgba(255,255,255,0.1);
font-size: 1.1rem; font-weight: 600;
}
.sidebar .brand i { color: #3b82f6; margin-right: 8px; }
.sidebar .nav-link {
color: rgba(255,255,255,0.7); padding: 0.7rem 1rem;
border-radius: 8px; margin: 2px 8px; font-size: 0.9rem;
transition: all 0.2s;
}
.sidebar .nav-link:hover { color: #fff; background: var(--sidebar-hover); }
.sidebar .nav-link.active { color: #fff; background: var(--sidebar-active); }
.sidebar .nav-link i { margin-right: 10px; width: 20px; text-align: center; }
.main-content { margin-left: var(--sidebar-width); padding: 24px; min-height: 100vh; }
.page-header { margin-bottom: 24px; }
.page-header h2 { font-weight: 600; color: #1a1d23; }
.stat-card {
background: #fff; border-radius: 12px; padding: 1.2rem;
box-shadow: 0 1px 3px rgba(0,0,0,0.08); border: none;
}
.stat-card .stat-icon {
width: 48px; height: 48px; border-radius: 12px;
display: flex; align-items: center; justify-content: center;
font-size: 1.3rem;
}
.stat-card .stat-value { font-size: 1.8rem; font-weight: 700; color: #1a1d23; }
.stat-card .stat-label { color: #6b7280; font-size: 0.85rem; }
.card { border: none; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
.card-header { background: #fff; border-bottom: 1px solid #f0f0f0; font-weight: 600; }
.badge-running { background: #10b981; }
.badge-stopped { background: #ef4444; }
.badge-dnd { background: #f59e0b; }
.btn-icon { width: 32px; height: 32px; padding: 0; display: inline-flex; align-items: center; justify-content: center; border-radius: 8px; }
.table th { font-weight: 600; color: #6b7280; font-size: 0.85rem; text-transform: uppercase; }
</style>
</head>
<body>
<!-- Sidebar -->
<nav class="sidebar">
<div class="brand">
<i class="bi bi-bell-fill"></i> Emby Notifier
</div>
<div class="nav flex-column mt-3">
<a class="nav-link {dashboard_active}" href="/"><i class="bi bi-speedometer2"></i> 仪表盘</a>
<a class="nav-link {ports_active}" href="/ports"><i class="bi bi-hdd-network"></i> 端口管理</a>
<a class="nav-link {dnd_active}" href="/dnd"><i class="bi bi-moon-fill"></i> 勿扰设置</a>
<a class="nav-link {queue_active}" href="/queue"><i class="bi bi-inbox"></i> 消息队列</a>
<a class="nav-link {logs_active}" href="/logs"><i class="bi bi-list-ul"></i> 系统日志</a>
<a class="nav-link {channels_active}" href="/channels"><i class="bi bi-broadcast"></i> 推送通道</a>
<a class="nav-link {templates_active}" href="/templates"><i class="bi bi-file-earmark-text"></i> 推送模板</a>
<a class="nav-link {settings_active}" href="/settings"><i class="bi bi-gear-fill"></i> 系统设置</a>
</div>
<div style="position:absolute;bottom:16px;left:0;right:0;text-align:center;">
<small class="text-muted">{version}</small>
</div>
</nav>
<!-- Main Content -->
<div class="main-content">
{content}
</div>
<script src="/static/bootstrap.bundle.min.js"></script>
<script>
// API helper
async function api(url, method='GET', body=null) {
const opts = { method, headers: {'Content-Type': 'application/json'} };
if (body) opts.body = JSON.stringify(body);
const res = await fetch(url, opts);
return res.json();
}
async function apiPost(url, body=null) { return api(url, 'POST', body); }
async function apiPut(url, body) { return api(url, 'PUT', body); }
async function apiDelete(url) { return api(url, 'DELETE'); }
// Toast notification
function showToast(msg, type='success') {
let container = document.getElementById('toast-container');
if (!container) {
container = document.createElement('div');
container.id = 'toast-container';
container.style.cssText = 'position:fixed;top:20px;right:20px;z-index:9999;';
document.body.appendChild(container);
}
const toast = document.createElement('div');
toast.className = 'alert alert-' + type + ' alert-dismissible fade show';
toast.style.cssText = 'min-width:250px;box-shadow:0 4px 12px rgba(0,0,0,0.15);';
toast.innerHTML = msg + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
container.appendChild(toast);
setTimeout(function() { toast.remove(); }, 3000);
}
</script>
{extra_js}
</body>
</html>"""
# Inject current version into the base template
BASE_TEMPLATE = BASE_TEMPLATE.replace("{version}", f"v{__version__}")
INDEX_CONTENT = """
<div class="page-header d-flex justify-content-between align-items-center">
<h2><i class="bi bi-speedometer2"></i> 仪表盘</h2>
<button class="btn btn-outline-primary btn-sm" onclick="location.reload()">
<i class="bi bi-arrow-clockwise"></i> 刷新
</button>
</div>
<div class="row g-3 mb-4">
<div class="col-md-3">
<div class="stat-card">
<div class="d-flex align-items-center">
<div class="stat-icon bg-primary bg-opacity-10 text-primary me-3">
<i class="bi bi-hdd-network"></i>
</div>
<div>
<div class="stat-value">{{ stats.active_ports }}</div>
<div class="stat-label">活跃端口</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="stat-card">
<div class="d-flex align-items-center">
<div class="stat-icon bg-success bg-opacity-10 text-success me-3">
<i class="bi bi-check-circle"></i>
</div>
<div>
<div class="stat-value">{{ stats.queue_sent }}</div>
<div class="stat-label">已推送</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="stat-card">
<div class="d-flex align-items-center">
<div class="stat-icon bg-warning bg-opacity-10 text-warning me-3">
<i class="bi bi-clock"></i>
</div>
<div>
<div class="stat-value">{{ stats.queue_pending }}</div>
<div class="stat-label">待推送</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="stat-card">
<div class="d-flex align-items-center">
<div class="stat-icon bg-{% if stats.dnd_enabled %}warning{% else %}secondary{% endif %} bg-opacity-10 text-{% if stats.dnd_enabled %}warning{% else %}secondary{% endif %} me-3">
<i class="bi bi-moon-fill"></i>
</div>
<div>
<div class="stat-value">{% if stats.dnd_enabled %}开{% else %}关{% endif %}</div>
<div class="stat-label">勿扰模式</div>
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header py-3">
<i class="bi bi-hdd-network me-2"></i>端口状态
</div>
<div class="card-body p-0">
<table class="table table-hover mb-0">
<thead>
<tr>
<th>端口</th>
<th>服务器名称</th>
<th>状态</th>
</tr>
</thead>
<tbody>
{% for port in ports %}
<tr>
<td><code>{{ port.port }}</code></td>
<td>{{ port.server_name }}</td>
<td>
{% if port.enabled %}
<span class="badge badge-running">运行中</span>
{% else %}
<span class="badge badge-stopped">已停止</span>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
"""
INDEX_JS = """
<script>
setInterval(() => location.reload(), 30000);
</script>
"""
PORTS_CONTENT = """
<div class="page-header d-flex justify-content-between align-items-center">
<h2><i class="bi bi-hdd-network"></i> 端口管理</h2>
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addPortModal">
<i class="bi bi-plus-lg"></i> 添加端口
</button>
</div>
<div class="card">
<div class="card-body p-0">
<table class="table table-hover mb-0">
<thead>
<tr>
<th>组名</th>
<th>端口</th>
<th>推送模板</th>
<th>推送通道</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody id="portsTable">
{% for port in ports %}
<tr data-port-id="{{ port.id }}">
<td>{{ port.server_name }}</td>
<td><code>{{ port.port }}</code></td>
<td>{{ template_names.get(port.template_id, '标准') }}</td>
<td>
{% if port.channels %}
{% for ch in port.channels %}
<span class="badge bg-{% if ch.type == 'wechat_work_api' %}primary{% elif ch.type == 'wechat_work_bot' %}success{% elif ch.type == 'dingtalk' %}info{% elif ch.type == 'feishu' %}warning text-dark{% elif ch.type == 'telegram_bot' %}secondary{% elif ch.type == 'bark' %}dark{% else %}secondary{% endif %} me-1">{{ ch.name }}</span>
{% endfor %}
{% else %}
<span class="text-muted">未配置</span>
{% endif %}
</td>
<td>
{% if port.enabled %}
<span class="badge badge-running">运行中</span>
{% else %}
<span class="badge badge-stopped">已停止</span>
{% endif %}
</td>
<td>
<button class="btn btn-icon btn-outline-primary btn-sm" onclick="editPort({{ port.id }})" title="编辑">
<i class="bi bi-pencil"></i>
</button>
<button class="btn btn-icon btn-outline-success btn-sm" onclick="testPush({{ port.id }})" title="测试推送">
<i class="bi bi-send"></i>
</button>
<button class="btn btn-icon btn-outline-{% if port.enabled %}warning{% else %}success{% endif %} btn-sm" onclick="togglePort({{ port.id }})" title="{% if port.enabled %}停止{% else %}启动{% endif %}">
<i class="bi bi-{% if port.enabled %}pause{% else %}play{% endif %}-fill"></i>
</button>
<button class="btn btn-icon btn-outline-danger btn-sm" onclick="deletePort({{ port.id }})" title="删除">
<i class="bi bi-trash"></i>
</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<!-- Add Port Modal -->
<div class="modal fade" id="addPortModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">添加端口</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<form id="addPortForm">
<div class="mb-3">
<label class="form-label">组名 <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="addPortName" required placeholder="例如:家庭服务器">
</div>