以下是由AI根据历史对话总结生成

Anytype ↔ CalDAV 双向无感同步脚本 这是一个 Python 脚本,实现了 Anytype 本地笔记与 CalDAV 日历(如 iCloud, Nextcloud, 群晖 Calendar 等)之间的双向同步。

✨ 功能特性 双向同步:任意一端修改(新增/编辑/删除),自动同步到另一端。

云端记忆:同步历史存储在 CalDAV 服务端,无需本地文件,支持多设备(Win/Mac)无缝切换运行。

智能链接:自动在日历备注中生成 https:// 跳转链接,点击即可唤起 Anytype 并打开对应笔记。

循环支持:完美支持每日、每周、每月、每年及自定义间隔(如每2天)的循环日程。

防冲突:智能对比最后修改时间,防止数据回滚。

⚙️ 配置指南 在使用脚本前,请确保获取以下关键信息:

Anytype API 凭证:

进入 Space Settings > Integrations > Manage Keys 创建 API Key。

获取 ID (Space/Type/Relation):

开启 Anytype 的 Show ID 功能(通常在开发者设置中)。

右键点击你的空间、对象类型(如 Task/Note)以及具体的属性(如 Date, Tag, Checkbox),选择 Copy ID。

CalDAV 信息:

获取你的日历服务器地址、用户名和密码。

📦 安装依赖 需要安装 requests 和 caldav 库:

🐍 完整代码 复制以下代码保存为 sync_anytype_caldav.py,并根据代码头部的 【请在此处填写…】 提示填入你的配置信息即可运行。

  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
import json
import requests
import caldav
import os
import sys
import urllib3
import platform
import traceback
from datetime import datetime, timedelta, timezone, date

# ==============================================================================
# 🛠️ 用户配置区域 (User Configuration)
# 请务必在使用前填写以下所有带 【...】 的配置项
# ==============================================================================

# 1. Anytype API 设置
# 获取方式: Anytype > Space Settings > Integrations > Manage Keys
ANYTYPE_API_KEY = "【请填写你的 Anytype API Key】" 
ANYTYPE_HOST = "http://127.0.0.1:31009/v1" # 默认本地 API 地址,通常无需修改

# 2. CalDAV (日历服务器) 设置
# 你的日历服务器地址 (例如群晖、Nextcloud、iCloud等生成的 CalDAV 链接)
CALDAV_URL = "【请填写 CalDAV 地址,例如 https://caldav.example.com/calendars/user/work/】"
CALDAV_USER = "【请填写日历用户名】"
CALDAV_PASS = "【请填写日历密码】"

# 3. Anytype 空间与对象设置
# 获取方式: 右键对象/空间 -> Copy ID,或通过 API 查询
TARGET_SPACE_ID = "【请填写 Anytype Space ID】"
TARGET_TYPE_ID = "【请填写要同步的 Object Type ID,例如 Note 或 Task 的 ID】"

# 4. 属性 Relation ID (关键配置)
# 你需要在 Anytype 中找到对应属性的 Relation ID (Key)。
# 建议先创建一个包含所有属性的测试对象,通过 API 读取一次来获取这些 ID。
START_DATE_KEY      = "【请填写 Start Date 属性的 ID】"
END_DATE_KEY        = "【请填写 End Date 属性的 ID (用于存储循环截止日期)】"
IS_ALL_DAY_KEY      = "【请填写 Is All Day (Checkbox) 属性的 ID】"
REPEAT_KEY          = "【请填写 Repeat (Select) 属性的 ID】"
REPEAT_INTERVAL_KEY = "【请填写 Repeat Interval (Number) 属性的 ID】"
END_TYPE_KEY        = "【请填写 End Type (Select) 属性的 ID】"
END_COUNT_KEY       = "【请填写 End Count (Number) 属性的 ID】"
ALARM_KEY           = "【请填写 Reminder/Alarm (Multi-Select) 属性的 ID】"
LAST_MODIFIED_KEY   = "【请填写 Last Modified Date (Date) 属性的 ID】"

