Compare commits
7
Commits
v0.0.7
..
8ae4e11507
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ae4e11507 | ||
|
|
c4dc27ef3a | ||
|
|
bd3afb7bd1 | ||
|
|
3025f92cb6 | ||
|
|
d890a2b053 | ||
|
|
19cfe3cf34 | ||
|
|
a49e7d03b1 |
+2
-2
@@ -2,8 +2,8 @@
|
||||
"app": {
|
||||
"bundleName": "synccalendar.yangyq.net",
|
||||
"vendor": "yangyq",
|
||||
"versionCode": 700,
|
||||
"versionName": "0.0.7",
|
||||
"versionCode": 800,
|
||||
"versionName": "0.0.8",
|
||||
"buildVersion": "1",
|
||||
"icon": "$media:layered_image",
|
||||
"label": "$string:app_name"
|
||||
|
||||
@@ -20,6 +20,10 @@ export class AppSettings {
|
||||
private static readonly KEY_MANUAL_READONLY: string = 'manual_readonly_keys'; // 手动标记只读的 calKey
|
||||
private static readonly KEY_MUTED_REMINDER: string = 'muted_reminder_keys'; // 提醒静音的 calKey
|
||||
private static readonly KEY_REMINDER_TICK: string = 'reminder_tick'; // 应用内提醒上次检查时间戳
|
||||
// ⭐ 卡片刷新驱动的后台同步:上次执行时间戳(用于节流)。
|
||||
// 服务卡片每 30 分钟被系统刷新一次(form_config 的 updateDuration=1),
|
||||
// 借这个时机顺带跑一次后台同步 —— 得到"约 30 分钟一次"的定期同步。
|
||||
private static readonly KEY_CARD_SYNC_AT: string = 'card_sync_at';
|
||||
private static readonly KEY_FULL_REFETCH: string = 'full_refetch_done'; // 一次性全量重拉已完成
|
||||
private static readonly KEY_DEFAULT_VIEW: string = 'default_view'; // 打开 App 默认视图
|
||||
private static readonly KEY_DISPLAY_STYLE: string = 'display_style'; // 日程显示方式:'timeline' | 'list'
|
||||
@@ -27,6 +31,9 @@ export class AppSettings {
|
||||
private static readonly KEY_MIRROR_KEYS: string = 'mirror_cal_keys'; // 要镜像的 DAV 日历本 calKey 列表
|
||||
private static readonly KEY_MIRROR_BOOK_IDS: string = 'mirror_book_ids'; // ⭐ 要镜像的日历本**稳定标识** bookId(由服务器 href 派生,不随序号变)
|
||||
private static readonly KEY_MIRROR_INBOUND: string = 'mirror_inbound'; // 是否把系统日历的改动回写 CalDAV(默认关)
|
||||
// ⭐ 系统日历账户的**显示名格式**(1/2/3,默认 3=`<账号>·<本名>`)。
|
||||
// 因平台无"改账户名"API,切换格式需删账户重建(用户显式点「应用」才执行)。
|
||||
private static readonly KEY_MIRROR_DISPLAY_FORMAT: string = 'mirror_display_format';
|
||||
private static readonly KEY_POLICY_AGREED: string = 'policy_agreed'; // 是否已同意隐私政策与用户协议
|
||||
// 首启功能引导"用户已看过并关闭"的标记。键名带版本号:改动引导内容后把 vN 加 1,用户即可再看一次。
|
||||
// 注意:只在用户主动关闭("开始使用" / ✕ / 点遮罩)时才置 true,**不再"显示前就置 true"**——
|
||||
@@ -293,6 +300,56 @@ export class AppSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ⭐ 系统日历账户显示名格式:1=`同步日历·本名`,2=`同步日历·账号·本名`,3=`账号·本名`(默认)。
|
||||
* 只接受 1/2/3,其它值一律回落到默认 3(防止脏数据导致拼出意外名字)。
|
||||
*/
|
||||
static async getMirrorDisplayFormat(context: common.Context): Promise<number> {
|
||||
try {
|
||||
const store: preferences.Preferences =
|
||||
await preferences.getPreferences(context, AppSettings.STORE);
|
||||
const v = await store.get(AppSettings.KEY_MIRROR_DISPLAY_FORMAT, 3) as number;
|
||||
return (v === 1 || v === 2 || v === 3) ? v : 3;
|
||||
} catch (err) {
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
|
||||
static async setMirrorDisplayFormat(context: common.Context, value: number): Promise<void> {
|
||||
try {
|
||||
const store: preferences.Preferences =
|
||||
await preferences.getPreferences(context, AppSettings.STORE);
|
||||
await store.put(AppSettings.KEY_MIRROR_DISPLAY_FORMAT, value);
|
||||
await store.flush();
|
||||
} catch (err) {
|
||||
const e = err as BusinessError;
|
||||
console.error(`保存显示名格式失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** ⭐ 卡片刷新驱动的后台同步:上次执行时间戳(0 = 从未执行) */
|
||||
static async getCardSyncAt(context: common.Context): Promise<number> {
|
||||
try {
|
||||
const store: preferences.Preferences =
|
||||
await preferences.getPreferences(context, AppSettings.STORE);
|
||||
return await store.get(AppSettings.KEY_CARD_SYNC_AT, 0) as number;
|
||||
} catch (err) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static async setCardSyncAt(context: common.Context, ts: number): Promise<void> {
|
||||
try {
|
||||
const store: preferences.Preferences =
|
||||
await preferences.getPreferences(context, AppSettings.STORE);
|
||||
await store.put(AppSettings.KEY_CARD_SYNC_AT, ts);
|
||||
await store.flush();
|
||||
} catch (err) {
|
||||
const e = err as BusinessError;
|
||||
console.error(`保存卡片同步时间失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否还需要一次性全量重拉:修复历史同步(REPORT 剥离 VALARM 时期)落库的残缺数据。
|
||||
* 全量重拉期间忽略 etag 复用,所有资源 GET 完整 ICS;成功完成后标记,恢复增量模式。
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
//
|
||||
// ⚠️ 与 SyncEngine.syncAccount 的分工:本类不关心超时与互斥锁(由 SyncEngine 内部处理)。
|
||||
import { common } from '@kit.AbilityKit';
|
||||
import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
|
||||
import { BusinessError } from '@kit.BasicServicesKit';
|
||||
import { DavAccount, AccountStore, TYPE_CALDAV } from './AccountStore';
|
||||
import { SyncEngine } from './SyncEngine';
|
||||
@@ -27,6 +28,135 @@ export class BackgroundSyncResult {
|
||||
}
|
||||
|
||||
export class BackgroundSyncRunner {
|
||||
/**
|
||||
* ⭐ 卡片的系统定时刷新间隔(与 form_config.json 的 updateDuration=1 保持一致,单位 30 分钟)。
|
||||
* ⚠️ 两处必须同步修改:改这里也要改 form_config.json,否则节流窗口对不上。
|
||||
*/
|
||||
static readonly CARD_TICK_MS: number = 30 * 60 * 1000;
|
||||
/** 距上次同步不足该时长则跳过(略小于卡片周期,避免系统刷新漂移导致被误跳过) */
|
||||
private static readonly CARD_MIN_GAP_MS: number = 25 * 60 * 1000;
|
||||
/**
|
||||
* 卡片进程的软超时(**未申请到短时任务时**):官方规定 FormExtensionAbility
|
||||
* 生命周期回调后进程**仅存续 10 秒**,超过就被回收(异步任务被强制中止)。
|
||||
* 这里主动在 9 秒收手,让"这一次同步"**干净地放弃**而不是被硬杀在半途。
|
||||
*/
|
||||
private static readonly CARD_SOFT_TIMEOUT_MS: number = 9 * 1000;
|
||||
/**
|
||||
* 申请到短时任务后的软超时:短时任务单次最长 3 分钟(低电量 1 分钟),
|
||||
* 但实际时长以 `actualDelayTime` 为准 → 留 15 秒余量提前收手,保证能干净地
|
||||
* `cancelSuspendDelay`(否则超时不取消会被系统强制终止进程、并浪费当日配额)。
|
||||
*/
|
||||
private static readonly CARD_EXT_SOFT_RESERVE_MS: number = 15 * 1000;
|
||||
/**
|
||||
* 卡片驱动同步可用的**总时长上限**:即使申请到短时任务也不超过这个值。
|
||||
* 理由:短时任务**单日总配额仅 10 分钟**,30 分钟一次的话每次平均只能分到约 20 秒,
|
||||
* 全用光会让"退后台那一次同步"(EntryAbility.onBackground 申请)无配额可用。
|
||||
*/
|
||||
private static readonly CARD_MAX_TOTAL_MS: number = 60 * 1000;
|
||||
|
||||
/** 本次卡片同步申请的短时任务 requestId(0 = 未申请到) */
|
||||
private static cardTransientId: number = 0;
|
||||
|
||||
/**
|
||||
* ⭐⭐ 由**服务卡片定时刷新**(`onUpdateForm`)驱动的后台同步(0.0.8)。
|
||||
*
|
||||
* 为什么用它:系统给普通应用的后台调度很受限 ——
|
||||
* `workScheduler` 的周期被"应用活跃分组"压制到 **≥2 小时**;
|
||||
* 而服务卡片配置了 `updateDuration: 1`(**单位 30 分钟**),系统会**每 30 分钟**
|
||||
* 触发一次 `onUpdateForm()`,且不受活跃分组压制(每天上限 50 次)。
|
||||
* 借这个时机跑一次完整同步,即可得到"约 30 分钟一次"的定期后台同步。
|
||||
*
|
||||
* ⚠️ 节流:系统刷新本身可能有漂移、也可能因故重入 → 用时间戳挡一道,
|
||||
* 保证两次真实同步之间至少间隔 `CARD_MIN_GAP_MS`。
|
||||
* ⚠️ 本方法**永不抛错**(后台路径没有 UI 承担异常)。
|
||||
*/
|
||||
static async runOnceThrottledByCard(context: common.Context): Promise<void> {
|
||||
try {
|
||||
const last: number = await AppSettings.getCardSyncAt(context);
|
||||
const now: number = Date.now();
|
||||
if (last > 0 && now - last < BackgroundSyncRunner.CARD_MIN_GAP_MS) {
|
||||
const mins: number = Math.round((now - last) / 60000);
|
||||
LogUtil.write(`卡片驱动同步:距上次仅 ${mins} 分钟,跳过(节流 ${BackgroundSyncRunner.CARD_MIN_GAP_MS / 60000} 分钟)`);
|
||||
return;
|
||||
}
|
||||
// 先写时间戳:避免同步执行期间卡片再次刷新导致并发重入
|
||||
await AppSettings.setCardSyncAt(context, now);
|
||||
// ⭐ 尝试申请**短时任务**,把 10 秒窗口延长到最多 3 分钟。
|
||||
// ⚠️ 官方规定 requestSuspendDelay 应在"应用处于前台"或"onBackground 回调"里调用;
|
||||
// 卡片进程(FormExtensionAbility)是否符合**未知** → 故此处**容错尝试**:
|
||||
// 成功则按实际时长延长,失败(抛错/时长为 0)则退回 9 秒软超时。
|
||||
// ⚠️ 配额:短时任务单日总配额 10 分钟、单次最长 3 分钟(低电量 1 分钟),
|
||||
// 且**被挂起后才计时**(10 秒内跑完不消耗)→ 对我们很划算。
|
||||
const windowMs: number = await BackgroundSyncRunner.acquireCardWindow();
|
||||
const budget: number = Math.min(windowMs, BackgroundSyncRunner.CARD_MAX_TOTAL_MS);
|
||||
LogUtil.write(`卡片驱动同步:开始(卡片 30 分钟定时刷新触发,可用窗口 ${Math.round(budget / 1000)} 秒)`);
|
||||
// 软超时:预算内没跑完就主动放弃(幂等同步,中断不损坏数据,下轮会重试)
|
||||
const worker: Promise<void> =
|
||||
BackgroundSyncRunner.runOnce(context, 'cardTick').then((): void => {});
|
||||
const guard: Promise<void> = new Promise<void>((_res: () => void, rej: (e: Error) => void) => {
|
||||
setTimeout((): void => rej(new Error('本次同步时间预算用尽,主动收手')),
|
||||
budget);
|
||||
});
|
||||
try {
|
||||
await Promise.race<void>([worker, guard]);
|
||||
} catch (err) {
|
||||
const e = err as Error;
|
||||
LogUtil.write(`卡片驱动同步提前收手:${e.message}(幂等,下轮会重试)`);
|
||||
} finally {
|
||||
// 无论成败都释放短时任务:① 归还当日配额 ② 避免超时不取消被系统强杀进程
|
||||
BackgroundSyncRunner.releaseCardWindow();
|
||||
}
|
||||
} catch (err) {
|
||||
const e = err as BusinessError;
|
||||
LogUtil.write(`卡片驱动同步异常: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 为卡片同步申请短时任务,返回**实际可用窗口(毫秒)**。
|
||||
* 申请失败/异常/时长为 0 → 返回 0,由调用方退回默认的 9 秒软超时(不阻塞流程)。
|
||||
*/
|
||||
private static async acquireCardWindow(): Promise<number> {
|
||||
try {
|
||||
const info: backgroundTaskManager.DelaySuspendInfo =
|
||||
backgroundTaskManager.requestSuspendDelay('正在同步日历数据', (): void => {
|
||||
// 超时回调:配额即将用尽,清掉本地记录(系统会自行处理挂起)
|
||||
LogUtil.write('卡片同步的短时任务即将超时');
|
||||
BackgroundSyncRunner.cardTransientId = 0;
|
||||
});
|
||||
BackgroundSyncRunner.cardTransientId = info.requestId;
|
||||
const actual: number = info.actualDelayTime ?? 0;
|
||||
if (actual <= 0) {
|
||||
// 拿到了 requestId 但没有实际时长 → 视为不可用
|
||||
BackgroundSyncRunner.releaseCardWindow();
|
||||
LogUtil.write('卡片同步:短时任务时长为 0,退回 9 秒软超时');
|
||||
return BackgroundSyncRunner.CARD_SOFT_TIMEOUT_MS;
|
||||
}
|
||||
// 留 15 秒余量提前收手,保证能干净地取消
|
||||
const usable: number = Math.max(actual - BackgroundSyncRunner.CARD_EXT_SOFT_RESERVE_MS,
|
||||
BackgroundSyncRunner.CARD_SOFT_TIMEOUT_MS);
|
||||
LogUtil.write(`卡片同步:短时任务已获批,实际时长 ${Math.round(actual / 1000)} 秒`);
|
||||
return usable;
|
||||
} catch (err) {
|
||||
// 例如"未在前台/退后台时机申请"被拒 —— 退回 9 秒软超时,不影响流程
|
||||
const e = err as BusinessError;
|
||||
LogUtil.write(`卡片同步:短时任务申请失败(${e.code ?? ''} ${e.message}),退回 9 秒软超时`);
|
||||
return BackgroundSyncRunner.CARD_SOFT_TIMEOUT_MS;
|
||||
}
|
||||
}
|
||||
|
||||
/** 释放卡片同步的短时任务(幂等) */
|
||||
private static releaseCardWindow(): void {
|
||||
if (BackgroundSyncRunner.cardTransientId === 0) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
backgroundTaskManager.cancelSuspendDelay(BackgroundSyncRunner.cardTransientId);
|
||||
} catch (err) {
|
||||
// 取消失败无需处理
|
||||
}
|
||||
BackgroundSyncRunner.cardTransientId = 0;
|
||||
}
|
||||
/**
|
||||
* 跑一次完整同步。全流程 try-catch,**永不抛错**(后台路径没有 UI 承担异常)。
|
||||
* @param context 应用上下文
|
||||
|
||||
@@ -229,7 +229,10 @@ export class IcsUtil {
|
||||
}
|
||||
|
||||
/**
|
||||
* 由本地事件构建 VCALENDAR 文本(时间统一转 UTC,保证服务器端时区正确)。
|
||||
* 由本地事件构建 VCALENDAR 文本。
|
||||
*
|
||||
* ⚠️ 事件时间写的是**浮动本地时间**(不是 UTC),原因见 `vevent()` 里的详细说明
|
||||
* (服务器会删掉 `Z`/`TZID` 且不做时移)。`DTSTAMP` 仍按 RFC 规定写 UTC+`Z`。
|
||||
*
|
||||
* 已知取舍:摘要 / 地点 / 备注等文本字段**未做 ICS 转义**(`,` `;` `\` 与换行)。
|
||||
* 含这些字符的标题在服务器端可能被截断或串行;
|
||||
@@ -273,10 +276,25 @@ export class IcsUtil {
|
||||
/** 单个 VEVENT 块(主事件带 RRULE/EXDATE,覆盖行带 RECURRENCE-ID) */
|
||||
private static vevent(e: LocalEvent, now: string): string {
|
||||
const pad = (n: number): string => n < 10 ? '0' + n : String(n);
|
||||
const fmtUtc = (ms: number): string => {
|
||||
/**
|
||||
* ⭐⭐ 事件时间一律写**浮动本地时间**(`YYYYMMDDTHHMMSS`,**不带 `Z`、不带 `TZID`**)。
|
||||
*
|
||||
* 为什么不写 RFC 最正统的 UTC+`Z` —— 因为服务器会把它弄坏:
|
||||
* 本项目的服务器(家书日历 / family.yangyq.net)会**直接删掉** `DTSTART`/`DTEND`
|
||||
* 上的 `Z` 与 `TZID` 参数,**且不对数值做任何时移**
|
||||
* (2026-10-15 实测:PUT `DTSTART:20261020T060000Z` → 存回 `DTSTART:20261020T060000`;
|
||||
* PUT `DTSTART;TZID=Asia/Shanghai:20261020T140000` → 存回 `20261020T140000`)。
|
||||
* 于是"UTC 00:00"被当成"**本地** 00:00"。而本地 08:00 的正确 UTC 恰好就是 00:00,
|
||||
* 所以症状正好是**阅读端少了 8 小时**(用户实测:"8:00 的日程同步后变成 0:00")。
|
||||
*
|
||||
* 该服务器上全部计时事件(1163 条)的 `DTSTART` **无一例外都是浮动本地时间**
|
||||
* (带 `Z` 的数量为 **0**、带 `TZID` 为 **0**)→ 这就是它的事实约定,我们随它。
|
||||
* 浮动时间在任何阅读端都按"当地墙钟"解析,本机 CST 往返完全一致。
|
||||
*/
|
||||
const fmtLocal = (ms: number): string => {
|
||||
const d = new Date(ms);
|
||||
return `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}` +
|
||||
`T${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}Z`;
|
||||
return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}` +
|
||||
`T${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
||||
};
|
||||
const fmtDate = (ms: number): string => {
|
||||
const d = new Date(ms);
|
||||
@@ -289,8 +307,8 @@ export class IcsUtil {
|
||||
// 存储的 endTime 为排他日前一毫秒,+1s 得到排他日期
|
||||
dtend = 'DTEND;VALUE=DATE:' + fmtDate(e.endTime + 1000);
|
||||
} else {
|
||||
dtstart = 'DTSTART:' + fmtUtc(e.startTime);
|
||||
dtend = 'DTEND:' + fmtUtc(e.endTime);
|
||||
dtstart = 'DTSTART:' + fmtLocal(e.startTime);
|
||||
dtend = 'DTEND:' + fmtLocal(e.endTime);
|
||||
}
|
||||
// ⭐ 覆盖实例(RECURRENCE-ID 行):必须写出 RECURRENCE-ID,否则服务器无法把它
|
||||
// 关联到主事件的哪一次发生 → 要么整系列被破坏,要么原时间残留成"幽灵日程"。
|
||||
@@ -298,7 +316,7 @@ export class IcsUtil {
|
||||
if (e.rrule === '' && e.recurrenceId > 0) {
|
||||
recId = e.isAllDay
|
||||
? `RECURRENCE-ID;VALUE=DATE:${fmtDate(e.recurrenceId)}\r\n`
|
||||
: `RECURRENCE-ID:${fmtUtc(e.recurrenceId)}\r\n`;
|
||||
: `RECURRENCE-ID:${fmtLocal(e.recurrenceId)}\r\n`;
|
||||
}
|
||||
// ⭐ EXDATE:主事件排除掉的若干次发生("仅删除这一次"就是往这里加)
|
||||
let exdate: string = '';
|
||||
@@ -307,7 +325,7 @@ export class IcsUtil {
|
||||
for (const raw of e.exdate.split(';')) {
|
||||
const t = IcsUtil.parseTime(raw, !raw.includes('T'));
|
||||
if (t !== null) {
|
||||
vals.push(t.allDay ? fmtDate(t.time) : fmtUtc(t.time));
|
||||
vals.push(t.allDay ? fmtDate(t.time) : fmtLocal(t.time));
|
||||
}
|
||||
}
|
||||
if (vals.length > 0) {
|
||||
@@ -341,8 +359,9 @@ export class IcsUtil {
|
||||
}
|
||||
|
||||
/**
|
||||
* 毫秒时间戳 → 用于 EXDATE / RECURRENCE-ID 的 ICS 时间串。
|
||||
* @param dateOnly 全天日程用 `YYYYMMDD`,否则用 UTC 的 `YYYYMMDDTHHMMSSZ`
|
||||
* 毫秒时间戳 → 用于 EXDATE / RECURRENCE-ID / UNTIL 的 ICS 时间串。
|
||||
* @param dateOnly 全天日程用 `YYYYMMDD`,否则用**浮动本地时间** `YYYYMMDDTHHMMSS`
|
||||
* (不带 `Z`:必须与 `DTSTART` 的形态一致,见 `vevent()` 里的说明)
|
||||
*/
|
||||
static fmtIcsTime(ms: number, dateOnly: boolean): string {
|
||||
const pad = (n: number): string => n < 10 ? '0' + n : String(n);
|
||||
@@ -350,20 +369,19 @@ export class IcsUtil {
|
||||
if (dateOnly) {
|
||||
return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}`;
|
||||
}
|
||||
return `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}` +
|
||||
`T${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}Z`;
|
||||
return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}` +
|
||||
`T${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* ⭐ 给 RRULE 加上/替换 UNTIL("此次及以后"改期/删除时,把原系列截断到指定时刻之前)。
|
||||
* - 会**移除 COUNT**(RFC 5545:UNTIL 与 COUNT 不可同时出现)
|
||||
* - UNTIL 用 UTC 形式;`untilMs` 一般是"该次发生的开始时刻 − 1 秒"
|
||||
* - UNTIL 用**浮动本地时间**(RFC 5545:`DTSTART` 是本地时间时,`UNTIL` **必须**也是本地时间;
|
||||
* 而我们把所有事件时间都写成浮动本地 —— 二者必须一致,否则不同阅读端的展开会错位)
|
||||
* - `untilMs` 一般是"该次发生的开始时刻 − 1 秒"
|
||||
*/
|
||||
static rruleWithUntil(rrule: string, untilMs: number): string {
|
||||
const pad = (n: number): string => n < 10 ? '0' + n : String(n);
|
||||
const d = new Date(untilMs);
|
||||
const until: string = `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}` +
|
||||
`T${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}Z`;
|
||||
const until: string = IcsUtil.fmtIcsTime(untilMs, false);
|
||||
const kept: string[] = [];
|
||||
for (const part of rrule.split(';')) {
|
||||
const k: string = part.split('=')[0].trim().toUpperCase();
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// entry/src/main/ets/common/MirrorRenamer.ets
|
||||
// ⭐ 一键重命名镜像账户的显示名(0.0.8)
|
||||
//
|
||||
// 为什么需要这个模块:HarmonyOS 的 `@ohos.calendarManager` **没有"修改账户"的 API**
|
||||
// (只有 create/delete/get/getAll;CalendarConfig 仅 enableReminder+color;
|
||||
// CalendarAccount.name 是 readonly)→ `displayName` 只能在创建时定,之后改不了。
|
||||
// ⇒ 想换显示名,只能"**删掉旧账户 → 按新名字重建**"。
|
||||
//
|
||||
// ⭐⭐ 安全顺序(不可调换):先回读 → 再删 → 重建 → 全量重写
|
||||
// ① `MirrorInbound.reconcile()`:把用户在系统日历里**手动新建/修改**的日程先收进本地库(置 dirty)
|
||||
// —— 因为 `deleteCalendar` 会删掉该账户下**所有**日程(含用户手动加的),不回读就会丢数据。
|
||||
// ② 删除旧镜像账户(按 bookId 精确定位)
|
||||
// ③ 立即 `syncNow()`:按用户所选的新格式重建账户并全量写回(含刚回读的 dirty 项)
|
||||
//
|
||||
// 为什么放在独立模块:`MirrorInbound` 已经 import 了 `SystemCalendarMirror`,
|
||||
// 若再把 `MirrorInbound` 反向 import 进 `SystemCalendarMirror` 会形成循环依赖;
|
||||
// 本模块作为"编排层"同时依赖二者,方向单一、无环。
|
||||
import { common } from '@kit.AbilityKit';
|
||||
import { BusinessError } from '@kit.BasicServicesKit';
|
||||
import { SystemCalendarMirror, BookRef, MirrorResult } from './SystemCalendarMirror';
|
||||
import { MirrorInbound, InboundResult } from './MirrorInbound';
|
||||
import { LogUtil } from './LogUtil';
|
||||
|
||||
/** 重命名结果(供 UI 提示) */
|
||||
export class RenameResult {
|
||||
ok: boolean = false;
|
||||
readBack: number = 0; // 回读到的用户改动条数(created+updated+deleted)
|
||||
removed: number = 0; // 删除的旧账户数
|
||||
mirrored: number = 0; // 重建后镜像的日历本数
|
||||
message: string = '';
|
||||
}
|
||||
|
||||
export class MirrorRenamer {
|
||||
/**
|
||||
* 按当前(已落盘的)显示名格式,重建全部镜像账户的显示名。
|
||||
*
|
||||
* ⚠️ 前提:调用方已把用户所选格式写入 `AppSettings`(`setMirrorDisplayFormat`);
|
||||
* 本方法只负责"按现有配置重新应用"。
|
||||
* ⚠️ 需要系统日历读写权限(调用方先校验 / 申请)。
|
||||
*/
|
||||
static async reapplyDisplayNames(context: common.Context): Promise<RenameResult> {
|
||||
const res = new RenameResult();
|
||||
if (!await SystemCalendarMirror.hasPermission()) {
|
||||
res.message = '未获得系统日历读写权限';
|
||||
return res;
|
||||
}
|
||||
|
||||
// ① 先回读:把用户在系统日历里的手动新建/修改收进本地库(置 dirty),避免删除时丢数据
|
||||
try {
|
||||
const inbound: InboundResult = await MirrorInbound.reconcile(context);
|
||||
res.readBack = inbound.created + inbound.updated + inbound.deleted;
|
||||
LogUtil.write(`重命名-回读完成:新增=${inbound.created} 修改=${inbound.updated} 删除=${inbound.deleted}`);
|
||||
} catch (err) {
|
||||
// 回读失败 → **中止重命名**(宁可不改,也不能冒着丢数据的风险删账户)
|
||||
const e = err as BusinessError;
|
||||
LogUtil.write(`重命名中止:回读失败 ${e.message}`);
|
||||
res.message = '未能先同步系统日历中的改动,已取消操作(避免数据丢失)。请稍后重试。';
|
||||
return res;
|
||||
}
|
||||
|
||||
// ② 取出当前选中的镜像本(当前配置)
|
||||
let refs: BookRef[] = [];
|
||||
try {
|
||||
refs = await SystemCalendarMirror.selectedBookRefs(context);
|
||||
} catch (err) {
|
||||
res.message = '读取镜像日历本失败';
|
||||
return res;
|
||||
}
|
||||
if (refs.length === 0) {
|
||||
res.message = '当前没有选中的镜像日历本';
|
||||
return res;
|
||||
}
|
||||
|
||||
// ③ 删除这些本的旧镜像账户(按 bookId,与名字无关)
|
||||
const bookIds: string[] = refs.map((r: BookRef): string => r.bookId);
|
||||
res.removed = await SystemCalendarMirror.removeAccountsByBookIds(context, bookIds);
|
||||
LogUtil.write(`重命名:已删除 ${res.removed} 个旧账户,准备按新格式重建`);
|
||||
|
||||
// ④ 立即按新格式重建并全量写回(含刚回读的 dirty 项)
|
||||
try {
|
||||
const mr: MirrorResult = await SystemCalendarMirror.syncNow(context);
|
||||
res.mirrored = mr.books;
|
||||
res.ok = true;
|
||||
res.message = '已按新的显示方式重新写入系统日历';
|
||||
LogUtil.write(`重命名完成:重建 ${mr.books} 个本(新增=${mr.added} 更新=${mr.updated} 删除=${mr.deleted})`);
|
||||
} catch (err) {
|
||||
const e = err as BusinessError;
|
||||
res.ok = false;
|
||||
res.message = `重建失败:${e.message}`;
|
||||
LogUtil.write(`重命名重建失败:${e.message}`);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测是否还有"旧格式"(`同步日历 · xxx`)的镜像账户 —— 用于设置页给出"可更换"的弱提示。
|
||||
* 只读,不做任何修改。
|
||||
*/
|
||||
static async hasLegacyNamedAccounts(context: common.Context): Promise<boolean> {
|
||||
return await SystemCalendarMirror.hasLegacyDisplayName(context);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import { BusinessError } from '@kit.BasicServicesKit';
|
||||
import { EventDb, LocalEvent } from './EventDb';
|
||||
import { AppSettings } from './AppSettings';
|
||||
import { AccountStore } from './AccountStore';
|
||||
import { SystemCalendarMirror } from './SystemCalendarMirror';
|
||||
import { LogUtil } from './LogUtil';
|
||||
|
||||
export class ReminderService {
|
||||
@@ -26,6 +27,39 @@ export class ReminderService {
|
||||
private static calNameCache: Map<string, string> = new Map();
|
||||
private static calNameLoadedAt: number = 0;
|
||||
|
||||
/** 已镜像到系统日历的 calKey 集合缓存(避免重复排提醒),30 秒刷新一次 */
|
||||
private static mirroredCalKeys: Set<string> = new Set();
|
||||
private static mirroredLoadedAt: number = 0;
|
||||
|
||||
/**
|
||||
* ⭐⭐ 取"已镜像到系统日历"的日历本 calKey 集合(0.0.8 修复双通道重复提醒)。
|
||||
*
|
||||
* 镜像到系统日历后,**系统日历自己会提醒**(条目的 reminderTime);
|
||||
* 若 App 再为同一个本排代理提醒 → 同一条日程提醒两次。
|
||||
* 因此这里返回"该由系统日历负责提醒"的本,App 侧**完全不再提醒**它们。
|
||||
*
|
||||
* ⚠️ 判据是"**镜像账户真实存在**"(`SystemCalendarMirror.mirroredCalKeys`),
|
||||
* 而不是"用户勾选了要镜像"—— 后者只是意图,本可能还没被真正写进系统日历;
|
||||
* 按意图跳过会导致"两边都不提醒"(漏提醒)。
|
||||
* ⚠️ 返回空集 = 不跳过任何本(保守:宁可多提醒,不可漏提醒)。
|
||||
*/
|
||||
private static async mirroredKeys(context: common.Context): Promise<Set<string>> {
|
||||
if (Date.now() - ReminderService.mirroredLoadedAt < 30000
|
||||
&& ReminderService.mirroredCalKeys.size > 0) {
|
||||
return ReminderService.mirroredCalKeys;
|
||||
}
|
||||
const out: Set<string> = await SystemCalendarMirror.mirroredCalKeys(context);
|
||||
ReminderService.mirroredCalKeys = out;
|
||||
ReminderService.mirroredLoadedAt = Date.now();
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 镜像开关变化后调用,让缓存立即失效(如用户关闭镜像 → 立刻恢复 App 提醒) */
|
||||
static invalidateMirrorCache(): void {
|
||||
ReminderService.mirroredLoadedAt = 0;
|
||||
ReminderService.mirroredCalKeys = new Set();
|
||||
}
|
||||
|
||||
/** 日历本名称(通知文案用):缓存 60 秒,'local' = 本机日历 */
|
||||
private static async calName(context: common.Context, calKey: string): Promise<string> {
|
||||
if (Date.now() - ReminderService.calNameLoadedAt > 60000
|
||||
@@ -131,10 +165,18 @@ export class ReminderService {
|
||||
await EventDb.queryRemindable(context, now, now + ReminderService.WINDOW);
|
||||
// 提醒静音的日历本(如别人分享的本):其中所有日程都不再提醒
|
||||
const muted: string[] = await AppSettings.getMutedReminderKeys(context);
|
||||
// ⭐⭐ 已镜像到系统日历的本:由系统日历负责提醒,App 不再重复排(消除"提醒两次")
|
||||
const mirrored: Set<string> = await ReminderService.mirroredKeys(context);
|
||||
if (mirrored.size > 0) {
|
||||
LogUtil.write(`提醒跳过 ${mirrored.size} 个已镜像到系统日历的日历本(交由系统日历提醒)`);
|
||||
}
|
||||
for (const e of rows) {
|
||||
if (muted.includes(e.calKey)) {
|
||||
continue;
|
||||
}
|
||||
if (mirrored.has(e.calKey)) {
|
||||
continue; // ⭐ 已镜像 → 系统日历会提醒,这里跳过避免重复
|
||||
}
|
||||
if (published >= ReminderService.MAX_REMINDERS) {
|
||||
break;
|
||||
}
|
||||
@@ -211,11 +253,16 @@ export class ReminderService {
|
||||
const rows: LocalEvent[] =
|
||||
await EventDb.queryRemindable(context, now, now + ReminderService.WINDOW);
|
||||
const muted: string[] = await AppSettings.getMutedReminderKeys(context);
|
||||
// ⭐⭐ 已镜像到系统日历的本:由系统日历负责提醒,App 侧不再补发(消除"提醒两次")
|
||||
const mirrored: Set<string> = await ReminderService.mirroredKeys(context);
|
||||
let fired: number = 0;
|
||||
for (const e of rows) {
|
||||
if (muted.includes(e.calKey)) {
|
||||
continue;
|
||||
}
|
||||
if (mirrored.has(e.calKey)) {
|
||||
continue; // ⭐ 已镜像 → 交由系统日历提醒
|
||||
}
|
||||
const rems: number[] = e.reminders.length > 0 ? e.reminders
|
||||
: (e.reminder > 0 ? [e.reminder] : []);
|
||||
for (const rem of rems) {
|
||||
|
||||
@@ -80,8 +80,14 @@ export class SystemCalendarMirror {
|
||||
];
|
||||
/** 系统日历账户 name 前缀。name 是开发者定义且 readonly,必须稳定可复现才能找到已有账户 */
|
||||
private static readonly ACCOUNT_PREFIX: string = 'synccalendar.mirror.';
|
||||
/** 系统日历账户 displayName 前缀,便于用户在系统日历里识别来源 */
|
||||
private static readonly DISPLAY_PREFIX: string = '同步日历 · ';
|
||||
/**
|
||||
* 系统日历账户 displayName 中「同步日历」字面量 —— **仅供"兜底识别"使用**。
|
||||
* ⚠️ 0.0.8 起 displayName 变为可切换(三种格式),本常量**不再用于生成名字**,
|
||||
* 只用于判断"这个名字是否含我们的归属标识"(格式 1/2 含、格式 3 不含)。
|
||||
*/
|
||||
private static readonly DISPLAY_MARK: string = '同步日历';
|
||||
/** 旧版固定前缀(`同步日历 · `,半角点 U+00B7 带空格)——仅用于识别/迁移历史账户 */
|
||||
private static readonly LEGACY_DISPLAY_PREFIX: string = '同步日历 · ';
|
||||
private static readonly DAY: number = 86400000;
|
||||
/** getEvents() 显式指定返回字段:identifier 只在 API20+ 的默认字段里,写死更保险 */
|
||||
private static readonly QUERY_FIELDS: (keyof calendarManager.Event)[] = [
|
||||
@@ -148,6 +154,71 @@ export class SystemCalendarMirror {
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================== 账户显示名(0.0.8 可切换) ==================== */
|
||||
|
||||
/**
|
||||
* ⭐ 生成系统日历账户的 displayName。
|
||||
*
|
||||
* 三种格式(分隔符统一为**半角点 `·`(U+00B7)+ 无空格**,尽量短):
|
||||
* 1 = `同步日历·<本名>` —— 保留应用名
|
||||
* 2 = `同步日历·<账号>·<本名>` —— 平板/大屏,信息最全
|
||||
* 3 = `<账号>·<本名>` ★默认 —— 短、能区分账号
|
||||
*
|
||||
* ⚠️ **不提供"仅本名"**:用户原系统日历里可能有同名日历本,裸本名无法与之区分 → 有误删风险。
|
||||
* 每个镜像账户名**至少要带一个归属标识**(`同步日历` / `账号名` / 两者)。
|
||||
*
|
||||
* ⚠️ displayName 上限 64 字符(系统限制)→ 超长时截断,避免 createCalendar 失败。
|
||||
*/
|
||||
static displayNameFor(ref: BookRef, format: number): string {
|
||||
const sep: string = '·';
|
||||
const book: string = ref.name !== '' ? ref.name : '日历本';
|
||||
const acc: string = ref.accountName !== '' ? ref.accountName : '账号';
|
||||
let out: string;
|
||||
if (format === 1) {
|
||||
out = `${SystemCalendarMirror.DISPLAY_MARK}${sep}${book}`;
|
||||
} else if (format === 2) {
|
||||
out = `${SystemCalendarMirror.DISPLAY_MARK}${sep}${acc}${sep}${book}`;
|
||||
} else {
|
||||
out = `${acc}${sep}${book}`;
|
||||
}
|
||||
// displayName 系统上限 64 字符:超长截断(保留前面的归属标识,它比本名更重要)
|
||||
if (out.length > 64) {
|
||||
out = out.substring(0, 64);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 某个 displayName 是否**含我们的归属标识**(用于兜底识别;格式 1/2 含、格式 3 不含) */
|
||||
static displayNameHasMark(display: string): boolean {
|
||||
return display.startsWith(SystemCalendarMirror.DISPLAY_MARK);
|
||||
}
|
||||
|
||||
/** 某个 displayName 是否是**旧版固定格式**(`同步日历 · xxx`,用于提示用户可更换) */
|
||||
static isLegacyDisplayName(display: string): boolean {
|
||||
return display.startsWith(SystemCalendarMirror.LEGACY_DISPLAY_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否还存在"旧格式"镜像账户 —— 设置页据此给出"可更换显示名称"的弱提示(只读,不修改)。
|
||||
* 判据:`name` 是我们的前缀 + `displayName` 是旧格式。
|
||||
*/
|
||||
static async hasLegacyDisplayName(context: common.Context): Promise<boolean> {
|
||||
try {
|
||||
const cm: calendarManager.CalendarManager = calendarManager.getCalendarManager(context);
|
||||
const all: calendarManager.Calendar[] = await cm.getAllCalendars();
|
||||
for (const cal of all) {
|
||||
const acc: calendarManager.CalendarAccount = cal.getAccount();
|
||||
if (acc.name.startsWith(SystemCalendarMirror.ACCOUNT_PREFIX) &&
|
||||
SystemCalendarMirror.isLegacyDisplayName(acc.displayName ?? '')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================== 主入口 ==================== */
|
||||
|
||||
/**
|
||||
@@ -168,6 +239,117 @@ export class SystemCalendarMirror {
|
||||
return name.startsWith(SystemCalendarMirror.ACCOUNT_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* ⭐⭐ 取"**确实已经镜像到系统日历**"的日历本 calKey 集合(按镜像账户的**真实存在性**判定)。
|
||||
*
|
||||
* 与"用户勾选了要镜像的本"不同 —— 后者只是**意图**,本可能还没被真正写进系统日历
|
||||
* (如刚勾选但没点「立即执行镜像」、或根本没开镜像开关)。
|
||||
* 若按"意图"跳过 App 提醒,而系统日历里其实还没有 → **两边都不提醒 = 漏提醒**。
|
||||
* 故这里只认**镜像账户真实存在**这一条。
|
||||
*
|
||||
* ⚠️ 返回**空集**=不跳过任何本(读不到账户时保守处理,宁可多提醒)。
|
||||
* ⚠️ 未开启镜像开关时直接返回空集(省一次系统查询)。
|
||||
*/
|
||||
static async mirroredCalKeys(context: common.Context): Promise<Set<string>> {
|
||||
const out: Set<string> = new Set<string>();
|
||||
try {
|
||||
if (!await AppSettings.getMirrorEnabled(context)) {
|
||||
return out; // 未开启镜像 → 没有任何本由系统日历负责
|
||||
}
|
||||
if (!await SystemCalendarMirror.hasPermission()) {
|
||||
return out; // 无权限 → 系统日历里不可能有我们的条目
|
||||
}
|
||||
const cm: calendarManager.CalendarManager = calendarManager.getCalendarManager(context);
|
||||
const all: calendarManager.Calendar[] = [];
|
||||
const cals: calendarManager.Calendar[] = await cm.getAllCalendars();
|
||||
for (const c of cals) {
|
||||
all.push(c);
|
||||
}
|
||||
// 存在镜像账户 → 其 bookId 对应的本由系统日历负责
|
||||
const presentBookIds: Set<string> = new Set<string>();
|
||||
for (const c of all) {
|
||||
const name: string = c.getAccount().name;
|
||||
if (name.startsWith(SystemCalendarMirror.ACCOUNT_PREFIX)) {
|
||||
presentBookIds.add(name.substring(SystemCalendarMirror.ACCOUNT_PREFIX.length));
|
||||
}
|
||||
}
|
||||
if (presentBookIds.size === 0) {
|
||||
return out;
|
||||
}
|
||||
// bookId → calKey(从当前账号配置解析)
|
||||
const refs: BookRef[] = await SystemCalendarMirror.listBooks(context);
|
||||
for (const r of refs) {
|
||||
if (presentBookIds.has(r.bookId) && r.calKey !== '') {
|
||||
out.add(r.calKey);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
LogUtil.write(`判定"已镜像本"失败(按未镜像处理): ${(err as BusinessError).message}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ==================== 账户身份判定(0.0.8) ==================== */
|
||||
|
||||
/**
|
||||
* 取当前 App 里真实存在的账号 id 集合(用于识别"我们的镜像账户"的身份)。
|
||||
* ⚠️ 读取失败返回**空集**,调用方据此**跳过清理**(宁可不清,也不误删)。
|
||||
*/
|
||||
private static async currentAccountIds(context: common.Context): Promise<Set<string>> {
|
||||
const ids: Set<string> = new Set<string>();
|
||||
try {
|
||||
const accounts: DavAccount[] = await AccountStore.loadAll(context);
|
||||
for (const a of accounts) {
|
||||
if (a.id !== '') {
|
||||
ids.add(a.id);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
LogUtil.write(`读取账号列表失败(清理将保守跳过): ${(err as BusinessError).message}`);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* ⭐ 某个系统日历账户是不是**本应用镜像出去的**(身份级判定)。
|
||||
*
|
||||
* 两道闸:
|
||||
* ① `name` 以 `synccalendar.mirror.` 开头 —— 挡掉所有"别人家的账户";
|
||||
* ② 从 `name` 切出 `accId`(`<accId>-<href哈希>`,取**最后一个** `-` 之前的部分),
|
||||
* 并确认它在当前账号库里 —— 精准识别"账号已删的孤儿",**与显示名完全解耦**。
|
||||
*
|
||||
* ⚠️ 为什么不能只靠 displayName:显示名现在**可切换**(格式 3 不含"同步日历"),
|
||||
* 且格式 3(`账号·本名`)可能与别的 App 的账户同名 → 只按名字判定会**误删用户数据**。
|
||||
*
|
||||
* @param knownIds 当前真实账号 id 集合(**空集 = 读不到账号 → 一律返回 false**,保守)
|
||||
* @param allowDisplayMark 是否允许"仅 displayName 含归属标识"兜底(**仅格式 1/2 可用**)
|
||||
*/
|
||||
static isOurMirrorAccount(
|
||||
name: string,
|
||||
display: string,
|
||||
knownIds: Set<string>,
|
||||
allowDisplayMark: boolean
|
||||
): boolean {
|
||||
if (knownIds.size === 0) {
|
||||
return false; // 安全阀:拿不到账号身份就不认为任何账户是我们的
|
||||
}
|
||||
if (name.startsWith(SystemCalendarMirror.ACCOUNT_PREFIX)) {
|
||||
// ① name 前缀命中 → 切出 accId 做身份校验
|
||||
const bookId: string = name.substring(SystemCalendarMirror.ACCOUNT_PREFIX.length);
|
||||
const cut: number = bookId.lastIndexOf('-');
|
||||
const accId: string = cut > 0 ? bookId.substring(0, cut) : bookId;
|
||||
// ② accId 在库里 → 确认是我们的;
|
||||
// 不在库里 → 视作"账号已删的孤儿/历史脏数据"(仍需清理)→ 也返回 true
|
||||
if (knownIds.has(accId)) {
|
||||
return true;
|
||||
}
|
||||
LogUtil.write(`镜像账户 name=${name} 的 accId=${accId} 不在账号库 → 按孤儿处理`);
|
||||
return true;
|
||||
}
|
||||
// ③ name 不像我们 → 仅当 displayName 带归属标识、且允许兜底时,才认为是我们的
|
||||
return allowDisplayMark && SystemCalendarMirror.displayNameHasMark(display);
|
||||
}
|
||||
|
||||
/* ==================== 孤儿账户清理 ==================== */
|
||||
|
||||
/**
|
||||
@@ -196,9 +378,18 @@ export class SystemCalendarMirror {
|
||||
LogUtil.write(`清理镜像账户失败:读不到系统日历账户列表 ${(err as BusinessError).message}`);
|
||||
return out;
|
||||
}
|
||||
// ⭐ 0.0.8 身份校验:拿"当前真实账号 id"当判据 —— 读不到就保守跳过,绝不误删
|
||||
const knownIds: Set<string> = await SystemCalendarMirror.currentAccountIds(context);
|
||||
if (knownIds.size === 0) {
|
||||
LogUtil.write('⚠️ 清理跳过:读不到任何账号 id(安全阀,避免误删)');
|
||||
return out;
|
||||
}
|
||||
// displayName 兜底**仅格式 1/2 可用**(含"同步日历",可与他人区分);格式 3 不参与兜底
|
||||
const fmt: number = await AppSettings.getMirrorDisplayFormat(context);
|
||||
const allowDisplayMark: boolean = aggressive && (fmt === 1 || fmt === 2);
|
||||
// ① 诊断:把**全部**账户列一遍(不只是我们的),才能看出残留账户到底是什么名字
|
||||
for (const cal of all) {
|
||||
out.detail.push(SystemCalendarMirror.describeCal(cal, validNames, aggressive));
|
||||
out.detail.push(SystemCalendarMirror.describeCal(cal, validNames, allowDisplayMark));
|
||||
}
|
||||
LogUtil.write(`系统日历账户清单(共 ${all.length}):`);
|
||||
for (const line of out.detail) {
|
||||
@@ -211,10 +402,9 @@ export class SystemCalendarMirror {
|
||||
const name: string = acc.name;
|
||||
const display: string = acc.displayName ?? '';
|
||||
const mineByName: boolean = name.startsWith(SystemCalendarMirror.ACCOUNT_PREFIX);
|
||||
const mineByDisplay: boolean = aggressive &&
|
||||
display.startsWith(SystemCalendarMirror.DISPLAY_PREFIX);
|
||||
if (!mineByName && !mineByDisplay) {
|
||||
continue;
|
||||
// ⭐ 身份级判定:name 前缀 → 切出 accId → 必须匹配当前真实账号(详见 isOurMirrorAccount)
|
||||
if (!SystemCalendarMirror.isOurMirrorAccount(name, display, knownIds, allowDisplayMark)) {
|
||||
continue; // 身份不符 → 绝不碰(可能用户原有的日历本 / 别的 App 建的)
|
||||
}
|
||||
if (validNames.has(name)) {
|
||||
continue; // 本次还要用,保留
|
||||
@@ -275,18 +465,78 @@ export class SystemCalendarMirror {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* ⭐ 删除指定的若干镜像账户(按 bookId 精确定位,用于"一键重命名"前清空旧账户)。
|
||||
*
|
||||
* ⚠️ 调用方**必须**已先回读(`MirrorInbound.reconcile`),否则会丢掉用户手动加的日程。
|
||||
* ⚠️ 只需 `name` 精确匹配即可 —— 不需要 displayName 判定(bookId 是身份,名字已无关)。
|
||||
* 每个账户独立 try/catch + "清空日程后重试"降级,与 purgeOrphans 同策略。
|
||||
*/
|
||||
static async removeAccountsByBookIds(context: common.Context, bookIds: string[]): Promise<number> {
|
||||
if (bookIds.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
const cm: calendarManager.CalendarManager = calendarManager.getCalendarManager(context);
|
||||
const targets: Set<string> = new Set<string>();
|
||||
for (const b of bookIds) {
|
||||
targets.add(SystemCalendarMirror.ACCOUNT_PREFIX + b);
|
||||
}
|
||||
let removed: number = 0;
|
||||
let all: calendarManager.Calendar[] = [];
|
||||
try {
|
||||
all = await cm.getAllCalendars();
|
||||
} catch (err) {
|
||||
LogUtil.write(`重命名-删除旧账户失败:读不到账户列表 ${(err as BusinessError).message}`);
|
||||
return 0;
|
||||
}
|
||||
for (const cal of all) {
|
||||
const acc: calendarManager.CalendarAccount = cal.getAccount();
|
||||
const name: string = acc.name;
|
||||
if (!targets.has(name)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await cm.deleteCalendar(cal);
|
||||
removed++;
|
||||
LogUtil.write(`重命名:已删除旧账户 id=${cal.id} name=${name}`);
|
||||
} catch (err) {
|
||||
const e1 = err as BusinessError;
|
||||
LogUtil.write(`重命名:删除账户失败,尝试清空后重试 name=${name}: ${e1.message}`);
|
||||
try {
|
||||
const evs: calendarManager.Event[] = await SystemCalendarMirror.queryEvents(cal);
|
||||
const ids: number[] = [];
|
||||
for (const ev of evs) {
|
||||
if (ev.id !== undefined) {
|
||||
ids.push(ev.id);
|
||||
}
|
||||
}
|
||||
if (ids.length > 0) {
|
||||
await cal.deleteEvents(ids);
|
||||
}
|
||||
await cm.deleteCalendar(cal);
|
||||
removed++;
|
||||
LogUtil.write(`重命名:清空后删除成功 name=${name}`);
|
||||
} catch (err2) {
|
||||
LogUtil.write(`重命名:删除账户最终失败 name=${name}: ${(err2 as BusinessError).message}`);
|
||||
}
|
||||
}
|
||||
// 快照按键是 bookId(与账户名无关),账户删了但快照应保留 → 重建后仍幂等,故不动快照
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
/** 一个账户的诊断行:`#id [KEEP/MINE/other] name=… display=… type=…` */
|
||||
private static describeCal(
|
||||
cal: calendarManager.Calendar,
|
||||
validNames: Set<string>,
|
||||
aggressive: boolean
|
||||
allowDisplayMark: boolean
|
||||
): string {
|
||||
const acc: calendarManager.CalendarAccount = cal.getAccount();
|
||||
const name: string = acc.name;
|
||||
const display: string = acc.displayName ?? '';
|
||||
const mineByName: boolean = name.startsWith(SystemCalendarMirror.ACCOUNT_PREFIX);
|
||||
const mineByDisplay: boolean = aggressive &&
|
||||
display.startsWith(SystemCalendarMirror.DISPLAY_PREFIX);
|
||||
const mineByDisplay: boolean = allowDisplayMark &&
|
||||
display.startsWith(SystemCalendarMirror.DISPLAY_MARK);
|
||||
let tag: string = 'other ';
|
||||
if (mineByName || mineByDisplay) {
|
||||
tag = validNames.has(name) ? 'KEEP ' : 'MINE ';
|
||||
@@ -346,13 +596,15 @@ export class SystemCalendarMirror {
|
||||
|
||||
const winStart: number = SystemCalendarMirror.windowStart();
|
||||
const winEnd: number = SystemCalendarMirror.windowEnd();
|
||||
// ⭐ 0.0.8:读取用户所选的显示名格式(仅影响**新建**账户的名字;已有账户不在此处改名)
|
||||
const format: number = await AppSettings.getMirrorDisplayFormat(context);
|
||||
const plans: Map<string, MirrorOcc[]> = new Map<string, MirrorOcc[]>();
|
||||
for (const ref of refs) {
|
||||
try {
|
||||
const plan: MirrorOcc[] =
|
||||
await SystemCalendarMirror.planFor(context, ref, winStart, winEnd, res);
|
||||
plans.set(ref.bookId, plan);
|
||||
await SystemCalendarMirror.syncBook(context, cm, ref, plan, winStart, winEnd, res);
|
||||
await SystemCalendarMirror.syncBook(context, cm, ref, plan, winStart, winEnd, res, format);
|
||||
res.books++;
|
||||
} catch (err) {
|
||||
const e = err as BusinessError;
|
||||
@@ -689,11 +941,12 @@ export class SystemCalendarMirror {
|
||||
plan: MirrorOcc[],
|
||||
winStart: number,
|
||||
winEnd: number,
|
||||
res: MirrorResult
|
||||
res: MirrorResult,
|
||||
format: number
|
||||
): Promise<void> {
|
||||
// ⭐ 账户名与 identifier 一律用 **bookId**(由 href 派生、稳定),绝不用 calKey
|
||||
const cal: calendarManager.Calendar =
|
||||
await SystemCalendarMirror.ensureCalendar(cm, ref.sysAccountName, ref);
|
||||
await SystemCalendarMirror.ensureCalendar(cm, ref.sysAccountName, ref, format);
|
||||
|
||||
// 现有镜像条目:identifier -> Event
|
||||
const existing: Map<string, calendarManager.Event> = new Map<string, calendarManager.Event>();
|
||||
@@ -998,16 +1251,24 @@ export class SystemCalendarMirror {
|
||||
}
|
||||
}
|
||||
|
||||
/** 幂等地取得本应用自己的镜像账户(已存在则复用,不存在则创建并设色) */
|
||||
/**
|
||||
* 幂等地取得本应用自己的镜像账户(已存在则复用,不存在则创建并设色)。
|
||||
*
|
||||
* ⭐ 0.0.8:displayName 按用户所选格式生成。
|
||||
* ⚠️ **已存在的账户不会被改名**(平台无"改账户名"API;改名是破坏性操作,
|
||||
* 必须由用户显式触发 `reapplyDisplayNames`)。此处仅保证**新建**时用对格式。
|
||||
*/
|
||||
private static async ensureCalendar(
|
||||
cm: calendarManager.CalendarManager,
|
||||
accountName: string,
|
||||
ref: BookRef
|
||||
ref: BookRef,
|
||||
format: number
|
||||
): Promise<calendarManager.Calendar> {
|
||||
const calendars: calendarManager.Calendar[] = await cm.getAllCalendars();
|
||||
for (const cal of calendars) {
|
||||
if (cal.getAccount().name === accountName) {
|
||||
// 每次都尝试同步一次显示名与颜色(用户可能改过日历本名/色)
|
||||
// 每次都尝试同步一次颜色(用户可能改过日历本色)
|
||||
// ⚠️ displayName 不在此处改:改账户名需删账户重建(破坏性),由用户显式触发
|
||||
try {
|
||||
await cal.setConfig({ enableReminder: true, color: ref.color });
|
||||
} catch (err) {
|
||||
@@ -1019,7 +1280,7 @@ export class SystemCalendarMirror {
|
||||
const cal: calendarManager.Calendar = await cm.createCalendar({
|
||||
name: accountName,
|
||||
type: calendarManager.CalendarType.LOCAL,
|
||||
displayName: SystemCalendarMirror.DISPLAY_PREFIX + ref.name
|
||||
displayName: SystemCalendarMirror.displayNameFor(ref, format)
|
||||
});
|
||||
try {
|
||||
await cal.setConfig({ enableReminder: true, color: ref.color });
|
||||
@@ -1057,14 +1318,62 @@ export class SystemCalendarMirror {
|
||||
ev.location = { location: e.location };
|
||||
}
|
||||
const reminders: number[] = SystemCalendarMirror.remindersOf(e);
|
||||
if (reminders.length > 0) {
|
||||
ev.reminderTime = reminders;
|
||||
// ⭐⭐ 只写"提醒时刻尚未到"的提醒(0.0.8 修复"已过日程仍提醒")。
|
||||
// 原因:写进系统日历的 reminderTime 一旦其时刻已过,系统会在**任何一次覆写**时
|
||||
// 立即补发一条通知 → 表现为"日程都过去了还提醒"。这类提醒已无意义,索性不写。
|
||||
const future: number[] = SystemCalendarMirror.futureReminders(
|
||||
reminders, startTs, e.isAllDay, Date.now());
|
||||
if (future.length > 0) {
|
||||
ev.reminderTime = future;
|
||||
}
|
||||
// ⚠️ 这里**故意不设 recurrenceRule**:重复日程由我们自己按窗口展开成多条实例,
|
||||
// 交给系统日历展开会因 RecurrenceRule 表达不全而出现错误的重复(09-19 事故)。
|
||||
return ev;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提醒时刻的"基准时刻"(系统口径):
|
||||
* - 普通日程:以**开始时刻**为基准(提前 N 分钟 = start - N);
|
||||
* - 全天日程:系统文档规定以**当日 09:00**为基准(提前 N 分钟 = 当天 09:00 - N)。
|
||||
*/
|
||||
private static reminderBaseMs(startTs: number, isAllDay: boolean): number {
|
||||
if (isAllDay) {
|
||||
const d: Date = new Date(startTs);
|
||||
d.setHours(9, 0, 0, 0);
|
||||
return d.getTime();
|
||||
}
|
||||
return startTs;
|
||||
}
|
||||
|
||||
/** 过滤出"提醒时刻还没到"的提醒(用于避免写入已过期的提醒而触发补发) */
|
||||
private static futureReminders(
|
||||
reminders: number[],
|
||||
startTs: number,
|
||||
isAllDay: boolean,
|
||||
now: number
|
||||
): number[] {
|
||||
const base: number = SystemCalendarMirror.reminderBaseMs(startTs, isAllDay);
|
||||
const kept: number[] = [];
|
||||
for (const r of reminders) {
|
||||
if (r > 0 && base - r * 60000 > now) {
|
||||
kept.push(r);
|
||||
}
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
/** 提醒数组的规范化字符串(排序去重后拼接),用于比较 */
|
||||
private static reminderKey(reminders: number[]): string {
|
||||
const s: number[] = reminders.slice().sort((a: number, b: number): number => a - b);
|
||||
const out: string[] = [];
|
||||
for (const n of s) {
|
||||
if (out.indexOf(String(n)) < 0) {
|
||||
out.push(String(n));
|
||||
}
|
||||
}
|
||||
return out.join(',');
|
||||
}
|
||||
|
||||
/** 本地时区当天 0 点的时间戳 */
|
||||
private static dayStart(ts: number): number {
|
||||
const d: Date = new Date(ts);
|
||||
@@ -1127,6 +1436,15 @@ export class SystemCalendarMirror {
|
||||
if ((cur.location?.location ?? '') !== (want.location?.location ?? '')) {
|
||||
return 'location';
|
||||
}
|
||||
// ⭐ 0.0.8:提醒也要比较 —— 否则用户改了提醒时间,系统日历侧**永远不会更新**
|
||||
// (旧版 diffOf 不比 reminderTime,改动被判定为"无差异" → 不触发 updateEvent)。
|
||||
// ⚠️ 写入侧已过滤掉"已过期"的提醒(见 toSystemEvent / futureReminders),
|
||||
// 所以这里的比较也用同一口径,避免"每轮都因提醒不同而重写"。
|
||||
const curRem: number[] = cur.reminderTime ?? [];
|
||||
const wantRem: number[] = want.reminderTime ?? [];
|
||||
if (SystemCalendarMirror.reminderKey(curRem) !== SystemCalendarMirror.reminderKey(wantRem)) {
|
||||
return `reminder ${SystemCalendarMirror.reminderKey(curRem) || '(无)'} != ${SystemCalendarMirror.reminderKey(wantRem) || '(无)'}`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { FormExtensionAbility, formBindingData, formProvider } from '@kit.FormKi
|
||||
import { Want } from '@kit.AbilityKit';
|
||||
import { BusinessError } from '@kit.BasicServicesKit';
|
||||
import { CardDataService, CardData } from '../common/CardDataService';
|
||||
import { BackgroundSyncRunner } from '../common/BackgroundSyncRunner';
|
||||
import { LogUtil } from '../common/LogUtil';
|
||||
|
||||
export default class EntryFormAbility extends FormExtensionAbility {
|
||||
@@ -42,8 +43,28 @@ export default class EntryFormAbility extends FormExtensionAbility {
|
||||
LogUtil.init(this.context);
|
||||
LogUtil.write(`系统触发卡片更新: formId=${formId}`);
|
||||
CardDataService.registerForm(this.context, formId);
|
||||
// ⭐ ① 先用**本地缓存**立刻刷新卡片(几毫秒,不依赖网络)
|
||||
// 保留用户翻到的日期(系统定时刷新不应把用户翻走的日期拽回今天)
|
||||
this.pushData(formId, CardDataService.getDayOffset(formId));
|
||||
// ⭐ ② 再借这次系统刷新顺带跑一次后台同步(见 runOnceThrottledByCard:带节流、永不抛错)
|
||||
// 同步成功后再推一次,让卡片显示刚同步回来的最新数据。
|
||||
//
|
||||
// ⚠️ 关键约束(依据官方 FormExtensionAbility 生命周期文档):
|
||||
// "FormExtensionAbility 进程不能常驻后台,生命周期回调中无法处理长时间的任务,
|
||||
// 生命周期调度完成后会继续存在 **10 秒**……可能需要 10 秒以上才能完成的业务逻辑,
|
||||
// 建议拉起主应用进行处理。"
|
||||
// ⇒ 本处同步**可能被进程回收中断**。这是**可接受**的,因为:
|
||||
// · 同步是幂等的(基于 etag 增量比对 + dirty 标记),中断不会损坏任何数据;
|
||||
// · 中断只是"这一次没同步成",下个 30 分钟卡片再刷新时会重试;
|
||||
// · 正常网络下 1~3 个账号的**增量**同步通常数秒内完成,落在 10 秒窗口内。
|
||||
// ⇒ 因此它是"**尽力而为地提高后台同步频率**",与 workScheduler 2 小时兜底、
|
||||
// 回前台/网络恢复补同步共同构成多层保障,**不承诺 30 分钟必然同步成功**。
|
||||
// (不采用"拉起主应用同步"是因为会每 30 分钟弹出一次界面,体验不可接受。)
|
||||
BackgroundSyncRunner.runOnceThrottledByCard(this.context).then((): void => {
|
||||
this.pushData(formId, CardDataService.getDayOffset(formId));
|
||||
}).catch((err: BusinessError): void => {
|
||||
LogUtil.write(`卡片驱动同步失败: ${err.message}`);
|
||||
});
|
||||
}
|
||||
|
||||
onRemoveForm(formId: string): void {
|
||||
|
||||
@@ -11,6 +11,7 @@ import { AccountStore, DavAccount } from '../common/AccountStore';
|
||||
import { ReminderService } from '../common/ReminderService';
|
||||
import { BusinessError } from '@kit.BasicServicesKit';
|
||||
import { BackupTargetCheck, BookRef, MirrorResult, PurgeResult, SystemCalendarMirror } from '../common/SystemCalendarMirror';
|
||||
import { MirrorRenamer, RenameResult } from '../common/MirrorRenamer';
|
||||
import { DocViewer } from '../common/DocViewer';
|
||||
|
||||
const INTERVAL_OPTIONS: number[] = [1, 5, 15, 30, 60];
|
||||
@@ -51,6 +52,12 @@ struct SettingsPage {
|
||||
@State mirrorCandidates: BackupTarget[] = []; // 可镜像的本(已排除"系统日历备份目标本",防回灌)
|
||||
@State mirrorInbound: boolean = false; // 是否把系统日历的改动回写 CalDAV(默认关)
|
||||
@State accountDump: string = ''; // 系统日历账户清单(诊断用,清理后填充)
|
||||
// ⭐ 系统日历账户显示名格式:1=`同步日历·本名` 2=`同步日历·账号·本名` 3=`账号·本名`(默认)
|
||||
@State displayFormat: number = 3;
|
||||
@State displayFormatApplied: number = 3; // 已生效的格式(用于判断"应用"按钮是否可点)
|
||||
@State formatRunning: boolean = false; // 正在按新格式重建镜像
|
||||
@State hasLegacyNames: boolean = false; // 是否还有旧格式账户(给出"可更换"弱提示)
|
||||
@State formatPreview: string = ''; // 实时预览示例
|
||||
private context?: common.Context;
|
||||
|
||||
aboutToAppear(): void {
|
||||
@@ -103,6 +110,8 @@ struct SettingsPage {
|
||||
if (!ok && this.context !== undefined) {
|
||||
this.mirrorEnabled = false;
|
||||
AppSettings.setMirrorEnabled(this.context, false);
|
||||
// 权限被回收 → 镜像失效 → 提醒应交回 App 负责
|
||||
ReminderService.invalidateMirrorCache();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -118,6 +127,71 @@ struct SettingsPage {
|
||||
AppSettings.getMirrorInbound(ctx).then((v: boolean): void => {
|
||||
this.mirrorInbound = v;
|
||||
});
|
||||
// ⭐ 显示名格式:加载当前值 + 实时预览 + 检查是否还有旧格式账户
|
||||
AppSettings.getMirrorDisplayFormat(ctx).then((v: number): void => {
|
||||
this.displayFormat = v;
|
||||
this.displayFormatApplied = v;
|
||||
this.refreshFormatPreview();
|
||||
});
|
||||
MirrorRenamer.hasLegacyNamedAccounts(ctx).then((v: boolean): void => {
|
||||
this.hasLegacyNames = v;
|
||||
});
|
||||
}
|
||||
|
||||
/** 用用户**实际的第一个账号名 + 第一个本名**拼出示例,让他所见即所得 */
|
||||
private refreshFormatPreview(): void {
|
||||
const ctx = this.context;
|
||||
if (ctx === undefined) {
|
||||
return;
|
||||
}
|
||||
const f: number = this.displayFormat;
|
||||
SystemCalendarMirror.selectedBookRefs(ctx).then((refs: BookRef[]): void => {
|
||||
if (refs.length > 0) {
|
||||
this.formatPreview = SystemCalendarMirror.displayNameFor(refs[0], f);
|
||||
} else {
|
||||
// 没有可用本时用占位示例
|
||||
const dummy = new BookRef();
|
||||
dummy.name = '个人日程';
|
||||
dummy.accountName = '工作';
|
||||
this.formatPreview = SystemCalendarMirror.displayNameFor(dummy, f);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** ⭐ 按新格式重建镜像(回读→删→重建),期间日程短暂消失几秒 */
|
||||
private async applyDisplayFormat(): Promise<void> {
|
||||
const ctx = this.context;
|
||||
if (ctx === undefined || this.formatRunning) {
|
||||
return;
|
||||
}
|
||||
if (this.displayFormat === this.displayFormatApplied) {
|
||||
return; // 未变化,不需要重建
|
||||
}
|
||||
this.formatRunning = true;
|
||||
try {
|
||||
// 先落盘(reapplyDisplayNames 会按现有配置重建)
|
||||
await AppSettings.setMirrorDisplayFormat(ctx, this.displayFormat);
|
||||
const res: RenameResult = await MirrorRenamer.reapplyDisplayNames(
|
||||
ctx as common.UIAbilityContext);
|
||||
if (res.ok) {
|
||||
this.displayFormatApplied = this.displayFormat;
|
||||
this.hasLegacyNames = false;
|
||||
this.getUIContext().getPromptAction().showToast({
|
||||
message: `已更新系统日历中的名称(${res.mirrored} 个日历本)`
|
||||
});
|
||||
} else {
|
||||
// 失败 → 回滚选项与配置,避免"设置显示已改、实际没改"的错觉
|
||||
this.displayFormat = this.displayFormatApplied;
|
||||
await AppSettings.setMirrorDisplayFormat(ctx, this.displayFormatApplied);
|
||||
this.getUIContext().getPromptAction().showToast({ message: res.message });
|
||||
}
|
||||
} catch (err) {
|
||||
const e = err as BusinessError;
|
||||
this.displayFormat = this.displayFormatApplied;
|
||||
this.getUIContext().getPromptAction().showToast({ message: `更新失败:${e.message}` });
|
||||
}
|
||||
this.formatRunning = false;
|
||||
this.refreshFormatPreview();
|
||||
}
|
||||
|
||||
/** 重新检测通知权限状态 */
|
||||
@@ -446,13 +520,19 @@ struct SettingsPage {
|
||||
}
|
||||
this.mirrorEnabled = isOn;
|
||||
await AppSettings.setMirrorEnabled(this.context, isOn);
|
||||
// ⭐ 镜像开关变化 → 立即失效提醒侧的"已镜像本"缓存,并重排提醒
|
||||
// (开启:这些本改由系统日历提醒,App 不再重复;关闭:必须立刻恢复 App 提醒,避免漏提醒)
|
||||
ReminderService.invalidateMirrorCache();
|
||||
if (isOn) {
|
||||
this.getUIContext().getPromptAction().showToast({
|
||||
message: '已开启镜像:勾选要同步的日历本后点「立即执行镜像」'
|
||||
});
|
||||
await ReminderService.refreshReminders(this.context as common.UIAbilityContext);
|
||||
return;
|
||||
}
|
||||
const n: number = await SystemCalendarMirror.removeAll(this.context);
|
||||
// 关闭镜像后,这些本的提醒要交回 App 负责
|
||||
await ReminderService.refreshReminders(this.context as common.UIAbilityContext);
|
||||
this.getUIContext().getPromptAction().showToast({
|
||||
message: n > 0 ? `已关闭镜像,并清除系统日历中的 ${n} 个镜像账户` : '已关闭镜像'
|
||||
});
|
||||
@@ -473,6 +553,9 @@ struct SettingsPage {
|
||||
return;
|
||||
}
|
||||
await AppSettings.setMirrorBookIds(this.context, this.mirrorKeys);
|
||||
// ⭐ 勾选本变化 → 提醒侧"已镜像本"集合变化:失效缓存并重排提醒
|
||||
ReminderService.invalidateMirrorCache();
|
||||
await ReminderService.refreshReminders(this.context as common.UIAbilityContext);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -936,6 +1019,67 @@ struct SettingsPage {
|
||||
.width('100%')
|
||||
.padding({ top: 4 })
|
||||
|
||||
// ⭐ 系统日历中的显示名称(0.0.8):三种格式,切换需重建镜像
|
||||
Column({ space: 6 }) {
|
||||
Text('系统日历中的显示名称')
|
||||
.fontSize(13)
|
||||
.fontWeight(FontWeight.Medium)
|
||||
.fontColor($r('app.color.text_primary'))
|
||||
.width('100%')
|
||||
if (this.hasLegacyNames) {
|
||||
Text('当前名称是旧格式,你可以在下方更换显示方式')
|
||||
.fontSize(12)
|
||||
.fontColor($r('app.color.brand_text'))
|
||||
.width('100%')
|
||||
}
|
||||
Flex({ wrap: FlexWrap.Wrap }) {
|
||||
ForEach([
|
||||
{ v: 1, label: '同步日历·本名' },
|
||||
{ v: 2, label: '同步日历·账号·本名' },
|
||||
{ v: 3, label: '账号·本名' }
|
||||
], (opt: Record<string, string | number>): void => {
|
||||
Text(opt.label as string)
|
||||
.fontSize(12)
|
||||
.padding({ left: 10, right: 10, top: 5, bottom: 5 })
|
||||
.margin({ right: 8, bottom: 6 })
|
||||
.borderRadius(14)
|
||||
.backgroundColor(this.displayFormat === (opt.v as number)
|
||||
? $r('app.color.brand') : $r('app.color.card_bg'))
|
||||
.fontColor(this.displayFormat === (opt.v as number)
|
||||
? $r('app.color.button_text') : $r('app.color.text_primary'))
|
||||
.border({
|
||||
width: 1,
|
||||
color: this.displayFormat === (opt.v as number)
|
||||
? $r('app.color.brand') : $r('app.color.shadow_color')
|
||||
})
|
||||
.onClick(() => {
|
||||
this.displayFormat = opt.v as number;
|
||||
this.refreshFormatPreview();
|
||||
})
|
||||
}, (opt: Record<string, string | number>): string => `fmt_${opt.v}`)
|
||||
}
|
||||
.width('100%')
|
||||
Text(`示例:${this.formatPreview}`)
|
||||
.fontSize(12)
|
||||
.fontColor($r('app.color.text_secondary'))
|
||||
.width('100%')
|
||||
Text('修改后需重新写入系统日历,期间日程会短暂消失几秒')
|
||||
.fontSize(11)
|
||||
.fontColor($r('app.color.text_hint'))
|
||||
.width('100%')
|
||||
Button(this.formatRunning ? '正在应用…'
|
||||
: (this.displayFormat === this.displayFormatApplied ? '已应用' : '应用'))
|
||||
.fontSize(13)
|
||||
.width('100%')
|
||||
.enabled(!this.formatRunning && this.displayFormat !== this.displayFormatApplied)
|
||||
.onClick(() => {
|
||||
this.applyDisplayFormat();
|
||||
})
|
||||
}
|
||||
.alignItems(HorizontalAlign.Start)
|
||||
.width('100%')
|
||||
.padding({ top: 8 })
|
||||
|
||||
Button(this.mirrorRunning ? '正在执行…' : '立即执行镜像')
|
||||
.fontSize(14)
|
||||
.width('100%')
|
||||
|
||||
@@ -11,8 +11,12 @@ struct Widget2x2Card {
|
||||
@LocalStorageProp('dateMd') dateMd: string = '';
|
||||
@LocalStorageProp('weekday') weekday: string = '';
|
||||
@LocalStorageProp('todayCount') todayCount: number = 0;
|
||||
/** 卡片当前显示的那一天 0 点毫秒 —— 点卡片进 App 时定位到这一天 */
|
||||
@LocalStorageProp('selectedDate') selectedDate: number = 0;
|
||||
|
||||
/** 右上角添加按钮:拉起 App 直接进入新建日程页(阻止冒泡,避免同时打开 App 首页) */
|
||||
/** 右上角添加按钮:拉起 App 直接进入新建日程页。
|
||||
* ⭐ 无需阻止冒泡:ArkUI 的 `onClick` 是**非冒泡**事件,父子同绑时**子组件优先**,
|
||||
* 故点 + 不会连带触发根容器的"打开首页"。 */
|
||||
@Builder
|
||||
addButton() {
|
||||
Button() {
|
||||
@@ -35,12 +39,12 @@ struct Widget2x2Card {
|
||||
})
|
||||
}
|
||||
|
||||
/** 卡片"打开 App":点击日期区或今日日程数区域触发;添加按钮是 header 行的兄弟节点,其点击不会冒泡到这里 */
|
||||
/** 打开 App 并**定位到卡片当前显示的那一天**(用户可能已翻到其他日期) */
|
||||
private openApp(): void {
|
||||
postCardAction(this, {
|
||||
action: 'router',
|
||||
abilityName: 'EntryAbility',
|
||||
params: {}
|
||||
params: { openDate: `${this.selectedDate}` }
|
||||
});
|
||||
}
|
||||
|
||||
@@ -61,7 +65,6 @@ struct Widget2x2Card {
|
||||
}
|
||||
.layoutWeight(1)
|
||||
.alignItems(HorizontalAlign.Start)
|
||||
.onClick(() => this.openApp())
|
||||
|
||||
this.addButton()
|
||||
}
|
||||
@@ -92,12 +95,13 @@ struct Widget2x2Card {
|
||||
.width('100%')
|
||||
.layoutWeight(1)
|
||||
.alignItems(VerticalAlign.Center)
|
||||
.onClick(() => this.openApp())
|
||||
}
|
||||
.width('100%')
|
||||
.height('100%')
|
||||
.padding(14)
|
||||
.backgroundColor('#FFFFFF')
|
||||
.borderRadius(16)
|
||||
// ⭐ 整卡可点:空白处也能进 App 并定位到当前显示日(原来只有日期区/条数区可点)
|
||||
.onClick(() => this.openApp())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@ struct Widget4x2Card {
|
||||
@LocalStorageProp('lunarText') lunarText: string = '';
|
||||
@LocalStorageProp('todayCount') todayCount: number = 0;
|
||||
@LocalStorageProp('ongoingJson') ongoingJson: string = '[]';
|
||||
/** 卡片当前显示的那一天 0 点毫秒 —— 点卡片进 App 时定位到这一天 */
|
||||
@LocalStorageProp('selectedDate') selectedDate: number = 0;
|
||||
|
||||
/** 右侧最多渲染 2 条(数据侧已裁剪,这里再兜底截断) */
|
||||
private parseOngoing(): CardItem2x4[] {
|
||||
@@ -57,12 +59,12 @@ struct Widget4x2Card {
|
||||
})
|
||||
}
|
||||
|
||||
/** 卡片"打开 App":点击左侧日期区、今日条数区、右侧日程区触发;添加按钮是 header 行兄弟节点,不冒泡 */
|
||||
/** 打开 App 并**定位到卡片当前显示的那一天**(用户可能已翻到其他日期) */
|
||||
private openApp(): void {
|
||||
postCardAction(this, {
|
||||
action: 'router',
|
||||
abilityName: 'EntryAbility',
|
||||
params: {}
|
||||
params: { openDate: `${this.selectedDate}` }
|
||||
});
|
||||
}
|
||||
|
||||
@@ -118,7 +120,6 @@ struct Widget4x2Card {
|
||||
.width('100%')
|
||||
.layoutWeight(1)
|
||||
.justifyContent(FlexAlign.Center)
|
||||
.onClick(() => this.openApp())
|
||||
}
|
||||
|
||||
build() {
|
||||
@@ -141,7 +142,6 @@ struct Widget4x2Card {
|
||||
}
|
||||
.layoutWeight(1)
|
||||
.alignItems(HorizontalAlign.Start)
|
||||
.onClick(() => this.openApp())
|
||||
|
||||
this.addButton()
|
||||
}
|
||||
@@ -173,7 +173,6 @@ struct Widget4x2Card {
|
||||
.width('100%')
|
||||
.layoutWeight(1)
|
||||
.alignItems(VerticalAlign.Center)
|
||||
.onClick(() => this.openApp())
|
||||
}
|
||||
.layoutWeight(1)
|
||||
.height('100%')
|
||||
@@ -197,7 +196,6 @@ struct Widget4x2Card {
|
||||
.width('100%')
|
||||
.layoutWeight(1)
|
||||
.justifyContent(FlexAlign.Center)
|
||||
.onClick(() => this.openApp())
|
||||
}
|
||||
}
|
||||
.layoutWeight(1)
|
||||
@@ -208,5 +206,7 @@ struct Widget4x2Card {
|
||||
.padding(12)
|
||||
.backgroundColor('#FFFFFF')
|
||||
.borderRadius(16)
|
||||
// ⭐ 整卡可点:左右空白处也能进 App 并定位到当前显示日
|
||||
.onClick(() => this.openApp())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -387,7 +387,9 @@ struct Widget4x4Card {
|
||||
return h < 10 ? `0${h}` : `${h}`;
|
||||
}
|
||||
|
||||
/** 右上角添加按钮:拉起 App 直接进入新建日程页(兄弟节点布局,不冒泡到其它点击区) */
|
||||
/** 右上角添加按钮:拉起 App 直接进入新建日程页。
|
||||
* ⭐ 无需阻止冒泡:ArkUI 的 `onClick` 是**非冒泡**事件,父子同绑时**子组件优先**,
|
||||
* 故点 + 不会连带触发根容器的"打开首页"。 */
|
||||
@Builder
|
||||
addButton() {
|
||||
Button() {
|
||||
@@ -442,6 +444,7 @@ struct Widget4x4Card {
|
||||
.borderRadius(11)
|
||||
.padding(0)
|
||||
.backgroundColor('#F2F3F5')
|
||||
// ⭐ 无需阻止冒泡:onClick 非冒泡、子组件优先 → 点翻页不会连带打开 App
|
||||
.onClick(() => this.page(act))
|
||||
}
|
||||
|
||||
@@ -462,6 +465,7 @@ struct Widget4x4Card {
|
||||
.borderRadius(11)
|
||||
.padding(0)
|
||||
.backgroundColor('#007DFF')
|
||||
// ⭐ 无需阻止冒泡:onClick 非冒泡、子组件优先
|
||||
.onClick(() => this.page('today'))
|
||||
}
|
||||
}
|
||||
@@ -554,7 +558,6 @@ struct Widget4x4Card {
|
||||
.width('100%')
|
||||
.layoutWeight(1)
|
||||
.justifyContent(FlexAlign.Center)
|
||||
.onClick(() => this.openApp())
|
||||
} else {
|
||||
List({ space: 4 }) {
|
||||
ForEach(this.parseList(), (item: LItem4) => {
|
||||
@@ -568,7 +571,6 @@ struct Widget4x4Card {
|
||||
.layoutWeight(1)
|
||||
.scrollBar(BarState.Auto)
|
||||
.cachedCount(8)
|
||||
.onClick(() => this.openApp())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -589,7 +591,6 @@ struct Widget4x4Card {
|
||||
}
|
||||
.layoutWeight(1)
|
||||
.alignItems(HorizontalAlign.Start)
|
||||
.onClick(() => this.openApp())
|
||||
this.pageBtn('›', 'next')
|
||||
this.sideBtn()
|
||||
}
|
||||
@@ -630,7 +631,6 @@ struct Widget4x4Card {
|
||||
.padding({ left: 5, right: 5 })
|
||||
.borderRadius(5)
|
||||
.backgroundColor(a.color)
|
||||
.onClick(() => this.openApp())
|
||||
}, (a: TAllDay, idx: number) => `ad_${idx}_${a.eventKey}`)
|
||||
if (this.w4AllDayRest() > 0) {
|
||||
Text(`还有 ${this.w4AllDayRest()} 个全天日程`)
|
||||
@@ -690,6 +690,9 @@ struct Widget4x4Card {
|
||||
.padding(12)
|
||||
.backgroundColor('#FFFFFF')
|
||||
.borderRadius(16)
|
||||
// ⭐ 整卡可点:空白处也能进 App 并定位到当前显示日。
|
||||
// ⚠️ onClick 是**非冒泡**事件且**子组件优先** → 内部的 ‹ › 今 + 按钮不会被这里抢走
|
||||
.onClick(() => this.openApp())
|
||||
}
|
||||
|
||||
/** 第 1 层:整点网格(每小时一格,格底一条灰线) */
|
||||
@@ -815,7 +818,6 @@ struct Widget4x4Card {
|
||||
.width('100%')
|
||||
.height(this.w4BlockVp(b))
|
||||
.constraintSize({ minHeight: 14 })
|
||||
.onClick(() => this.openApp())
|
||||
}, (b: TBlock) => `b_${r.key}_${b.eventKey}`)
|
||||
}
|
||||
.layoutWeight(1)
|
||||
|
||||
@@ -384,7 +384,9 @@ struct Widget6x4Card {
|
||||
return h < 10 ? `0${h}:00` : `${h}:00`;
|
||||
}
|
||||
|
||||
/** 右上角添加按钮:拉起 App 直接进入新建日程页(兄弟节点布局,不冒泡) */
|
||||
/** 右上角添加按钮:拉起 App 直接进入新建日程页。
|
||||
* ⭐ 无需阻止冒泡:ArkUI 的 `onClick` 是**非冒泡**事件,父子同绑时**子组件优先**,
|
||||
* 故点 + 不会连带触发根容器的"打开首页"。 */
|
||||
@Builder
|
||||
addButton() {
|
||||
Button() {
|
||||
@@ -439,6 +441,7 @@ struct Widget6x4Card {
|
||||
.borderRadius(11)
|
||||
.padding(0)
|
||||
.backgroundColor('#F2F3F5')
|
||||
// ⭐ 无需阻止冒泡:onClick 非冒泡、子组件优先 → 点翻页不会连带打开 App
|
||||
.onClick(() => this.page(act))
|
||||
}
|
||||
|
||||
@@ -457,6 +460,7 @@ struct Widget6x4Card {
|
||||
.borderRadius(11)
|
||||
.padding(0)
|
||||
.backgroundColor('#007DFF')
|
||||
// ⭐ 无需阻止冒泡:onClick 非冒泡、子组件优先
|
||||
.onClick(() => this.page('today'))
|
||||
}
|
||||
}
|
||||
@@ -549,7 +553,6 @@ struct Widget6x4Card {
|
||||
.width('100%')
|
||||
.layoutWeight(1)
|
||||
.justifyContent(FlexAlign.Center)
|
||||
.onClick(() => this.openApp())
|
||||
} else {
|
||||
List({ space: 4 }) {
|
||||
ForEach(this.parseList(), (item: LItem6) => {
|
||||
@@ -563,7 +566,6 @@ struct Widget6x4Card {
|
||||
.layoutWeight(1)
|
||||
.scrollBar(BarState.Auto)
|
||||
.cachedCount(8)
|
||||
.onClick(() => this.openApp())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -584,7 +586,6 @@ struct Widget6x4Card {
|
||||
}
|
||||
.layoutWeight(1)
|
||||
.alignItems(HorizontalAlign.Start)
|
||||
.onClick(() => this.openApp())
|
||||
Text(`${this.dayCount} 条`)
|
||||
.fontSize(10)
|
||||
.fontColor('#B0B0B0')
|
||||
@@ -629,7 +630,6 @@ struct Widget6x4Card {
|
||||
.padding({ left: 6, right: 6 })
|
||||
.borderRadius(6)
|
||||
.backgroundColor(a.color)
|
||||
.onClick(() => this.openApp())
|
||||
}, (a: TAllDay6, idx: number) => `ad_${idx}_${a.eventKey}`)
|
||||
if (this.w6AllDayRest() > 0) {
|
||||
Text(`还有 ${this.w6AllDayRest()} 个全天日程`)
|
||||
@@ -689,6 +689,9 @@ struct Widget6x4Card {
|
||||
.padding(12)
|
||||
.backgroundColor('#FFFFFF')
|
||||
.borderRadius(16)
|
||||
// ⭐ 整卡可点:空白处也能进 App 并定位到当前显示日。
|
||||
// ⚠️ onClick 是**非冒泡**事件且**子组件优先** → 内部的 ‹ › 今 + 按钮不会被这里抢走
|
||||
.onClick(() => this.openApp())
|
||||
}
|
||||
|
||||
/** 第 1 层:整点网格(每小时一格,格底一条灰线) */
|
||||
@@ -814,7 +817,6 @@ struct Widget6x4Card {
|
||||
.width('100%')
|
||||
.height(this.w6BlockVp(b))
|
||||
.constraintSize({ minHeight: 16 })
|
||||
.onClick(() => this.openApp())
|
||||
}, (b: TBlock6) => `b_${r.key}_${b.eventKey}`)
|
||||
}
|
||||
.layoutWeight(1)
|
||||
|
||||
Reference in New Issue
Block a user