Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f015b72ad8 | ||
|
|
bb07d320f2 |
83
app.py
83
app.py
@@ -225,6 +225,89 @@ def api_reorder_wishes():
|
|||||||
return jsonify({'ok': True})
|
return jsonify({'ok': True})
|
||||||
|
|
||||||
|
|
||||||
|
# ── 日历同步 API ────────────────────────────
|
||||||
|
|
||||||
|
CALENDAR_CACHE = os.path.join(os.path.expanduser('~'), '.workbuddy', 'data', 'ziwei-power', 'calendar_cache.json')
|
||||||
|
DING_MCP_URL = 'https://mcp-gw.dingtalk.com/server/95959163f85d8b58a167f65cd8bd3d22690b16c75ebacd0fa095016396a10e0d?key=0993e4d4e44c50ea25a0db840cc5815e'
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_dingtalk_events(date_str):
|
||||||
|
"""调用钉钉 MCP 实时查询指定日期的日程"""
|
||||||
|
import json as _json, urllib.request as _ur
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
tz = timezone(timedelta(hours=8))
|
||||||
|
try:
|
||||||
|
d = datetime.strptime(date_str, '%Y-%m-%d').replace(tzinfo=tz)
|
||||||
|
except ValueError:
|
||||||
|
return []
|
||||||
|
start_ts = int(d.replace(hour=0, minute=0, second=0).timestamp() * 1000)
|
||||||
|
end_ts = int(d.replace(hour=23, minute=59, second=59).timestamp() * 1000)
|
||||||
|
body = _json.dumps({
|
||||||
|
'jsonrpc': '2.0', 'method': 'tools/call', 'id': 1,
|
||||||
|
'params': {'name': 'list_calendar_events', 'arguments': {
|
||||||
|
'calendarId': 'primary', 'startTime': start_ts, 'endTime': end_ts, 'limit': 20
|
||||||
|
}}
|
||||||
|
}).encode('utf-8')
|
||||||
|
req = _ur.Request(DING_MCP_URL, data=body, headers={
|
||||||
|
'Content-Type': 'application/json', 'Accept': 'application/json'
|
||||||
|
})
|
||||||
|
try:
|
||||||
|
with _ur.urlopen(req, timeout=10) as resp:
|
||||||
|
data = _json.loads(resp.read())
|
||||||
|
events = data.get('result', {}).get('structuredContent', {}).get('result', {}).get('events', [])
|
||||||
|
except Exception:
|
||||||
|
return None # 网络错误返回 None,调用方回退缓存
|
||||||
|
results = []
|
||||||
|
for e in events:
|
||||||
|
summary = (e.get('summary') or '').strip()
|
||||||
|
if not summary:
|
||||||
|
continue
|
||||||
|
start = e.get('start', {}).get('dateTime', '')
|
||||||
|
end = e.get('end', {}).get('dateTime', '')
|
||||||
|
time_str = ''
|
||||||
|
if start and end:
|
||||||
|
time_str = start[11:16] + '-' + end[11:16]
|
||||||
|
results.append({
|
||||||
|
'date': date_str, 'summary': summary,
|
||||||
|
'time': time_str, 'location': e.get('location') or ''
|
||||||
|
})
|
||||||
|
# 写入缓存
|
||||||
|
try:
|
||||||
|
all_cached = []
|
||||||
|
try:
|
||||||
|
with open(CALENDAR_CACHE, 'r') as f:
|
||||||
|
all_cached = _json.load(f)
|
||||||
|
except (FileNotFoundError, _json.JSONDecodeError):
|
||||||
|
pass
|
||||||
|
# 替换同一天的旧缓存
|
||||||
|
all_cached = [c for c in all_cached if c.get('date') != date_str] + results
|
||||||
|
with open(CALENDAR_CACHE, 'w') as f:
|
||||||
|
_json.dump(all_cached, f, ensure_ascii=False, indent=2)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/api/calendar-sync', methods=['GET'])
|
||||||
|
@login_required
|
||||||
|
def api_calendar_sync():
|
||||||
|
import json as _json
|
||||||
|
date = request.args.get('date', '')
|
||||||
|
if not date:
|
||||||
|
return jsonify({'ok': False, 'error': '缺少 date 参数'}), 400
|
||||||
|
# 优先实时查询钉钉 MCP
|
||||||
|
events = _fetch_dingtalk_events(date)
|
||||||
|
if events is None:
|
||||||
|
# MCP 不可用,回退缓存
|
||||||
|
try:
|
||||||
|
with open(CALENDAR_CACHE, 'r') as f:
|
||||||
|
all_cached = _json.load(f)
|
||||||
|
events = [e for e in all_cached if e.get('date') == date]
|
||||||
|
except (FileNotFoundError, _json.JSONDecodeError):
|
||||||
|
events = []
|
||||||
|
return jsonify({'ok': True, 'data': events})
|
||||||
|
|
||||||
|
|
||||||
# ── 启动 ──────────────────────────────────────────────
|
# ── 启动 ──────────────────────────────────────────────
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
@@ -362,6 +362,45 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── 日历同步 ── */
|
||||||
|
|
||||||
|
window.syncCalendar = function() {
|
||||||
|
var date = document.getElementById('check-date').value;
|
||||||
|
var btn = document.querySelector('.btn-cal-sync');
|
||||||
|
if (btn) { btn.style.opacity = '0.5'; btn.disabled = true; }
|
||||||
|
fetch('/api/calendar-sync?date=' + encodeURIComponent(date))
|
||||||
|
.then(function(r){ return r.json(); })
|
||||||
|
.then(function(res){
|
||||||
|
if (btn) { btn.style.opacity = '1'; btn.disabled = false; }
|
||||||
|
if (!res.ok) { showToast(res.error || '同步失败', 'error'); return; }
|
||||||
|
var events = res.data || [];
|
||||||
|
if (events.length === 0) { showToast('今日无日程', 'info'); return; }
|
||||||
|
var added = 0;
|
||||||
|
events.forEach(function(e) {
|
||||||
|
var text = '【' + e.time + '】' + e.summary;
|
||||||
|
if (e.location) text += ' @' + e.location;
|
||||||
|
var existing = document.querySelectorAll('#morning-list input[type="text"]');
|
||||||
|
var already = false;
|
||||||
|
existing.forEach(function(inp){ if (inp.value.indexOf(e.summary) >= 0) already = true; });
|
||||||
|
if (already) return;
|
||||||
|
var count = document.querySelectorAll('#morning-list .item-row').length;
|
||||||
|
if (count >= 3) return;
|
||||||
|
addMorningRow(text);
|
||||||
|
added++;
|
||||||
|
});
|
||||||
|
if (added > 0) {
|
||||||
|
showToast('已同步 ' + added + ' 条日程', 'info');
|
||||||
|
triggerAutoSave();
|
||||||
|
} else {
|
||||||
|
showToast('日程已存在或已满', 'info');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(function(){
|
||||||
|
if (btn) { btn.style.opacity = '1'; btn.disabled = false; }
|
||||||
|
showToast('同步失败', 'error');
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
window.addMorning = function() {
|
window.addMorning = function() {
|
||||||
var count = document.querySelectorAll('#morning-list .item-row').length;
|
var count = document.querySelectorAll('#morning-list .item-row').length;
|
||||||
if (count >= 3) { showToast('最多 3 条立志', 'error'); return; }
|
if (count >= 3) { showToast('最多 3 条立志', 'error'); return; }
|
||||||
|
|||||||
@@ -535,6 +535,26 @@ body {
|
|||||||
color: var(--primary);
|
color: var(--primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 日历同步按钮 */
|
||||||
|
.btn-cal-sync {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-muted);
|
||||||
|
border-radius: 6px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.btn-cal-sync:hover {
|
||||||
|
background: var(--success-light);
|
||||||
|
color: var(--success);
|
||||||
|
}
|
||||||
|
|
||||||
/* 编辑模式下才显示的元素 */
|
/* 编辑模式下才显示的元素 */
|
||||||
.edit-only { display: none; }
|
.edit-only { display: none; }
|
||||||
.card.editing .edit-only { display: flex; }
|
.card.editing .edit-only { display: flex; }
|
||||||
|
|||||||
@@ -113,6 +113,9 @@
|
|||||||
<svg class="icon-h2"><use href="#icon-sun"/></svg>
|
<svg class="icon-h2"><use href="#icon-sun"/></svg>
|
||||||
<h3>早间立志</h3>
|
<h3>早间立志</h3>
|
||||||
</div>
|
</div>
|
||||||
|
<button class="btn-cal-sync" onclick="syncCalendar()" title="同步钉钉日历">
|
||||||
|
<svg class="icon-sm"><use href="#icon-calendar"/></svg>
|
||||||
|
</button>
|
||||||
<button class="btn-edit-toggle" onclick="toggleEditMode(this)" title="编辑">
|
<button class="btn-edit-toggle" onclick="toggleEditMode(this)" title="编辑">
|
||||||
<svg class="icon-sm"><use href="#icon-pencil"/></svg>
|
<svg class="icon-sm"><use href="#icon-pencil"/></svg>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
Reference in New Issue
Block a user