# 5. SSL 证书路径 (可选)
# 如果你的 CalDAV 服务器是自签名证书,请在此指定证书路径;否则设为 None
CURRENT_OS = platform.system()
if CURRENT_OS == "Windows":
    CLIENT_CERT_PATH = None # r"C:\Path\To\Your\Certificate.pem" 
else:
    CLIENT_CERT_PATH = None # "/Users/yourname/Certificate.pem"   

# [云端记忆锚点] 用于在日历中存储同步历史,无需修改
HISTORY_ANCHOR_UID = "000000-ANYTYPE-SYNC-HISTORY-DO-NOT-DELETE"

# ==============================================================================
# 🧩 选项映射配置 (Option ID Mapping)
# Anytype 的单选/多选值都有唯一的 Option ID。
# 请将下方的 "bafyre..." 替换为你 Anytype 中对应选项的真实 ID。
# ==============================================================================

# 映射: ICS 频率 -> Anytype 选项 ID
REPEAT_MAP = {
    'DAILY':   "【请填写 'Daily' 选项的 ID】",
    'WEEKLY':  "【请填写 'Weekly' 选项的 ID】",
    'MONTHLY': "【请填写 'Monthly' 选项的 ID】",
    'YEARLY':  "【请填写 'Yearly' 选项的 ID】",
    'NONE':    "【请填写 'None' 选项的 ID】"
}
REPEAT_MAP_REV = {v: k for k, v in REPEAT_MAP.items()}

# 映射: ICS 结束类型 -> Anytype 选项 ID
END_TYPE_MAP = {
    'By Count': "【请填写 'By Count' 选项的 ID】",
    'By Date':  "【请填写 'By Date' 选项的 ID】",
    'Never':    "【请填写 'Never' 选项的 ID】"
}
END_TYPE_MAP_REV = {v: k for k, v in END_TYPE_MAP.items()}

# 映射: 提醒分钟数 -> Anytype 选项 ID
ALARM_MAP = {
    0:     "【请填写 'At time' (0分钟) 选项的 ID】",
    5:     "【请填写 '5 min before' 选项的 ID】",
    30:    "【请填写 '30 min before' 选项的 ID】",
    60:    "【请填写 '1 hour before' 选项的 ID】",
    120:   "【请填写 '2 hours before' 选项的 ID】",
    1440:  "【请填写 '1 day before' 选项的 ID】",
    2880:  "【请填写 '2 days before' 选项的 ID】",
    4320:  "【请填写 '3 days before' 选项的 ID】",
    10080: "【请填写 '1 week before' 选项的 ID】"
}
ALARM_MAP_REV = {v: k for k, v in ALARM_MAP.items()}

# ==============================================================================
# 🚀 代码逻辑区域 (无需修改)
# ==============================================================================

os.environ['no_proxy'] = '*'
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
headers = {"Authorization": f"Bearer {ANYTYPE_API_KEY}", "Content-Type": "application/json"}

# ----------------- 云端状态管理 -----------------

def load_remote_history(calendar):
    """从 CalDAV 服务器的一个特殊隐藏事件中读取历史同步 ID"""
    try:
        evt = calendar.event_by_uid(HISTORY_ANCHOR_UID)
        vobj = evt.vobject_instance.vevent
        if hasattr(vobj, 'description'):
            raw_json = vobj.description.value
            if raw_json:
                print("   📖 Loaded history from Cloud.")
                return json.loads(raw_json)
    except:
        print("   🆕 No remote history found. Starting fresh.")
        return []
    return []

