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
| import fs from 'node:fs'; import yaml from 'js-yaml'; import axios from 'axios'; import ical from 'node-ical'; import dayjs from 'dayjs';
const config = yaml.load(fs.readFileSync('./config.yaml', 'utf8'));
const FEISHU_HOST = 'https://open.feishu.cn/open-apis'; let TENANT_ACCESS_TOKEN = '';
async function getAccessToken() { try { const res = await axios.post(`${FEISHU_HOST}/auth/v3/tenant_access_token/internal`, { app_id: config.feishu.app_id, app_secret: config.feishu.app_secret }); if (res.data.code !== 0) throw new Error(res.data.msg); TENANT_ACCESS_TOKEN = res.data.tenant_access_token; console.log('✅ 获取 Access Token 成功'); } catch (e) { console.error('❌ 获取 Token 失败:', e.message); process.exit(1); } }
async function getOrCreateCalendar() { const headers = { Authorization: `Bearer ${TENANT_ACCESS_TOKEN}` }; let pageToken = ''; let foundCal = null; do { const res = await axios.get(`${FEISHU_HOST}/calendar/v4/calendars`, { headers, params: { page_size: 500, page_token: pageToken } }); if (res.data.code !== 0) throw new Error(res.data.msg); foundCal = (res.data.data.calendar_list || []).find(c => c.summary === config.calendar.name); pageToken = res.data.data.page_token; } while (pageToken && !foundCal);
if (foundCal) { console.log(`✅ 找到日历: ${foundCal.summary}`); return foundCal.calendar_id; }
console.log(`ℹ️ 创建新日历: ${config.calendar.name}...`); const createRes = await axios.post(`${FEISHU_HOST}/calendar/v4/calendars`, { summary: config.calendar.name, description: "自动同步的节假日日历", permissions: "public", color: config.calendar.color, summary_alias: config.calendar.name }, { headers }); return createRes.data.data.calendar.calendar_id; }
async function fetchICloudEvents() { console.log('⬇️ 正在下载 iCloud 数据...'); const events = await ical.async.fromURL(config.source.icloud_url); const validEvents = []; const now = dayjs().startOf('day'); const oneYearLater = now.add(1, 'year').endOf('day');
for (const k in events) { const ev = events[k]; if (ev.type !== 'VEVENT') continue;
let summaryText = ''; if (ev.summary && typeof ev.summary === 'object' && ev.summary.val) { summaryText = ev.summary.val; } else { summaryText = String(ev.summary || ''); }
const startDate = dayjs(ev.start); let endDate; if (ev.end) { const tempEnd = dayjs(ev.end); if (tempEnd.isAfter(startDate, 'day')) { endDate = tempEnd.subtract(1, 'day'); } else { endDate = tempEnd; } } else { endDate = startDate; }
if (startDate.isAfter(now) && startDate.isBefore(oneYearLater)) { validEvents.push({ summary: summaryText, startDate: startDate.format('YYYY-MM-DD'), endDate: endDate.format('YYYY-MM-DD'), uid: ev.uid }); } } console.log(`✅ 解析到源数据: ${validEvents.length} 条`); return validEvents; }
async function fetchFeishuEvents(calendarId) { const headers = { Authorization: `Bearer ${TENANT_ACCESS_TOKEN}` }; const now = dayjs().unix(); const oneYearLater = dayjs().add(1, 'year').unix();
const res = await axios.get(`${FEISHU_HOST}/calendar/v4/calendars/${calendarId}/events`, { headers, params: { start_time: String(now), end_time: String(oneYearLater), page_size: 500 } });
return (res.data.data.items || []).map(e => ({ ...e, event_id: e.event_id, summary: e.summary, startDate: e.start_time.date, endDate: e.end_time.date })); }
async function main() { await getAccessToken(); const calendarId = await getOrCreateCalendar(); const sourceEvents = await fetchICloudEvents(); const existingEvents = await fetchFeishuEvents(calendarId);
console.log('sourceEvents:', sourceEvents); console.log('existingEvents:', existingEvents);
const toCreate = []; const toDelete = [];
for (const src of sourceEvents) { const exists = existingEvents.find( e => e.startDate === src.startDate && e.summary === src.summary ); if (!exists) toCreate.push(src); }
for (const exist of existingEvents) { const inSource = sourceEvents.find( s => s.startDate === exist.startDate && s.summary === exist.summary ); if (exist.status === 'confirmed' && !inSource) toDelete.push(exist); }
console.log('[toCreate]', toCreate); console.log('[toDelete]', toDelete);
console.log(`📊 变更计划: 新增/修正 ${toCreate.length}, 删除/清理 ${toDelete.length}`);
if (toDelete.length > 0) { const headers = { Authorization: `Bearer ${TENANT_ACCESS_TOKEN}` }; for (const evt of toDelete) { try { await axios.delete(`${FEISHU_HOST}/calendar/v4/calendars/${calendarId}/events/${evt.event_id}`, { headers }); console.log(` - 已删除旧日程: [${evt.startDate} - ${evt.endDate}] ${evt.summary}`); } catch (e) { console.error(` ! 删除失败: ${e.message}`); } } }
if (toCreate.length > 0) { const headers = { Authorization: `Bearer ${TENANT_ACCESS_TOKEN}` }; for (const evt of toCreate) { try { await axios.post(`${FEISHU_HOST}/calendar/v4/calendars/${calendarId}/events`, { summary: evt.summary, start_time: { date: evt.startDate }, end_time: { date: evt.endDate }, visibility: "public", is_all_day_event: true }, { headers }); console.log(` + 已创建: [${evt.startDate}${evt.startDate === evt.endDate ? '' : ' -> ' + evt.endDate}] ${evt.summary}`); } catch (e) { console.error(`. ! 创建失败 [${evt.startDate}]:`, e.response?.data?.msg || e.message); } } }
console.log('🎉 同步完成'); }
main().catch(console.error);
|