Repository navigation
Expand file tree
/
Copy pathcalendar.ts
More file actions
94 lines (83 loc) · 2.68 KB
/
Copy pathcalendar.ts
File metadata and controls
94 lines (83 loc) · 2.68 KB
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
import { Utils } from "@nativescript/core";
import { hasCalendarPermission } from "../g2/android-permissions";
import { spanCurrent } from "./frame-timings";
declare const com: any;
/**
* Reads upcoming calendar events through the Android Calendar provider
* (FaceclawCalendarProvider). Results are cached briefly so repeated paints of
* the Calendar app don't re-run the content-provider query every frame.
*/
export type CalendarEvent = {
id: number;
title: string;
startMs: number;
endMs: number;
allDay: boolean;
location: string;
calendarName: string;
};
const DEFAULT_MAX_EVENTS = 50;
const DEFAULT_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;
const CACHE_MS = 30_000;
let cache: { events: CalendarEvent[]; atMs: number; maxEvents: number; windowMs: number } | null = null;
/**
* Upcoming events from now through the given window, ordered by start time.
* Returns [] when calendar permission is absent. Cached for CACHE_MS; pass
* forceRefresh to bypass the cache (e.g. right after the permission grant).
*/
export function readUpcomingEvents(
maxEvents = DEFAULT_MAX_EVENTS,
windowMs = DEFAULT_WINDOW_MS,
forceRefresh = false,
): CalendarEvent[] {
if (!global.isAndroid || !hasCalendarPermission()) return [];
const now = Date.now();
if (
!forceRefresh &&
cache &&
cache.maxEvents === maxEvents &&
cache.windowMs === windowMs &&
now - cache.atMs < CACHE_MS
) {
return cache.events;
}
const context = Utils.android.getApplicationContext();
if (!context) return [];
try {
const json = spanCurrent("fetch-calendar-events", () =>
String(
com.faceclaw.app.FaceclawCalendarProvider.getUpcomingEventsJson(
context,
Math.max(0, Math.round(maxEvents)),
Math.max(0, Math.round(windowMs)),
),
),
);
const parsed = JSON.parse(json);
const events = Array.isArray(parsed)
? parsed.map(normalizeEvent).filter((event): event is CalendarEvent => Boolean(event))
: [];
cache = { events, atMs: now, maxEvents, windowMs };
return events;
} catch {
return [];
}
}
/** Drop the cached events so the next read re-queries the provider. */
export function invalidateCalendarCache(): void {
cache = null;
}
function normalizeEvent(value: any): CalendarEvent | null {
if (!value || typeof value !== "object") return null;
const startMs = Number(value.startMs);
if (!Number.isFinite(startMs)) return null;
return {
id: Number(value.id) || 0,
title: String(value.title ?? ""),
startMs,
endMs: Number(value.endMs) || startMs,
allDay: Boolean(value.allDay),
location: String(value.location ?? ""),
calendarName: String(value.calendarName ?? ""),
};
}