def save_remote_history(calendar, ids):
    """将同步历史保存回 CalDAV 服务器"""
    id_list_json = json.dumps(list(ids))
    ical_data = [
        "BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Anytype Sync History//EN",
        "BEGIN:VEVENT", f"UID:{HISTORY_ANCHOR_UID}",
        f"DTSTAMP:{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}",
        "DTSTART;VALUE=DATE:20000101", "DTEND;VALUE=DATE:20000102",
        "SUMMARY:⚠️_SYNC_DATA_DO_NOT_DELETE", f"DESCRIPTION:{id_list_json}", 
        "END:VEVENT", "END:VCALENDAR"
    ]
    try: calendar.save_event("\n".join(ical_data)); print("   ☁️  History saved to Cloud.")
    except Exception as e: print(f"   ❌ Failed to save cloud history: {e}")

# ----------------- 数据标准化工具 -----------------

def to_utc_iso(dt_input):
    if not dt_input: return None
    dt = None
    if isinstance(dt_input, date) and not isinstance(dt_input, datetime):
        dt = datetime(dt_input.year, dt_input.month, dt_input.day, tzinfo=timezone.utc)
    elif isinstance(dt_input, datetime): dt = dt_input
    elif isinstance(dt_input, str):
        try:
            s = dt_input.replace("Z", "+00:00")
            if "." in s: s = s.split(".", 1)[0] + "+00:00"
            if "+" not in s and "-" not in s[-6:]: s += "+00:00"
            dt = datetime.fromisoformat(s)
        except: return None
    if dt:
        if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc)
        else: dt = dt.astimezone(timezone.utc)
        return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
    return None

def to_timestamp(dt_iso_str):
    if not dt_iso_str: return 0.0
    try:
        s = str(dt_iso_str).replace("Z", "+00:00")
        if "T" in s:
            dt = datetime.fromisoformat(s)
            if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc)
            return dt.timestamp()
    except: return 0.0

