Your favorite shift management application!
feat: Add ICS upload and custom external calendar support (#32)
panteL35804c374083
diff --git a/README.md b/README.mdindex 1f746ee..c8f8ad2 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")-- **External Calendar Sync**: Automatically or manually synchronize multiple external calendars at configurable intervals+- **External Calendars**: Automatically or manually synchronize multiple external calendars at configurable intervals or import ICS files### 🎨 Customization & Organization@@ -89,6 +89,11 @@ $ git clone https://github.com/pantelx/bettershift.git && cd bettershift# Install dependencies$ npm install+# Copy the example environment file+$ cp .env.example .env++# Adjust .env settings as needed+# Set up the database$ npm run db:migrate@@ -138,6 +143,11 @@ $ docker exec bettershift npm run db:migrate# Clone the repository$ git clone https://github.com/pantelx/bettershift.git && cd bettershift+# Copy the example environment file+$ cp .env.example .env++# Adjust .env settings as needed+# Build and start the container$ docker-compose up -d --builddiff --git a/app/api/external-syncs/route.ts b/app/api/external-syncs/route.tsindex fdb2bd7..37c6901 100644--- a/app/api/external-syncs/route.ts+++ b/app/api/external-syncs/route.ts@@ -1,9 +1,11 @@import { NextResponse } from "next/server";import { db } from "@/lib/db";import { externalSyncs } from "@/lib/db/schema";-import { eq } from "drizzle-orm";+import { eq, desc } from "drizzle-orm";import {isValidCalendarUrl,+ detectCalendarSyncType,+ isValidICSContent,type CalendarSyncType,} from "@/lib/external-calendar-utils";@@ -24,7 +26,7 @@ export async function GET(request: Request) {.select().from(externalSyncs).where(eq(externalSyncs.calendarId, calendarId))- .orderBy(externalSyncs.createdAt);+ .orderBy(desc(externalSyncs.createdAt));return NextResponse.json(syncs);} catch (error) {@@ -43,46 +45,79 @@ export async function POST(request: Request) {const {calendarId,name,- syncType,calendarUrl,color,displayMode,autoSyncInterval,+ icsContent, // For file uploads+ isHidden,+ hideFromStats,} = body;- if (!calendarId || !name || !calendarUrl || !syncType) {+ if (!calendarId || !name) {return NextResponse.json({- error: "Calendar ID, name, sync type, and calendar URL are required",+ error: "Calendar ID and name are required",},{ status: 400 });}- // Validate sync type- if (!["icloud", "google"].includes(syncType)) {- return NextResponse.json(- { error: "Sync type must be either 'icloud' or 'google'" },- { status: 400 }- );- }+ let finalCalendarUrl;+ let isOneTimeImport = false;+ let syncType: CalendarSyncType;- // Validate calendar URL to prevent SSRF- if (!isValidCalendarUrl(calendarUrl, syncType as CalendarSyncType)) {- const domain = syncType === "icloud" ? "icloud.com" : "google.com";+ // Handle different scenarios+ if (icsContent) {+ // Validate ICS content+ if (!isValidICSContent(icsContent)) {+ return NextResponse.json(+ { error: "Invalid ICS file format or file contains no events" },+ { status: 400 }+ );+ }++ // File upload - one-time import, always custom type+ isOneTimeImport = true;+ syncType = "custom";+ // Store content as data URL for later retrieval+ finalCalendarUrl = `data:text/calendar;base64,${Buffer.from(+ icsContent+ ).toString("base64")}`;+ } else if (calendarUrl) {+ // URL-based import - detect type from URL+ syncType = detectCalendarSyncType(calendarUrl);+ isOneTimeImport = false;++ // Validate calendar URL to prevent SSRF+ if (!isValidCalendarUrl(calendarUrl, syncType)) {+ const domainMsg =+ syncType === "icloud"+ ? "icloud.com domain"+ : syncType === "google"+ ? "google.com domain"+ : "valid domain";+ return NextResponse.json(+ {+ error: `Invalid ${syncType} calendar URL. URL must use webcal:// or https:// protocol and be from ${domainMsg}`,+ },+ { status: 400 }+ );+ }+ finalCalendarUrl = calendarUrl;+ } else {return NextResponse.json(- {- error: `Invalid ${syncType} calendar URL. URL must use webcal:// or https:// protocol and be from ${domain} domain`,- },+ { error: "Either calendar URL or ICS content is required" },{ status: 400 });}- // Validate autoSyncInterval+ // Validate autoSyncInterval (should be 0 for one-time imports)const validIntervals = [0, 5, 15, 30, 60, 120, 360, 720, 1440];+ const finalAutoSyncInterval = isOneTimeImport ? 0 : autoSyncInterval || 0;if (- autoSyncInterval !== undefined &&- !validIntervals.includes(autoSyncInterval)+ finalAutoSyncInterval !== undefined &&+ !validIntervals.includes(finalAutoSyncInterval)) {return NextResponse.json({@@ -101,10 +136,13 @@ export async function POST(request: Request) {calendarId,name,syncType,- calendarUrl,+ calendarUrl: finalCalendarUrl,color: color || "#3b82f6",displayMode: displayMode || "normal",- autoSyncInterval: autoSyncInterval || 0,+ autoSyncInterval: finalAutoSyncInterval,+ isOneTimeImport,+ isHidden: isHidden || false,+ hideFromStats: hideFromStats || false,createdAt: new Date(),updatedAt: new Date(),})diff --git a/components/external-sync-manage-dialog.tsx b/components/external-sync-manage-dialog.tsxindex fcd2a63..4ce1e7e 100644--- a/components/external-sync-manage-dialog.tsx+++ b/components/external-sync-manage-dialog.tsx@@ -23,11 +23,19 @@ import { ColorPicker } from "@/components/ui/color-picker";import { Slider } from "@/components/ui/slider";import { useTranslations } from "next-intl";import { ExternalSync } from "@/lib/db/schema";-import { Loader2, Trash2, RefreshCw, Plus, Edit2 } from "lucide-react";+import {+ Loader2,+ Trash2,+ RefreshCw,+ Plus,+ Edit2,+ ChevronDown,+} from "lucide-react";import { toast } from "sonner";import { PRESET_COLORS } from "@/lib/constants";import {isValidCalendarUrl,+ detectCalendarSyncType,type CalendarSyncType,} from "@/lib/external-calendar-utils";@@ -55,14 +63,21 @@ export function ExternalSyncManageDialog({// Form stateconst [formName, setFormName] = useState("");const [formUrl, setFormUrl] = useState("");- const [formSyncType, setFormSyncType] = useState("icloud");const [formColor, setFormColor] = useState("#3b82f6");const [formDisplayMode, setFormDisplayMode] = useState("normal");const [formAutoSyncInterval, setFormAutoSyncInterval] = useState(0);+ const [icsFile, setIcsFile] = useState<File | null>(null);+ const [importType, setImportType] = useState<"url" | "file">("url");+ const [formIsHidden, setFormIsHidden] = useState(false);+ const [formHideFromStats, setFormHideFromStats] = useState(false);+ const [expandedHint, setExpandedHint] = useState<CalendarSyncType | null>(+ null+ );const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);const initialFormDataRef = useRef<{name: string;+ url: string;color: string;displayMode: string;autoSyncInterval: number;@@ -102,46 +117,82 @@ export function ExternalSyncManageDialog({setEditingSync(null);setFormName("");setFormUrl("");- setFormSyncType("icloud");setFormColor("#3b82f6");setFormDisplayMode("normal");setFormAutoSyncInterval(0);+ setIcsFile(null);+ setImportType("url");+ setFormIsHidden(false);+ setFormHideFromStats(false);}}, [open, calendarId, fetchSyncs]);const handleAddSync = async () => {- if (!calendarId || !formName.trim() || !formUrl.trim()) return;+ if (!calendarId || !formName.trim()) return;- // Validate calendar URL format- if (!isValidCalendarUrl(formUrl.trim(), formSyncType as CalendarSyncType)) {- toast.error(t("externalSync.invalidUrlFormat"));- return;- }+ // For file upload+ if (importType === "file") {+ if (!icsFile) {+ toast.error(t("externalSync.fileRequired"));+ return;+ }+ } else {+ // For URL-based imports+ if (!formUrl.trim()) {+ toast.error(t("externalSync.urlRequired"));+ return;+ }- // Check if URL already exists- const normalizedUrl = formUrl.trim().toLowerCase();- const urlExists = syncs.some(- (sync) => sync.calendarUrl.toLowerCase() === normalizedUrl- );+ // Detect and validate calendar URL format+ const detectedType = detectCalendarSyncType(formUrl.trim());+ if (!isValidCalendarUrl(formUrl.trim(), detectedType)) {+ toast.error(t("externalSync.invalidUrlFormat"));+ return;+ }- if (urlExists) {- toast.error(t("externalSync.urlAlreadyExists"));- return;+ // Check if URL already exists (only for URL-based imports, not file uploads)+ const normalizedUrl = formUrl.trim().toLowerCase();+ const urlExists = syncs.some(+ (sync) =>+ !sync.isOneTimeImport &&+ sync.calendarUrl.toLowerCase() === normalizedUrl+ );++ if (urlExists) {+ toast.error(t("externalSync.urlAlreadyExists"));+ return;+ }}setIsLoading(true);try {+ let icsContent: string | undefined;++ // Read file content if file upload+ if (importType === "file" && icsFile) {+ // Check file size (limit: 5MB)+ const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB+ if (icsFile.size > MAX_FILE_SIZE) {+ toast.error(t("externalSync.fileTooLarge"));+ setIsLoading(false);+ return;+ }+ icsContent = await icsFile.text();+ }+const response = await fetch("/api/external-syncs", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({calendarId,name: formName.trim(),- calendarUrl: formUrl.trim(),- syncType: formSyncType,+ calendarUrl: formUrl.trim() || undefined,color: formColor,displayMode: formDisplayMode,autoSyncInterval: formAutoSyncInterval,+ icsContent,+ isHidden: formIsHidden,+ hideFromStats: formHideFromStats,}),});@@ -149,10 +200,13 @@ export function ExternalSyncManageDialog({const newSync = await response.json();setFormName("");setFormUrl("");- setFormSyncType("icloud");setFormColor("#3b82f6");setFormDisplayMode("normal");setFormAutoSyncInterval(0);+ setIcsFile(null);+ setImportType("url");+ setFormIsHidden(false);+ setFormHideFromStats(false);setShowAddForm(false);await fetchSyncs();onSyncComplete?.(); // Trigger refresh to update parent state@@ -181,7 +235,7 @@ export function ExternalSyncManageDialog({headers: { "Content-Type": "application/json" },body: JSON.stringify({name: formName.trim(),- icloudUrl: formUrl.trim() || undefined,+ calendarUrl: formUrl.trim() || undefined,color: formColor,displayMode: formDisplayMode,autoSyncInterval: formAutoSyncInterval,@@ -192,7 +246,6 @@ export function ExternalSyncManageDialog({setEditingSync(null);setFormName("");setFormUrl("");- setFormSyncType("icloud");setFormColor("#3b82f6");setFormDisplayMode("normal");setFormAutoSyncInterval(0);@@ -273,17 +326,20 @@ export function ExternalSyncManageDialog({const startEdit = (sync: ExternalSync) => {setEditingSync(sync);- setFormName(sync.name);- setFormUrl(sync.calendarUrl);- setFormColor(sync.color);+ setFormName(sync.name || "");+ setFormUrl(sync.calendarUrl || "");+ setFormColor(sync.color || "#3b82f6");setFormDisplayMode(sync.displayMode || "normal");setFormAutoSyncInterval(sync.autoSyncInterval || 0);+ setFormIsHidden(sync.isHidden || false);+ setFormHideFromStats(sync.hideFromStats || false);setShowAddForm(false);// Set initial data for auto-save comparisoninitialFormDataRef.current = {- name: sync.name,- color: sync.color,+ name: sync.name || "",+ url: sync.calendarUrl || "",+ color: sync.color || "#3b82f6",displayMode: sync.displayMode || "normal",autoSyncInterval: sync.autoSyncInterval || 0,};@@ -294,7 +350,6 @@ export function ExternalSyncManageDialog({setEditingSync(null);setFormName("");setFormUrl("");- setFormSyncType("icloud");setFormColor("#3b82f6");setFormDisplayMode("normal");setFormAutoSyncInterval(0);@@ -364,10 +419,13 @@ export function ExternalSyncManageDialog({setEditingSync(null);setFormName("");setFormUrl("");- setFormSyncType("icloud");setFormColor("#3b82f6");setFormDisplayMode("normal");setFormAutoSyncInterval(0);+ setIcsFile(null);+ setImportType("url");+ setFormIsHidden(false);+ setFormHideFromStats(false);};// Shared function to save external sync changes@@ -381,6 +439,9 @@ export function ExternalSyncManageDialog({headers: { "Content-Type": "application/json" },body: JSON.stringify({name: formName.trim(),+ calendarUrl: !editingSync.isOneTimeImport+ ? formUrl.trim()+ : undefined,color: formColor,displayMode: formDisplayMode,autoSyncInterval: formAutoSyncInterval,@@ -394,6 +455,7 @@ export function ExternalSyncManageDialog({// Update initial data ref after successful saveinitialFormDataRef.current = {name: formName,+ url: formUrl,color: formColor,displayMode: formDisplayMode,autoSyncInterval: formAutoSyncInterval,@@ -415,6 +477,7 @@ export function ExternalSyncManageDialog({[editingSync,formName,+ formUrl,formColor,formDisplayMode,formAutoSyncInterval,@@ -442,6 +505,7 @@ export function ExternalSyncManageDialog({// Check if data has changedconst currentFormData = {name: formName,+ url: formUrl,color: formColor,displayMode: formDisplayMode,autoSyncInterval: formAutoSyncInterval,@@ -464,6 +528,7 @@ export function ExternalSyncManageDialog({};}, [formName,+ formUrl,formColor,formDisplayMode,formAutoSyncInterval,@@ -490,6 +555,7 @@ export function ExternalSyncManageDialog({// Check if data has changedconst currentFormData = {name: formName,+ url: formUrl,color: formColor,displayMode: formDisplayMode,autoSyncInterval: formAutoSyncInterval,@@ -514,19 +580,16 @@ export function ExternalSyncManageDialog({onOpenChange(false);};- // Get URL placeholder and hint based on sync type+ // Get URL placeholder - show generic placeholder for allconst getUrlPlaceholder = () => {- if (formSyncType === "google") {- return t("externalSync.urlPlaceholderGoogle");- }- return t("externalSync.urlPlaceholderICloud");+ return t("externalSync.urlPlaceholder");};const getUrlHint = () => {- if (formSyncType === "google") {- return t("externalSync.urlHintGoogle");+ if (!editingSync) {+ // When creating new calendar, show custom hint+ return t("externalSync.urlHintCustom");}- return t("externalSync.urlHintICloud");};return (@@ -542,95 +605,110 @@ export function ExternalSyncManageDialog({</DialogHeader><div className="space-y-3 overflow-y-auto flex-1 p-6">- {/* Existing Syncs List */}- {syncs.length > 0 && (+ {/* Existing Syncs List - hide when adding new sync, show only edited sync when editing */}+ {syncs.length > 0 && !showAddForm && (<div className="space-y-3">- {syncs.map((sync) => (- <div- key={sync.id}- className="flex flex-col gap-3 p-4 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all"- style={{ borderLeftColor: sync.color, borderLeftWidth: 4 }}- >- {/* Title row - always full width on mobile */}- <div className="flex items-start gap-2">- <div- className="w-1 h-4 rounded-full shrink-0 mt-0.5"- style={{ backgroundColor: sync.color }}- />- <span className="font-semibold flex-1 min-w-0 break-words">- {sync.name}- </span>- </div>-- {/* Badges and buttons row */}- <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:justify-between">- <div className="flex flex-wrap items-center gap-2">- <span className="text-xs px-2 py-0.5 rounded-full bg-muted border border-border/50 font-normal">- {sync.syncType === "google"- ? t("externalSync.syncTypeGoogle")- : t("externalSync.syncTypeICloud")}+ {syncs+ .filter((sync) => !editingSync || sync.id === editingSync.id)+ .map((sync) => (+ <div+ key={sync.id}+ className="flex flex-col gap-3 p-4 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all"+ style={{ borderLeftColor: sync.color, borderLeftWidth: 4 }}+ >+ {/* Title row - always full width on mobile */}+ <div className="flex items-start gap-2">+ <div+ className="w-1 h-4 rounded-full shrink-0 mt-0.5"+ style={{ backgroundColor: sync.color }}+ />+ <span className="font-semibold flex-1 min-w-0 break-words">+ {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("externalSync.autoSyncManual")}- </span>- )}- {sync.lastSyncedAt && (- <span className="text-xs text-muted-foreground">- {t("externalSync.lastSynced")}:{" "}- {new Date(sync.lastSyncedAt).toLocaleString()}- </span>- )}</div>- <div className="flex gap-1 shrink-0">- <Button- size="icon"- variant="ghost"- className="h-8 w-8"- onClick={() => startEdit(sync)}- disabled={!!isSyncing || !!isDeleting}- >- <Edit2 className="h-4 w-4" />- </Button>- <Button- size="icon"- variant="ghost"- className="h-8 w-8"- onClick={() => handleSync(sync.id)}- disabled={!!isSyncing || !!isDeleting}- >- {isSyncing === sync.id ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : (- <RefreshCw className="h-4 w-4" />++ {/* Badges and buttons row */}+ <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:justify-between">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-xs px-2 py-0.5 rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400 border border-blue-500/20 font-medium">+ {sync.syncType === "google"+ ? t("externalSync.syncTypeGoogle")+ : sync.syncType === "custom"+ ? t("externalSync.syncTypeCustom")+ : t("externalSync.syncTypeICloud")}+ </span>+ {sync.isOneTimeImport && (+ <span className="text-xs px-2 py-0.5 rounded-full bg-amber-500/10 text-amber-600 dark:text-amber-400 border border-amber-500/20 font-medium">+ {t("externalSync.oneTimeImport")}+ </span>)}- </Button>- <Button- size="icon"- variant="ghost"- className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"- onClick={() => handleDelete(sync.id)}- disabled={!!isSyncing || !!isDeleting}- >- {isDeleting === sync.id ? (- <Loader2 className="h-4 w-4 animate-spin" />+ {!sync.isOneTimeImport && sync.autoSyncInterval > 0 ? (+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-green-500/10 text-green-600 dark:text-green-400 border border-green-500/20 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>) : (- <Trash2 className="h-4 w-4" />+ !sync.isOneTimeImport && (+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-gray-500/10 text-gray-600 dark:text-gray-400 border border-gray-500/20 text-xs font-medium">+ {t("externalSync.autoSyncManual")}+ </span>+ )+ )}+ </div>+ <div className="flex gap-1 shrink-0">+ <Button+ size="icon"+ variant="ghost"+ className="h-8 w-8"+ onClick={() => startEdit(sync)}+ disabled={!!isSyncing || !!isDeleting}+ >+ <Edit2 className="h-4 w-4" />+ </Button>+ {!sync.isOneTimeImport && (+ <Button+ size="icon"+ variant="ghost"+ className="h-8 w-8"+ onClick={() => handleSync(sync.id)}+ disabled={!!isSyncing || !!isDeleting}+ >+ {isSyncing === sync.id ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <RefreshCw className="h-4 w-4" />+ )}+ </Button>)}- </Button>+ <Button+ size="icon"+ variant="ghost"+ className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"+ onClick={() => handleDelete(sync.id)}+ disabled={!!isSyncing || !!isDeleting}+ >+ {isDeleting === sync.id ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Trash2 className="h-4 w-4" />+ )}+ </Button>+ </div></div>++ {/* Last synced info - always below badges */}+ {sync.lastSyncedAt && (+ <div className="text-xs text-muted-foreground pt-1 border-t border-border/30">+ {t("externalSync.lastSynced")}:{" "}+ {new Date(sync.lastSyncedAt).toLocaleString()}+ </div>+ )}</div>- </div>- ))}+ ))}</div>)}@@ -657,41 +735,90 @@ export function ExternalSyncManageDialog({{!editingSync && (<div className="space-y-2">- <Label htmlFor="sync-type">- {t("externalSync.syncTypeLabel")}+ <Label htmlFor="import-type">+ {t("externalSync.importMethod")}</Label>- <Select value={formSyncType} onValueChange={setFormSyncType}>- <SelectTrigger id="sync-type" className="bg-background/50">+ <Select+ value={importType}+ onValueChange={(value: "url" | "file") => {+ setImportType(value);+ setFormUrl("");+ setIcsFile(null);+ }}+ >+ <SelectTrigger+ id="import-type"+ className="bg-background/50"+ ><SelectValue /></SelectTrigger><SelectContent>- <SelectItem value="icloud">- {t("externalSync.syncTypeICloud")}+ <SelectItem value="url">+ {t("externalSync.importMethodUrl")}</SelectItem>- <SelectItem value="google">- {t("externalSync.syncTypeGoogle")}+ <SelectItem value="file">+ {t("externalSync.importMethodFile")}</SelectItem></SelectContent></Select>+ <p className="text-xs text-muted-foreground">+ {importType === "url"+ ? t("externalSync.importMethodUrlHint")+ : t("externalSync.importMethodFileHint")}+ </p></div>)}- <div className="space-y-2">- <Label htmlFor="sync-url">{t("externalSync.urlLabel")}</Label>- <Input- id="sync-url"- type="text"- placeholder={getUrlPlaceholder()}- value={formUrl}- onChange={(e) => setFormUrl(e.target.value)}- disabled={isLoading || !!editingSync}- />- {!editingSync && (- <p className="text-xs text-muted-foreground">- {getUrlHint()}- </p>- )}- </div>+ {!editingSync && importType === "file" ? (+ <div className="space-y-2">+ <Label htmlFor="ics-file">+ {t("externalSync.fileLabel")}+ </Label>+ <Input+ id="ics-file"+ type="file"+ accept=".ics,.ical"+ onChange={(e) => {+ const file = e.target.files?.[0];+ setIcsFile(file || null);+ }}+ disabled={isLoading}+ className="cursor-pointer"+ value=""+ />+ {icsFile && (+ <p className="text-xs text-muted-foreground">+ {t("externalSync.fileSelected")}: {icsFile.name}+ </p>+ )}+ </div>+ ) : (+ // Show URL input for new syncs OR when editing non-one-time-import syncs+ (!editingSync || !editingSync.isOneTimeImport) && (+ <div className="space-y-2">+ <Label htmlFor="sync-url">+ {t("externalSync.urlLabel")}+ </Label>+ <Input+ id="sync-url"+ type="text"+ placeholder={getUrlPlaceholder()}+ value={formUrl || ""}+ onChange={(e) => setFormUrl(e.target.value)}+ disabled={isLoading}+ readOnly={!!editingSync}+ className={+ editingSync+ ? "bg-muted/30 cursor-default font-mono text-sm"+ : ""+ }+ />+ <p className="text-xs text-muted-foreground">+ {getUrlHint()}+ </p>+ </div>+ )+ )}<div className="space-y-2"><ColorPicker@@ -733,104 +860,121 @@ export function ExternalSyncManageDialog({</p></div>- <div className="space-y-3">- <div className="flex items-center justify-between">- <Label>{t("externalSync.autoSyncLabel")}</Label>- <span className="text-sm font-medium text-primary">- {formAutoSyncInterval === 0- ? t("externalSync.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("externalSync.autoSyncManual")}</span>- <span>{t("externalSync.autoSync24hShort")}</span>- </div>- <p className="text-xs text-muted-foreground">- {t("externalSync.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("externalSync.hideCalendar")}- </Label>+ {/* Only show auto-sync for URL-based imports (both creating and editing) */}+ {!(importType === "file") &&+ !(editingSync && editingSync.isOneTimeImport) && (+ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <Label>{t("externalSync.autoSyncLabel")}</Label>+ <span className="text-sm font-medium text-primary">+ {formAutoSyncInterval === 0+ ? t("externalSync.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("externalSync.autoSyncManual")}</span>+ <span>{t("externalSync.autoSync24hShort")}</span></div>- <p className="text-xs text-muted-foreground pl-6">- {t("externalSync.hideCalendarHint")}+ <p className="text-xs text-muted-foreground">+ {t("externalSync.autoSyncHint")}</p>+ </div>+ )}++ {/* Visibility options - both for creating and editing */}+ <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 ? editingSync.isHidden || false : formIsHidden+ }+ onCheckedChange={(checked) => {+ if (editingSync) {+ handleToggleVisibility(+ editingSync.id,+ "isHidden",+ editingSync.isHidden || false+ );+ } else {+ setFormIsHidden(checked as boolean);+ }+ }}+ />+ <Label+ htmlFor="hide-calendar"+ className="text-sm font-normal cursor-pointer"+ >+ {t("externalSync.hideCalendar")}+ </Label>+ </div>+ <p className="text-xs text-muted-foreground pl-6">+ {t("externalSync.hideCalendarHint")}+ </p>- <div className="flex items-center gap-2">- <Checkbox- id="hide-from-stats"- checked={- editingSync.isHidden ||+ <div className="flex items-center gap-2">+ <Checkbox+ id="hide-from-stats"+ checked={+ editingSync+ ? 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("externalSync.hideFromStats")}- </Label>- </div>- <p className="text-xs text-muted-foreground pl-6">- {t("externalSync.hideFromStatsHint")}- </p>- </div>- </>- )}+ : formIsHidden || formHideFromStats+ }+ onCheckedChange={(checked) => {+ if (editingSync) {+ handleToggleVisibility(+ editingSync.id,+ "hideFromStats",+ editingSync.hideFromStats || false+ );+ } else {+ setFormHideFromStats(checked as boolean);+ }+ }}+ disabled={editingSync ? editingSync.isHidden : formIsHidden}+ />+ <Label+ htmlFor="hide-from-stats"+ className={`text-sm font-normal ${+ (editingSync ? editingSync.isHidden : formIsHidden)+ ? "cursor-not-allowed opacity-50"+ : "cursor-pointer"+ }`}+ >+ {t("externalSync.hideFromStats")}+ </Label>+ </div>+ <p className="text-xs text-muted-foreground pl-6">+ {t("externalSync.hideFromStatsHint")}+ </p>+ </div>{editingSync ? (<div className="flex gap-2">@@ -850,10 +994,13 @@ export function ExternalSyncManageDialog({setShowAddForm(false);setFormName("");setFormUrl("");- setFormSyncType("icloud");setFormColor("#3b82f6");setFormDisplayMode("normal");setFormAutoSyncInterval(0);+ setIcsFile(null);+ setImportType("url");+ setFormIsHidden(false);+ setFormHideFromStats(false);}}disabled={isLoading}>@@ -861,7 +1008,11 @@ export function ExternalSyncManageDialog({</Button><ButtononClick={handleAddSync}- disabled={isLoading || !formName.trim() || !formUrl.trim()}+ disabled={+ isLoading ||+ !formName.trim() ||+ (importType === "file" ? !icsFile : !formUrl.trim())+ }>{isLoading ? (<Loader2 className="mr-2 h-4 w-4 animate-spin" />@@ -885,47 +1036,89 @@ export function ExternalSyncManageDialog({</Button>)}- {/* Instructions - only show when adding/editing */}- {(showAddForm || editingSync) && (- <div className="rounded-lg border bg-blue-50 dark:bg-blue-950/20 p-4">- <div className="text-sm space-y-2">- <div className="font-medium">- {t(- formSyncType === "google"- ? "externalSync.howToTitleGoogle"- : "externalSync.howToTitleICloud"- )}- </div>- <ol className="list-decimal list-inside space-y-1 text-muted-foreground">- <li>- {t(- formSyncType === "google"- ? "externalSync.howToStep1Google"- : "externalSync.howToStep1ICloud"- )}- </li>- <li>- {t(- formSyncType === "google"- ? "externalSync.howToStep2Google"- : "externalSync.howToStep2ICloud"- )}- </li>- <li>- {t(- formSyncType === "google"- ? "externalSync.howToStep3Google"- : "externalSync.howToStep3ICloud"- )}- </li>- <li>- {t(- formSyncType === "google"- ? "externalSync.howToStep4Google"- : "externalSync.howToStep4ICloud"- )}- </li>- </ol>+ {/* Hints Section - show only when creating */}+ {showAddForm && (+ <div className="rounded-xl border border-border/50 bg-gradient-to-br from-blue-50/50 to-indigo-50/50 dark:from-blue-950/20 dark:to-indigo-950/20 p-4 space-y-2">+ <h4 className="text-sm font-semibold text-foreground/90">+ {t("externalSync.hintsTitle")}+ </h4>+ <p className="text-xs text-muted-foreground">+ {t("externalSync.hintsDescription")}+ </p>++ {/* iCloud Hint */}+ <div className="border border-border/50 rounded-lg overflow-hidden bg-background/50">+ <button+ type="button"+ onClick={() =>+ setExpandedHint(expandedHint === "icloud" ? null : "icloud")+ }+ className="w-full flex items-center justify-between p-3 hover:bg-muted/50 transition-colors"+ >+ <span className="text-sm font-medium">+ {t("externalSync.syncTypeICloud")}+ </span>+ <ChevronDown+ className={`h-4 w-4 transition-transform ${+ expandedHint === "icloud" ? "rotate-180" : ""+ }`}+ />+ </button>+ {expandedHint === "icloud" && (+ <div className="px-3 pb-3 text-sm text-muted-foreground space-y-1">+ <p>{t("externalSync.hintICloud")}</p>+ </div>+ )}+ </div>++ {/* Google Hint */}+ <div className="border border-border/50 rounded-lg overflow-hidden bg-background/50">+ <button+ type="button"+ onClick={() =>+ setExpandedHint(expandedHint === "google" ? null : "google")+ }+ className="w-full flex items-center justify-between p-3 hover:bg-muted/50 transition-colors"+ >+ <span className="text-sm font-medium">+ {t("externalSync.syncTypeGoogle")}+ </span>+ <ChevronDown+ className={`h-4 w-4 transition-transform ${+ expandedHint === "google" ? "rotate-180" : ""+ }`}+ />+ </button>+ {expandedHint === "google" && (+ <div className="px-3 pb-3 text-sm text-muted-foreground space-y-1">+ <p>{t("externalSync.hintGoogle")}</p>+ </div>+ )}+ </div>++ {/* Custom Calendar Hint */}+ <div className="border border-border/50 rounded-lg overflow-hidden bg-background/50">+ <button+ type="button"+ onClick={() =>+ setExpandedHint(expandedHint === "custom" ? null : "custom")+ }+ className="w-full flex items-center justify-between p-3 hover:bg-muted/50 transition-colors"+ >+ <span className="text-sm font-medium">+ {t("externalSync.customCalendar")}+ </span>+ <ChevronDown+ className={`h-4 w-4 transition-transform ${+ expandedHint === "custom" ? "rotate-180" : ""+ }`}+ />+ </button>+ {expandedHint === "custom" && (+ <div className="px-3 pb-3 text-sm text-muted-foreground space-y-1">+ <p>{t("externalSync.hintCustom")}</p>+ </div>+ )}</div></div>)}diff --git a/drizzle/0009_omniscient_magma.sql b/drizzle/0009_omniscient_magma.sqlnew file mode 100644index 0000000..44c3df5--- /dev/null+++ b/drizzle/0009_omniscient_magma.sql@@ -0,0 +1 @@+ALTER TABLE `external_syncs` ADD `is_one_time_import` integer DEFAULT false NOT NULL;\ No newline at end of filediff --git a/drizzle/meta/0009_snapshot.json b/drizzle/meta/0009_snapshot.jsonnew file mode 100644index 0000000..1eadad0--- /dev/null+++ b/drizzle/meta/0009_snapshot.json@@ -0,0 +1,562 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "fd73869c-1ddc-4926-af8e-b1551f13f226",+ "prevId": "bcf5231c-497a-43be-b87a-51cdf54d82c7",+ "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": {}+ },+ "external_syncs": {+ "name": "external_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+ },+ "sync_type": {+ "name": "sync_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'icloud'"+ },+ "calendar_url": {+ "name": "calendar_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+ },+ "is_one_time_import": {+ "name": "is_one_time_import",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "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": {+ "external_syncs_calendar_id_calendars_id_fk": {+ "name": "external_syncs_calendar_id_calendars_id_fk",+ "tableFrom": "external_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+ },+ "external_event_id": {+ "name": "external_event_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "external_sync_id": {+ "name": "external_sync_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "synced_from_external": {+ "name": "synced_from_external",+ "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_external_sync_id_external_syncs_id_fk": {+ "name": "shifts_external_sync_id_external_syncs_id_fk",+ "tableFrom": "shifts",+ "tableTo": "external_syncs",+ "columnsFrom": [+ "external_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 filediff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.jsonindex 35ee4bf..a5c834c 100644--- a/drizzle/meta/_journal.json+++ b/drizzle/meta/_journal.json@@ -64,6 +64,13 @@"when": 1764883523241,"tag": "0008_big_reavers","breakpoints": true+ },+ {+ "idx": 9,+ "version": "6",+ "when": 1765071171359,+ "tag": "0009_omniscient_magma",+ "breakpoints": true}]}\ No newline at end of filediff --git a/lib/db/schema.ts b/lib/db/schema.tsindex 0fadd37..38a23f0 100644--- a/lib/db/schema.ts+++ b/lib/db/schema.ts@@ -25,7 +25,7 @@ export const externalSyncs = sqliteTable("external_syncs", {.notNull().references(() => calendars.id, { onDelete: "cascade" }),name: text("name").notNull(),- syncType: text("sync_type").notNull().default("icloud"), // icloud, google, etc.+ syncType: text("sync_type").notNull().default("icloud"), // icloud, google, customcalendarUrl: text("calendar_url").notNull(),color: text("color").notNull().default("#3b82f6"),displayMode: text("display_mode").notNull().default("normal"),@@ -34,6 +34,9 @@ export const externalSyncs = sqliteTable("external_syncs", {.notNull().default(false),autoSyncInterval: integer("auto_sync_interval").notNull().default(0), // 0 = manual, otherwise minutes+ isOneTimeImport: integer("is_one_time_import", { mode: "boolean" })+ .notNull()+ .default(false), // true for uploaded files (no sync), false for URLs (can sync)lastSyncedAt: integer("last_synced_at", { mode: "timestamp" }),createdAt: integer("created_at", { mode: "timestamp" }).notNull()diff --git a/lib/external-calendar-utils.ts b/lib/external-calendar-utils.tsindex f000e0b..7b0e2b5 100644--- a/lib/external-calendar-utils.ts+++ b/lib/external-calendar-utils.ts@@ -5,12 +5,44 @@import ICAL from "ical.js";-export type CalendarSyncType = "icloud" | "google";+export type CalendarSyncType = "icloud" | "google" | "custom";++/**+ * Detects the calendar sync type based on the URL+ * @param url - The calendar URL+ * @returns The detected sync type (icloud, google, or custom)+ */+export function detectCalendarSyncType(url: string): CalendarSyncType {+ try {+ const parsedUrl = new URL(url);+ const hostname = parsedUrl.hostname.toLowerCase();++ // Check for iCloud domain+ if (hostname.endsWith(".icloud.com") || hostname === "icloud.com") {+ return "icloud";+ }++ // Check for Google domain+ if (+ hostname.endsWith(".google.com") ||+ hostname === "google.com" ||+ hostname === "calendar.google.com"+ ) {+ return "google";+ }++ // Everything else is custom+ return "custom";+ } catch {+ // Invalid URL, default to custom+ return "custom";+ }+}/*** Validates external calendar URL to prevent SSRF vulnerabilities* @param url - The URL to validate- * @param syncType - The type of calendar sync (icloud or google)+ * @param syncType - The type of calendar sync (icloud, google, or custom)* @returns true if valid, false otherwise*/export function isValidCalendarUrl(@@ -42,6 +74,23 @@ export function isValidCalendarUrl() {return false;}+ } else if (syncType === "custom") {+ // For custom calendars, validate against SSRF+ // Block localhost, private IPs, and internal domains+ if (+ hostname === "localhost" ||+ hostname.match(/^127\./) ||+ hostname.match(/^10\./) ||+ hostname.match(/^172\.(1[6-9]|2[0-9]|3[01])\./) ||+ hostname.match(/^192\.168\./) ||+ hostname.match(/^169\.254\./) ||+ hostname === "::1" ||+ hostname === "0.0.0.0"+ ) {+ return false;+ }++ return true;}return true;@@ -51,6 +100,22 @@ export function isValidCalendarUrl(}}+/**+ * Validates ICS file content+ * @param icsContent - The ICS file content as string+ * @returns true if valid ICS format, false otherwise+ */+export function isValidICSContent(icsContent: string): boolean {+ try {+ const jcalData = ICAL.parse(icsContent);+ const comp = new ICAL.Component(jcalData);+ const vevents = comp.getAllSubcomponents("vevent");+ return vevents.length > 0;+ } catch {+ return false;+ }+}+/*** Backwards compatibility - validates iCloud URLs* @deprecated Use isValidCalendarUrl insteaddiff --git a/messages/de.json b/messages/de.jsonindex 58128df..094abc8 100644--- a/messages/de.json+++ b/messages/de.json@@ -172,27 +172,35 @@"support": "Unterstützen"},"externalSync": {- "manageTitle": "Kalender-Synchronisierungen verwalten",- "manageDescription": "Füge mehrere Kalendersynchronisierungen für diesen Kalender hinzu und verwalte sie",- "syncTypeLabel": "Kalender-Typ",+ "manageTitle": "Externe Kalender verwalten",+ "manageDescription": "Füge mehrere externe Kalender für diesen Kalender hinzu und verwalte sie","syncTypeICloud": "iCloud","syncTypeGoogle": "Google",+ "syncTypeCustom": "Eigener Kalender",+ "importMethod": "Import-Methode",+ "importMethodUrl": "URL (kann synchronisiert werden)",+ "importMethodFile": "Datei hochladen (einmaliger Import)",+ "importMethodUrlHint": "Externe Kalender-URL (iCloud, Google oder andere ICS-URLs)",+ "importMethodFileHint": "ICS-Datei einmalig importieren",+ "urlPlaceholder": "https://example.com/calendar.ics oder webcal://...",+ "fileLabel": "ICS-Datei",+ "fileRequired": "Bitte wähle eine ICS-Datei aus",+ "fileTooLarge": "Datei ist zu groß. Maximale Größe beträgt 5 MB.",+ "fileSelected": "Datei ausgewählt",+ "urlRequired": "Bitte gib eine Kalender-URL ein",+ "oneTimeImport": "Einmaliger Import","displayMode": "Synchronisierte Schichten anzeigen","displayModeNormal": "Normal (alle Schichten anzeigen)","displayModeMinimal": "Minimalistisch (nur Anzahl anzeigen)","displayModeHint": "Wähle, wie synchronisierte Schichten im Kalender angezeigt werden sollen",- "viewSyncedShifts": "Synchronisierte Schichten anzeigen",- "syncedShiftsTitle": "Synchronisierte Schichten - {date}",+ "viewSyncedShifts": "Importierte Schichten anzeigen",+ "syncedShiftsTitle": "Importierte Schichten - {date}","addSync": "Hinzufügen",- "addNewSync": "Neue Synchronisierung hinzufügen",- "editSync": "Kalender-Synchronisierung bearbeiten",- "nameLabel": "Synchronisierungsname",+ "addNewSync": "Neuen externen Kalender hinzufügen",+ "editSync": "Externen Kalender bearbeiten",+ "nameLabel": "Name","namePlaceholder": "z.B. Arbeitskalender, Privatkalender","urlLabel": "Kalender URL",- "urlPlaceholderICloud": "webcal://p108-caldav.icloud.com/published/2/...",- "urlPlaceholderGoogle": "https://calendar.google.com/calendar/ical/.../basic.ics",- "urlHintICloud": "Füge die webcal:// URL des iCloud Kalenders ein (beginnt mit webcal://)",- "urlHintGoogle": "Füge die private iCal URL des Google Kalenders ein (endet mit .ics)","urlAlreadyExists": "Diese URL wurde bereits hinzugefügt","invalidUrlFormat": "Ungültiges Kalender URL-Format. URL muss mit webcal:// oder https:// beginnen","colorLabel": "Schichten-Farbe",@@ -203,27 +211,24 @@"hideFromStatsHint": "Schichten dieses Kalenders aus der Statistik ausschließen","lastSynced": "Zuletzt synchronisiert","syncError": "Kalender konnte nicht synchronisiert werden",- "createError": "Synchronisierung konnte nicht erstellt werden",- "createSuccess": "Synchronisierung erfolgreich erstellt",- "updateError": "Synchronisierung konnte nicht aktualisiert werden",- "updateSuccess": "Synchronisierung erfolgreich aktualisiert",- "deleteError": "Synchronisierung konnte nicht gelöscht werden",- "deleteSuccess": "Synchronisierung erfolgreich gelöscht",- "deleteConfirm": "Diese Kalender-Synchronisierung löschen? Alle synchronisierten Schichten werden entfernt.",+ "createError": "Externer Kalender konnte nicht erstellt werden",+ "createSuccess": "Externer Kalender erfolgreich erstellt",+ "updateError": "Externer Kalender konnte nicht aktualisiert werden",+ "updateSuccess": "Externer Kalender erfolgreich aktualisiert",+ "deleteError": "Externer Kalender konnte nicht gelöscht werden",+ "deleteSuccess": "Externer Kalender erfolgreich gelöscht",+ "deleteConfirm": "Diesen externen Kalender löschen? Alle importierten Schichten werden entfernt.","syncSuccess": "Synchronisierung erfolgreich","statsCreated": "erstellt","statsUpdated": "aktualisiert","statsDeleted": "gelöscht",- "howToTitleICloud": "So erhältst du deine iCloud-Kalender URL:",- "howToStep1ICloud": "Öffne iCloud.com und gehe zu Kalender",- "howToStep2ICloud": "Klicke auf das Teilen-Symbol neben deinem Kalender",- "howToStep3ICloud": "Aktiviere 'Öffentlicher Kalender'",- "howToStep4ICloud": "Kopiere die URL und füge sie hier ein",- "howToTitleGoogle": "So erhältst du deine Google Kalender URL:",- "howToStep1Google": "Öffne Google Kalender und gehe zu Einstellungen",- "howToStep2Google": "Wähle deinen Kalender aus",- "howToStep3Google": "Scrolle zu 'Geheime Adresse im iCal-Format'",- "howToStep4Google": "Kopiere die URL und füge sie hier ein",+ "hintsTitle": "Kalender-URL finden",+ "hintsDescription": "Wähle deinen Kalendertyp, um Anweisungen zu erhalten:",+ "customCalendar": "Eigener Kalender",+ "urlHintCustom": "Füge die URL deines ICS-Kalenders ein (webcal:// oder https://)",+ "hintICloud": "Öffne iCloud.com → Kalender → Klicke auf das Teilen-Symbol neben deinem Kalender → Aktiviere 'Öffentlicher Kalender' → Kopiere die webcal:// URL und füge sie hier ein.",+ "hintGoogle": "Öffne Google Kalender → Einstellungen → Wähle deinen Kalender → Scrolle zu 'Geheime Adresse im iCal-Format' → Kopiere die URL und füge sie hier ein.",+ "hintCustom": "Jeder öffentlich zugängliche ICS-Kalender funktioniert. Die URL muss mit https:// oder webcal:// beginnen und auf .ics enden. Beispiel: https://example.com/calendar.ics","autoSyncLabel": "Automatische Synchronisierung","autoSyncHint": "Wähle wie oft dieser Kalender automatisch synchronisiert werden soll","autoSyncManual": "Manuell",diff --git a/messages/en.json b/messages/en.jsonindex 2f1576a..2095654 100644--- a/messages/en.json+++ b/messages/en.json@@ -172,27 +172,35 @@"support": "Support"},"externalSync": {- "manageTitle": "Manage Calendar Syncs",- "manageDescription": "Add and manage multiple calendar syncs for this calendar",- "syncTypeLabel": "Calendar Type",+ "manageTitle": "Manage External Calendars",+ "manageDescription": "Add and manage multiple external calendars for this calendar","syncTypeICloud": "iCloud","syncTypeGoogle": "Google",+ "syncTypeCustom": "Custom Calendar",+ "importMethod": "Import Method",+ "importMethodUrl": "URL (can be synced)",+ "importMethodFile": "Upload File (one-time import)",+ "importMethodUrlHint": "External calendar URL (iCloud, Google, or other ICS URLs)",+ "importMethodFileHint": "Import ICS file once",+ "urlPlaceholder": "https://example.com/calendar.ics or webcal://...",+ "fileLabel": "ICS File",+ "fileRequired": "Please select an ICS file",+ "fileTooLarge": "File is too large. Maximum size is 5MB.",+ "fileSelected": "File selected",+ "urlRequired": "Please enter a calendar URL",+ "oneTimeImport": "One-time import","displayMode": "Display synced shifts","displayModeNormal": "Normal (show all shifts)","displayModeMinimal": "Minimal (show count only)",- "displayModeHint": "Choose how synced shifts are displayed in the calendar",- "viewSyncedShifts": "View synced shifts",- "syncedShiftsTitle": "Synced Shifts - {date}",- "addSync": "Add Sync",- "addNewSync": "Add New Calendar Sync",- "editSync": "Edit Calendar Sync",- "nameLabel": "Sync Name",+ "displayModeHint": "Choose how synced shifts should be displayed in the calendar",+ "viewSyncedShifts": "View Imported Shifts",+ "syncedShiftsTitle": "Imported Shifts - {date}",+ "addSync": "Add",+ "addNewSync": "Add New External Calendar",+ "editSync": "Edit External Calendar",+ "nameLabel": "Name","namePlaceholder": "e.g., Work Calendar, Personal Calendar","urlLabel": "Calendar URL",- "urlPlaceholderICloud": "webcal://p108-caldav.icloud.com/published/2/...",- "urlPlaceholderGoogle": "https://calendar.google.com/calendar/ical/.../basic.ics",- "urlHintICloud": "Paste the webcal:// URL from iCloud (starts with webcal://)",- "urlHintGoogle": "Paste the private iCal URL from Google Calendar (ends with .ics)","urlAlreadyExists": "This URL has already been added","invalidUrlFormat": "Invalid calendar URL format. URL must start with webcal:// or https://","colorLabel": "Shift Color",@@ -203,27 +211,24 @@"hideFromStatsHint": "Exclude shifts from this calendar from statistics","lastSynced": "Last synced","syncError": "Failed to sync calendar",- "createError": "Failed to create sync",- "createSuccess": "Sync created successfully",- "updateError": "Failed to update sync",- "updateSuccess": "Sync updated successfully",- "deleteError": "Failed to delete sync",- "deleteSuccess": "Sync deleted successfully",- "deleteConfirm": "Delete this calendar sync? All synced shifts will be removed.",+ "createError": "Failed to create external calendar",+ "createSuccess": "External calendar created successfully",+ "updateError": "Failed to update external calendar",+ "updateSuccess": "External calendar updated successfully",+ "deleteError": "Failed to delete external calendar",+ "deleteSuccess": "External calendar deleted successfully",+ "deleteConfirm": "Delete this external calendar? All imported shifts will be removed.","syncSuccess": "Sync successful","statsCreated": "created","statsUpdated": "updated","statsDeleted": "deleted",- "howToTitleICloud": "How to get your iCloud calendar URL:",- "howToStep1ICloud": "Open iCloud.com and go to Calendar",- "howToStep2ICloud": "Click the share icon next to your calendar",- "howToStep3ICloud": "Enable 'Public Calendar'",- "howToStep4ICloud": "Copy the URL and paste it here",- "howToTitleGoogle": "How to get your Google Calendar URL:",- "howToStep1Google": "Open Google Calendar and go to Settings",- "howToStep2Google": "Select your calendar",- "howToStep3Google": "Scroll to 'Secret address in iCal format'",- "howToStep4Google": "Copy the URL and paste it here",+ "hintsTitle": "Finding Your Calendar URL",+ "hintsDescription": "Select your calendar type to see instructions:",+ "customCalendar": "Custom Calendar",+ "urlHintCustom": "Paste the URL of your ICS calendar (webcal:// or https://)",+ "hintICloud": "Open iCloud.com → Calendar → Click the share icon next to your calendar → Enable 'Public Calendar' → Copy the webcal:// URL and paste it here.",+ "hintGoogle": "Open Google Calendar → Settings → Select your calendar → Scroll to 'Secret address in iCal format' → Copy the URL and paste it here.",+ "hintCustom": "Any publicly accessible ICS calendar will work. The URL must start with https:// or webcal:// and end with .ics. Example: https://example.com/calendar.ics","autoSyncLabel": "Auto Sync","autoSyncHint": "Choose how often this calendar should automatically sync","autoSyncManual": "Manual",