Skip to content

Your favorite shift management application!

feat: Adds configurable auto-sync intervals for iCloud calendars (#22)

panteLb74d01db883f
diff --git a/README.md b/README.md
index 9687745..c50e1b3 100644
--- a/README.md
+++ b/README.md
@@ -36,7 +36,7 @@
- **Shift Presets**: Create reusable shift templates with custom times, colors, and labels
- **Drag & Drop**: Reorder calendars and presets with intuitive drag-and-drop functionality
- **Calendar Notes**: Right-click any day to add custom notes (e.g., "Morning shift because afternoon hairdresser")
-- **ICloud Sync**: Import shifts from multiple iCloud calendars with individual sync management
+- **ICloud Sync**: Automatically or manually synchronize multiple iCloud calendars at configurable intervals
### 🎨 Customization & Organization
diff --git a/app/api/icloud-syncs/[id]/route.ts b/app/api/icloud-syncs/[id]/route.ts
index dbdd625..b0fe77a 100644
--- a/app/api/icloud-syncs/[id]/route.ts
+++ b/app/api/icloud-syncs/[id]/route.ts
@@ -44,8 +44,15 @@ export async function PATCH(
try {
const { id } = await params;
const body = await request.json();
- const { name, icloudUrl, color, displayMode, isHidden, hideFromStats } =
- body;
+ const {
+ name,
+ icloudUrl,
+ color,
+ displayMode,
+ isHidden,
+ hideFromStats,
+ autoSyncInterval,
+ } = body;
// Validate iCloud URL if provided
if (icloudUrl !== undefined && !isValidICloudUrl(icloudUrl)) {
@@ -58,6 +65,22 @@ export async function PATCH(
);
}
+ // Validate autoSyncInterval if provided
+ const validIntervals = [0, 5, 15, 30, 60, 120, 360, 720, 1440];
+ if (
+ autoSyncInterval !== undefined &&
+ !validIntervals.includes(autoSyncInterval)
+ ) {
+ return NextResponse.json(
+ {
+ error: `Invalid auto-sync interval. Must be one of: ${validIntervals.join(
+ ", "
+ )} minutes`,
+ },
+ { status: 400 }
+ );
+ }
+
const updateData: Record<string, unknown> = {
updatedAt: new Date(),
};
@@ -68,6 +91,8 @@ export async function PATCH(
if (displayMode !== undefined) updateData.displayMode = displayMode;
if (isHidden !== undefined) updateData.isHidden = isHidden;
if (hideFromStats !== undefined) updateData.hideFromStats = hideFromStats;
+ if (autoSyncInterval !== undefined)
+ updateData.autoSyncInterval = autoSyncInterval;
const [updated] = await db
.update(icloudSyncs)
diff --git a/app/api/icloud-syncs/[id]/sync/route.ts b/app/api/icloud-syncs/[id]/sync/route.ts
index 4a2fea5..5d02c55 100644
--- a/app/api/icloud-syncs/[id]/sync/route.ts
+++ b/app/api/icloud-syncs/[id]/sync/route.ts
@@ -5,218 +5,231 @@ import { eq, inArray } from "drizzle-orm";
import ICAL from "ical.js";
import { expandRecurringEvents, splitMultiDayEvent } from "@/lib/icloud-utils";
-export async function POST(
- request: Request,
- { params }: { params: Promise<{ id: string }> }
-) {
- try {
- const { id: syncId } = await params;
+/**
+ * Core sync logic extracted for reuse by both API route and auto-sync service
+ */
+export async function syncICloudCalendar(syncId: string) {
+ // Get the iCloud sync configuration
+ const [icloudSync] = await db
+ .select()
+ .from(icloudSyncs)
+ .where(eq(icloudSyncs.id, syncId))
+ .limit(1);
+
+ if (!icloudSync) {
+ throw new Error("iCloud sync configuration not found");
+ }
- // Get the iCloud sync configuration
- const [icloudSync] = await db
- .select()
- .from(icloudSyncs)
- .where(eq(icloudSyncs.id, syncId))
- .limit(1);
+ // Convert webcal:// to https:// for iCloud URLs
+ const fetchUrl = icloudSync.icloudUrl.replace(/^webcal:\/\//i, "https://");
- if (!icloudSync) {
- return NextResponse.json(
- { error: "iCloud sync configuration not found" },
- { status: 404 }
- );
- }
-
- // Convert webcal:// to https:// for iCloud URLs
- const fetchUrl = icloudSync.icloudUrl.replace(/^webcal:\/\//i, "https://");
+ // Fetch the calendar from the specified iCloud URL with timeout protection
+ let icsData: string;
+ try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
- // Fetch the calendar from the specified iCloud URL
- let icsData: string;
try {
- const response = await fetch(fetchUrl);
+ const response = await fetch(fetchUrl, { signal: controller.signal });
+ clearTimeout(timeoutId);
+
if (!response.ok) {
throw new Error(`Failed to fetch calendar: ${response.statusText}`);
}
icsData = await response.text();
- } catch (error) {
- console.error("Error fetching iCloud calendar:", error);
- return NextResponse.json(
- { error: "Failed to fetch iCloud calendar. Please check the URL." },
- { status: 500 }
- );
+ } catch (fetchError) {
+ clearTimeout(timeoutId);
+
+ // Check if this was a timeout/abort error
+ if (fetchError instanceof Error && fetchError.name === "AbortError") {
+ throw new Error(
+ "Request timed out after 10 seconds. Please try again."
+ );
+ }
+ throw fetchError;
}
+ } catch (error) {
+ console.error("Error fetching iCloud calendar:", error);
+ throw new Error(
+ error instanceof Error
+ ? error.message
+ : "Failed to fetch iCloud calendar. Please check the URL."
+ );
+ }
- // Parse the ICS data
- let jcalData;
- try {
- jcalData = ICAL.parse(icsData);
- } catch (error) {
- console.error("Error parsing ICS data:", error);
- return NextResponse.json(
- { error: "Failed to parse calendar data. Invalid ICS format." },
- { status: 500 }
- );
- }
+ // Parse the ICS data
+ let jcalData;
+ try {
+ jcalData = ICAL.parse(icsData);
+ } catch (error) {
+ console.error("Error parsing ICS data:", error);
+ throw new Error("Failed to parse calendar data. Invalid ICS format.");
+ }
- const comp = new ICAL.Component(jcalData);
- const vevents = comp.getAllSubcomponents("vevent");
-
- // Define sync window: 3 months back to 1 year forward
- const syncWindowStart = new Date();
- syncWindowStart.setMonth(syncWindowStart.getMonth() - 3);
- const syncWindowEnd = new Date();
- syncWindowEnd.setFullYear(syncWindowEnd.getFullYear() + 1);
-
- // Get existing iCloud synced shifts for this sync
- const existingShifts = await db
- .select()
- .from(shifts)
- .where(eq(shifts.icloudSyncId, syncId));
-
- const existingEventIds = new Set(
- existingShifts
- .filter((s) => s.icloudEventId)
- .map((s) => s.icloudEventId as string)
+ const comp = new ICAL.Component(jcalData);
+ const vevents = comp.getAllSubcomponents("vevent");
+
+ // Define sync window: 3 months back to 1 year forward
+ const syncWindowStart = new Date();
+ syncWindowStart.setMonth(syncWindowStart.getMonth() - 3);
+ const syncWindowEnd = new Date();
+ syncWindowEnd.setFullYear(syncWindowEnd.getFullYear() + 1);
+
+ // Get existing iCloud synced shifts for this sync
+ const existingShifts = await db
+ .select()
+ .from(shifts)
+ .where(eq(shifts.icloudSyncId, syncId));
+
+ const processedEventIds = new Set<string>();
+ const shiftsToInsert: (typeof shifts.$inferInsert)[] = [];
+ const shiftsToUpdate: Array<typeof shifts.$inferInsert & { id: string }> = [];
+
+ // Process each vevent, expanding recurring events
+ for (const vevent of vevents) {
+ const occurrences = expandRecurringEvents(
+ vevent,
+ syncWindowStart,
+ syncWindowEnd
);
- const processedEventIds = new Set<string>();
- const shiftsToInsert: (typeof shifts.$inferInsert)[] = [];
- const shiftsToUpdate: Array<typeof shifts.$inferInsert & { id: string }> =
- [];
-
- // Process each vevent, expanding recurring events
- for (const vevent of vevents) {
- const occurrences = expandRecurringEvents(
- vevent,
- syncWindowStart,
- syncWindowEnd
- );
-
- for (const occurrence of occurrences) {
- const { event, startDate, endDate, recurrenceId } = occurrence;
-
- // Create a unique ID for each occurrence
- // For recurring events, append the recurrence date to make it unique
- const baseEventId = recurrenceId
- ? `${event.uid}_${recurrenceId.toICALString()}`
- : event.uid;
-
- if (!startDate || !endDate) {
- continue; // Skip events without dates
- }
+ for (const occurrence of occurrences) {
+ const { event, startDate, endDate, recurrenceId } = occurrence;
- const isAllDay = startDate.isDate;
-
- // Convert ICAL.Time to JavaScript Date
- const startJsDate = startDate.toJSDate();
- const endJsDate = endDate.toJSDate();
-
- // Split multi-day events into separate shifts for each day
- const dayEntries = splitMultiDayEvent(startJsDate, endJsDate, isAllDay);
-
- for (const dayEntry of dayEntries) {
- // Create unique event ID for multi-day events by appending day index
- const eventId =
- dayEntries.length > 1
- ? `${baseEventId}_day${dayEntry.dayIndex}`
- : baseEventId;
-
- processedEventIds.add(eventId);
-
- const shiftData = {
- calendarId: icloudSync.calendarId,
- date: dayEntry.date,
- startTime: dayEntry.startTime,
- endTime: dayEntry.endTime,
- title: event.summary || "Untitled Event",
- color: icloudSync.color,
- notes: event.description || null,
- isAllDay,
- isSecondary: false,
- icloudEventId: eventId,
- icloudSyncId: syncId,
- syncedFromIcloud: true,
- presetId: null,
- };
-
- // Check if this event already exists
- const existingShift = existingShifts.find(
- (s) => s.icloudEventId === eventId
- );
-
- if (existingShift) {
- // Collect for batch update
- shiftsToUpdate.push({
- id: existingShift.id,
- ...shiftData,
- updatedAt: new Date(),
- });
- } else {
- // Collect for batch insert
- shiftsToInsert.push({
- id: crypto.randomUUID(),
- ...shiftData,
- createdAt: new Date(),
- updatedAt: new Date(),
- });
- }
+ // Create a unique ID for each occurrence
+ // For recurring events, append the recurrence date to make it unique
+ const baseEventId = recurrenceId
+ ? `${event.uid}_${recurrenceId.toICALString()}`
+ : event.uid;
+
+ if (!startDate || !endDate) {
+ continue; // Skip events without dates
+ }
+
+ const isAllDay = startDate.isDate;
+
+ // Convert ICAL.Time to JavaScript Date
+ const startJsDate = startDate.toJSDate();
+ const endJsDate = endDate.toJSDate();
+
+ // Split multi-day events into separate shifts for each day
+ const dayEntries = splitMultiDayEvent(startJsDate, endJsDate, isAllDay);
+
+ for (const dayEntry of dayEntries) {
+ // Create unique event ID for multi-day events by appending day index
+ const eventId =
+ dayEntries.length > 1
+ ? `${baseEventId}_day${dayEntry.dayIndex}`
+ : baseEventId;
+
+ processedEventIds.add(eventId);
+
+ const shiftData = {
+ calendarId: icloudSync.calendarId,
+ date: dayEntry.date,
+ startTime: dayEntry.startTime,
+ endTime: dayEntry.endTime,
+ title: event.summary || "Untitled Event",
+ color: icloudSync.color,
+ notes: event.description || null,
+ isAllDay,
+ isSecondary: false,
+ icloudEventId: eventId,
+ icloudSyncId: syncId,
+ syncedFromIcloud: true,
+ presetId: null,
+ };
+
+ // Check if this event already exists
+ const existingShift = existingShifts.find(
+ (s) => s.icloudEventId === eventId
+ );
+
+ if (existingShift) {
+ // Collect for batch update
+ shiftsToUpdate.push({
+ id: existingShift.id,
+ ...shiftData,
+ updatedAt: new Date(),
+ });
+ } else {
+ // Collect for batch insert
+ shiftsToInsert.push({
+ id: crypto.randomUUID(),
+ ...shiftData,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ });
}
}
}
+ }
- // Calculate which shifts to delete before transaction
- const shiftIdsToDelete = existingShifts
- .filter((s) => s.icloudEventId && !processedEventIds.has(s.icloudEventId))
- .map((s) => s.id);
+ // Calculate which shifts to delete before transaction
+ const shiftIdsToDelete = existingShifts
+ .filter((s) => s.icloudEventId && !processedEventIds.has(s.icloudEventId))
+ .map((s) => s.id);
- // Perform batch operations in a transaction for atomicity and better performance
- const transactionResult = db.transaction((tx) => {
- // Insert new shifts in one batch
- if (shiftsToInsert.length > 0) {
- tx.insert(shifts).values(shiftsToInsert).run();
- }
+ // Perform batch operations in a transaction for atomicity and better performance
+ const transactionResult = db.transaction((tx) => {
+ // Insert new shifts in one batch
+ if (shiftsToInsert.length > 0) {
+ tx.insert(shifts).values(shiftsToInsert).run();
+ }
- // Update existing shifts (SQLite doesn't support batch updates directly,
- // but doing them in a transaction improves performance)
- if (shiftsToUpdate.length > 0) {
- for (const shiftUpdate of shiftsToUpdate) {
- const { id, ...updateData } = shiftUpdate;
- tx.update(shifts).set(updateData).where(eq(shifts.id, id)).run();
- }
+ // Update existing shifts (SQLite doesn't support batch updates directly,
+ // but doing them in a transaction improves performance)
+ if (shiftsToUpdate.length > 0) {
+ for (const shiftUpdate of shiftsToUpdate) {
+ const { id, ...updateData } = shiftUpdate;
+ tx.update(shifts).set(updateData).where(eq(shifts.id, id)).run();
}
+ }
- // Delete shifts that are no longer in the iCloud calendar in one batch
- if (shiftIdsToDelete.length > 0) {
- tx.delete(shifts).where(inArray(shifts.id, shiftIdsToDelete)).run();
- }
+ // Delete shifts that are no longer in the iCloud calendar in one batch
+ if (shiftIdsToDelete.length > 0) {
+ tx.delete(shifts).where(inArray(shifts.id, shiftIdsToDelete)).run();
+ }
- // Update last sync time
- tx.update(icloudSyncs)
- .set({
- lastSyncedAt: new Date(),
- updatedAt: new Date(),
- })
- .where(eq(icloudSyncs.id, syncId))
- .run();
-
- // Return transaction stats
- return {
- created: shiftsToInsert.length,
- updated: shiftsToUpdate.length,
- deleted: shiftIdsToDelete.length,
- totalEvents: vevents.length,
- totalOccurrences: shiftsToInsert.length + shiftsToUpdate.length,
- };
- });
+ // Update last sync time
+ tx.update(icloudSyncs)
+ .set({
+ lastSyncedAt: new Date(),
+ updatedAt: new Date(),
+ })
+ .where(eq(icloudSyncs.id, syncId))
+ .run();
+
+ // Return transaction stats
+ return {
+ created: shiftsToInsert.length,
+ updated: shiftsToUpdate.length,
+ deleted: shiftIdsToDelete.length,
+ totalEvents: vevents.length,
+ totalOccurrences: shiftsToInsert.length + shiftsToUpdate.length,
+ calendarId: icloudSync.calendarId,
+ };
+ });
+
+ return transactionResult;
+}
+
+export async function POST(
+ request: Request,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const { id: syncId } = await params;
+ const stats = await syncICloudCalendar(syncId);
return NextResponse.json({
success: true,
- stats: transactionResult,
+ stats,
});
} catch (error) {
console.error("Error syncing iCloud calendar:", error);
- return NextResponse.json(
- { error: "Internal server error" },
- { status: 500 }
- );
+ const errorMessage =
+ error instanceof Error ? error.message : "Internal server error";
+ return NextResponse.json({ error: errorMessage }, { status: 500 });
}
}
diff --git a/app/api/icloud-syncs/route.ts b/app/api/icloud-syncs/route.ts
index a268591..03572b2 100644
--- a/app/api/icloud-syncs/route.ts
+++ b/app/api/icloud-syncs/route.ts
@@ -37,7 +37,14 @@ export async function GET(request: Request) {
export async function POST(request: Request) {
try {
const body = await request.json();
- const { calendarId, name, icloudUrl, color, displayMode } = body;
+ const {
+ calendarId,
+ name,
+ icloudUrl,
+ color,
+ displayMode,
+ autoSyncInterval,
+ } = body;
if (!calendarId || !name || !icloudUrl) {
return NextResponse.json(
@@ -57,6 +64,22 @@ export async function POST(request: Request) {
);
}
+ // Validate autoSyncInterval
+ const validIntervals = [0, 5, 15, 30, 60, 120, 360, 720, 1440];
+ if (
+ autoSyncInterval !== undefined &&
+ !validIntervals.includes(autoSyncInterval)
+ ) {
+ return NextResponse.json(
+ {
+ error: `Invalid auto-sync interval. Must be one of: ${validIntervals.join(
+ ", "
+ )} minutes`,
+ },
+ { status: 400 }
+ );
+ }
+
const [icloudSync] = await db
.insert(icloudSyncs)
.values({
@@ -66,6 +89,7 @@ export async function POST(request: Request) {
icloudUrl,
color: color || "#3b82f6",
displayMode: displayMode || "normal",
+ autoSyncInterval: autoSyncInterval || 0,
createdAt: new Date(),
updatedAt: new Date(),
})
diff --git a/components/icloud-sync-manage-dialog.tsx b/components/icloud-sync-manage-dialog.tsx
index b78f527..86ddbfb 100644
--- a/components/icloud-sync-manage-dialog.tsx
+++ b/components/icloud-sync-manage-dialog.tsx
@@ -20,6 +20,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { ColorPicker } from "@/components/ui/color-picker";
+import { Slider } from "@/components/ui/slider";
import { useTranslations } from "next-intl";
import { ICloudSync } from "@/lib/db/schema";
import { Loader2, Trash2, RefreshCw, Plus, Edit2 } from "lucide-react";
@@ -53,6 +54,7 @@ export function ICloudSyncManageDialog({
const [formUrl, setFormUrl] = useState("");
const [formColor, setFormColor] = useState("#3b82f6");
const [formDisplayMode, setFormDisplayMode] = useState("normal");
+ const [formAutoSyncInterval, setFormAutoSyncInterval] = useState(0);
const fetchSyncs = useCallback(async () => {
if (!calendarId) return;
@@ -89,6 +91,7 @@ export function ICloudSyncManageDialog({
setFormUrl("");
setFormColor("#3b82f6");
setFormDisplayMode("normal");
+ setFormAutoSyncInterval(0);
}
}, [open, calendarId, fetchSyncs]);
@@ -123,6 +126,7 @@ export function ICloudSyncManageDialog({
icloudUrl: formUrl.trim(),
color: formColor,
displayMode: formDisplayMode,
+ autoSyncInterval: formAutoSyncInterval,
}),
});
@@ -132,6 +136,7 @@ export function ICloudSyncManageDialog({
setFormUrl("");
setFormColor("#3b82f6");
setFormDisplayMode("normal");
+ setFormAutoSyncInterval(0);
setShowAddForm(false);
await fetchSyncs();
onSyncComplete?.(); // Trigger refresh to update parent state
@@ -163,6 +168,7 @@ export function ICloudSyncManageDialog({
icloudUrl: formUrl.trim() || undefined,
color: formColor,
displayMode: formDisplayMode,
+ autoSyncInterval: formAutoSyncInterval,
}),
});
@@ -172,6 +178,7 @@ export function ICloudSyncManageDialog({
setFormUrl("");
setFormColor("#3b82f6");
setFormDisplayMode("normal");
+ setFormAutoSyncInterval(0);
await fetchSyncs();
onSyncComplete?.(); // Trigger refresh of shifts and iCloudSyncs
toast.success(t("icloud.updateSuccess"));
@@ -253,6 +260,7 @@ export function ICloudSyncManageDialog({
setFormUrl(sync.icloudUrl);
setFormColor(sync.color);
setFormDisplayMode(sync.displayMode || "normal");
+ setFormAutoSyncInterval(sync.autoSyncInterval || 0);
setShowAddForm(false);
};
@@ -262,6 +270,7 @@ export function ICloudSyncManageDialog({
setFormUrl("");
setFormColor("#3b82f6");
setFormDisplayMode("normal");
+ setFormAutoSyncInterval(0);
};
const handleToggleVisibility = async (
@@ -269,6 +278,14 @@ export function ICloudSyncManageDialog({
field: "isHidden" | "hideFromStats",
currentValue: boolean
) => {
+ // Optimistically update local editingSync state for immediate UI feedback
+ if (editingSync && editingSync.id === syncId) {
+ setEditingSync({
+ ...editingSync,
+ [field]: !currentValue,
+ });
+ }
+
try {
const response = await fetch(`/api/icloud-syncs/${syncId}`, {
method: "PATCH",
@@ -285,10 +302,26 @@ export function ICloudSyncManageDialog({
} else {
const data = await response.json();
toast.error(data.error || t("icloud.updateError"));
+
+ // Revert optimistic update on error
+ if (editingSync && editingSync.id === syncId) {
+ setEditingSync({
+ ...editingSync,
+ [field]: currentValue,
+ });
+ }
}
} catch (error) {
console.error("Failed to update visibility:", error);
toast.error(t("icloud.updateError"));
+
+ // Revert optimistic update on error
+ if (editingSync && editingSync.id === syncId) {
+ setEditingSync({
+ ...editingSync,
+ [field]: currentValue,
+ });
+ }
}
};
@@ -299,6 +332,7 @@ export function ICloudSyncManageDialog({
setFormUrl("");
setFormColor("#3b82f6");
setFormDisplayMode("normal");
+ setFormAutoSyncInterval(0);
};
return (
@@ -331,6 +365,20 @@ export function ICloudSyncManageDialog({
style={{ backgroundColor: sync.color }}
/>
<span className="truncate">{sync.name}</span>
+ {sync.autoSyncInterval > 0 ? (
+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-primary/10 text-primary text-xs font-medium">
+ <RefreshCw className="h-3 w-3" />
+ {sync.autoSyncInterval < 60
+ ? `${sync.autoSyncInterval} min`
+ : sync.autoSyncInterval < 1440
+ ? `${sync.autoSyncInterval / 60} h`
+ : `${sync.autoSyncInterval / 1440} d`}
+ </span>
+ ) : (
+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-muted/50 text-muted-foreground text-xs font-medium">
+ {t("icloud.autoSyncManual")}
+ </span>
+ )}
</div>
{sync.lastSyncedAt && (
<p className="text-xs text-muted-foreground mt-1">
@@ -377,61 +425,6 @@ export function ICloudSyncManageDialog({
</Button>
</div>
</div>
-
- {/* Visibility Toggles */}
- <div className="flex flex-col gap-2 pl-3 border-t border-border/30 pt-3">
- <div className="flex items-center gap-2">
- <Checkbox
- id={`hide-${sync.id}`}
- checked={sync.isHidden || false}
- onCheckedChange={() =>
- handleToggleVisibility(
- sync.id,
- "isHidden",
- sync.isHidden || false
- )
- }
- disabled={!!isSyncing || !!isDeleting}
- />
- <Label
- htmlFor={`hide-${sync.id}`}
- className="text-sm font-normal cursor-pointer"
- >
- {t("icloud.hideCalendar")}
- </Label>
- </div>
- <p className="text-xs text-muted-foreground pl-6">
- {t("icloud.hideCalendarHint")}
- </p>
-
- <div className="flex items-center gap-2 mt-1">
- <Checkbox
- id={`hide-stats-${sync.id}`}
- checked={sync.isHidden || sync.hideFromStats || false}
- onCheckedChange={() =>
- handleToggleVisibility(
- sync.id,
- "hideFromStats",
- sync.hideFromStats || false
- )
- }
- disabled={!!isSyncing || !!isDeleting || sync.isHidden}
- />
- <Label
- htmlFor={`hide-stats-${sync.id}`}
- className={`text-sm font-normal ${
- sync.isHidden
- ? "cursor-not-allowed opacity-50"
- : "cursor-pointer"
- }`}
- >
- {t("icloud.hideFromStats")}
- </Label>
- </div>
- <p className="text-xs text-muted-foreground pl-6">
- {t("icloud.hideFromStatsHint")}
- </p>
- </div>
</div>
))}
</div>
@@ -513,6 +506,103 @@ export function ICloudSyncManageDialog({
</p>
</div>
+ <div className="space-y-3">
+ <div className="flex items-center justify-between">
+ <Label>{t("icloud.autoSyncLabel")}</Label>
+ <span className="text-sm font-medium text-primary">
+ {formAutoSyncInterval === 0
+ ? t("icloud.autoSyncManual")
+ : formAutoSyncInterval < 60
+ ? `${formAutoSyncInterval} min`
+ : formAutoSyncInterval < 1440
+ ? `${formAutoSyncInterval / 60} h`
+ : `${formAutoSyncInterval / 1440} d`}
+ </span>
+ </div>
+ <Slider
+ value={[
+ (() => {
+ const intervals = [0, 5, 15, 30, 60, 120, 360, 720, 1440];
+ const index = intervals.indexOf(formAutoSyncInterval);
+ return index >= 0 ? index : 0;
+ })(),
+ ]}
+ onValueChange={(value: number[]) => {
+ const intervals = [0, 5, 15, 30, 60, 120, 360, 720, 1440];
+ setFormAutoSyncInterval(intervals[value[0]]);
+ }}
+ max={8}
+ step={1}
+ className="w-full"
+ />
+ <div className="flex justify-between text-xs text-muted-foreground">
+ <span>{t("icloud.autoSyncManual")}</span>
+ <span>{t("icloud.autoSync24hShort")}</span>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {t("icloud.autoSyncHint")}
+ </p>
+ </div>
+
+ {editingSync && (
+ <div className="space-y-3 pt-2 border-t border-border/30">
+ <div className="flex items-center gap-2">
+ <Checkbox
+ id="hide-calendar"
+ checked={editingSync.isHidden || false}
+ onCheckedChange={() => {
+ handleToggleVisibility(
+ editingSync.id,
+ "isHidden",
+ editingSync.isHidden || false
+ );
+ }}
+ />
+ <Label
+ htmlFor="hide-calendar"
+ className="text-sm font-normal cursor-pointer"
+ >
+ {t("icloud.hideCalendar")}
+ </Label>
+ </div>
+ <p className="text-xs text-muted-foreground pl-6">
+ {t("icloud.hideCalendarHint")}
+ </p>
+
+ <div className="flex items-center gap-2">
+ <Checkbox
+ id="hide-from-stats"
+ checked={
+ editingSync.isHidden ||
+ editingSync.hideFromStats ||
+ false
+ }
+ onCheckedChange={() => {
+ handleToggleVisibility(
+ editingSync.id,
+ "hideFromStats",
+ editingSync.hideFromStats || false
+ );
+ }}
+ disabled={editingSync.isHidden}
+ />
+ <Label
+ htmlFor="hide-from-stats"
+ className={`text-sm font-normal ${
+ editingSync.isHidden
+ ? "cursor-not-allowed opacity-50"
+ : "cursor-pointer"
+ }`}
+ >
+ {t("icloud.hideFromStats")}
+ </Label>
+ </div>
+ <p className="text-xs text-muted-foreground pl-6">
+ {t("icloud.hideFromStatsHint")}
+ </p>
+ </div>
+ )}
+
<div className="flex gap-2">
<Button
variant="outline"
@@ -525,6 +615,7 @@ export function ICloudSyncManageDialog({
setFormUrl("");
setFormColor("#3b82f6");
setFormDisplayMode("normal");
+ setFormAutoSyncInterval(0);
}
}}
disabled={isLoading}
diff --git a/components/ui/slider.tsx b/components/ui/slider.tsx
new file mode 100644
index 0000000..9f2954a
--- /dev/null
+++ b/components/ui/slider.tsx
@@ -0,0 +1,28 @@
+"use client";
+
+import * as React from "react";
+import * as SliderPrimitive from "@radix-ui/react-slider";
+
+import { cn } from "@/lib/utils";
+
+const Slider = React.forwardRef<
+ React.ElementRef<typeof SliderPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
+>(({ className, ...props }, ref) => (
+ <SliderPrimitive.Root
+ ref={ref}
+ className={cn(
+ "relative flex w-full touch-none select-none items-center",
+ className
+ )}
+ {...props}
+ >
+ <SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
+ <SliderPrimitive.Range className="absolute h-full bg-primary" />
+ </SliderPrimitive.Track>
+ <SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
+ </SliderPrimitive.Root>
+));
+Slider.displayName = SliderPrimitive.Root.displayName;
+
+export { Slider };
diff --git a/drizzle/0007_flippant_betty_brant.sql b/drizzle/0007_flippant_betty_brant.sql
new file mode 100644
index 0000000..39ab2c9
--- /dev/null
+++ b/drizzle/0007_flippant_betty_brant.sql
@@ -0,0 +1 @@
+ALTER TABLE `icloud_syncs` ADD `auto_sync_interval` integer DEFAULT 0 NOT NULL;
\ No newline at end of file
diff --git a/drizzle/meta/0007_snapshot.json b/drizzle/meta/0007_snapshot.json
new file mode 100644
index 0000000..90c7fe7
--- /dev/null
+++ b/drizzle/meta/0007_snapshot.json
@@ -0,0 +1,546 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "a698f740-4747-466e-ab6a-79cb5de013a7",
+ "prevId": "bcb20d16-59cb-4659-8304-31cc39e260fb",
+ "tables": {
+ "calendar_notes": {
+ "name": "calendar_notes",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "calendar_notes_calendar_id_calendars_id_fk": {
+ "name": "calendar_notes_calendar_id_calendars_id_fk",
+ "tableFrom": "calendar_notes",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "calendars": {
+ "name": "calendars",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "password_hash": {
+ "name": "password_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_locked": {
+ "name": "is_locked",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "icloud_syncs": {
+ "name": "icloud_syncs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "icloud_url": {
+ "name": "icloud_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "display_mode": {
+ "name": "display_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "is_hidden": {
+ "name": "is_hidden",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "hide_from_stats": {
+ "name": "hide_from_stats",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "auto_sync_interval": {
+ "name": "auto_sync_interval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "last_synced_at": {
+ "name": "last_synced_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "icloud_syncs_calendar_id_calendars_id_fk": {
+ "name": "icloud_syncs_calendar_id_calendars_id_fk",
+ "tableFrom": "icloud_syncs",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shift_presets": {
+ "name": "shift_presets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_secondary": {
+ "name": "is_secondary",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "is_all_day": {
+ "name": "is_all_day",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "hide_from_stats": {
+ "name": "hide_from_stats",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "shift_presets_calendar_id_calendars_id_fk": {
+ "name": "shift_presets_calendar_id_calendars_id_fk",
+ "tableFrom": "shift_presets",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "shifts": {
+ "name": "shifts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "calendar_id": {
+ "name": "calendar_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "preset_id": {
+ "name": "preset_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "end_time": {
+ "name": "end_time",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'#3b82f6'"
+ },
+ "notes": {
+ "name": "notes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_all_day": {
+ "name": "is_all_day",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "is_secondary": {
+ "name": "is_secondary",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "icloud_event_id": {
+ "name": "icloud_event_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "icloud_sync_id": {
+ "name": "icloud_sync_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "synced_from_icloud": {
+ "name": "synced_from_icloud",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "shifts_calendar_id_calendars_id_fk": {
+ "name": "shifts_calendar_id_calendars_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "calendars",
+ "columnsFrom": [
+ "calendar_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "shifts_preset_id_shift_presets_id_fk": {
+ "name": "shifts_preset_id_shift_presets_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "shift_presets",
+ "columnsFrom": [
+ "preset_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "shifts_icloud_sync_id_icloud_syncs_id_fk": {
+ "name": "shifts_icloud_sync_id_icloud_syncs_id_fk",
+ "tableFrom": "shifts",
+ "tableTo": "icloud_syncs",
+ "columnsFrom": [
+ "icloud_sync_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index 47af2c0..cef15e0 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -50,6 +50,13 @@
"when": 1764788029911,
"tag": "0006_first_tana_nile",
"breakpoints": true
+ },
+ {
+ "idx": 7,
+ "version": "6",
+ "when": 1764876813553,
+ "tag": "0007_flippant_betty_brant",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/instrumentation.ts b/instrumentation.ts
new file mode 100644
index 0000000..06e1529
--- /dev/null
+++ b/instrumentation.ts
@@ -0,0 +1,12 @@
+/**
+ * Next.js Instrumentation Hook
+ * Runs once when the server starts
+ */
+
+export async function register() {
+ if (process.env.NEXT_RUNTIME === "nodejs") {
+ // Import and start the auto-sync service
+ const { autoSyncService } = await import("@/lib/auto-sync-service");
+ await autoSyncService.start();
+ }
+}
diff --git a/lib/auto-sync-service.ts b/lib/auto-sync-service.ts
new file mode 100644
index 0000000..343ca26
--- /dev/null
+++ b/lib/auto-sync-service.ts
@@ -0,0 +1,216 @@
+/**
+ * Auto-Sync Service for iCloud Calendars
+ * Runs in the background and periodically syncs calendars based on their autoSyncInterval
+ */
+
+import { db } from "@/lib/db";
+import { icloudSyncs } from "@/lib/db/schema";
+import { gt, eq } from "drizzle-orm";
+import { eventEmitter } from "@/lib/event-emitter";
+import { syncICloudCalendar } from "@/app/api/icloud-syncs/[id]/sync/route";
+
+interface SyncJob {
+ syncId: string;
+ nextSyncTime: number;
+ intervalMs: number;
+}
+
+class AutoSyncService {
+ private jobs: Map<string, SyncJob> = new Map();
+ private timers: Map<string, NodeJS.Timeout> = new Map();
+ private pollInterval: NodeJS.Timeout | null = null;
+ private isRunning = false;
+
+ /**
+ * Start the auto-sync service
+ */
+ async start() {
+ if (this.isRunning) {
+ console.log("Auto-sync service already running");
+ return;
+ }
+
+ this.isRunning = true;
+ console.log("Starting auto-sync service...");
+
+ // Load all syncs with auto-sync enabled
+ await this.loadSyncs();
+
+ // Check for syncs every 5 minutes in case of changes
+ this.pollInterval = setInterval(() => this.loadSyncs(), 5 * 60 * 1000);
+ }
+
+ /**
+ * Stop the auto-sync service
+ */
+ stop() {
+ console.log("Stopping auto-sync service...");
+ this.isRunning = false;
+
+ // Clear the polling interval
+ if (this.pollInterval) {
+ clearInterval(this.pollInterval);
+ this.pollInterval = null;
+ }
+
+ // Clear all sync job timers
+ for (const timer of this.timers.values()) {
+ clearTimeout(timer);
+ }
+ this.timers.clear();
+ this.jobs.clear();
+ }
+
+ /**
+ * Load syncs from database and schedule jobs
+ */
+ private async loadSyncs() {
+ try {
+ // Get all syncs with auto-sync enabled (autoSyncInterval > 0)
+ const syncs = await db
+ .select()
+ .from(icloudSyncs)
+ .where(gt(icloudSyncs.autoSyncInterval, 0));
+
+ // Remove jobs for syncs that were deleted or disabled
+ for (const [syncId] of this.jobs) {
+ if (!syncs.find((s) => s.id === syncId)) {
+ this.removeJob(syncId);
+ }
+ }
+
+ // Add or update jobs for active syncs
+ for (const sync of syncs) {
+ const intervalMs = sync.autoSyncInterval * 60 * 1000; // Convert minutes to milliseconds
+ const existingJob = this.jobs.get(sync.id);
+
+ // If interval changed, reschedule
+ if (existingJob && existingJob.intervalMs !== intervalMs) {
+ this.removeJob(sync.id);
+ this.scheduleJob(sync.id, intervalMs, sync.lastSyncedAt);
+ } else if (!existingJob) {
+ // New job
+ this.scheduleJob(sync.id, intervalMs, sync.lastSyncedAt);
+ }
+ }
+ } catch (error) {
+ console.error("Failed to load syncs:", error);
+ }
+ }
+
+ /**
+ * Schedule a sync job
+ */
+ private scheduleJob(
+ syncId: string,
+ intervalMs: number,
+ lastSyncedAt: Date | null
+ ) {
+ const now = Date.now();
+ let nextSyncTime: number;
+
+ if (lastSyncedAt) {
+ // Schedule next sync based on last sync time + interval
+ const lastSyncTime = lastSyncedAt.getTime();
+ nextSyncTime = lastSyncTime + intervalMs;
+
+ // If we're already past the next sync time, sync immediately
+ if (nextSyncTime <= now) {
+ nextSyncTime = now;
+ }
+ } else {
+ // Never synced before, sync immediately
+ nextSyncTime = now;
+ }
+
+ const delay = Math.max(0, nextSyncTime - now);
+
+ console.log(
+ `Scheduling sync ${syncId} in ${Math.round(delay / 1000)}s (interval: ${
+ intervalMs / 60000
+ }min)`
+ );
+
+ const timer = setTimeout(() => {
+ this.executeSync(syncId, intervalMs);
+ }, delay);
+
+ this.jobs.set(syncId, { syncId, nextSyncTime, intervalMs });
+ this.timers.set(syncId, timer);
+ }
+
+ /**
+ * Execute a sync job
+ */
+ private async executeSync(syncId: string, intervalMs: number) {
+ console.log(`Executing auto-sync for ${syncId}`);
+
+ try {
+ // Call sync function directly instead of HTTP fetch
+ const stats = await syncICloudCalendar(syncId);
+
+ if (stats) {
+ console.log(`Auto-sync completed for ${syncId}:`, stats);
+
+ // Emit event to notify connected clients
+ eventEmitter.emit("calendar-change", {
+ type: "shift",
+ action: "update",
+ calendarId: stats.calendarId,
+ data: { autoSync: true, syncId, stats },
+ });
+ }
+ } catch (error) {
+ console.error(`Auto-sync error for ${syncId}:`, error);
+ }
+
+ // Schedule next sync
+ this.scheduleJob(syncId, intervalMs, new Date());
+ }
+
+ /**
+ * Remove a sync job
+ */
+ private removeJob(syncId: string) {
+ const timer = this.timers.get(syncId);
+ if (timer) {
+ clearTimeout(timer);
+ this.timers.delete(syncId);
+ }
+ this.jobs.delete(syncId);
+ console.log(`Removed sync job ${syncId}`);
+ }
+
+ /**
+ * Manually trigger a sync (doesn't affect schedule)
+ */
+ async triggerSync(syncId: string) {
+ console.log(`Manually triggering sync for ${syncId}`);
+
+ try {
+ // Call sync function directly instead of HTTP fetch
+ const stats = await syncICloudCalendar(syncId);
+
+ if (stats) {
+ console.log(`Manual sync completed for ${syncId}:`, stats);
+
+ // Reschedule based on new lastSyncedAt
+ const job = this.jobs.get(syncId);
+ if (job) {
+ this.removeJob(syncId);
+ this.scheduleJob(syncId, job.intervalMs, new Date());
+ }
+
+ return { stats };
+ }
+
+ return null;
+ } catch (error) {
+ console.error(`Manual sync error for ${syncId}:`, error);
+ return null;
+ }
+ }
+}
+
+// Singleton instance
+export const autoSyncService = new AutoSyncService();
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 15af97c..a83001d 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -32,6 +32,7 @@ export const icloudSyncs = sqliteTable("icloud_syncs", {
hideFromStats: integer("hide_from_stats", { mode: "boolean" })
.notNull()
.default(false),
+ autoSyncInterval: integer("auto_sync_interval").notNull().default(0), // 0 = manual, otherwise minutes
lastSyncedAt: integer("last_synced_at", { mode: "timestamp" }),
createdAt: integer("created_at", { mode: "timestamp" })
.notNull()
diff --git a/messages/de.json b/messages/de.json
index b461b17..3d0aa4a 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -212,6 +212,10 @@
"howToStep1": "Öffne iCloud.com und gehe zu Kalender",
"howToStep2": "Klicke auf das Teilen-Symbol neben deinem Kalender",
"howToStep3": "Aktiviere 'Öffentlicher Kalender'",
- "howToStep4": "Kopiere die URL und füge sie hier ein"
+ "howToStep4": "Kopiere die URL und füge sie hier ein",
+ "autoSyncLabel": "Automatische Synchronisierung",
+ "autoSyncHint": "Wähle wie oft dieser Kalender automatisch synchronisiert werden soll",
+ "autoSyncManual": "Manuell",
+ "autoSync24hShort": "24 h"
}
}
diff --git a/messages/en.json b/messages/en.json
index 723c298..678c9c0 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -212,6 +212,10 @@
"howToStep1": "Open iCloud.com and go to Calendar",
"howToStep2": "Click the share icon next to your calendar",
"howToStep3": "Enable 'Public Calendar'",
- "howToStep4": "Copy the URL and paste it here"
+ "howToStep4": "Copy the URL and paste it here",
+ "autoSyncLabel": "Auto Sync",
+ "autoSyncHint": "Choose how often this calendar should automatically sync",
+ "autoSyncManual": "Manual",
+ "autoSync24hShort": "24 h"
}
}
diff --git a/package-lock.json b/package-lock.json
index 1729370..3086857 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -12,6 +12,7 @@
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-select": "^2.2.6",
+ "@radix-ui/react-slider": "^1.3.6",
"@radix-ui/react-slot": "^1.2.4",
"better-sqlite3": "^12.5.0",
"class-variance-authority": "^0.7.1",
@@ -2706,6 +2707,39 @@
}
}
},
+ "node_modules/@radix-ui/react-slider": {
+ "version": "1.3.6",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.3.6.tgz",
+ "integrity": "sha512-JPYb1GuM1bxfjMRlNLE+BcmBC8onfCi60Blk7OBqi2MLTFdS+8401U4uFjnwkOr49BLmXxLC6JHkvAsx5OJvHw==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/number": "1.1.1",
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-collection": "1.1.7",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-direction": "1.1.1",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "@radix-ui/react-use-layout-effect": "1.1.1",
+ "@radix-ui/react-use-previous": "1.1.1",
+ "@radix-ui/react-use-size": "1.1.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-slot": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.4.tgz",
diff --git a/package.json b/package.json
index 2525547..1e3ca66 100644
--- a/package.json
+++ b/package.json
@@ -20,6 +20,7 @@
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-select": "^2.2.6",
+ "@radix-ui/react-slider": "^1.3.6",
"@radix-ui/react-slot": "^1.2.4",
"better-sqlite3": "^12.5.0",
"class-variance-authority": "^0.7.1",