def standardize_server_obj(evt):
    vobj = evt.vobject_instance.vevent
    summary = str(vobj.summary.value) if hasattr(vobj, 'summary') else ""
    description = str(vobj.description.value) if hasattr(vobj, 'description') else ""
    
    dtstart = vobj.dtstart.value if hasattr(vobj, 'dtstart') else None
    dtend = vobj.dtend.value if hasattr(vobj, 'dtend') else None
    
    is_all_day = False
    if dtstart and isinstance(dtstart, date) and not isinstance(dtstart, datetime):
        is_all_day = True
    if is_all_day and dtend: dtend = dtend - timedelta(days=1)

    repeat = "NONE"; end_type = "Never"; end_val = None; interval = 1
    if hasattr(vobj, 'rrule'):
        try:
            rr = vobj.rrule.value
            if not isinstance(rr, dict):
                parts = str(rr).split(';')
                rr = {}
                for p in parts:
                    if '=' in p: k, v = p.split('=', 1); rr[k.upper()] = v.upper()
            freq = rr.get('FREQ')
            if freq in REPEAT_MAP: repeat = freq
            if 'INTERVAL' in rr:
                try: interval = int(rr['INTERVAL'])
                except: interval = 1
            if 'COUNT' in rr: end_type = "By Count"; end_val = int(rr['COUNT'])
            elif 'UNTIL' in rr:
                end_type = "By Date"; u_val = rr['UNTIL']
                if isinstance(u_val, list): u_val = u_val[0]
                if isinstance(u_val, (datetime, date)): end_val = u_val.strftime("%Y-%m-%d")
                elif isinstance(u_val, str):
                    clean_s = u_val.split('T')[0]
                    if len(clean_s) == 8: end_val = f"{clean_s[:4]}-{clean_s[4:6]}-{clean_s[6:]}"
                    else: end_val = clean_s
        except: pass
        
    alarms = []
    if hasattr(vobj, 'components'):
        for child in vobj.components():
            if child.name == 'VALARM' and hasattr(child, 'trigger'):
                trigger = child.trigger.value
                if isinstance(trigger, timedelta):
                    mins = int(abs(trigger.total_seconds()) // 60)
                    if mins in ALARM_MAP: alarms.append(mins)
    alarms.sort()

    mod_ts = 0.0
    if hasattr(vobj, 'last_modified'): mod_ts = vobj.last_modified.value.timestamp()
    elif hasattr(vobj, 'dtstamp'): mod_ts = vobj.dtstamp.value.timestamp()

    return { 
        "summary": summary, "description": description, 
        "dtstart": to_utc_iso(dtstart), "dtend": to_utc_iso(dtend), 
        "is_all_day": is_all_day, "repeat": repeat, "end_type": end_type, 
        "end_val": end_val, "interval": interval, "alarms": alarms, 
        "mod_time": mod_ts, "origin_ref": evt 
    }

def standardize_anytype_obj(obj):
    prop_map = {}
    raw_props = obj.get('properties', {})
    if isinstance(raw_props, list):
        for p in raw_props:
            pid = p.get('id'); val = p.get('date') or p.get('text') or p.get('number') or p.get('checkbox')
            if val is None and 'select' in p and p['select']: val = p['select'].get('id')
            if val is None and 'multi_select' in p and p['multi_select']: val = [x.get('id') for x in p['multi_select']]
            if pid: prop_map[pid] = val
    else: prop_map = raw_props

    mod_str = prop_map.get(LAST_MODIFIED_KEY) or obj.get('details', {}).get('last_modified_date') or obj.get('last_modified_date')
    rep_id = prop_map.get(REPEAT_KEY); repeat = REPEAT_MAP_REV.get(rep_id, "NONE")
    et_id = prop_map.get(END_TYPE_KEY); end_type = END_TYPE_MAP_REV.get(et_id, "Never")
    end_val = prop_map.get(END_COUNT_KEY)
    
    interval = prop_map.get(REPEAT_INTERVAL_KEY)
    try: interval = int(interval) if interval else 1
    except: interval = 1

    if end_type == "By Date":
        raw_end_date = prop_map.get(END_DATE_KEY)
        if raw_end_date and "T" in str(raw_end_date): end_val = str(raw_end_date).split("T")[0]
        else: end_val = raw_end_date
        
    alarm_ids = prop_map.get(ALARM_KEY); alarms = []
    if isinstance(alarm_ids, list):
        for aid in alarm_ids:
            if aid in ALARM_MAP_REV: alarms.append(ALARM_MAP_REV[aid])
    alarms.sort()

    is_all_day = bool(prop_map.get(IS_ALL_DAY_KEY))
    dtstart_iso = to_utc_iso(prop_map.get(START_DATE_KEY))
    dtend_iso = None 
    if is_all_day and dtstart_iso: dtstart_iso = dtstart_iso.split("T")[0] + "T00:00:00Z"

    return { "summary": obj.get('name', '') or obj.get('details', {}).get('name', ''), "dtstart": dtstart_iso, "dtend": dtend_iso, "is_all_day": is_all_day, "repeat": repeat, "end_type": end_type, "end_val": end_val, "interval": interval, "alarms": alarms, "mod_time": to_timestamp(mod_str), "origin_id": obj['id'] }

# ----------------- API 操作函数 -----------------

def push_to_anytype(std_data, target_id=None):
    payload_props_list = []
    if std_data['dtstart']: payload_props_list.append({"key": START_DATE_KEY, "date": std_data['dtstart']})
    payload_props_list.append({"key": IS_ALL_DAY_KEY, "checkbox": std_data['is_all_day']})
    
    val = REPEAT_MAP[std_data['repeat']] if std_data['repeat'] in REPEAT_MAP else REPEAT_MAP['NONE']
    payload_props_list.append({"key": REPEAT_KEY, "select": val})
    
    if std_data['interval'] > 1:
        payload_props_list.append({"key": REPEAT_INTERVAL_KEY, "number": std_data['interval']})

    if std_data['end_type'] in END_TYPE_MAP: payload_props_list.append({"key": END_TYPE_KEY, "select": END_TYPE_MAP[std_data['end_type']]})
    
    if std_data['end_type'] == "By Date" and std_data['end_val']:
        val_str = str(std_data['end_val'])
        if len(val_str) == 10: val_str += "T00:00:00Z"
        payload_props_list.append({"key": END_DATE_KEY, "date": val_str})
    elif std_data['end_type'] == "By Count":
        payload_props_list.append({"key": END_COUNT_KEY, "number": int(std_data['end_val'])})

    if std_data['alarms']:
        alarm_ids = [ALARM_MAP[m] for m in std_data['alarms'] if m in ALARM_MAP]
        if alarm_ids: payload_props_list.append({"key": ALARM_KEY, "multi_select": alarm_ids})

    final_data = { "properties": payload_props_list }
    if std_data['summary']: final_data["name"] = std_data['summary']
    if not target_id: final_data["type_key"] = TARGET_TYPE_ID
    
    url = f"{ANYTYPE_HOST}/spaces/{TARGET_SPACE_ID}/objects"
    if target_id: url += f"/{target_id}"
    method = "PATCH" if target_id else "POST"
    
    try:
        resp = requests.patch(url, headers=headers, json=final_data) if target_id else requests.post(url, headers=headers, json=final_data)
        if resp.status_code in [200, 201]:
            print(f"   ✅ Anytype {method} Success")
            return resp.json().get('data', {}).get('id') or resp.json().get('id')
        else:
            print(f"   ⚠️ {method} Failed ({resp.status_code}): {resp.text}")
            return None
    except Exception as e:
        print(f"   ❌ Network Error: {e}")
        return None

def push_to_server(calendar, std_data, uid):
    if not std_data['dtstart']:
        print(f"   ⚠️ Skipping: '{std_data['summary']}' has no Start Date.")
        return

    dtstart_obj = None
    if std_data['dtstart']:
        s = std_data['dtstart'].replace("Z", "+00:00")
        dtstart_obj = datetime.fromisoformat(s)

    dtend_final_str = ""
    if std_data['dtend']:
        if std_data['is_all_day']:
            t = datetime.fromisoformat(std_data['dtend'].replace("Z", "+00:00")) + timedelta(days=1)
            dtend_final_str = t.strftime("%Y%m%d")
        else:
             dtend_final_str = std_data['dtend'].replace("-", "").replace(":", "").replace(".000", "").replace("Z", "") + "Z"
    elif dtstart_obj:
        if std_data['is_all_day']:
            end_t = dtstart_obj + timedelta(days=1)
            dtend_final_str = end_t.strftime("%Y%m%d")
        else:
            end_t = dtstart_obj + timedelta(hours=1)
            if end_t.tzinfo is None: end_t = end_t.replace(tzinfo=timezone.utc)
            else: end_t = end_t.astimezone(timezone.utc)
            dtend_final_str = end_t.strftime("%Y%m%dT%H%M%SZ")

    # 生成标准 HTTPS 跳转链接,确保手机端可点击
    anytype_link = f"https://object.any.coop/{uid}?spaceId={TARGET_SPACE_ID}"

    lines = [
        "BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Anytype Sync//EN", "BEGIN:VEVENT",
        f"UID:{uid}", f"DTSTAMP:{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}",
        f"SUMMARY:{std_data['summary']}",
        f"DESCRIPTION:{anytype_link}", 
    ]
    if std_data['is_all_day']:
        ds = std_data['dtstart'][:10].replace("-", "")
        lines.append(f"DTSTART;VALUE=DATE:{ds}")
        if dtend_final_str: lines.append(f"DTEND;VALUE=DATE:{dtend_final_str}")
    else:
        ds = std_data['dtstart'].replace("-", "").replace(":", "").replace(".000", "").replace("Z", "") + "Z"
        lines.append(f"DTSTART:{ds}")
        if dtend_final_str: lines.append(f"DTEND:{dtend_final_str}")

    if std_data['repeat'] != "NONE":
        parts = [f"FREQ={std_data['repeat']}"]
        if std_data['interval'] > 1: parts.append(f"INTERVAL={std_data['interval']}")
        if std_data['end_type'] == "By Count": parts.append(f"COUNT={std_data['end_val']}")
        elif std_data['end_type'] == "By Date" and std_data['end_val']:
            ed = std_data['end_val'].replace("-", "")
            parts.append(f"UNTIL={ed}T235959Z")
        lines.append("RRULE:" + ";".join(parts))

    for m in std_data['alarms']:
        lines.extend(["BEGIN:VALARM", "ACTION:DISPLAY", f"TRIGGER:-PT{m}M", "DESCRIPTION:Reminder", "END:VALARM"])

    lines.extend(["END:VEVENT", "END:VCALENDAR"])
    
    try: calendar.save_event("\n".join(lines)); print("   ✅ Server Update Success")
    except Exception as e: print(f"   ❌ Server Update Failed: {e}")

def delete_from_anytype(oid):
    url = f"{ANYTYPE_HOST}/spaces/{TARGET_SPACE_ID}/objects/{oid}"
    try:
        resp = requests.delete(url, headers=headers)
        if resp.status_code in [200, 204]: print("   ✅ Anytype Delete Success")
        else: print(f"   ⚠️ Anytype Delete Failed ({resp.status_code}): {resp.text}")
    except Exception as e: print(f"   ❌ Anytype Delete Error: {e}")

def print_diff_log(name, server_data, anytype_data):
    print(f"\n📊 [对比分析] 对象: {name}")
    print(f"{'Field':<15} | {'Server Value':<30} | {'Anytype Value':<30} | {'Match'}")
    print("-" * 90)
    keys = ["summary", "dtstart", "dtend", "is_all_day", "repeat", "interval", "end_type", "end_val", "alarms"]
    is_content_same = True
    for k in keys:
        sv = server_data.get(k) if server_data else "MISSING"
        av = anytype_data.get(k) if anytype_data else "MISSING"
        match = (sv == av)
        if not sv and not av: match = True
        if k == "summary" and sv and av: match = (str(sv).strip() == str(av).strip())
        if k == "dtend" and sv and not av: match = True 
        if not match: is_content_same = False
        mark = "✅" if match else "❌ Diff"
        print(f"{k:<15} | {str(sv)[:28]:<30} | {str(av)[:28]:<30} | {mark}")
    
    st = server_data['mod_time'] if server_data else 0
    at = anytype_data['mod_time'] if anytype_data else 0
    diff = st - at
    print("-" * 90)
    print(f"{'Mod Time':<15} | {datetime.fromtimestamp(st).strftime('%H:%M:%S'):<30} | {datetime.fromtimestamp(at).strftime('%H:%M:%S'):<30} | Diff: {diff:.1f}s")
    return is_content_same, diff

# ----------------- 主程序逻辑 -----------------

def sync_strict():
    print("🚀 启动 Anytype <-> CalDAV 严格同步...")
    
    # 1. 连接 CalDAV
    try:
        ssl_cert = CLIENT_CERT_PATH if CLIENT_CERT_PATH and os.path.exists(CLIENT_CERT_PATH) else None
        client = caldav.DAVClient(url=CALDAV_URL, username=CALDAV_USER, password=CALDAV_PASS, ssl_verify_cert=(ssl_cert is not None), ssl_cert=ssl_cert)
        calendar = client.calendar(url=CALDAV_URL)
        known_ids = set(load_remote_history(calendar))
    except Exception as e:
        print(f"❌ CalDAV 连接失败: {e}")
        return

    # 2. 读取 Server
    server_map = {}
    print("☁️ Reading Server...", end="")
    try:
        for evt in calendar.events():
            try:
                vobj = evt.vobject_instance.vevent
                uid = str(vobj.uid.value)
                if uid == HISTORY_ANCHOR_UID: continue 
                server_map[uid] = standardize_server_obj(evt)
            except: pass
        print(f" Done ({len(server_map)} items)")
    except Exception as e: print(f" Error: {e}"); return

    # 3. 读取 Anytype
    anytype_map = {}
    print("📡 Reading Anytype...", end="")
    offset = 0; limit = 50
    while True:
        resp = requests.get(f"{ANYTYPE_HOST}/spaces/{TARGET_SPACE_ID}/objects", headers=headers, params={"limit": limit, "offset": offset})
        if resp.status_code != 200: break
        items = resp.json()
        if isinstance(items, dict): items = items.get('data', [])
        if not items: break
        for obj in items:
            t_id = obj.get('type', {}).get('id') if isinstance(obj.get('type'), dict) else obj.get('type')
            if not t_id and 'details' in obj: t_id = obj['details'].get('type', {}).get('id')
            if t_id != TARGET_TYPE_ID: continue
            if obj.get('archived') or obj.get('details', {}).get('archived'): continue
            anytype_map[obj['id']] = standardize_anytype_obj(obj)
        if len(items) < limit: break
        offset += limit
    print(f" Done ({len(anytype_map)} items)")

    # 4. 删除检测
    current_server_ids = set(server_map.keys())
    current_anytype_ids = set(anytype_map.keys())
    deleted_on_server = known_ids - current_server_ids
    deleted_on_anytype = known_ids - current_anytype_ids

    for uid in deleted_on_server:
        if uid in current_anytype_ids:
            print(f"🗑️ [Delete] Item {uid} removed from Server -> Deleting from Anytype")
            delete_from_anytype(anytype_map[uid]['origin_id'])
            del anytype_map[uid]

    for uid in deleted_on_anytype:
        if uid in current_server_ids:
            print(f"🗑️ [Delete] Item {uid} removed from Anytype -> Deleting from Server")
            try: 
                server_map[uid]['origin_ref'].delete()
                print("   ✅ Server Delete Success")
                del server_map[uid]
            except Exception as e: print(f"   ❌ Delete Failed: {e}")

    # 5. 同步与更新
    all_uids = set(server_map.keys()) | set(anytype_map.keys())
    final_synced_ids = set()

    for uid in all_uids:
        s_data = server_map.get(uid)
        a_data = anytype_map.get(uid)
        
        name = "Untitled"
        if s_data: name = s_data['summary']
        elif a_data: name = a_data['summary']
        
        same_content, time_diff = print_diff_log(name, s_data, a_data)
        
        if s_data and not a_data:
            print(f"➡️ [New] Server -> Anytype")
            new_id = push_to_anytype(s_data)
            if new_id:
                print(f"   ⚠️ ID Mismatch Fix: {uid} -> {new_id}")
                push_to_server(calendar, s_data, new_id)
                s_data['origin_ref'].delete()
                final_synced_ids.add(new_id)
            else: final_synced_ids.add(uid)

        elif a_data and not s_data:
            print(f"⬅️ [New] Anytype -> Server")
            push_to_server(calendar, a_data, uid)
            final_synced_ids.add(uid)
            
        elif s_data and a_data:
            final_synced_ids.add(uid)
            target_link = f"https://object.any.coop/{uid}?spaceId={TARGET_SPACE_ID}"
            link_missing = (s_data.get('description') != target_link)

            if same_content:
                if link_missing:
                    print(f"   🔗 Adding Link to Server")
                    push_to_server(calendar, a_data, uid)
                else:
                    print("✅ In Sync")
            else:
                if time_diff > 30:
                    print(f"➡️ [Update] Server is newer -> Anytype")
                    push_to_anytype(s_data, target_id=a_data['origin_id'])
                elif time_diff < -30:
                    print(f"⬅️ [Update] Anytype is newer -> Server")
                    push_to_server(calendar, a_data, uid)
                else:
                    print("⚠️ Time Conflict. Preferring Server.")
                    push_to_anytype(s_data, target_id=a_data['origin_id'])

    print(f"💾 Saving history ({len(final_synced_ids)} items) to Cloud...")
    save_remote_history(calendar, final_synced_ids)
    print("\n🎉 Sync Complete.")

if __name__ == "__main__":
    sync_strict()