-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapp.py
More file actions
2493 lines (2233 loc) · 102 KB
/
app.py
File metadata and controls
2493 lines (2233 loc) · 102 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
from __future__ import annotations
import base64
import csv
import hashlib
import hmac
import json
import os
import re
import secrets
from dataclasses import asdict, is_dataclass
from functools import wraps
from io import StringIO
from pathlib import Path
from typing import Any, Callable
from flask import Flask, jsonify, render_template, request, send_from_directory, session
from services.outlook_manager import (
FlagStateUpdateRequest,
MailboxConfig,
MailboxDetailRequest,
MailboxError,
MailboxManager,
MailboxQuery,
MessageDeleteRequest,
MessageMoveRequest,
ReadStateUpdateRequest,
)
from services.storage import MailboxProfile, MailboxStore, MailboxStoreError
MAILBOX_IMPORT_DELIMITER = "----"
MAILBOX_IMPORT_TABULAR_DELIMITERS = ",\t;|"
EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
CLIENT_ID_PATTERN = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.IGNORECASE)
ADMIN_PASSWORD_MIN_LENGTH = 8
ADMIN_PASSWORD_HASH_ITERATIONS = 200_000
def _hash_admin_password(password: str, *, salt: str, iterations: int = ADMIN_PASSWORD_HASH_ITERATIONS) -> str:
return hashlib.pbkdf2_hmac(
"sha256",
password.encode("utf-8"),
salt.encode("utf-8"),
iterations,
).hex()
def _build_admin_password_state(
password: str,
*,
salt: str | None = None,
iterations: int = ADMIN_PASSWORD_HASH_ITERATIONS,
) -> dict[str, Any]:
resolved_salt = salt or secrets.token_hex(16)
return {
"salt": resolved_salt,
"iterations": iterations,
"password_hash": _hash_admin_password(password, salt=resolved_salt, iterations=iterations),
}
def _load_admin_password_state(default_password: str, auth_path: Path) -> dict[str, Any]:
if auth_path.exists():
try:
payload = json.loads(auth_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
payload = {}
if isinstance(payload, dict):
password_hash = payload.get("password_hash")
salt = payload.get("salt")
iterations = payload.get("iterations", ADMIN_PASSWORD_HASH_ITERATIONS)
if (
isinstance(password_hash, str)
and password_hash
and isinstance(salt, str)
and salt
and isinstance(iterations, int)
and iterations > 0
):
return {
"salt": salt,
"iterations": iterations,
"password_hash": password_hash,
}
return _build_admin_password_state(default_password)
def _save_admin_password_state(auth_path: Path, username: str, password_state: dict[str, Any]) -> None:
auth_path.parent.mkdir(parents=True, exist_ok=True)
auth_path.write_text(
json.dumps(
{
"username": username,
"salt": password_state["salt"],
"iterations": password_state["iterations"],
"password_hash": password_state["password_hash"],
},
ensure_ascii=False,
indent=2,
),
encoding="utf-8",
)
def _verify_admin_password(password: str, password_state: dict[str, Any]) -> bool:
expected_hash = _hash_admin_password(
password,
salt=str(password_state["salt"]),
iterations=int(password_state["iterations"]),
)
return hmac.compare_digest(expected_hash, str(password_state["password_hash"]))
def create_app(
manager: MailboxManager | None = None,
store: MailboxStore | None = None,
*,
database_path: str | Path | None = None,
admin_username: str | None = None,
admin_password: str | None = None,
admin_auth_path: str | Path | None = None,
public_api_key: str | None = None,
) -> Flask:
app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False
app.config["SECRET_KEY"] = os.getenv("MAIL_ADMIN_SECRET_KEY", "change-me-before-production")
frontend_dist_dir = Path(app.static_folder or "static") / "frontend"
frontend_index_file = frontend_dist_dir / "index.html"
mailbox_manager = manager or MailboxManager()
mailbox_store = store or MailboxStore(database_path or os.getenv("MAILBOX_DB_PATH", "data/mailboxes.db"))
admin_user = admin_username or os.getenv("MAIL_ADMIN_USERNAME", "admin")
admin_pass = admin_password or os.getenv("MAIL_ADMIN_PASSWORD", "admin123456")
admin_auth_file = Path(admin_auth_path or os.getenv("MAIL_ADMIN_AUTH_FILE", "data/admin_auth.json"))
admin_password_state = _load_admin_password_state(admin_pass, admin_auth_file)
access_key = public_api_key if public_api_key is not None else os.getenv("INBOXOPS_API_KEY", "")
def auth_required(handler: Callable[..., Any]) -> Callable[..., Any]:
@wraps(handler)
def wrapper(*args: Any, **kwargs: Any) -> Any:
if not session.get("admin_authenticated"):
raise MailboxError("请先登录管理员账号", code="unauthorized", status_code=401)
return handler(*args, **kwargs)
return wrapper
def api_key_required(handler: Callable[..., Any]) -> Callable[..., Any]:
@wraps(handler)
def wrapper(*args: Any, **kwargs: Any) -> Any:
if not access_key:
raise MailboxError("项目未配置访问 Key", code="api_key_not_configured", status_code=503)
provided_key = _extract_access_key_from_request()
if not provided_key or not hmac.compare_digest(provided_key, access_key):
raise MailboxError("访问 Key 无效", code="invalid_api_key", status_code=401)
return handler(*args, **kwargs)
return wrapper
@app.get("/")
def index() -> str:
return _serve_frontend_index(frontend_index_file, frontend_dist_dir)
@app.get("/favicon.ico")
def favicon() -> tuple[str, int]:
return "", 204
@app.get("/<path:path>")
def frontend_routes(path: str) -> Any:
normalized_path = path.strip()
if normalized_path.startswith("api/") or normalized_path == "api":
raise MailboxError("接口不存在", code="not_found", status_code=404)
if normalized_path.startswith("static/"):
raise MailboxError("静态资源不存在", code="not_found", status_code=404)
return _serve_frontend_index(frontend_index_file, frontend_dist_dir)
@app.get("/api/health")
def health() -> Any:
return jsonify({"status": "ok", "service": "inboxops"})
@app.get("/api/auth/me")
def auth_me() -> Any:
authenticated = bool(session.get("admin_authenticated"))
return jsonify(
{
"authenticated": authenticated,
"username": session.get("admin_username") if authenticated else None,
}
)
@app.post("/api/auth/login")
def auth_login() -> Any:
payload = request.get_json(silent=True) or {}
username = _require_text(payload, "username", "管理员账号不能为空")
password = _require_text(payload, "password", "管理员密码不能为空")
if not hmac.compare_digest(username, admin_user) or not _verify_admin_password(password, admin_password_state):
raise MailboxError("管理员账号或密码错误", code="invalid_credentials", status_code=401)
session["admin_authenticated"] = True
session["admin_username"] = admin_user
return jsonify({"authenticated": True, "username": admin_user})
@app.post("/api/auth/logout")
@auth_required
def auth_logout() -> Any:
session.clear()
return jsonify({"authenticated": False})
@app.post("/api/auth/password")
@auth_required
def auth_change_password() -> Any:
payload = request.get_json(silent=True) or {}
current_password = _require_text(payload, "current_password", "当前管理员密码不能为空")
new_password = _require_text(payload, "new_password", "新管理员密码不能为空")
confirm_password = _require_text(payload, "confirm_password", "确认新密码不能为空")
if not _verify_admin_password(current_password, admin_password_state):
raise MailboxError("当前管理员密码错误", code="invalid_current_password", status_code=400)
if len(new_password) < ADMIN_PASSWORD_MIN_LENGTH:
raise MailboxError(
f"新管理员密码长度不能少于 {ADMIN_PASSWORD_MIN_LENGTH} 位",
code="invalid_new_password",
status_code=400,
)
if not hmac.compare_digest(new_password, confirm_password):
raise MailboxError("两次输入的新密码不一致", code="password_mismatch", status_code=400)
if hmac.compare_digest(current_password, new_password):
raise MailboxError("新密码不能与当前密码相同", code="password_unchanged", status_code=400)
next_password_state = _build_admin_password_state(new_password)
try:
_save_admin_password_state(admin_auth_file, admin_user, next_password_state)
except OSError as exc:
raise MailboxError("保存管理员密码失败", code="admin_password_save_failed", status_code=500) from exc
admin_password_state.clear()
admin_password_state.update(next_password_state)
session["admin_username"] = admin_user
return jsonify({"updated": True, "username": admin_user})
@app.get("/api/mailboxes")
@auth_required
def list_mailboxes() -> Any:
query = _optional_text(request.args.get("q")) or ""
page = _parse_positive_int(request.args.get("page"), field_name="page", default=1, minimum=1)
page_size = _parse_positive_int(
request.args.get("page_size"),
field_name="page_size",
default=20,
minimum=1,
maximum=100,
)
items, total = mailbox_store.search_mailboxes_summary(query, page=page, page_size=page_size)
total_pages = (total + page_size - 1) // page_size if total else 0
return jsonify(
{
"items": _to_jsonable(items),
"meta": {
"q": query,
"page": page,
"page_size": page_size,
"total": total,
"total_pages": total_pages,
"has_prev": page > 1,
"has_next": page < total_pages,
},
}
)
@app.post("/api/mailboxes")
@auth_required
def create_mailbox() -> Any:
payload = request.get_json(silent=True) or {}
mailbox = mailbox_store.create_mailbox(_extract_mailbox_payload(payload))
return jsonify({"mailbox": _to_jsonable(mailbox)}), 201
@app.post("/api/mailboxes/import")
@auth_required
def import_mailboxes() -> Any:
payload = request.get_json(silent=True) or {}
raw_text = _require_text(payload, "raw_text", "批量导入文本不能为空")
preferred_method = _normalize_method(payload.get("preferred_method") or "graph_api")
parsed_payloads = _parse_import_mailboxes(
raw_text,
preferred_method=preferred_method,
allow_missing_email=True,
)
hydrated_payloads = _hydrate_import_mailboxes_missing_email(
mailbox_manager,
parsed_payloads,
preferred_method=preferred_method,
)
summary, mailboxes = mailbox_store.import_mailboxes(
hydrated_payloads
)
return jsonify({"summary": summary, "mailboxes": _to_jsonable(mailboxes)})
@app.get("/api/mailboxes/<int:mailbox_id>")
@auth_required
def get_mailbox(mailbox_id: int) -> Any:
mailbox = _get_mailbox_or_404(mailbox_store, mailbox_id)
return jsonify({"mailbox": _to_jsonable(mailbox)})
@app.put("/api/mailboxes/<int:mailbox_id>")
@auth_required
def update_mailbox(mailbox_id: int) -> Any:
payload = request.get_json(silent=True) or {}
mailbox = mailbox_store.update_mailbox(mailbox_id, _extract_mailbox_payload(payload, partial=True))
return jsonify({"mailbox": _to_jsonable(mailbox)})
@app.delete("/api/mailboxes/<int:mailbox_id>")
@auth_required
def delete_mailbox(mailbox_id: int) -> Any:
deleted = mailbox_store.delete_mailbox(mailbox_id)
if not deleted:
raise MailboxError("邮箱档案不存在", code="mailbox_not_found", status_code=404)
return jsonify({"deleted": True, "mailbox_id": mailbox_id})
@app.post("/api/mailboxes/delete/batch")
@auth_required
def batch_delete_mailboxes() -> Any:
payload = request.get_json(silent=True) or {}
mailbox_ids = _parse_mailbox_ids(payload.get("mailbox_ids"), maximum=100)
results: list[dict[str, Any]] = []
succeeded = 0
failed = 0
for mailbox_id in mailbox_ids:
profile = mailbox_store.get_mailbox(mailbox_id)
if not profile:
results.append(
{
"mailbox_id": mailbox_id,
"label": "",
"email": "",
"success": False,
"message": "邮箱档案不存在",
}
)
failed += 1
continue
deleted = mailbox_store.delete_mailbox(mailbox_id)
if deleted:
results.append(
{
"mailbox_id": mailbox_id,
"label": profile.label,
"email": profile.email,
"success": True,
"message": "邮箱档案已删除",
}
)
succeeded += 1
else:
results.append(
{
"mailbox_id": mailbox_id,
"label": profile.label,
"email": profile.email,
"success": False,
"message": "邮箱档案删除失败",
}
)
failed += 1
return jsonify(
{
"results": results,
"summary": {
"processed": len(results),
"succeeded": succeeded,
"failed": failed,
},
}
)
@app.post("/api/mailboxes/test-connection")
@auth_required
def test_mailbox_connection() -> Any:
payload = request.get_json(silent=True) or {}
config, method = _build_runtime_config_from_payload(payload)
message = _probe_mailbox_connection(mailbox_manager, config=config, method=method)
return jsonify(
{
"success": True,
"method": method,
"label": _label_for_method(method),
"message": message,
}
)
@app.post("/api/mailboxes/test-connection/batch")
@auth_required
def test_mailbox_connection_batch() -> Any:
payload = request.get_json(silent=True) or {}
mailbox_ids = _parse_mailbox_ids(payload.get("mailbox_ids"), maximum=50)
raw_method = payload.get("method")
forced_method = _normalize_method(raw_method) if raw_method is not None else None
results: list[dict[str, Any]] = []
succeeded = 0
failed = 0
for raw_mailbox_id in mailbox_ids:
if not isinstance(raw_mailbox_id, int):
raise MailboxError("mailbox_ids 中的每一项都必须是整数", code="invalid_mailbox_ids")
profile = mailbox_store.get_mailbox(raw_mailbox_id)
if not profile:
results.append(
{
"mailbox_id": raw_mailbox_id,
"label": "",
"email": "",
"method": forced_method or "",
"success": False,
"message": "邮箱档案不存在",
}
)
failed += 1
continue
method = forced_method or profile.preferred_method
try:
message = _probe_mailbox_connection(
mailbox_manager,
config=_profile_to_config(profile, method=method),
method=method,
)
results.append(
{
"mailbox_id": profile.id,
"label": profile.label,
"email": profile.email,
"method": method,
"success": True,
"message": message,
}
)
succeeded += 1
except Exception as exc: # noqa: BLE001
results.append(
{
"mailbox_id": profile.id,
"label": profile.label,
"email": profile.email,
"method": method,
"success": False,
"message": str(exc),
}
)
failed += 1
return jsonify(
{
"results": results,
"summary": {
"processed": len(results),
"succeeded": succeeded,
"failed": failed,
},
}
)
@app.post("/api/mailboxes/preferred-method/batch")
@auth_required
def batch_update_preferred_method() -> Any:
payload = request.get_json(silent=True) or {}
mailbox_ids = _parse_mailbox_ids(payload.get("mailbox_ids"), maximum=100)
preferred_method = _normalize_method(payload.get("preferred_method"))
results: list[dict[str, Any]] = []
succeeded = 0
failed = 0
for mailbox_id in mailbox_ids:
profile = mailbox_store.get_mailbox(mailbox_id)
if not profile:
results.append(
{
"mailbox_id": mailbox_id,
"label": "",
"email": "",
"preferred_method": preferred_method,
"success": False,
"message": "邮箱档案不存在",
}
)
failed += 1
continue
updated = mailbox_store.update_mailbox(
mailbox_id,
{
"preferred_method": preferred_method,
},
)
results.append(
{
"mailbox_id": updated.id,
"label": updated.label,
"email": updated.email,
"preferred_method": updated.preferred_method,
"success": True,
"message": f"默认方法已切换为 {_label_for_method(updated.preferred_method)}",
}
)
succeeded += 1
return jsonify(
{
"results": results,
"summary": {
"processed": len(results),
"succeeded": succeeded,
"failed": failed,
},
}
)
@app.post("/api/mailbox/overview")
@auth_required
def mailbox_overview() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
config = _profile_to_config(profile)
overview = mailbox_manager.get_overview(config)
return jsonify({"mailbox": _to_jsonable(profile), "overview": _to_jsonable(overview)})
@app.post("/api/mailbox/folders")
@auth_required
def mailbox_folders() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
method = _normalize_method(payload.get("method") or profile.preferred_method)
config = _profile_to_config(profile, method=method)
folders = mailbox_manager.list_folders(config, method)
mailbox_store.cache_folders(profile.id, method, _to_jsonable(folders))
return jsonify({"mailbox": _to_jsonable(profile), "method": method, "folders": _to_jsonable(folders)})
@app.post("/api/mailbox/messages")
@auth_required
def mailbox_messages() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
query = _build_query(payload, default_method=profile.preferred_method)
config = _profile_to_config(profile, method=query.method)
result = mailbox_manager.list_messages(config, query)
messages = result.messages if hasattr(result, "messages") else result
count = getattr(result, "returned", len(messages))
mailbox_store.cache_messages(profile.id, query.method, _to_jsonable(messages))
return jsonify(
{
"mailbox": _to_jsonable(profile),
"method": query.method,
"folder": query.folder,
"messages": _to_jsonable(messages),
"count": count,
"meta": {
"total": getattr(result, "total", count),
"returned": count,
"page": getattr(result, "page", query.page),
"page_size": getattr(result, "page_size", query.page_size),
"total_pages": getattr(result, "total_pages", 1 if count else 0),
"has_prev": getattr(result, "has_prev", False),
"has_next": getattr(result, "has_next", False),
"folder": getattr(result, "folder", query.folder),
},
}
)
@app.post("/api/key/mailbox/messages")
@api_key_required
def mailbox_messages_by_key() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox_by_email(mailbox_store, payload)
query = _build_query(payload, default_method=profile.preferred_method)
config = _profile_to_config(profile, method=query.method)
result = mailbox_manager.list_messages(config, query)
messages = result.messages if hasattr(result, "messages") else result
count = getattr(result, "returned", len(messages))
mailbox_store.cache_messages(profile.id, query.method, _to_jsonable(messages))
return jsonify(
{
"mailbox": _profile_to_public_mailbox(profile),
"method": query.method,
"folder": query.folder,
"messages": _to_jsonable(messages),
"count": count,
"meta": {
"total": getattr(result, "total", count),
"returned": count,
"page": getattr(result, "page", query.page),
"page_size": getattr(result, "page_size", query.page_size),
"total_pages": getattr(result, "total_pages", 1 if count else 0),
"has_prev": getattr(result, "has_prev", False),
"has_next": getattr(result, "has_next", False),
"folder": getattr(result, "folder", query.folder),
},
}
)
@app.post("/api/mailbox/message")
@auth_required
def mailbox_message() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
detail_request = _build_detail_request(payload, default_method=profile.preferred_method)
config = _profile_to_config(profile, method=detail_request.method)
message = mailbox_manager.get_message_detail(config, detail_request)
mailbox_store.cache_message(profile.id, detail_request.method, _to_jsonable(message))
return jsonify({"mailbox": _to_jsonable(profile), "message": _to_jsonable(message)})
@app.post("/api/key/mailbox/message")
@api_key_required
def mailbox_message_by_key() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox_by_email(mailbox_store, payload)
detail_request = _build_detail_request(payload, default_method=profile.preferred_method)
config = _profile_to_config(profile, method=detail_request.method)
message = mailbox_manager.get_message_detail(config, detail_request)
mailbox_store.cache_message(profile.id, detail_request.method, _to_jsonable(message))
return jsonify(
{
"mailbox": _profile_to_public_mailbox(profile),
"message": _to_jsonable(message),
}
)
@app.post("/api/mailbox/message/read-state")
@auth_required
def mailbox_message_read_state() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
state_request = _build_read_state_request(payload, default_method=profile.preferred_method)
config = _profile_to_config(profile, method=state_request.method)
mailbox_manager.update_read_state(config, state_request)
message = mailbox_manager.get_message_detail(
config,
MailboxDetailRequest(
method=state_request.method,
message_id=state_request.message_id,
folder=state_request.folder,
),
)
mailbox_store.cache_message(profile.id, state_request.method, _to_jsonable(message))
return jsonify({"mailbox": _to_jsonable(profile), "message": _to_jsonable(message)})
@app.post("/api/mailbox/message/flag-state")
@auth_required
def mailbox_message_flag_state() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
state_request = _build_flag_state_request(payload, default_method=profile.preferred_method)
config = _profile_to_config(profile, method=state_request.method)
mailbox_manager.update_flag_state(config, state_request)
message = mailbox_manager.get_message_detail(
config,
MailboxDetailRequest(
method=state_request.method,
message_id=state_request.message_id,
folder=state_request.folder,
),
)
mailbox_store.cache_message(profile.id, state_request.method, _to_jsonable(message))
return jsonify({"mailbox": _to_jsonable(profile), "message": _to_jsonable(message)})
@app.post("/api/mailbox/message/move")
@auth_required
def mailbox_message_move() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
move_request = _build_move_request(payload, default_method=profile.preferred_method)
config = _profile_to_config(profile, method=move_request.method)
result = mailbox_manager.move_message(config, move_request)
mailbox_store.update_cached_message_state(
profile.id,
move_request.method,
move_request.message_id,
folder_id=move_request.destination_folder,
)
return jsonify({"mailbox": _to_jsonable(profile), "result": _to_jsonable(result)})
@app.post("/api/mailbox/message/delete")
@auth_required
def mailbox_message_delete() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
delete_request = _build_delete_request(payload, default_method=profile.preferred_method)
config = _profile_to_config(profile, method=delete_request.method)
result = mailbox_manager.delete_message(config, delete_request)
mailbox_store.remove_cached_message(profile.id, delete_request.method, delete_request.message_id)
return jsonify({"mailbox": _to_jsonable(profile), "result": _to_jsonable(result)})
@app.post("/api/mailbox/messages/actions/batch")
@auth_required
def mailbox_messages_batch_actions() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
method = _normalize_method(payload.get("method") or profile.preferred_method)
folder = _optional_text(payload.get("folder")) or "INBOX"
action = _normalize_message_action(payload.get("action"))
message_ids = _parse_message_ids(payload.get("message_ids"), maximum=100)
destination_folder = _optional_text(payload.get("destination_folder"))
if action == "move" and not destination_folder:
raise MailboxError("移动邮件时必须提供目标文件夹", code="invalid_destination_folder")
if action == "archive" and not destination_folder:
destination_folder = "archive"
config = _profile_to_config(profile, method=method)
results: list[dict[str, Any]] = []
succeeded = 0
failed = 0
for message_id in message_ids:
try:
if action == "mark_read":
result = mailbox_manager.update_read_state(
config,
ReadStateUpdateRequest(method=method, message_id=message_id, is_read=True, folder=folder),
)
elif action == "mark_unread":
result = mailbox_manager.update_read_state(
config,
ReadStateUpdateRequest(method=method, message_id=message_id, is_read=False, folder=folder),
)
elif action == "flag":
result = mailbox_manager.update_flag_state(
config,
FlagStateUpdateRequest(method=method, message_id=message_id, is_flagged=True, folder=folder),
)
elif action == "unflag":
result = mailbox_manager.update_flag_state(
config,
FlagStateUpdateRequest(method=method, message_id=message_id, is_flagged=False, folder=folder),
)
elif action in {"move", "archive"}:
result = mailbox_manager.move_message(
config,
MessageMoveRequest(
method=method,
message_id=message_id,
destination_folder=destination_folder or "archive",
folder=folder,
),
)
else:
result = mailbox_manager.delete_message(
config,
MessageDeleteRequest(method=method, message_id=message_id, folder=folder),
)
results.append(
{
"message_id": message_id,
"success": True,
"status": getattr(result, "status", "updated"),
"result": _to_jsonable(result),
}
)
succeeded += 1
except Exception as exc: # noqa: BLE001
results.append(
{
"message_id": message_id,
"success": False,
"status": "error",
"message": str(exc),
}
)
failed += 1
return jsonify(
{
"mailbox": _to_jsonable(profile),
"action": action,
"results": results,
"summary": {
"processed": len(results),
"succeeded": succeeded,
"failed": failed,
},
}
)
@app.post("/api/mailbox/message/draft")
@auth_required
def mailbox_message_draft() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
method = _normalize_method(payload.get("method") or profile.preferred_method)
config = _profile_to_config(profile, method=method)
draft = mailbox_manager.save_draft(config, _build_compose_payload(payload, require_to=False))
mailbox_store.cache_message(profile.id, method, draft)
mailbox_store.record_audit_log(
mailbox_id=profile.id,
actor="admin",
action="draft_saved",
target_type="message",
target_id=str(draft.get("message_id", "")),
details={"method": method},
)
return jsonify({"mailbox": _to_jsonable(profile), "message": _to_jsonable(draft)})
@app.post("/api/mailbox/message/send")
@auth_required
def mailbox_message_send() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
method = _normalize_method(payload.get("method") or profile.preferred_method)
config = _profile_to_config(profile, method=method)
result = mailbox_manager.send_message(config, _build_compose_payload(payload, require_to=True))
if result.get("message_id"):
mailbox_store.cache_message(profile.id, method, result)
mailbox_store.record_audit_log(
mailbox_id=profile.id,
actor="admin",
action="message_sent",
target_type="message",
target_id=str(result.get("message_id", "")),
details={"method": method},
)
return jsonify({"mailbox": _to_jsonable(profile), "message": _to_jsonable(result)})
@app.post("/api/mailbox/message/reply")
@auth_required
def mailbox_message_reply() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
method = _normalize_method(payload.get("method") or profile.preferred_method)
message_id = _require_text(payload, "message_id", "缺少邮件标识")
config = _profile_to_config(profile, method=method)
result = mailbox_manager.reply_message(
config,
message_id,
_build_compose_payload(payload, require_to=False),
reply_all=False,
)
mailbox_store.cache_message(profile.id, method, result)
mailbox_store.record_audit_log(
mailbox_id=profile.id,
actor="admin",
action="message_replied",
target_type="message",
target_id=message_id,
details={"method": method},
)
return jsonify({"mailbox": _to_jsonable(profile), "message": _to_jsonable(result)})
@app.post("/api/mailbox/message/reply-all")
@auth_required
def mailbox_message_reply_all() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
method = _normalize_method(payload.get("method") or profile.preferred_method)
message_id = _require_text(payload, "message_id", "缺少邮件标识")
config = _profile_to_config(profile, method=method)
result = mailbox_manager.reply_message(
config,
message_id,
_build_compose_payload(payload, require_to=False),
reply_all=True,
)
mailbox_store.cache_message(profile.id, method, result)
mailbox_store.record_audit_log(
mailbox_id=profile.id,
actor="admin",
action="message_replied_all",
target_type="message",
target_id=message_id,
details={"method": method},
)
return jsonify({"mailbox": _to_jsonable(profile), "message": _to_jsonable(result)})
@app.post("/api/mailbox/message/forward")
@auth_required
def mailbox_message_forward() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
method = _normalize_method(payload.get("method") or profile.preferred_method)
message_id = _require_text(payload, "message_id", "缺少邮件标识")
config = _profile_to_config(profile, method=method)
result = mailbox_manager.forward_message(
config,
message_id,
_build_compose_payload(payload, require_to=True),
)
mailbox_store.cache_message(profile.id, method, result)
mailbox_store.record_audit_log(
mailbox_id=profile.id,
actor="admin",
action="message_forwarded",
target_type="message",
target_id=message_id,
details={"method": method},
)
return jsonify({"mailbox": _to_jsonable(profile), "message": _to_jsonable(result)})
@app.post("/api/mailbox/message/attachment/upload")
@auth_required
def mailbox_message_attachment_upload() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
method = _normalize_method(payload.get("method") or profile.preferred_method)
message_id = _require_text(payload, "message_id", "缺少邮件标识")
config = _profile_to_config(profile, method=method)
attachment_payload = _build_attachment_payload(payload)
attachment = mailbox_manager.upload_attachment(config, message_id, attachment_payload)
mailbox_store.ensure_cached_message_placeholder(profile.id, method, message_id, folder_id="drafts")
mailbox_store.upsert_attachment_content(profile.id, method, message_id, attachment)
mailbox_store.record_audit_log(
mailbox_id=profile.id,
actor="admin",
action="attachment_uploaded",
target_type="attachment",
target_id=str(attachment.get("id") or attachment.get("attachment_id", "")),
details={"message_id": message_id, "method": method},
)
return jsonify({"mailbox": _to_jsonable(profile), "attachment": _to_jsonable(attachment)})
@app.post("/api/mailbox/message/attachment/download")
@auth_required
def mailbox_message_attachment_download() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
method = _normalize_method(payload.get("method") or profile.preferred_method)
message_id = _require_text(payload, "message_id", "缺少邮件标识")
attachment_id = _require_text(payload, "attachment_id", "缺少附件标识")
config = _profile_to_config(profile, method=method)
attachment = mailbox_manager.download_attachment(config, message_id, attachment_id)
mailbox_store.ensure_cached_message_placeholder(
profile.id,
method,
message_id,
folder_id=_optional_text(payload.get("folder")) or "",
)
mailbox_store.upsert_attachment_content(profile.id, method, message_id, attachment)
return jsonify({"mailbox": _to_jsonable(profile), "attachment": _to_jsonable(attachment)})
@app.post("/api/mailbox/folder/create")
@auth_required
def mailbox_folder_create() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
method = _normalize_method(payload.get("method") or profile.preferred_method)
config = _profile_to_config(profile, method=method)
folder = mailbox_manager.create_folder(config, payload)
mailbox_store.cache_folders(profile.id, method, _to_jsonable(mailbox_manager.list_folders(config, method)))
mailbox_store.record_audit_log(
mailbox_id=profile.id,
actor="admin",
action="folder_created",
target_type="folder",
target_id=str(folder.get("id", "")),
details={"method": method},
)
return jsonify({"mailbox": _to_jsonable(profile), "folder": _to_jsonable(folder)})
@app.post("/api/mailbox/folder/rename")
@auth_required
def mailbox_folder_rename() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
method = _normalize_method(payload.get("method") or profile.preferred_method)
config = _profile_to_config(profile, method=method)
folder = mailbox_manager.rename_folder(config, payload)
mailbox_store.cache_folders(profile.id, method, _to_jsonable(mailbox_manager.list_folders(config, method)))
mailbox_store.record_audit_log(
mailbox_id=profile.id,
actor="admin",
action="folder_renamed",
target_type="folder",
target_id=str(folder.get("id", "")),
details={"method": method},
)
return jsonify({"mailbox": _to_jsonable(profile), "folder": _to_jsonable(folder)})
@app.post("/api/mailbox/folder/delete")
@auth_required
def mailbox_folder_delete() -> Any:
payload = request.get_json(silent=True) or {}
profile = _resolve_mailbox(mailbox_store, payload)
method = _normalize_method(payload.get("method") or profile.preferred_method)
config = _profile_to_config(profile, method=method)
folder = mailbox_manager.delete_folder(config, payload)
mailbox_store.cache_folders(profile.id, method, _to_jsonable(mailbox_manager.list_folders(config, method)))
mailbox_store.record_audit_log(
mailbox_id=profile.id,
actor="admin",
action="folder_deleted",
target_type="folder",
target_id=str(folder.get("id", "")),
details={"method": method},
)
return jsonify({"mailbox": _to_jsonable(profile), "folder": _to_jsonable(folder)})
@app.post("/api/mailbox/message/meta")