sophhub 0.2.3 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/skills/consensus/skill.json +20 -0
- package/skills/consensus/src/SKILL.md +93 -0
- package/skills/deepwiki/skill.json +20 -0
- package/skills/deepwiki/src/SKILL.md +45 -0
- package/skills/deepwiki/src/_meta.json +6 -0
- package/skills/deepwiki/src/scripts/deepwiki.js +135 -0
- package/skills/feishu-bitable/skill.json +20 -0
- package/skills/feishu-bitable/src/CHECKLIST.md +150 -0
- package/skills/feishu-bitable/src/README.md +178 -0
- package/skills/feishu-bitable/src/SKILL.md +113 -0
- package/skills/feishu-bitable/src/_meta.json +6 -0
- package/skills/feishu-bitable/src/api.js +381 -0
- package/skills/feishu-bitable/src/bin/cli.js +284 -0
- package/skills/feishu-bitable/src/description.md +143 -0
- package/skills/feishu-bitable/src/examples/create-records.json +52 -0
- package/skills/feishu-bitable/src/examples/create-table.json +64 -0
- package/skills/feishu-bitable/src/package-lock.json +324 -0
- package/skills/feishu-bitable/src/package.json +33 -0
- package/skills/feishu-bitable/src/publish-config.json +14 -0
- package/skills/feishu-bitable/src/test-simple.js +61 -0
- package/skills/feishu-bitable/src/utils.js +261 -0
- package/skills/google-maps/skill.json +20 -0
- package/skills/google-maps/src/SKILL.md +237 -0
- package/skills/google-maps/src/_meta.json +6 -0
- package/skills/google-maps/src/lib/map_helper.py +912 -0
- package/skills/large-task-router/skill.json +20 -0
- package/skills/large-task-router/src/SKILL.md +79 -0
- package/skills/large-task-router/src/templates/plan.md +74 -0
- package/skills/skillhub/skill.json +11 -4
- package/skills/skillhub/src/SKILL.md +11 -1
- package/skills/sophnet-dailynews/skill.json +20 -0
- package/skills/sophnet-dailynews/src/SKILL.md +179 -0
- package/skills/sophnet-dailynews/src/cache.json +151 -0
- package/skills/sophnet-dailynews/src/sources.json +230 -0
- package/skills/sophnet-schedule/skill.json +20 -0
- package/skills/sophnet-schedule/src/ARCHITECTURE.md +321 -0
- package/skills/sophnet-schedule/src/IMPROVEMENTS.md +145 -0
- package/skills/sophnet-schedule/src/SKILL.md +1050 -0
- package/skills/sophnet-schedule/src/_meta.json +6 -0
- package/skills/sophnet-schedule/src/api/__init__.py +0 -0
- package/skills/sophnet-schedule/src/api/models.py +245 -0
- package/skills/sophnet-schedule/src/apps/add_event.py +237 -0
- package/skills/sophnet-schedule/src/apps/check_reminders.py +112 -0
- package/skills/sophnet-schedule/src/apps/check_roc.py +246 -0
- package/skills/sophnet-schedule/src/apps/generate_daily_plan.py +342 -0
- package/skills/sophnet-schedule/src/apps/import_events.py +216 -0
- package/skills/sophnet-schedule/src/apps/monitor_calendar_changes.py +140 -0
- package/skills/sophnet-schedule/src/apps/register_tasks.py +169 -0
- package/skills/sophnet-schedule/src/apps/sync_roc_to_gcal.py +174 -0
- package/skills/sophnet-schedule/src/compat.py +66 -0
- package/skills/sophnet-schedule/src/config/__init__.py +0 -0
- package/skills/sophnet-schedule/src/config/reminder_rules.yaml +96 -0
- package/skills/sophnet-schedule/src/config/roc_events.yaml +44 -0
- package/skills/sophnet-schedule/src/config/settings.py +133 -0
- package/skills/sophnet-schedule/src/config/task_registry.yaml +92 -0
- package/skills/sophnet-schedule/src/docs/FRONTEND_INTEGRATION_GUIDE.md +437 -0
- package/skills/sophnet-schedule/src/gcal/__init__.py +0 -0
- package/skills/sophnet-schedule/src/gcal/client.py +374 -0
- package/skills/sophnet-schedule/src/gcal/models.py +91 -0
- package/skills/sophnet-schedule/src/requirements.txt +6 -0
- package/skills/sophnet-schedule/src/scripts/setup_gcal_token.py +85 -0
- package/skills/sophnet-schedule/src/server.py +669 -0
- package/skills/sophnet-schedule/src/services/__init__.py +0 -0
- package/skills/sophnet-schedule/src/services/calendar_backend.py +139 -0
- package/skills/sophnet-schedule/src/services/conflict_detector.py +96 -0
- package/skills/sophnet-schedule/src/services/datetime_utils.py +117 -0
- package/skills/sophnet-schedule/src/services/event_classifier.py +100 -0
- package/skills/sophnet-schedule/src/services/event_diff.py +160 -0
- package/skills/sophnet-schedule/src/services/google_integration.py +500 -0
- package/skills/sophnet-schedule/src/services/job_store.py +100 -0
- package/skills/sophnet-schedule/src/services/local_event_store.py +266 -0
- package/skills/sophnet-schedule/src/services/reminder_planner.py +116 -0
- package/skills/sophnet-schedule/src/services/runtime_utils.py +31 -0
- package/skills/sophnet-schedule/src/services/table_parser.py +286 -0
- package/skills/sophnet-schedule/src/services/task_builder.py +167 -0
- package/skills/sophnet-schedule/src/services/time_window.py +72 -0
- package/skills/sophnet-stock/skill.json +20 -0
- package/skills/sophnet-stock/src/App-Plan.md +442 -0
- package/skills/sophnet-stock/src/README.md +214 -0
- package/skills/sophnet-stock/src/SKILL.md +236 -0
- package/skills/sophnet-stock/src/TODO.md +394 -0
- package/skills/sophnet-stock/src/_meta.json +6 -0
- package/skills/sophnet-stock/src/docs/ARCHITECTURE.md +408 -0
- package/skills/sophnet-stock/src/docs/CONCEPT.md +233 -0
- package/skills/sophnet-stock/src/docs/HOT_SCANNER.md +288 -0
- package/skills/sophnet-stock/src/docs/README.md +95 -0
- package/skills/sophnet-stock/src/docs/USAGE.md +465 -0
- package/skills/sophnet-stock/src/scripts/analyze_stock.py +2565 -0
- package/skills/sophnet-stock/src/scripts/dividends.py +365 -0
- package/skills/sophnet-stock/src/scripts/hot_scanner.py +582 -0
- package/skills/sophnet-stock/src/scripts/portfolio.py +548 -0
- package/skills/sophnet-stock/src/scripts/rumor_scanner.py +342 -0
- package/skills/sophnet-stock/src/scripts/test_stock_analysis.py +409 -0
- package/skills/sophnet-stock/src/scripts/watchlist.py +336 -0
- package/skills/xiaohongshu/skill.json +20 -0
- package/skills/xiaohongshu/src/SKILL.md +91 -0
- package/skills/xiaohongshu/src/_meta.json +6 -0
- package/skills/xiaohongshu/src/assets/card.html +216 -0
- package/skills/xiaohongshu/src/assets/cover.html +82 -0
- package/skills/xiaohongshu/src/assets/example.md +84 -0
- package/skills/xiaohongshu/src/assets/styles.css +318 -0
- package/skills/xiaohongshu/src/scripts/render_xhs_v2.py +737 -0
- package/skills/xiaohongshu/src/scripts/sign_server.py +158 -0
- package/skills/xiaohongshu/src/scripts/stealth.min.js +7 -0
- package/skills/xiaohongshu/src/scripts/xhs_tool.py +186 -0
- package/skills/xiaohongshu/src/workflow.py +185 -0
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Sophnet 日程提醒 HTTP API 服务。
|
|
3
|
+
|
|
4
|
+
启动(在 skills/sophnet-schedule/src 目录下):
|
|
5
|
+
uv run uvicorn server:app --host 0.0.0.0 --port 8765 --reload
|
|
6
|
+
|
|
7
|
+
认证:
|
|
8
|
+
所有接口需要在 Header 中携带 X-API-Key(值来自 .env 中 API_KEY)。
|
|
9
|
+
开发时可设置 API_KEY=dev 跳过认证(不建议生产使用)。
|
|
10
|
+
|
|
11
|
+
接口概览:
|
|
12
|
+
GET /health
|
|
13
|
+
GET /events?date=YYYY-MM-DD
|
|
14
|
+
GET /events?start=...&end=...
|
|
15
|
+
POST /events
|
|
16
|
+
DELETE /events/{event_id}
|
|
17
|
+
GET /events/conflicts?date=YYYY-MM-DD
|
|
18
|
+
GET /roc/events
|
|
19
|
+
POST /roc/events
|
|
20
|
+
PUT /roc/events/{id}
|
|
21
|
+
DELETE /roc/events/{id}
|
|
22
|
+
GET /roc/upcoming?days=30
|
|
23
|
+
GET /reminders?window=30
|
|
24
|
+
GET /tasks
|
|
25
|
+
POST /tasks/trigger/daily-plan
|
|
26
|
+
POST /tasks/sync
|
|
27
|
+
GET /daily-plan?date=YYYY-MM-DD
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import os
|
|
33
|
+
import subprocess
|
|
34
|
+
import sys
|
|
35
|
+
from datetime import datetime, timedelta
|
|
36
|
+
from pathlib import Path
|
|
37
|
+
from typing import Optional
|
|
38
|
+
|
|
39
|
+
import yaml
|
|
40
|
+
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request
|
|
41
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
42
|
+
from fastapi.responses import HTMLResponse
|
|
43
|
+
|
|
44
|
+
# ── sys.path ──────────────────────────────────────────────────────────
|
|
45
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
46
|
+
|
|
47
|
+
from config.settings import TIMEZONE, SKILL_BASE, TASK_REGISTRY_FILE
|
|
48
|
+
from gcal.client import CalendarAPIError, CalendarAuthError
|
|
49
|
+
from gcal.models import CalendarEvent
|
|
50
|
+
from services.calendar_backend import (
|
|
51
|
+
active_provider,
|
|
52
|
+
create_event as backend_create_event,
|
|
53
|
+
delete_event as backend_delete_event,
|
|
54
|
+
list_event_views,
|
|
55
|
+
sync_local_events,
|
|
56
|
+
)
|
|
57
|
+
from services.conflict_detector import ConflictPair, detect_conflicts
|
|
58
|
+
from services.time_window import get_today_window
|
|
59
|
+
from services.datetime_utils import (
|
|
60
|
+
DateTimeValidationError,
|
|
61
|
+
build_event_range,
|
|
62
|
+
current_date_str,
|
|
63
|
+
current_year,
|
|
64
|
+
local_date_label,
|
|
65
|
+
local_date_window,
|
|
66
|
+
now_local,
|
|
67
|
+
parse_iso_datetime,
|
|
68
|
+
)
|
|
69
|
+
from services.job_store import append_job_if_absent, list_job_names
|
|
70
|
+
from services.google_integration import (
|
|
71
|
+
complete_oauth_callback,
|
|
72
|
+
get_guide_payload,
|
|
73
|
+
get_last_sync_status,
|
|
74
|
+
get_status_payload,
|
|
75
|
+
start_oauth_session,
|
|
76
|
+
)
|
|
77
|
+
from services.runtime_utils import build_python_command
|
|
78
|
+
from apps.check_roc import build_year_events, upcoming_events, _load_config as _roc_config
|
|
79
|
+
|
|
80
|
+
from api.models import (
|
|
81
|
+
ConflictOut, DailyPlanResponse, EventCreateRequest, EventCreateResponse,
|
|
82
|
+
EventDeleteResponse, EventOut, EventsResponse, OkResponse,
|
|
83
|
+
GoogleGuideResponse, GoogleStartRequest, GoogleStartResponse,
|
|
84
|
+
GoogleStatusResponse, GoogleSyncResponse, GoogleSyncSummary,
|
|
85
|
+
RemindersResponse, RocEventCreateRequest, RocEventOut, RocEventUpdateRequest,
|
|
86
|
+
RocListResponse, RocUpcomingItem, RocUpcomingResponse,
|
|
87
|
+
TaskItem, TasksResponse, TaskSyncResponse,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
# ── 应用初始化 ────────────────────────────────────────────────────────
|
|
91
|
+
|
|
92
|
+
app = FastAPI(
|
|
93
|
+
title="Sophnet 日程提醒 API",
|
|
94
|
+
description="Google Calendar 日程调度 + ROC 周期事件 HTTP 接口",
|
|
95
|
+
version="1.0.0",
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
app.add_middleware(
|
|
99
|
+
CORSMiddleware,
|
|
100
|
+
allow_origins=["*"], # 生产环境请限定前端域名
|
|
101
|
+
allow_methods=["*"],
|
|
102
|
+
allow_headers=["*"],
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
_ROC_CONFIG_FILE = SKILL_BASE / "config" / "roc_events.yaml"
|
|
106
|
+
_API_KEY = os.environ.get("API_KEY", "dev")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# ── 认证 ──────────────────────────────────────────────────────────────
|
|
110
|
+
|
|
111
|
+
def _auth(x_api_key: Optional[str] = Header(None, alias="X-API-Key")) -> None:
|
|
112
|
+
if x_api_key is None or (_API_KEY != "dev" and x_api_key != _API_KEY):
|
|
113
|
+
raise HTTPException(status_code=401, detail="Invalid API key")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# ── 内部工具 ──────────────────────────────────────────────────────────
|
|
117
|
+
|
|
118
|
+
def _event_out(ev: CalendarEvent, provider: str = "", sync_state: str = "") -> EventOut:
|
|
119
|
+
return EventOut(
|
|
120
|
+
id=ev.id,
|
|
121
|
+
summary=ev.summary,
|
|
122
|
+
start=ev.start.isoformat(),
|
|
123
|
+
end=ev.end.isoformat(),
|
|
124
|
+
is_all_day=ev.is_all_day,
|
|
125
|
+
location=ev.location,
|
|
126
|
+
description=ev.description,
|
|
127
|
+
status=ev.status,
|
|
128
|
+
duration_minutes=ev.duration_minutes(),
|
|
129
|
+
provider=provider,
|
|
130
|
+
sync_state=sync_state,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _conflict_out(cp: ConflictPair) -> ConflictOut:
|
|
135
|
+
ta = f"{cp.a.start.strftime('%H:%M')}–{cp.a.end.strftime('%H:%M')}"
|
|
136
|
+
tb = f"{cp.b.start.strftime('%H:%M')}–{cp.b.end.strftime('%H:%M')}"
|
|
137
|
+
gap = int((cp.b.start - cp.a.end).total_seconds() / 60) if cp.is_tight else 0
|
|
138
|
+
return ConflictOut(
|
|
139
|
+
type="tight" if cp.is_tight else "conflict",
|
|
140
|
+
event_a=cp.a.summary,
|
|
141
|
+
event_b=cp.b.summary,
|
|
142
|
+
time_a=ta,
|
|
143
|
+
time_b=tb,
|
|
144
|
+
overlap_minutes=cp.overlap_minutes,
|
|
145
|
+
gap_minutes=gap,
|
|
146
|
+
text=cp.format_text(),
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _parse_date_window(date: str) -> tuple[datetime, datetime]:
|
|
151
|
+
"""将 YYYY-MM-DD 转为业务时区当日区间。"""
|
|
152
|
+
try:
|
|
153
|
+
return local_date_window(date, TIMEZONE)
|
|
154
|
+
except DateTimeValidationError as e:
|
|
155
|
+
raise HTTPException(400, str(e))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _read_roc_yaml() -> dict:
|
|
159
|
+
with open(_ROC_CONFIG_FILE, encoding="utf-8") as f:
|
|
160
|
+
return yaml.safe_load(f)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _write_roc_yaml(data: dict) -> None:
|
|
164
|
+
with open(_ROC_CONFIG_FILE, "w", encoding="utf-8") as f:
|
|
165
|
+
yaml.dump(data, f, allow_unicode=True, sort_keys=False)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _callback_url(request: Request) -> str:
|
|
169
|
+
return str(request.base_url).rstrip("/") + "/integrations/google/callback"
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _callback_html(ok: bool, message: str) -> HTMLResponse:
|
|
173
|
+
title = "授权成功" if ok else "授权失败"
|
|
174
|
+
color = "#1b7f3b" if ok else "#b42318"
|
|
175
|
+
body = (
|
|
176
|
+
"<!doctype html><html><head><meta charset='utf-8'>"
|
|
177
|
+
f"<title>{title}</title></head>"
|
|
178
|
+
"<body style='font-family:sans-serif;padding:32px'>"
|
|
179
|
+
f"<h2 style='color:{color}'>{title}</h2>"
|
|
180
|
+
f"<p>{message}</p>"
|
|
181
|
+
"<p>现在可以关闭这个窗口。</p>"
|
|
182
|
+
"</body></html>"
|
|
183
|
+
)
|
|
184
|
+
return HTMLResponse(body, status_code=200 if ok else 400)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# ── 健康检查 ──────────────────────────────────────────────────────────
|
|
188
|
+
|
|
189
|
+
@app.get("/health", tags=["系统"])
|
|
190
|
+
def health() -> dict:
|
|
191
|
+
return {"ok": True, "service": "sophnet-schedule", "version": "1.0.0"}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# ── 日历事件 ──────────────────────────────────────────────────────────
|
|
195
|
+
|
|
196
|
+
@app.get("/events", response_model=EventsResponse, tags=["日历"])
|
|
197
|
+
def list_events(
|
|
198
|
+
date: Optional[str] = Query(None, description="YYYY-MM-DD,查询当日"),
|
|
199
|
+
start: Optional[str] = Query(None, description="ISO 8601 开始时间"),
|
|
200
|
+
end: Optional[str] = Query(None, description="ISO 8601 结束时间"),
|
|
201
|
+
_: None = Depends(_auth),
|
|
202
|
+
) -> EventsResponse:
|
|
203
|
+
if date:
|
|
204
|
+
t_start, t_end = _parse_date_window(date)
|
|
205
|
+
label = date
|
|
206
|
+
elif start and end:
|
|
207
|
+
try:
|
|
208
|
+
t_start = parse_iso_datetime(start, TIMEZONE)
|
|
209
|
+
t_end = parse_iso_datetime(end, TIMEZONE)
|
|
210
|
+
except DateTimeValidationError as e:
|
|
211
|
+
raise HTTPException(400, str(e))
|
|
212
|
+
if t_end <= t_start:
|
|
213
|
+
raise HTTPException(400, "end 必须晚于 start")
|
|
214
|
+
label = local_date_label(t_start, TIMEZONE)
|
|
215
|
+
else:
|
|
216
|
+
t_start, t_end = get_today_window(TIMEZONE)
|
|
217
|
+
label = current_date_str(TIMEZONE)
|
|
218
|
+
|
|
219
|
+
try:
|
|
220
|
+
views = list_event_views(t_start, t_end)
|
|
221
|
+
except (CalendarAuthError, CalendarAPIError) as e:
|
|
222
|
+
raise HTTPException(502, str(e))
|
|
223
|
+
|
|
224
|
+
events = [item.event for item in views]
|
|
225
|
+
conflicts = detect_conflicts(events)
|
|
226
|
+
provider = active_provider()
|
|
227
|
+
return EventsResponse(
|
|
228
|
+
date=label,
|
|
229
|
+
events=[_event_out(item.event, provider=item.provider, sync_state=item.sync_state) for item in views],
|
|
230
|
+
conflicts=[_conflict_out(c) for c in conflicts],
|
|
231
|
+
provider=provider,
|
|
232
|
+
active_mode=provider,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@app.post("/events", response_model=EventCreateResponse, tags=["日历"])
|
|
237
|
+
def create_event(
|
|
238
|
+
body: EventCreateRequest,
|
|
239
|
+
_: None = Depends(_auth),
|
|
240
|
+
) -> EventCreateResponse:
|
|
241
|
+
try:
|
|
242
|
+
start_dt, end_dt = build_event_range(
|
|
243
|
+
body.date,
|
|
244
|
+
body.start,
|
|
245
|
+
body.end,
|
|
246
|
+
body.duration,
|
|
247
|
+
TIMEZONE,
|
|
248
|
+
)
|
|
249
|
+
except DateTimeValidationError as e:
|
|
250
|
+
raise HTTPException(400, str(e))
|
|
251
|
+
|
|
252
|
+
try:
|
|
253
|
+
created = backend_create_event(
|
|
254
|
+
summary=body.summary,
|
|
255
|
+
start=start_dt,
|
|
256
|
+
end=end_dt,
|
|
257
|
+
location=body.location,
|
|
258
|
+
description=body.description,
|
|
259
|
+
remind_minutes=body.remind,
|
|
260
|
+
)
|
|
261
|
+
except (CalendarAuthError, CalendarAPIError) as e:
|
|
262
|
+
return EventCreateResponse(ok=False, error=str(e), provider=active_provider())
|
|
263
|
+
|
|
264
|
+
reminder_registered = False
|
|
265
|
+
if body.remind > 0 and created.event_id:
|
|
266
|
+
try:
|
|
267
|
+
_register_one_off_reminder(body, start_dt, created.event_id)
|
|
268
|
+
reminder_registered = True
|
|
269
|
+
except Exception:
|
|
270
|
+
pass # 提醒注册失败不影响事件创建结果
|
|
271
|
+
|
|
272
|
+
return EventCreateResponse(
|
|
273
|
+
ok=True,
|
|
274
|
+
event_id=created.event_id,
|
|
275
|
+
summary=body.summary,
|
|
276
|
+
start=start_dt.isoformat(),
|
|
277
|
+
end=end_dt.isoformat(),
|
|
278
|
+
reminder_registered=reminder_registered,
|
|
279
|
+
provider=created.provider,
|
|
280
|
+
sync_state=created.sync_state,
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
@app.delete("/events/{event_id}", response_model=EventDeleteResponse, tags=["日历"])
|
|
285
|
+
def delete_event(
|
|
286
|
+
event_id: str,
|
|
287
|
+
_: None = Depends(_auth),
|
|
288
|
+
) -> EventDeleteResponse:
|
|
289
|
+
try:
|
|
290
|
+
deleted = backend_delete_event(event_id)
|
|
291
|
+
if not deleted:
|
|
292
|
+
return EventDeleteResponse(ok=False, event_id=event_id, error="事件不存在")
|
|
293
|
+
return EventDeleteResponse(ok=True, event_id=event_id)
|
|
294
|
+
except (CalendarAuthError, CalendarAPIError) as e:
|
|
295
|
+
return EventDeleteResponse(ok=False, event_id=event_id, error=str(e))
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
@app.get("/events/conflicts", response_model=EventsResponse, tags=["日历"])
|
|
299
|
+
def get_conflicts(
|
|
300
|
+
date: Optional[str] = Query(None, description="YYYY-MM-DD,默认今日"),
|
|
301
|
+
_: None = Depends(_auth),
|
|
302
|
+
) -> EventsResponse:
|
|
303
|
+
return list_events(date=date, start=None, end=None, _=_)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
# ── ROC 周期事件 ──────────────────────────────────────────────────────
|
|
307
|
+
|
|
308
|
+
@app.get("/roc/events", response_model=RocListResponse, tags=["ROC"])
|
|
309
|
+
def roc_list(
|
|
310
|
+
year: Optional[int] = Query(None, description="年份,默认今年"),
|
|
311
|
+
_: None = Depends(_auth),
|
|
312
|
+
) -> RocListResponse:
|
|
313
|
+
y = year or current_year(TIMEZONE)
|
|
314
|
+
cfg = _read_roc_yaml()
|
|
315
|
+
year_events = build_year_events(y, cfg)
|
|
316
|
+
|
|
317
|
+
ev_map = {e["id"]: e for e in year_events}
|
|
318
|
+
result = []
|
|
319
|
+
for raw in cfg.get("events", []):
|
|
320
|
+
ye = ev_map.get(raw["id"], {})
|
|
321
|
+
result.append(RocEventOut(
|
|
322
|
+
id=raw["id"],
|
|
323
|
+
name=raw["name"],
|
|
324
|
+
rule=raw["rule"],
|
|
325
|
+
reminder_time=raw.get("reminder_time", "09:00"),
|
|
326
|
+
lead_days=int(raw.get("lead_days", 0)),
|
|
327
|
+
description=raw.get("description", ""),
|
|
328
|
+
event_date=ye.get("event_date"),
|
|
329
|
+
reminder_date=ye.get("reminder_date"),
|
|
330
|
+
))
|
|
331
|
+
return RocListResponse(year=y, events=result)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
@app.post("/roc/events", response_model=OkResponse, tags=["ROC"])
|
|
335
|
+
def roc_create(
|
|
336
|
+
body: RocEventCreateRequest,
|
|
337
|
+
_: None = Depends(_auth),
|
|
338
|
+
) -> OkResponse:
|
|
339
|
+
cfg = _read_roc_yaml()
|
|
340
|
+
events: list = cfg.get("events", [])
|
|
341
|
+
if any(e["id"] == body.id for e in events):
|
|
342
|
+
raise HTTPException(409, f"ROC 事件 ID 已存在:{body.id}")
|
|
343
|
+
events.append({
|
|
344
|
+
"id": body.id,
|
|
345
|
+
"name": body.name,
|
|
346
|
+
"rule": body.rule,
|
|
347
|
+
"reminder_time": body.reminder_time,
|
|
348
|
+
"lead_days": body.lead_days,
|
|
349
|
+
"description": body.description,
|
|
350
|
+
})
|
|
351
|
+
cfg["events"] = events
|
|
352
|
+
_write_roc_yaml(cfg)
|
|
353
|
+
return OkResponse(id=body.id, message=f"已添加 ROC 事件:{body.name}")
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
@app.put("/roc/events/{roc_id}", response_model=OkResponse, tags=["ROC"])
|
|
357
|
+
def roc_update(
|
|
358
|
+
roc_id: str,
|
|
359
|
+
body: RocEventUpdateRequest,
|
|
360
|
+
_: None = Depends(_auth),
|
|
361
|
+
) -> OkResponse:
|
|
362
|
+
cfg = _read_roc_yaml()
|
|
363
|
+
events: list = cfg.get("events", [])
|
|
364
|
+
for ev in events:
|
|
365
|
+
if ev["id"] == roc_id:
|
|
366
|
+
if body.name is not None: ev["name"] = body.name
|
|
367
|
+
if body.rule is not None: ev["rule"] = body.rule
|
|
368
|
+
if body.reminder_time is not None: ev["reminder_time"] = body.reminder_time
|
|
369
|
+
if body.lead_days is not None: ev["lead_days"] = body.lead_days
|
|
370
|
+
if body.description is not None: ev["description"] = body.description
|
|
371
|
+
cfg["events"] = events
|
|
372
|
+
_write_roc_yaml(cfg)
|
|
373
|
+
return OkResponse(message=f"已更新 ROC 事件:{roc_id}")
|
|
374
|
+
raise HTTPException(404, f"ROC 事件不存在:{roc_id}")
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
@app.delete("/roc/events/{roc_id}", response_model=OkResponse, tags=["ROC"])
|
|
378
|
+
def roc_delete(
|
|
379
|
+
roc_id: str,
|
|
380
|
+
_: None = Depends(_auth),
|
|
381
|
+
) -> OkResponse:
|
|
382
|
+
cfg = _read_roc_yaml()
|
|
383
|
+
events: list = cfg.get("events", [])
|
|
384
|
+
new_events = [e for e in events if e["id"] != roc_id]
|
|
385
|
+
if len(new_events) == len(events):
|
|
386
|
+
raise HTTPException(404, f"ROC 事件不存在:{roc_id}")
|
|
387
|
+
cfg["events"] = new_events
|
|
388
|
+
_write_roc_yaml(cfg)
|
|
389
|
+
return OkResponse(message=f"已删除 ROC 事件:{roc_id}")
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
@app.get("/roc/upcoming", response_model=RocUpcomingResponse, tags=["ROC"])
|
|
393
|
+
def roc_upcoming(
|
|
394
|
+
days: int = Query(30, description="查询未来 N 天"),
|
|
395
|
+
_: None = Depends(_auth),
|
|
396
|
+
) -> RocUpcomingResponse:
|
|
397
|
+
today = current_date_str(TIMEZONE)
|
|
398
|
+
year = int(today[:4])
|
|
399
|
+
cfg = _read_roc_yaml()
|
|
400
|
+
year_events = build_year_events(year, cfg)
|
|
401
|
+
ups = upcoming_events(year_events, today, days)
|
|
402
|
+
return RocUpcomingResponse(
|
|
403
|
+
today=today,
|
|
404
|
+
days=days,
|
|
405
|
+
upcoming=[RocUpcomingItem(**{
|
|
406
|
+
"id": u["id"],
|
|
407
|
+
"name": u["name"],
|
|
408
|
+
"event_date": u["event_date"],
|
|
409
|
+
"reminder_date": u["reminder_date"],
|
|
410
|
+
"days_until_reminder": u["days_until_reminder"],
|
|
411
|
+
"days_until_event": u["days_until_event"],
|
|
412
|
+
"description": u.get("description", ""),
|
|
413
|
+
}) for u in ups],
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
# ── 提醒 ──────────────────────────────────────────────────────────────
|
|
418
|
+
|
|
419
|
+
@app.get("/reminders", response_model=RemindersResponse, tags=["提醒"])
|
|
420
|
+
def get_reminders(
|
|
421
|
+
window: int = Query(30, description="时间窗口(分钟),默认 30"),
|
|
422
|
+
_: None = Depends(_auth),
|
|
423
|
+
) -> RemindersResponse:
|
|
424
|
+
result = subprocess.run(
|
|
425
|
+
build_python_command(SKILL_BASE / "apps" / "check_reminders.py", "--window", str(window), "--json"),
|
|
426
|
+
capture_output=True, text=True, cwd=str(SKILL_BASE),
|
|
427
|
+
)
|
|
428
|
+
if result.returncode != 0:
|
|
429
|
+
detail = result.stderr.strip() or result.stdout.strip() or "检查提醒失败"
|
|
430
|
+
raise HTTPException(502, detail[:300])
|
|
431
|
+
|
|
432
|
+
import json as _json
|
|
433
|
+
try:
|
|
434
|
+
data = _json.loads(result.stdout)
|
|
435
|
+
except Exception as e:
|
|
436
|
+
raise HTTPException(502, f"提醒结果解析失败:{e}")
|
|
437
|
+
|
|
438
|
+
if not data.get("ok", True):
|
|
439
|
+
raise HTTPException(502, data.get("error", "提醒检查失败"))
|
|
440
|
+
|
|
441
|
+
provider = active_provider()
|
|
442
|
+
return RemindersResponse(
|
|
443
|
+
window_minutes=window,
|
|
444
|
+
reminders=data.get("reminders", []),
|
|
445
|
+
provider=provider,
|
|
446
|
+
active_mode=provider,
|
|
447
|
+
)
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
# ── Cron 任务 ─────────────────────────────────────────────────────────
|
|
451
|
+
|
|
452
|
+
@app.get("/tasks", response_model=TasksResponse, tags=["任务"])
|
|
453
|
+
def list_tasks(_: None = Depends(_auth)) -> TasksResponse:
|
|
454
|
+
with open(TASK_REGISTRY_FILE, encoding="utf-8") as f:
|
|
455
|
+
cfg = yaml.safe_load(f)
|
|
456
|
+
tasks = []
|
|
457
|
+
for t in cfg.get("tasks", []):
|
|
458
|
+
sch = t.get("schedule", {})
|
|
459
|
+
tasks.append(TaskItem(
|
|
460
|
+
name=t["name"],
|
|
461
|
+
description=t.get("description", ""),
|
|
462
|
+
schedule_kind=sch.get("kind", ""),
|
|
463
|
+
schedule_expr=sch.get("time") or sch.get("expr") or "",
|
|
464
|
+
type=t.get("type", ""),
|
|
465
|
+
))
|
|
466
|
+
return TasksResponse(tasks=tasks)
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
@app.post("/tasks/trigger/daily-plan", response_model=OkResponse, tags=["任务"])
|
|
470
|
+
def trigger_daily_plan(
|
|
471
|
+
dry_run: bool = Query(False),
|
|
472
|
+
_: None = Depends(_auth),
|
|
473
|
+
) -> OkResponse:
|
|
474
|
+
cmd = build_python_command(SKILL_BASE / "apps" / "generate_daily_plan.py")
|
|
475
|
+
if dry_run:
|
|
476
|
+
cmd.append("--dry-run")
|
|
477
|
+
result = subprocess.run(cmd, capture_output=True, text=True, cwd=str(SKILL_BASE))
|
|
478
|
+
if result.returncode != 0:
|
|
479
|
+
raise HTTPException(500, f"生成失败:{result.stderr[:200]}")
|
|
480
|
+
return OkResponse(message="今日计划已生成" + ("(dry-run)" if dry_run else ",提醒已注册"))
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
@app.post("/tasks/sync", response_model=TaskSyncResponse, tags=["任务"])
|
|
484
|
+
def sync_tasks(
|
|
485
|
+
dry_run: bool = Query(False),
|
|
486
|
+
_: None = Depends(_auth),
|
|
487
|
+
) -> TaskSyncResponse:
|
|
488
|
+
"""
|
|
489
|
+
重读 task_registry.yaml 并立即同步到 jobs.json。
|
|
490
|
+
|
|
491
|
+
- 已存在同名任务:跳过(不覆盖)
|
|
492
|
+
- 新任务:写入 jobs.json,当天生效
|
|
493
|
+
- dry_run=true:只计算差异,不写入
|
|
494
|
+
"""
|
|
495
|
+
import json as _json
|
|
496
|
+
from apps.register_tasks import load_fixed_tasks, build_cron_job_from_task
|
|
497
|
+
|
|
498
|
+
today = now_local(TIMEZONE)
|
|
499
|
+
|
|
500
|
+
try:
|
|
501
|
+
tasks = load_fixed_tasks(provider=active_provider())
|
|
502
|
+
except Exception as e:
|
|
503
|
+
raise HTTPException(500, f"读取 task_registry.yaml 失败:{e}")
|
|
504
|
+
|
|
505
|
+
try:
|
|
506
|
+
existing = list_job_names()
|
|
507
|
+
except Exception as e:
|
|
508
|
+
raise HTTPException(500, f"读取 jobs.json 失败:{e}")
|
|
509
|
+
added: list = []
|
|
510
|
+
skipped: list = []
|
|
511
|
+
errors: list = []
|
|
512
|
+
|
|
513
|
+
for task in tasks:
|
|
514
|
+
name = task.get("name", "未命名")
|
|
515
|
+
try:
|
|
516
|
+
payload = build_cron_job_from_task(task, today)
|
|
517
|
+
if payload is None:
|
|
518
|
+
errors.append(f"{name}:配置不完整,跳过")
|
|
519
|
+
continue
|
|
520
|
+
if dry_run and name in existing:
|
|
521
|
+
skipped.append(name)
|
|
522
|
+
continue
|
|
523
|
+
if dry_run:
|
|
524
|
+
existing.add(name)
|
|
525
|
+
added.append(name)
|
|
526
|
+
continue
|
|
527
|
+
if append_job_if_absent(payload):
|
|
528
|
+
existing.add(name)
|
|
529
|
+
added.append(name)
|
|
530
|
+
else:
|
|
531
|
+
skipped.append(name)
|
|
532
|
+
except Exception as e:
|
|
533
|
+
errors.append(f"{name}:{e}")
|
|
534
|
+
|
|
535
|
+
suffix = "(dry-run,未写入)" if dry_run else ""
|
|
536
|
+
return TaskSyncResponse(
|
|
537
|
+
ok=True,
|
|
538
|
+
dry_run=dry_run,
|
|
539
|
+
added=added,
|
|
540
|
+
skipped=skipped,
|
|
541
|
+
errors=errors,
|
|
542
|
+
message=f"同步完成{suffix}:新增 {len(added)} 个,跳过 {len(skipped)} 个,失败 {len(errors)} 个",
|
|
543
|
+
)
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
# ── 日报 ──────────────────────────────────────────────────────────────
|
|
547
|
+
|
|
548
|
+
@app.get("/daily-plan", response_model=DailyPlanResponse, tags=["日报"])
|
|
549
|
+
def get_daily_plan(
|
|
550
|
+
date: Optional[str] = Query(None, description="YYYY-MM-DD,默认今日"),
|
|
551
|
+
_: None = Depends(_auth),
|
|
552
|
+
) -> DailyPlanResponse:
|
|
553
|
+
label = date or current_date_str(TIMEZONE)
|
|
554
|
+
t_start, t_end = _parse_date_window(label)
|
|
555
|
+
|
|
556
|
+
try:
|
|
557
|
+
views = list_event_views(t_start, t_end)
|
|
558
|
+
except (CalendarAuthError, CalendarAPIError) as e:
|
|
559
|
+
raise HTTPException(502, str(e))
|
|
560
|
+
|
|
561
|
+
events = [item.event for item in views]
|
|
562
|
+
conflicts = detect_conflicts(events)
|
|
563
|
+
|
|
564
|
+
# 尝试读取已生成的日报 Markdown
|
|
565
|
+
md_path = SKILL_BASE / "daily" / f"cron-{label.replace('-', '')}.md"
|
|
566
|
+
markdown = md_path.read_text(encoding="utf-8") if md_path.exists() else ""
|
|
567
|
+
|
|
568
|
+
return DailyPlanResponse(
|
|
569
|
+
date=label,
|
|
570
|
+
events=[_event_out(item.event, provider=item.provider, sync_state=item.sync_state) for item in views],
|
|
571
|
+
conflicts=[_conflict_out(c) for c in conflicts],
|
|
572
|
+
reminders_registered=0, # 只读接口,不注册
|
|
573
|
+
markdown=markdown,
|
|
574
|
+
provider=active_provider(),
|
|
575
|
+
)
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
# ── Google 接入 ──────────────────────────────────────────────────────
|
|
579
|
+
|
|
580
|
+
@app.get("/integrations/google/status", response_model=GoogleStatusResponse, tags=["集成"])
|
|
581
|
+
def google_status(_: None = Depends(_auth)) -> GoogleStatusResponse:
|
|
582
|
+
return GoogleStatusResponse(**get_status_payload())
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
@app.get("/integrations/google/guide", response_model=GoogleGuideResponse, tags=["集成"])
|
|
586
|
+
def google_guide(
|
|
587
|
+
request: Request,
|
|
588
|
+
_: None = Depends(_auth),
|
|
589
|
+
) -> GoogleGuideResponse:
|
|
590
|
+
return GoogleGuideResponse(**get_guide_payload(_callback_url(request)))
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
@app.post("/integrations/google/start", response_model=GoogleStartResponse, tags=["集成"])
|
|
594
|
+
def google_start(
|
|
595
|
+
body: GoogleStartRequest,
|
|
596
|
+
request: Request,
|
|
597
|
+
_: None = Depends(_auth),
|
|
598
|
+
) -> GoogleStartResponse:
|
|
599
|
+
result = start_oauth_session(
|
|
600
|
+
client_id=body.client_id,
|
|
601
|
+
client_secret=body.client_secret,
|
|
602
|
+
redirect_uri=_callback_url(request),
|
|
603
|
+
)
|
|
604
|
+
return GoogleStartResponse(**result)
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
@app.get("/integrations/google/callback", response_class=HTMLResponse, tags=["集成"])
|
|
608
|
+
def google_callback(
|
|
609
|
+
state: str,
|
|
610
|
+
code: Optional[str] = Query(None),
|
|
611
|
+
error: Optional[str] = Query(None),
|
|
612
|
+
error_description: Optional[str] = Query(None),
|
|
613
|
+
) -> HTMLResponse:
|
|
614
|
+
try:
|
|
615
|
+
complete_oauth_callback(state, code, error, error_description)
|
|
616
|
+
return _callback_html(True, "Google 授权成功,已保存凭据,下一步可执行首次同步。")
|
|
617
|
+
except CalendarAuthError as e:
|
|
618
|
+
return _callback_html(False, str(e))
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
@app.post("/integrations/google/sync", response_model=GoogleSyncResponse, tags=["集成"])
|
|
622
|
+
def google_sync(_: None = Depends(_auth)) -> GoogleSyncResponse:
|
|
623
|
+
try:
|
|
624
|
+
summary = sync_local_events()
|
|
625
|
+
except (CalendarAuthError, CalendarAPIError) as e:
|
|
626
|
+
raise HTTPException(502, str(e))
|
|
627
|
+
|
|
628
|
+
status = get_status_payload()
|
|
629
|
+
return GoogleSyncResponse(
|
|
630
|
+
active_mode=status["active_mode"],
|
|
631
|
+
google_state=status["google_state"],
|
|
632
|
+
summary=GoogleSyncSummary(**summary),
|
|
633
|
+
)
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
@app.get("/integrations/google/sync-status", response_model=GoogleSyncSummary, tags=["集成"])
|
|
637
|
+
def google_sync_status(_: None = Depends(_auth)) -> GoogleSyncSummary:
|
|
638
|
+
return GoogleSyncSummary(**get_last_sync_status())
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
# ── 内部:提醒注册 ────────────────────────────────────────────────────
|
|
642
|
+
|
|
643
|
+
def _register_one_off_reminder(
|
|
644
|
+
body: EventCreateRequest,
|
|
645
|
+
start_dt: datetime,
|
|
646
|
+
event_id: str,
|
|
647
|
+
) -> None:
|
|
648
|
+
"""直接用 task_builder 注册提醒 cron job,不再调用 add_event.py(避免重复创建事件)。"""
|
|
649
|
+
from datetime import timezone as _tz
|
|
650
|
+
from services.task_builder import build_reminder_task, build_reminder_task_name
|
|
651
|
+
from compat import make_aware
|
|
652
|
+
|
|
653
|
+
start_aware = make_aware(start_dt, TIMEZONE)
|
|
654
|
+
remind_at_utc = (start_aware - timedelta(minutes=body.remind)).astimezone(_tz.utc)
|
|
655
|
+
name = build_reminder_task_name(body.summary, start_aware, event_id)
|
|
656
|
+
payload = build_reminder_task(
|
|
657
|
+
name=name,
|
|
658
|
+
remind_at_utc=remind_at_utc,
|
|
659
|
+
message=(
|
|
660
|
+
f"⏰ **{body.summary}** 将在 {body.remind} 分钟后开始\n"
|
|
661
|
+
f"🕐 {start_dt.strftime('%H:%M')}"
|
|
662
|
+
+ (f" 📍 {body.location}" if body.location else "")
|
|
663
|
+
),
|
|
664
|
+
)
|
|
665
|
+
|
|
666
|
+
try:
|
|
667
|
+
append_job_if_absent(payload)
|
|
668
|
+
except Exception:
|
|
669
|
+
pass # jobs.json 不存在时静默忽略
|
|
File without changes
|