-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
3466 lines (3193 loc) · 140 KB
/
Copy pathserver.py
File metadata and controls
3466 lines (3193 loc) · 140 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/env python3
import json
import os
import base64
import io
import secrets
import smtplib
import sqlite3
import threading
import time
from http.cookies import SimpleCookie
from datetime import datetime, timezone
from email.message import EmailMessage
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib import error as urllib_error
from urllib import request as urllib_request
from urllib.parse import parse_qs, quote, unquote, urlencode, urlparse
ROOT = Path(__file__).resolve().parent
DB_PATH = Path(os.environ.get("MGPIC_DB", ROOT / "data" / "mgpic2026.sqlite3"))
BACKUP_DIR = Path(os.environ.get("MGPIC_BACKUP_DIR", DB_PATH.parent / "backups"))
SNAPSHOT_DIR = Path(os.environ.get("MGPIC_SNAPSHOT_DIR", DB_PATH.parent / "snapshots"))
LEDGER_PATH = Path(os.environ.get("MGPIC_LEDGER_PATH", DB_PATH.parent / "ledger" / "events.jsonl"))
MAX_BACKUPS = int(os.environ.get("MGPIC_MAX_BACKUPS", "30"))
MAX_SNAPSHOTS = int(os.environ.get("MGPIC_MAX_SNAPSHOTS", "100"))
GITHUB_SESSION_COOKIE = "mgpic_github_session"
GITHUB_SESSION_SECONDS = 60 * 60 * 24 * 14
GITHUB_AUTH_URL = "https://github.com/login/oauth/authorize"
GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token"
GITHUB_API_URL = "https://api.github.com"
FEISHU_API_BASE = os.environ.get("FEISHU_API_BASE", "https://open.feishu.cn/open-apis").rstrip("/")
FEISHU_TABLE_URL = "https://bxup9uklfcb.feishu.cn/wiki/UtVVwrmahiBQlokfhQrc0hh4np1?table=tblpdjqjCZdRNJah&view=vewygPXWz5"
FEISHU_TOKEN_CACHE = {"token": "", "expires_at": 0}
FEISHU_AUTO_SYNC_LOCK = threading.Lock()
FEISHU_AUTO_SYNC_STATE_LOCK = threading.Lock()
FEISHU_AUTO_SYNC_STATE = {
"running": False,
"lastStartedAt": "",
"lastFinishedAt": "",
"lastOkAt": "",
"lastErrorAt": "",
"lastError": "",
"lastTrigger": "",
"lastResult": None,
"nextRunAt": "",
}
FIELD_ALIASES = {
"name": ["姓名", "选手姓名", "参赛者", "项目负责人", "负责人", "name"],
"email": ["邮箱", "联系邮箱", "邮箱(唯一联系方式)", "联系方式", "email", "Email"],
"school": ["学校", "学校 / 组织", "组织", "高校", "school"],
"idNumber": ["身份证号", "身份证号码", "身份证", "证件号", "证件号码", "idNumber"],
"githubLogin": ["GitHub 账号", "Github 账号", "GitHub用户名", "GitHub 用户名", "github", "githubLogin"],
"githubRepo": ["GitHub 仓库", "Github 仓库", "项目 GitHub 链接", "GitHub仓库链接", "仓库链接", "githubRepo", "repo"],
"projectName": ["项目名称", "项目名", "参赛项目", "projectName", "project"],
"projectType": ["项目方向", "方向", "项目类型", "projectType"],
"summary": ["项目简介", "简介", "项目说明", "summary"],
"bankAccount": ["银行卡号", "银行账号", "收款账号", "银行卡", "bankAccount"],
"bankBranch": ["开户支行", "开户银行", "开户行", "支行", "bankBranch"],
"proposal": ["申报审核状态", "项目申报状态", "立项状态", "申报状态", "proposal", "proposalStatus"],
"acceptance": ["验收状态", "项目验收状态", "验收审核状态", "acceptance", "acceptanceStatus"],
"reward": ["奖励状态", "激励状态", "奖金状态", "reward", "rewardStatus"],
"showcase": ["作品墙状态", "展示状态", "上墙状态", "showcase", "showcaseStatus"],
"backendId": ["报名编号", "后台编号", "ID", "编号", "backendId"],
}
REGISTRATION_EXTRA_COLUMNS = {
"external_registration_no": "text not null default ''",
"id_number": "text not null default ''",
"bank_account": "text not null default ''",
"bank_branch": "text not null default ''",
"id_front_file_name": "text not null default ''",
"id_back_file_name": "text not null default ''",
"feishu_record_id": "text not null default ''",
"feishu_synced_at": "text not null default ''",
"archived_at": "text not null default ''",
"archived_reason": "text not null default ''",
}
DEFAULT_FEISHU_FIELD_MAP = {
"backendId": "后台编号",
"source": "报名来源",
"updatedAt": "后台更新时间",
"name": "姓名",
"email": "邮箱",
"school": "学校",
"idNumber": "身份证号",
"githubLogin": "GitHub 账号",
"githubRepo": "GitHub 仓库",
"projectName": "项目名称",
"projectType": "项目方向",
"summary": "项目简介",
"bankAccount": "银行卡号",
"bankBranch": "开户支行",
"proposal": "申报审核状态",
"acceptance": "验收状态",
"reward": "奖励状态",
"showcase": "作品墙状态",
}
FEISHU_FIELD_CANDIDATES = {
"name": ["姓名", "选手姓名", "参赛者", "项目负责人", "负责人"],
"email": ["邮箱", "联系邮箱", "邮箱(唯一联系方式)", "联系方式"],
"school": ["学校", "学校 / 组织", "组织", "高校"],
"idNumber": ["身份证号", "身份证号码", "身份证", "证件号", "证件号码"],
"githubLogin": ["GitHub 账号", "Github 账号", "GitHub用户名", "GitHub 用户名"],
"githubRepo": ["GitHub 仓库", "项目 GitHub 链接", "GitHub仓库链接", "仓库链接"],
"projectName": ["项目名称", "项目名", "参赛项目"],
"projectType": ["项目方向", "方向", "项目类型"],
"summary": ["项目简介", "简介", "项目说明"],
"bankAccount": ["银行卡号", "银行账号", "收款账号", "银行卡"],
"bankBranch": ["开户支行", "开户银行", "开户行", "支行"],
"proposal": ["申报审核状态", "项目申报状态", "立项状态", "申报状态"],
"acceptance": ["验收状态", "项目验收状态", "验收审核状态"],
"reward": ["奖励状态", "激励状态", "奖金状态"],
"showcase": ["作品墙状态", "展示状态", "上墙状态"],
"backendId": ["后台编号", "报名编号", "ID"],
"source": ["报名来源", "来源"],
"updatedAt": ["后台更新时间", "更新时间"],
}
CONTEST_REVIEW_RULES = [
"赛事名称:MoonBit 国产基础软件生态开源大赛。",
"面向在校生,个人参赛,每位参赛者提交一个参赛项目。",
"4 月 29 日前已经存在的项目可以继续维护,但有效工作量只统计 4 月 29 日起新增提交。",
"申报阶段需提交参赛信息、GitHub 仓库、一页左右 PDF 申报书;仓库建议已有 10-20 个有效 commits,不能用空提交或无意义拆分凑数。",
"项目应围绕 MoonBit 开源生态库、生态包、开发工具或示例工程,具备明确功能、真实使用场景和可复用价值。",
"项目可以原创,也可以移植或重写成熟语言生态中的开源库;移植项目必须说明原项目名称、链接、许可证和参考范围。",
"不得直接重复 MoonBit 生态中已经存在且功能高度重合的成熟项目;如基于已有项目扩展,应说明新增价值和独立贡献。",
"项目规模参考范围为 4-10k 有效 MoonBit 代码行数,重点看真实可用、边界清晰、文档完整、测试可运行和后续可维护。",
"验收阶段要求 MoonBit 为主要实现语言,公开 GitHub 仓库,README 说明目标、安装、使用方式、示例和可复现方式。",
"验收阶段要求 CI 覆盖检查、构建和测试流程,提供核心功能测试,至少一个可运行示例,并发布到 mooncakes.io。",
"项目须采用 OSI 认可开源许可证,并遵守第三方依赖及参考项目许可证要求。",
"优秀项目评选综合完成度、MoonBit 生态贡献、工程质量、文档体验、展示表现和长期维护潜力;入选项目可能参加决赛答辩,地点和流程后续公布。",
"AI 工具可以用于代码生成、接口设计、测试补全、文档撰写和移植分析,但最终质量、许可证和技术边界由参赛者负责。",
]
EXPORT_TABLES = [
"registrations",
"registration_statuses",
"status_events",
"repo_checks",
"imported_records",
"registration_payloads",
"registration_files",
"ai_reviews",
"notifications",
]
RESTORE_TABLES = list(reversed(EXPORT_TABLES))
def now_iso():
return datetime.now(timezone.utc).isoformat()
def env_bool(key, default=False):
value = os.environ.get(key)
if value is None or value == "":
return default
return str(value).strip().lower() in {"1", "true", "yes", "on"}
def env_int(key, default, minimum=None):
try:
value = int(os.environ.get(key, str(default)))
except (TypeError, ValueError):
value = default
if minimum is not None:
value = max(minimum, value)
return value
def db():
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
connection = sqlite3.connect(DB_PATH)
connection.row_factory = sqlite3.Row
connection.execute("pragma foreign_keys = on")
connection.execute("pragma busy_timeout = 5000")
connection.execute("pragma journal_mode = wal")
return connection
def backup_name(reason):
reason = "".join(char if char.isalnum() or char in {"-", "_"} else "-" for char in str(reason or "manual").lower())
reason = "-".join(part for part in reason.split("-") if part)[:40] or "manual"
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
return f"mgpic2026-{stamp}-{reason}.sqlite3"
def backup_info(path):
stat = path.stat()
return {
"name": path.name,
"size": stat.st_size,
"createdAt": datetime.fromtimestamp(stat.st_mtime, timezone.utc).isoformat(),
"downloadUrl": f"/api/admin/backups/{quote(path.name)}",
}
def list_backups(limit=20):
if not BACKUP_DIR.exists():
return []
backups = sorted(BACKUP_DIR.glob("mgpic2026-*.sqlite3"), key=lambda item: item.stat().st_mtime, reverse=True)
return [backup_info(path) for path in backups[:limit]]
def prune_backups():
if MAX_BACKUPS <= 0 or not BACKUP_DIR.exists():
return
backups = sorted(BACKUP_DIR.glob("mgpic2026-*.sqlite3"), key=lambda item: item.stat().st_mtime, reverse=True)
for path in backups[MAX_BACKUPS:]:
try:
path.unlink()
except OSError:
pass
def backup_database(reason="manual"):
if not DB_PATH.exists():
return None
BACKUP_DIR.mkdir(parents=True, exist_ok=True)
destination = BACKUP_DIR / backup_name(reason)
temporary = BACKUP_DIR / f"{destination.name}.tmp"
with sqlite3.connect(DB_PATH) as source, sqlite3.connect(temporary) as target:
source.backup(target)
temporary.replace(destination)
prune_backups()
return backup_info(destination)
def snapshot_name(reason):
reason = "".join(char if char.isalnum() or char in {"-", "_"} else "-" for char in str(reason or "manual").lower())
reason = "-".join(part for part in reason.split("-") if part)[:40] or "manual"
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
return f"mgpic2026-{stamp}-{reason}.json"
def snapshot_info(path):
stat = path.stat()
return {
"name": path.name,
"size": stat.st_size,
"createdAt": datetime.fromtimestamp(stat.st_mtime, timezone.utc).isoformat(),
"downloadUrl": f"/api/admin/snapshots/{quote(path.name)}",
}
def list_snapshots(limit=20):
if not SNAPSHOT_DIR.exists():
return []
snapshots = sorted(SNAPSHOT_DIR.glob("mgpic2026-*.json"), key=lambda item: item.stat().st_mtime, reverse=True)
return [snapshot_info(path) for path in snapshots[:limit]]
def prune_snapshots():
if MAX_SNAPSHOTS <= 0 or not SNAPSHOT_DIR.exists():
return
snapshots = sorted(SNAPSHOT_DIR.glob("mgpic2026-*.json"), key=lambda item: item.stat().st_mtime, reverse=True)
for path in snapshots[MAX_SNAPSHOTS:]:
try:
path.unlink()
except OSError:
pass
def write_text_atomic(path, text):
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f"{path.name}.tmp")
temporary.write_text(text, encoding="utf-8")
temporary.replace(path)
def write_json_atomic(path, payload):
write_text_atomic(path, json.dumps(payload, ensure_ascii=False, indent=2))
def append_ledger_event(event):
LEDGER_PATH.parent.mkdir(parents=True, exist_ok=True)
with LEDGER_PATH.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(event, ensure_ascii=False, separators=(",", ":")) + "\n")
def table_rows(connection, table):
rows = connection.execute(f"select * from {table}").fetchall()
return [dict(row) for row in rows]
def database_export(connection=None, reason="manual"):
close_connection = False
if connection is None:
connection = db()
close_connection = True
try:
tables = {table: table_rows(connection, table) for table in EXPORT_TABLES}
return {
"version": 1,
"reason": reason,
"exportedAt": now_iso(),
"database": str(DB_PATH),
"tables": tables,
"counts": {table: len(rows) for table, rows in tables.items()},
}
finally:
if close_connection:
connection.close()
def snapshot_database(reason="manual"):
if not DB_PATH.exists():
return None
with db() as connection:
export = database_export(connection, reason)
SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
destination = SNAPSHOT_DIR / snapshot_name(reason)
write_json_atomic(destination, export)
write_json_atomic(SNAPSHOT_DIR / "latest.json", export)
prune_snapshots()
append_ledger_event({
"event": "snapshot",
"reason": reason,
"createdAt": export["exportedAt"],
"snapshot": destination.name,
"counts": export["counts"],
})
return snapshot_info(destination)
def persist_database(reason="manual"):
backup = backup_database(reason)
snapshot = snapshot_database(reason)
return {"backup": backup, "snapshot": snapshot}
def restore_export(connection, export):
tables = export.get("tables") if isinstance(export, dict) else None
if not isinstance(tables, dict):
raise ValueError("恢复文件缺少 tables 字段")
for table in RESTORE_TABLES:
connection.execute(f"delete from {table}")
for table in EXPORT_TABLES:
rows = tables.get(table) or []
if not rows:
continue
columns = [row["name"] for row in connection.execute(f"pragma table_info({table})").fetchall()]
for row in rows:
if not isinstance(row, dict):
continue
available = [column for column in columns if column in row]
if not available:
continue
placeholders = ", ".join(["?"] * len(available))
column_sql = ", ".join(available)
connection.execute(
f"insert into {table} ({column_sql}) values ({placeholders})",
[row.get(column) for column in available],
)
def recover_database_from_latest_snapshot():
latest = SNAPSHOT_DIR / "latest.json"
if not latest.exists():
return None
with db() as connection:
count = connection.execute("select count(*) from registrations").fetchone()[0]
if count > 0:
return None
try:
export = json.loads(latest.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
return {"ok": False, "error": str(exc), "snapshot": str(latest)}
snapshot_count = len((export.get("tables") or {}).get("registrations") or [])
if snapshot_count <= 0:
return None
restore_export(connection, export)
append_ledger_event({
"event": "auto-recover",
"createdAt": now_iso(),
"snapshot": latest.name,
"registrations": snapshot_count,
})
return {"ok": True, "snapshot": str(latest), "registrations": snapshot_count}
def init_db():
with db() as connection:
connection.executescript(
"""
create table if not exists registrations (
id integer primary key autoincrement,
created_at text not null,
updated_at text not null,
name text not null default '',
email text not null default '',
school text not null default '',
github_login text not null default '',
github_repo text not null default '',
project_name text not null default '',
project_type text not null default '',
summary text not null default '',
proposal_file_name text not null default '',
student_file_name text not null default '',
source text not null default 'website'
);
create table if not exists registration_statuses (
registration_id integer primary key,
proposal text not null default '申报审核中',
acceptance text not null default '未提交',
reward text not null default '未开始',
showcase text not null default '待上墙',
notes text not null default '',
updated_at text not null,
foreign key (registration_id) references registrations(id) on delete cascade
);
create table if not exists status_events (
id integer primary key autoincrement,
registration_id integer not null,
created_at text not null,
action text not null default '',
action_label text not null default '',
operator text not null default '',
from_status_json text not null default '{}',
to_status_json text not null default '{}',
note text not null default '',
notification_id integer,
foreign key (registration_id) references registrations(id) on delete cascade
);
create table if not exists repo_checks (
id integer primary key autoincrement,
registration_id integer not null,
repo_url text not null default '',
commit_count integer not null default 0,
checks_json text not null default '[]',
checked_at text not null,
foreign key (registration_id) references registrations(id) on delete cascade
);
create table if not exists imported_records (
id integer primary key autoincrement,
created_at text not null,
source text not null default 'feishu',
payload_json text not null
);
create table if not exists registration_payloads (
registration_id integer primary key,
updated_at text not null,
source text not null default 'website',
payload_json text not null default '{}',
foreign key (registration_id) references registrations(id) on delete cascade
);
create table if not exists registration_files (
registration_id integer not null,
kind text not null,
filename text not null default '',
content_type text not null default 'application/octet-stream',
size integer not null default 0,
data_base64 text not null default '',
updated_at text not null,
primary key (registration_id, kind),
foreign key (registration_id) references registrations(id) on delete cascade
);
create table if not exists ai_reviews (
id integer primary key autoincrement,
registration_id integer not null,
created_at text not null,
mode text not null default 'proposal',
engine text not null default '',
model text not null default '',
decision text not null default '',
score integer not null default 0,
next_stage text not null default '',
summary text not null default '',
reasons_json text not null default '[]',
missing_items_json text not null default '[]',
email_subject text not null default '',
email_body text not null default '',
raw_json text not null default '{}',
foreign key (registration_id) references registrations(id) on delete cascade
);
create table if not exists notifications (
id integer primary key autoincrement,
registration_id integer not null,
created_at text not null,
sent_at text not null default '',
channel text not null default 'email',
recipient text not null default '',
subject text not null default '',
body text not null default '',
status text not null default 'pending',
error text not null default '',
foreign key (registration_id) references registrations(id) on delete cascade
);
create table if not exists github_oauth_states (
state text primary key,
return_to text not null default '/progress.html',
redirect_uri text not null default '',
created_at real not null
);
create table if not exists github_sessions (
session_id text primary key,
created_at real not null,
updated_at real not null,
expires_at real not null,
github_id text not null default '',
github_login text not null default '',
name text not null default '',
email text not null default '',
avatar_url text not null default '',
html_url text not null default '',
access_token text not null default ''
);
"""
)
ensure_registration_columns(connection)
def ensure_registration_columns(connection):
existing = {
row["name"]
for row in connection.execute("pragma table_info(registrations)").fetchall()
}
for column, definition in REGISTRATION_EXTRA_COLUMNS.items():
if column not in existing:
connection.execute(f"alter table registrations add column {column} {definition}")
def mask_middle(value, keep_start=3, keep_end=4):
value = str(value or "").strip()
if not value:
return ""
if len(value) <= keep_start + keep_end:
return "*" * len(value)
return f"{value[:keep_start]}{'*' * (len(value) - keep_start - keep_end)}{value[-keep_end:]}"
def github_oauth_configured():
return bool(os.environ.get("GITHUB_CLIENT_ID", "").strip() and os.environ.get("GITHUB_CLIENT_SECRET", "").strip())
class FeishuConfigError(Exception):
pass
class FeishuApiError(Exception):
pass
def feishu_config(include_secrets=False):
app_id = os.environ.get("FEISHU_APP_ID", "").strip()
app_secret = os.environ.get("FEISHU_APP_SECRET", "").strip()
app_token = os.environ.get("FEISHU_APP_TOKEN", "").strip()
table_id = os.environ.get("FEISHU_TABLE_ID", "tblpdjqjCZdRNJah").strip()
view_id = os.environ.get("FEISHU_VIEW_ID", "").strip()
result = {
"appIdConfigured": bool(app_id),
"appSecretConfigured": bool(app_secret),
"appTokenConfigured": bool(app_token),
"tableId": table_id,
"viewId": view_id,
"configured": bool(app_id and app_secret and app_token and table_id),
"missing": [
key
for key, value in (
("FEISHU_APP_ID", app_id),
("FEISHU_APP_SECRET", app_secret),
("FEISHU_APP_TOKEN", app_token),
("FEISHU_TABLE_ID", table_id),
)
if not value
],
"tableUrl": FEISHU_TABLE_URL,
}
if include_secrets:
result.update(
{
"appId": app_id,
"appSecret": app_secret,
"appToken": app_token,
}
)
return result
def feishu_auto_sync_config():
# Only imports Feishu registration data into SQLite by default. Writing
# website data back to Feishu remains a manual admin action.
interval_seconds = env_int("FEISHU_AUTO_SYNC_INTERVAL_SECONDS", 6 * 60 * 60, minimum=60)
return {
"enabled": env_bool("FEISHU_AUTO_SYNC_ENABLED", False),
"intervalSeconds": interval_seconds,
"intervalHours": round(interval_seconds / 3600, 2),
"runsPerDay": round(86400 / interval_seconds, 2),
"runOnStart": env_bool("FEISHU_AUTO_SYNC_RUN_ON_START", True),
"direction": "feishu-to-backend",
}
def update_feishu_auto_sync_state(**updates):
with FEISHU_AUTO_SYNC_STATE_LOCK:
FEISHU_AUTO_SYNC_STATE.update(updates)
return dict(FEISHU_AUTO_SYNC_STATE)
def feishu_auto_sync_status():
status = update_feishu_auto_sync_state()
status["config"] = feishu_auto_sync_config()
status["feishuConfigured"] = feishu_config()["configured"]
return status
def require_feishu_config():
config = feishu_config(include_secrets=True)
if not config["configured"]:
raise FeishuConfigError(
"飞书同步未配置:请在 Render 环境变量中设置 "
+ "、".join(config["missing"])
+ "。FEISHU_APP_TOKEN 是多维表格 app_token,不是 table_id。"
)
return config
def feishu_field_map():
field_map = dict(DEFAULT_FEISHU_FIELD_MAP)
configured = os.environ.get("FEISHU_FIELD_MAP", "").strip()
if configured:
try:
custom = json.loads(configured)
if isinstance(custom, dict):
for key, value in custom.items():
if isinstance(value, str) and value.strip():
field_map[key] = value.strip()
except json.JSONDecodeError:
raise FeishuConfigError("FEISHU_FIELD_MAP 必须是 JSON 对象,例如 {\"email\":\"联系邮箱\"}。")
return field_map
def http_json(method, url, headers=None, payload=None, timeout=30):
request_headers = {
"Accept": "application/json",
**(headers or {}),
}
data = None
if payload is not None:
request_headers["Content-Type"] = "application/json; charset=utf-8"
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
request = urllib_request.Request(url, data=data, headers=request_headers, method=method)
try:
with urllib_request.urlopen(request, timeout=timeout) as response:
body = response.read().decode("utf-8")
except urllib_error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")
raise FeishuApiError(f"飞书接口 HTTP {exc.code}:{body[:500]}")
except urllib_error.URLError as exc:
raise FeishuApiError(f"无法连接飞书接口:{exc.reason}")
if not body:
return {}
try:
return json.loads(body)
except json.JSONDecodeError:
raise FeishuApiError(f"飞书接口返回非 JSON 内容:{body[:200]}")
def feishu_tenant_access_token():
config = require_feishu_config()
now = time.time()
if FEISHU_TOKEN_CACHE["token"] and FEISHU_TOKEN_CACHE["expires_at"] > now + 60:
return FEISHU_TOKEN_CACHE["token"]
payload = {
"app_id": config["appId"],
"app_secret": config["appSecret"],
}
data = http_json(
"POST",
f"{FEISHU_API_BASE}/auth/v3/tenant_access_token/internal",
payload=payload,
)
if data.get("code") != 0:
raise FeishuApiError(f"获取飞书 tenant_access_token 失败:{data.get('msg') or data}")
token = data.get("tenant_access_token") or data.get("data", {}).get("tenant_access_token")
if not token:
raise FeishuApiError("飞书未返回 tenant_access_token。")
expire = int(data.get("expire") or data.get("data", {}).get("expire") or 7200)
FEISHU_TOKEN_CACHE["token"] = token
FEISHU_TOKEN_CACHE["expires_at"] = now + expire
return token
def feishu_request(method, path, payload=None, params=None):
token = feishu_tenant_access_token()
url = f"{FEISHU_API_BASE}{path}"
if params:
url = f"{url}?{urlencode({key: value for key, value in params.items() if value})}"
data = http_json(method, url, headers={"Authorization": f"Bearer {token}"}, payload=payload)
if data.get("code") not in (None, 0):
raise FeishuApiError(f"飞书接口错误 {data.get('code')}:{data.get('msg') or data}")
return data.get("data") or {}
def feishu_table_path(config=None):
config = config or require_feishu_config()
return f"/bitable/v1/apps/{quote(config['appToken'])}/tables/{quote(config['tableId'])}"
def feishu_list_records():
config = require_feishu_config()
records = []
page_token = ""
while True:
params = {"page_size": "500"}
if config["viewId"]:
params["view_id"] = config["viewId"]
if page_token:
params["page_token"] = page_token
data = feishu_request(
"GET",
f"{feishu_table_path(config)}/records",
params=params,
)
records.extend(data.get("items") or [])
if not data.get("has_more"):
break
page_token = data.get("page_token") or ""
if not page_token:
break
return records
def feishu_import_rows_from_records(records):
rows = []
for record in records:
if not isinstance(record, dict):
continue
rows.append(
{
"fields": record.get("fields") or {},
"__feishuRecordId": record.get("record_id") or record.get("id") or "",
}
)
return rows
def feishu_table_field_names():
config = require_feishu_config()
names = set()
page_token = ""
while True:
params = {"page_size": "200"}
if page_token:
params["page_token"] = page_token
data = feishu_request("GET", f"{feishu_table_path(config)}/fields", params=params)
names.update(
item.get("field_name")
for item in data.get("items", [])
if isinstance(item, dict) and item.get("field_name")
)
if not data.get("has_more"):
break
page_token = data.get("page_token") or ""
if not page_token:
break
return names
def registration_match_keys(values):
keys = []
email = str(values.get("email") or "").strip().lower()
repo = str(values.get("githubRepo") or values.get("github_repo") or "").strip().lower().rstrip("/")
if email:
keys.append(f"email:{email}")
if repo:
keys.append(f"repo:{repo}")
return keys
def feishu_remote_index(import_rows):
index = {}
for row in import_rows:
values = {
"email": import_field(row, "email"),
"githubRepo": import_field(row, "githubRepo"),
}
record_id = clean_text(row, "__feishuRecordId")
if not record_id:
continue
for key in registration_match_keys(values):
index.setdefault(key, record_id)
return index
def feishu_write_field_name(key, field_map, available_fields=None):
names = []
configured = field_map.get(key)
if configured:
names.append(configured)
names.extend(FEISHU_FIELD_CANDIDATES.get(key, []))
names = list(dict.fromkeys(name for name in names if name))
if available_fields is None:
return names[0] if names else ""
for name in names:
if name in available_fields:
return name
return ""
def feishu_fields_for_registration(row, available_fields=None):
field_map = feishu_field_map()
values = {
"backendId": str(row["id"]),
"source": row["source"] or "website",
"updatedAt": row["updated_at"],
"name": row["name"],
"email": row["email"],
"school": row["school"],
"idNumber": row["id_number"],
"githubLogin": row["github_login"],
"githubRepo": row["github_repo"],
"projectName": row["project_name"],
"projectType": row["project_type"],
"summary": row["summary"],
"bankAccount": row["bank_account"],
"bankBranch": row["bank_branch"],
"proposal": row["proposal"] or "申报审核中",
"acceptance": row["acceptance"] or "未提交",
"reward": row["reward"] or "未开始",
"showcase": row["showcase"] or "待上墙",
}
fields = {}
for key, value in values.items():
field_name = feishu_write_field_name(key, field_map, available_fields=available_fields)
text = str(value or "").strip()
if not field_name or not text:
continue
fields[field_name] = text
return fields
def admin_github_logins():
value = os.environ.get("ADMIN_GITHUB_LOGINS", "").strip()
if not value:
return set()
return {
item.strip().lower().lstrip("@")
for item in value.replace(";", ",").split(",")
if item.strip()
}
def request_host(handler):
return handler.headers.get("X-Forwarded-Host") or handler.headers.get("Host") or "127.0.0.1:4174"
def is_local_host(host):
hostname = host.split(":", 1)[0].lower()
return hostname in {"127.0.0.1", "localhost", "::1"}
def request_scheme(handler):
forwarded = handler.headers.get("X-Forwarded-Proto", "").split(",", 1)[0].strip()
if forwarded:
return forwarded
return "http" if is_local_host(request_host(handler)) else "https"
def github_redirect_uri(handler):
configured = os.environ.get("GITHUB_OAUTH_REDIRECT_URI", "").strip()
if configured:
return configured
return f"{request_scheme(handler)}://{request_host(handler)}/api/auth/github/callback"
def clean_return_to(value):
value = str(value or "/progress.html").strip() or "/progress.html"
parsed = urlparse(value)
if parsed.scheme or parsed.netloc:
return "/progress.html"
if not value.startswith("/"):
value = f"/{value}"
if "\r" in value or "\n" in value:
return "/progress.html"
return value
def append_query(path, params):
parsed = urlparse(path)
existing = parse_qs(parsed.query)
for key, value in params.items():
existing[key] = [value]
query = urlencode({key: values[-1] for key, values in existing.items()})
return parsed._replace(query=query).geturl()
def registration_from_row(row, include_sensitive=False):
if row is None:
return None
sensitive_submitted = any(
[
row["id_number"],
row["bank_account"],
row["bank_branch"],
row["id_front_file_name"],
row["id_back_file_name"],
]
)
result = {
"id": row["id"],
"serverId": row["id"],
"externalRegistrationNo": row["external_registration_no"] if "external_registration_no" in row.keys() else "",
"createdAt": row["created_at"],
"updatedAt": row["updated_at"],
"name": row["name"],
"email": row["email"],
"school": row["school"],
"githubLogin": row["github_login"],
"githubRepo": row["github_repo"],
"projectName": row["project_name"],
"projectType": row["project_type"],
"summary": row["summary"],
"proposalFileName": row["proposal_file_name"],
"studentFileName": row["student_file_name"],
"idFrontFileName": row["id_front_file_name"],
"idBackFileName": row["id_back_file_name"],
"idNumberMasked": mask_middle(row["id_number"]),
"bankAccountMasked": mask_middle(row["bank_account"]),
"sensitiveSubmitted": sensitive_submitted,
"source": row["source"],
"feishuRecordId": row["feishu_record_id"],
"feishuSyncedAt": row["feishu_synced_at"],
"archivedAt": row["archived_at"],
"archivedReason": row["archived_reason"],
"archived": bool(row["archived_at"]),
"backendMode": "sqlite",
}
if include_sensitive:
result.update(
{
"idNumber": row["id_number"],
"bankAccount": row["bank_account"],
"bankBranch": row["bank_branch"],
}
)
return result
def status_from_row(row):
if row is None:
return None
return {
"proposal": row["proposal"],
"acceptance": row["acceptance"],
"reward": row["reward"],
"showcase": row["showcase"],
"notes": row["notes"],
"updatedAt": row["updated_at"],
"source": "backend",
}
def status_snapshot(value):
if value is None:
return {
"proposal": "申报审核中",
"acceptance": "未提交",
"reward": "未开始",
"showcase": "待上墙",
"notes": "",
}
if isinstance(value, sqlite3.Row):
return {
"proposal": value["proposal"],
"acceptance": value["acceptance"],
"reward": value["reward"],
"showcase": value["showcase"],
"notes": value["notes"],
}
return {
"proposal": value.get("proposal") or "申报审核中",
"acceptance": value.get("acceptance") or "未提交",
"reward": value.get("reward") or "未开始",
"showcase": value.get("showcase") or "待上墙",
"notes": value.get("notes") or "",
}
def status_event_from_row(row):
if row is None:
return None
return {
"id": row["id"],
"registrationId": row["registration_id"],
"createdAt": row["created_at"],