You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@community.apache.org by hu...@apache.org on 2026/09/09 19:30:22 UTC

(comdev-calendar) branch main updated: Add ics import features

This is an automated email from the ASF dual-hosted git repository.

Humbedooh pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/comdev-calendar.git


The following commit(s) were added to refs/heads/main by this push:
     new c998f5a  Add ics import features
c998f5a is described below

commit c998f5adba51da0cf76465ac8ba543ff9c7ef8b0
Author: Daniel Gruno <hu...@apache.org>
AuthorDate: Wed Sep 9 21:30:11 2026 +0200

    Add ics import features
---
 README.md                                          |  97 ++++-
 backend/asfcalendar/api.py                         |  96 ++++-
 backend/asfcalendar/icsimport.py                   | 287 +++++++++++++
 backend/asfcalendar/openapi.py                     | 145 +++++++
 backend/asfcalendar/storage.py                     |  46 ++-
 backend/tests/test_icsimport.py                    | 278 +++++++++++++
 backend/tests/test_import_api.py                   | 266 ++++++++++++
 .../{index-Dbhcf4N0.css => index-CXgtmuq1.css}     |   2 +-
 frontend/dist/assets/index-CZgOqov1.js             |  61 ---
 frontend/dist/assets/index-CZgOqov1.js.map         |   1 -
 frontend/dist/assets/index-DwsHFb2B.js             |  68 +++
 frontend/dist/assets/index-DwsHFb2B.js.map         |   1 +
 frontend/dist/index.html                           |   4 +-
 frontend/src/App.svelte                            |  29 ++
 frontend/src/components/Header.svelte              |   5 +
 frontend/src/components/HelpPage.svelte            |  27 ++
 frontend/src/components/ImportDialog.svelte        | 455 +++++++++++++++++++++
 frontend/src/lib/api.ts                            |  25 +-
 frontend/src/lib/importing.test.ts                 | 235 +++++++++++
 frontend/src/lib/importing.ts                      | 175 ++++++++
 frontend/src/tests/components.test.ts              |   1 +
 frontend/src/tests/importdialog.test.ts            | 300 ++++++++++++++
 pyproject.toml                                     |   1 +
 uv.lock                                            |  28 ++
 24 files changed, 2557 insertions(+), 76 deletions(-)

diff --git a/README.md b/README.md
index 57f9e73..04ebd54 100644
--- a/README.md
+++ b/README.md
@@ -45,6 +45,7 @@ access rules are built on. The frontend is Svelte 5 built with Vite.
 - [Serving from a sub-directory](#serving-from-a-sub-directory)
 - [Embedding the agenda elsewhere](#embedding-the-agenda-elsewhere)
 - [Timezones](#timezones)
+- [Importing an iCalendar file](#importing-an-icalendar-file)
 - [The API](#the-api)
 - [API documentation](#api-documentation)
 - [Project layout](#project-layout)
@@ -566,6 +567,84 @@ whichever clock is on display. Offsets for named zones come from
 `Intl.DateTimeFormat`, so daylight saving is handled by the browser's own tz
 data rather than by us.
 
+## Importing an iCalendar file
+
+A logged-in user can upload an `.ics` file and have every event in it added to
+one calendar. **Import** appears next to **New event** once you are signed in.
+
+The form works in two steps, on purpose. Choosing a file shows a preview of what
+was found, and only then does it ask which calendar the events belong to. That
+second question is not defaulted: an import can create dozens of events at once,
+and a wrong default would publish somebody's private meetings or file them under
+the wrong project. The Import button stays disabled, with a line saying what is
+still to answer, until the calendar, the visibility and (for a project import)
+the project have all been chosen.
+
+Which options are offered follows the same rules as anywhere else: a committer
+is shown their projects but not the private option, a committee member gets
+both, and the foundation calendar only appears for foundation members.
+
+### What the importer does with a file
+
+Files come from Google Calendar, Outlook, Thunderbird and hand-rolled scripts,
+so the reading is forgiving. Rather than refusing a whole upload over one
+awkward entry, it repairs what it can and says what it changed - every note
+appears in the preview before anything is saved:
+
+| In the file                              | What happens                                            |
+| ---------------------------------------- | -------------------------------------------------------- |
+| `DTSTART;TZID=Europe/Berlin`             | kept as the event's organiser timezone                    |
+| `DTSTART;VALUE=DATE`                     | an all-day event, whole UTC days                          |
+| `DURATION` instead of `DTEND`            | used to work out the end                                  |
+| no end at all                            | an hour, or a day for an all-day event                    |
+| a floating time with no zone             | read as UTC, with a note                                  |
+| a title longer than the limit            | trimmed, with a note                                      |
+| a `mailto:` or other non-http `URL`      | dropped, with a note                                      |
+| `RRULE`                                  | imported as a single occurrence, with a note              |
+| `STATUS:CANCELLED`, or no `DTSTART`      | skipped, and counted in the file's warnings               |
+| `VTODO`, `VJOURNAL`                      | ignored; only `VEVENT` is an event                        |
+
+An event that survives all that still goes through exactly the same validation
+as one typed in by hand, so nothing gets in through the importer that could not
+have been created normally. The whole import is one transaction: every event is
+validated and the permission checked before any of them is written, so a file
+either lands completely or not at all.
+
+At most 200 events and 1 MiB per file.
+
+### From a script
+
+Two endpoints, both needing a session. `POST /api/import/preview` reads a file
+and says what is in it without writing anything; `POST /api/import` does the
+import. Either takes the file as the `file` part of a multipart form, or as the
+whole request body:
+
+```shell
+# What is in this file?
+curl -s -X POST --data-binary @events.ics \
+  -H 'Content-Type: text/calendar' -H 'X-No-Redirect: 1' \
+  -b cookies.txt https://calendar.apache.org/api/import/preview | jq
+
+# Import it as public httpd events
+curl -s -X POST -b cookies.txt -H 'X-No-Redirect: 1' \
+  -F file=@events.ics -F category=project -F project=httpd -F visibility=public \
+  https://calendar.apache.org/api/import
+```
+
+When the file is the request body there is nowhere to put the form fields, so
+they go on the query string instead:
+
+```shell
+curl -s -X POST --data-binary @events.ics \
+  -H 'Content-Type: text/calendar' -H 'X-No-Redirect: 1' -b cookies.txt \
+  'https://calendar.apache.org/api/import?category=project&project=httpd'
+```
+
+`category` is required. `visibility` defaults to `public`, the same as
+`POST /api/events` - the API keeps the single-event default, and it is the form
+that insists on an explicit answer. The response carries the created events and
+any warnings.
+
 ## The API
 
 Everything under `/api` speaks JSON, errors included. Anonymous reads are
@@ -583,6 +662,8 @@ allowed; anything that writes needs a session.
 | GET               | `/api/events/<id>.ics`   | one event as iCalendar                              |
 | GET               | `/api/events.ics`        | a filtered iCalendar feed                           |
 | GET               | `/api/shortlink/<token>` | look an event up by its shortlink token             |
+| POST              | `/api/import/preview`    | read an `.ics` file without saving anything         |
+| POST              | `/api/import`            | turn an `.ics` file into events                     |
 | GET               | `/api/healthz`           | liveness check                                      |
 
 Outside `/api`, the backend serves the built frontend: `/` for the calendar,
@@ -742,6 +823,7 @@ backend/
     storage.py       SQLite, including the visibility SQL
     models.py        the Event type and payload validation
     ics.py           iCalendar output
+    icsimport.py     reading an uploaded iCalendar file
     openapi.py       the OpenAPI description, built from the real constants
     shortlink.py     shortlink tokens
     config.py        reading config.yaml
@@ -751,13 +833,14 @@ frontend/
   src/
     App.svelte       state, loading and routing
     components/      Header, TimezoneSwitch, FilterPanel, the five views,
-                     EventDialog, HelpPage, EmbedAgenda, ApiDocs
+                     EventDialog, ImportDialog, HelpPage, EmbedAgenda, ApiDocs
     lib/
       api.ts         the API client
       base.ts        the deployment's mount point, for sub-directory installs
       dates.ts       date arithmetic and grid maths
       timezone.ts    wall-clock conversions, zone naming, the zone picker
       embed.ts       options for the embeddable agenda
+      importing.ts   where uploaded events should land
       events.ts      grouping, overlap layout, colours
       filters.ts     client-side filtering and sorting
       drafts.ts      new and edited events, and a local canEdit
@@ -923,6 +1006,15 @@ session = ClientSession({"uid": "bob", "pmcs": ["httpd"], "projects": ["httpd"]}
 can_view(some_event, session)
 ```
 
+**An import says "No events could be read from that file".** Either it is not
+iCalendar, or every entry in it was skipped. Run it through
+`POST /api/import/preview`, whose `warnings` say which: entries with no
+`DTSTART`, and ones marked `STATUS:CANCELLED`, are counted there.
+
+**An imported event is an hour out.** Look at its `DTSTART` in the file. A time
+with no `Z` and no `TZID` is "floating" and is read as UTC, which the preview
+warns about; the fix is in whatever produced the file.
+
 **The API documentation page is blank, or says Swagger UI could not be loaded.**
 The vendored files are missing from the build. Run `npm run build` in
 `frontend/`, which copies them in first, and check
@@ -1010,7 +1102,8 @@ again.
 
 Worth being clear about, so nobody goes looking:
 
-- No recurring events. Every event is a single occurrence.
+- No recurring events. Every event is a single occurrence, and a repeating
+  event in an imported file arrives as one.
 - No invitations, attendance or reminders. It is a calendar, not a scheduler.
 - No per-event access lists. Access follows the category and visibility, and
   nothing else.
diff --git a/backend/asfcalendar/api.py b/backend/asfcalendar/api.py
index 0812dd1..72df70e 100644
--- a/backend/asfcalendar/api.py
+++ b/backend/asfcalendar/api.py
@@ -16,9 +16,16 @@ import asfquart.session
 import quart
 import yaml
 
-from . import ics, openapi
+from . import ics, icsimport, openapi
 from .config import Config
-from .models import Event, ValidationError, parse_event_payload, parse_timestamp
+from .models import (
+    CATEGORIES,
+    VISIBILITIES,
+    Event,
+    ValidationError,
+    parse_event_payload,
+    parse_timestamp,
+)
 from .permissions import (
     PermissionDenied,
     SessionLike,
@@ -122,6 +129,10 @@ def create_blueprint(cfg: Config, store: Storage) -> quart.Blueprint:
         status = 401 if error.message == asfquart.auth.Requirements.E_NOT_LOGGED_IN else error.errorcode
         return _error(error.message, status)
 
+    @api.errorhandler(413)
+    async def _on_too_large(_exception: Any) -> quart.Response:
+        return _error(f"That upload is larger than the {icsimport.MAX_IMPORT_BYTES // 1024} KiB limit.", 413)
+
     @api.errorhandler(404)
     async def _on_404(_exception: Any) -> quart.Response:
         return _error("Not found", 404)
@@ -254,6 +265,87 @@ def create_blueprint(cfg: Config, store: Storage) -> quart.Blueprint:
         check_view(event, session)
         return _json({"event": dump(event)})
 
+    # ---- importing an iCalendar file ---------------------------------------
+
+    async def _uploaded_calendar() -> bytes | str:
+        """The .ics file, however it was sent.
+
+        A browser posts it as a multipart form; a script is more likely to pipe
+        the file straight into the body, so both are accepted.
+        """
+        content_type = quart.request.content_type or ""
+        if content_type.startswith("multipart/"):
+            files = await quart.request.files
+            upload = files.get("file")
+            if upload is None:
+                raise ValidationError("Attach the calendar as the 'file' part of the form.", "file")
+            return cast("bytes | str", upload.read())
+        body = await quart.request.get_data()
+        if not body:
+            raise ValidationError("The request body was empty; send an iCalendar file.", "file")
+        return body
+
+    async def _import_settings() -> tuple[str, str, str | None]:
+        """Which calendar the imported events should land in.
+
+        Taken from the form when there is one, and from the query string
+        otherwise, so a script piping a file in can still say where it goes.
+        """
+        form: Any = {}
+        if (quart.request.content_type or "").startswith("multipart/"):
+            form = await quart.request.form
+
+        def value(name: str) -> str | None:
+            return form.get(name) or quart.request.args.get(name)
+
+        category = (value("category") or "").strip()
+        if category not in CATEGORIES:
+            raise ValidationError(f"'category' is required and must be one of: {', '.join(CATEGORIES)}", "category")
+        # Personal events are forced private later; for the others this matches
+        # the default POST /api/events applies.
+        visibility = (value("visibility") or "public").strip()
+        if visibility not in VISIBILITIES:
+            raise ValidationError(f"'visibility' must be one of: {', '.join(VISIBILITIES)}", "visibility")
+        project = (value("project") or "").strip() or None
+        return category, visibility, project
+
+    @api.route("/import/preview", methods=["POST"])
+    @require_session
+    async def import_preview() -> quart.Response:
+        """Reads a file and says what it holds, without writing anything."""
+        result = icsimport.parse(await _uploaded_calendar())
+        return _json(result.to_json())
+
+    @api.route("/import", methods=["POST"])
+    @require_session
+    async def import_events() -> quart.Response:
+        session = await current_session()
+        data = await _uploaded_calendar()
+        category, visibility, project = await _import_settings()
+        result = icsimport.parse(data)
+
+        # Every candidate goes through the same validation as a hand-typed
+        # event, and all of them are checked before any of them is written.
+        payloads = [
+            parse_event_payload(candidate.to_payload(category, visibility, project))  # type: ignore[arg-type]
+            for candidate in result.candidates
+        ]
+        # They all land in the same calendar, so one permission check covers
+        # the batch.
+        check_write(payloads[0], session)
+
+        owner = uid_of(session)
+        assert owner is not None  # @require_session guarantees a session
+        created = await store.create_many(payloads, owner)
+        return _json(
+            {
+                "created": dump_all(created, session),
+                "count": len(created),
+                "warnings": result.warnings,
+            },
+            201,
+        )
+
     # ---- writing events ---------------------------------------------------
     #
     # The bare @require decorator only insists on a valid session; who may
diff --git a/backend/asfcalendar/icsimport.py b/backend/asfcalendar/icsimport.py
new file mode 100644
index 0000000..b2d9bd6
--- /dev/null
+++ b/backend/asfcalendar/icsimport.py
@@ -0,0 +1,287 @@
+"""Reading events out of an uploaded iCalendar file.
+
+The counterpart to ``ics.py``, which writes them. Files arrive from Google
+Calendar, Outlook, Thunderbird and hand-rolled scripts, so the parsing itself is
+left to the ``icalendar`` package; what is here is the translation from what a
+calendar file can say into what this application stores.
+
+The translation is deliberately forgiving. An import that refuses a whole file
+because one event has a 300-character title is no use to anybody, so fields are
+trimmed to fit and the reader is told what was changed. Anything that cannot be
+salvaged at all - an event with no start time - is skipped with a warning rather
+than failing the upload.
+
+A candidate is not an event yet. It has no calendar, no owner and no
+visibility; the caller supplies those and puts the result through
+``models.parse_event_payload``, exactly as it would for an event typed in by
+hand.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import datetime
+import zoneinfo
+from typing import Any
+
+import icalendar
+
+from .models import (
+    DAY_SECONDS,
+    DEFAULT_TIMEZONE,
+    MAX_DESCRIPTION_LENGTH,
+    MAX_LOCATION_LENGTH,
+    MAX_TITLE_LENGTH,
+    MAX_URL_LENGTH,
+    Category,
+    ValidationError,
+    Visibility,
+    to_iso,
+)
+
+# An .ics file this big is either a mistake or an attack; the biggest real
+# calendar exports are a few hundred kilobytes.
+MAX_IMPORT_BYTES = 1024 * 1024
+MAX_IMPORT_EVENTS = 200
+
+UNTITLED = "Untitled event"
+
+
+@dataclasses.dataclass(frozen=True, slots=True)
+class ImportCandidate:
+    """One event read out of a file, before it is given a calendar."""
+
+    title: str
+    start: int
+    end: int
+    all_day: bool
+    description: str
+    location: str
+    url: str
+    timezone: str
+    uid: str | None
+    warnings: tuple[str, ...]
+
+    def to_json(self) -> dict[str, Any]:
+        """What the preview endpoint shows."""
+        return {
+            "title": self.title,
+            "start": to_iso(self.start),
+            "end": to_iso(self.end),
+            "all_day": self.all_day,
+            "description": self.description,
+            "location": self.location,
+            "url": self.url,
+            "timezone": self.timezone,
+            "uid": self.uid,
+            "warnings": list(self.warnings),
+        }
+
+    def to_payload(
+        self,
+        category: Category,
+        visibility: Visibility,
+        project: str | None,
+    ) -> dict[str, Any]:
+        """The body ``parse_event_payload`` would have received had somebody
+        typed this event in, so an import goes through the same validation as
+        anything else."""
+        return {
+            "title": self.title,
+            "category": category,
+            "visibility": visibility,
+            "project": project,
+            # Absolute instants, so the timezone below is only recorded, never
+            # used to interpret these.
+            "start": to_iso(self.start),
+            "end": to_iso(self.end),
+            "all_day": self.all_day,
+            "description": self.description,
+            "location": self.location,
+            "url": self.url,
+            "timezone": self.timezone,
+        }
+
+
+@dataclasses.dataclass(frozen=True)
+class ImportResult:
+    candidates: list[ImportCandidate]
+    """Problems with the file as a whole, or with entries that were skipped."""
+    warnings: list[str]
+
+    def to_json(self) -> dict[str, Any]:
+        return {
+            "events": [candidate.to_json() for candidate in self.candidates],
+            "count": len(self.candidates),
+            "warnings": list(self.warnings),
+        }
+
+
+def decode(data: bytes | str) -> str:
+    """Turns an uploaded file into text.
+
+    iCalendar is specified as UTF-8, but exports with Latin-1 accents in them
+    are common enough to be worth surviving.
+    """
+    if isinstance(data, str):
+        return data.lstrip("\ufeff")
+    if len(data) > MAX_IMPORT_BYTES:
+        raise ValidationError(f"That file is larger than the {MAX_IMPORT_BYTES // 1024} KiB import limit.", "file")
+    for encoding in ("utf-8-sig", "utf-8", "latin-1"):
+        try:
+            return data.decode(encoding)
+        except UnicodeDecodeError:
+            continue
+    raise ValidationError("That file is not text this importer can read.", "file")
+
+
+def _text(component: icalendar.Component, name: str, limit: int, warnings: list[str]) -> str:
+    raw = component.get(name)
+    if raw is None:
+        return ""
+    value = str(raw).strip()
+    if len(value) > limit:
+        warnings.append(f"{name.capitalize()} was longer than {limit} characters and has been cut short.")
+        return value[:limit].rstrip()
+    return value
+
+
+def _zone_of(value: datetime.datetime, warnings: list[str]) -> str:
+    """The IANA name for a parsed timestamp's timezone.
+
+    A file may carry a VTIMEZONE that does not correspond to any zone the
+    system knows. The instant is still correct - icalendar has worked out the
+    offset - so the event imports fine; only the label falls back to UTC.
+    """
+    tzinfo = value.tzinfo
+    if tzinfo is None:
+        warnings.append("This event had no timezone, so its times have been read as UTC.")
+        return DEFAULT_TIMEZONE
+    if isinstance(tzinfo, zoneinfo.ZoneInfo):
+        return tzinfo.key
+    name = str(getattr(tzinfo, "key", "") or tzinfo)
+    try:
+        zoneinfo.ZoneInfo(name)
+    except (zoneinfo.ZoneInfoNotFoundError, ValueError, KeyError):
+        if name not in {DEFAULT_TIMEZONE, "UTC+00:00"}:
+            warnings.append(f"Timezone {name!r} is not one this server knows; recorded as UTC.")
+        return DEFAULT_TIMEZONE
+    return name
+
+
+def _epoch(value: datetime.date | datetime.datetime) -> int:
+    """Epoch seconds for a date or datetime.
+
+    A bare date is a calendar day rather than an instant, so it is anchored to
+    UTC midnight, matching how this application stores all-day events.
+    """
+    if isinstance(value, datetime.datetime):
+        moment = value if value.tzinfo else value.replace(tzinfo=datetime.UTC)
+        return int(moment.timestamp())
+    return int(datetime.datetime(value.year, value.month, value.day, tzinfo=datetime.UTC).timestamp())
+
+
+def _candidate(component: icalendar.Component) -> ImportCandidate | None:
+    """Reads one VEVENT, or returns None if there is nothing usable in it."""
+    warnings: list[str] = []
+
+    start_property = component.get("DTSTART")
+    if start_property is None:
+        return None
+
+    start_value = start_property.dt
+    all_day = not isinstance(start_value, datetime.datetime)
+    start = _epoch(start_value)
+
+    timezone = (
+        DEFAULT_TIMEZONE if all_day else _zone_of(start_value, warnings)  # type: ignore[arg-type]
+    )
+
+    end_property = component.get("DTEND")
+    duration = component.get("DURATION")
+    if end_property is not None:
+        end = _epoch(end_property.dt)
+    elif duration is not None and isinstance(duration.dt, datetime.timedelta):
+        end = start + int(duration.dt.total_seconds())
+    else:
+        # RFC 5545: a date-only event with no end lasts one day, and a timed
+        # one is instantaneous. An instant is no use in a grid, so give it an
+        # hour, the same as an event created without an end.
+        end = start + (DAY_SECONDS if all_day else 3600)
+
+    if end <= start:
+        warnings.append("This event ended before it started; it has been given a one-hour slot.")
+        end = start + (DAY_SECONDS if all_day else 3600)
+
+    title = _text(component, "SUMMARY", MAX_TITLE_LENGTH, warnings)
+    if not title:
+        title = UNTITLED
+        warnings.append("This event had no title.")
+
+    url = _text(component, "URL", MAX_URL_LENGTH, warnings)
+    if url and not url.startswith(("http://", "https://")):
+        warnings.append(f"Dropped a link that is not http or https: {url[:60]}")
+        url = ""
+
+    if component.get("RRULE") is not None:
+        warnings.append(
+            "This event repeats. The calendar does not support recurrence, so only the first "
+            "occurrence has been imported."
+        )
+
+    uid = component.get("UID")
+
+    return ImportCandidate(
+        title=title,
+        start=start,
+        end=end,
+        all_day=all_day,
+        description=_text(component, "DESCRIPTION", MAX_DESCRIPTION_LENGTH, warnings),
+        location=_text(component, "LOCATION", MAX_LOCATION_LENGTH, warnings),
+        url=url,
+        timezone=timezone,
+        uid=str(uid) if uid else None,
+        warnings=tuple(warnings),
+    )
+
+
+def parse(data: bytes | str, *, max_events: int = MAX_IMPORT_EVENTS) -> ImportResult:
+    """Reads every usable event out of an iCalendar document."""
+    text = decode(data)
+    if "BEGIN:VCALENDAR" not in text.upper():
+        raise ValidationError("That does not look like an iCalendar (.ics) file.", "file")
+
+    try:
+        calendar = icalendar.Calendar.from_ical(text)
+    except Exception as exc:  # icalendar raises a variety of parse errors
+        raise ValidationError(f"That iCalendar file could not be read: {exc}", "file") from exc
+
+    warnings: list[str] = []
+    candidates: list[ImportCandidate] = []
+    skipped = 0
+
+    for component in calendar.walk("VEVENT"):
+        status = component.get("STATUS")
+        if status is not None and str(status).upper() == "CANCELLED":
+            skipped += 1
+            continue
+        candidate = _candidate(component)
+        if candidate is None:
+            skipped += 1
+            continue
+        candidates.append(candidate)
+        if len(candidates) > max_events:
+            raise ValidationError(
+                f"That file holds more than {max_events} events. Split it up and import in batches.",
+                "file",
+            )
+
+    if skipped:
+        warnings.append(
+            f"Skipped {skipped} entr{'y' if skipped == 1 else 'ies'} with no start time, or marked cancelled."
+        )
+
+    if not candidates:
+        raise ValidationError("No events could be read from that file.", "file")
+
+    return ImportResult(candidates=candidates, warnings=warnings)
diff --git a/backend/asfcalendar/openapi.py b/backend/asfcalendar/openapi.py
index 4878fda..6e837a0 100644
--- a/backend/asfcalendar/openapi.py
+++ b/backend/asfcalendar/openapi.py
@@ -21,6 +21,7 @@ from typing import Any
 
 from . import __version__, shortlink
 from .config import Config
+from .icsimport import MAX_IMPORT_BYTES, MAX_IMPORT_EVENTS
 from .models import (
     CATEGORIES,
     DEFAULT_TIMEZONE,
@@ -94,6 +95,34 @@ def _calendar_response(description: str) -> dict[str, Any]:
     }
 
 
+def _calendar_upload(with_settings: bool = False) -> dict[str, Any]:
+    """The request body of an import: a multipart form, or the file itself."""
+    form: dict[str, Any] = {"file": {"type": "string", "format": "binary"}}
+    if with_settings:
+        form |= {
+            "category": {"type": "string", "enum": list(CATEGORIES)},
+            "project": {"type": "string", "pattern": PROJECT_RE.pattern},
+            "visibility": {"type": "string", "enum": list(VISIBILITIES), "default": "public"},
+        }
+    return {
+        "required": True,
+        "description": (
+            "An iCalendar document, either as the `file` part of a multipart form or as the "
+            f"whole request body. At most {MAX_IMPORT_BYTES // 1024} KiB."
+        ),
+        "content": {
+            "multipart/form-data": {
+                "schema": {
+                    "type": "object",
+                    "required": ["file"] + (["category"] if with_settings else []),
+                    "properties": form,
+                }
+            },
+            "text/calendar": {"schema": {"type": "string"}},
+        },
+    }
+
+
 def _schemas() -> dict[str, Any]:
     """The component schemas, with every limit taken from the real constant."""
     timestamp = {
@@ -211,6 +240,55 @@ def _schemas() -> dict[str, Any]:
                 "count": {"type": "integer", "description": "Number of events in this response."},
             },
         },
+        "ImportCandidate": {
+            "type": "object",
+            "description": "An event read out of a file, before it is given a calendar.",
+            "required": ["title", "start", "end", "all_day", "warnings"],
+            "properties": {
+                "title": {"type": "string"},
+                "start": {"type": "string", "description": "ISO 8601 UTC."},
+                "end": {"type": "string", "description": "ISO 8601 UTC, exclusive for all-day."},
+                "all_day": {"type": "boolean"},
+                "description": {"type": "string"},
+                "location": {"type": "string"},
+                "url": {"type": "string"},
+                "timezone": {"type": "string"},
+                "uid": {
+                    "type": ["string", "null"],
+                    "description": "The UID from the file. Not stored; shown so a reader can recognise the entry.",
+                },
+                "warnings": {
+                    "type": "array",
+                    "items": {"type": "string"},
+                    "description": "What had to be changed to make this event importable.",
+                },
+            },
+        },
+        "ImportPreview": {
+            "type": "object",
+            "required": ["events", "count", "warnings"],
+            "properties": {
+                "events": {
+                    "type": "array",
+                    "items": {"$ref": "#/components/schemas/ImportCandidate"},
+                },
+                "count": {"type": "integer"},
+                "warnings": {
+                    "type": "array",
+                    "items": {"type": "string"},
+                    "description": "Problems with the file as a whole, such as entries that were skipped.",
+                },
+            },
+        },
+        "ImportResult": {
+            "type": "object",
+            "required": ["created", "count", "warnings"],
+            "properties": {
+                "created": {"type": "array", "items": {"$ref": "#/components/schemas/Event"}},
+                "count": {"type": "integer"},
+                "warnings": {"type": "array", "items": {"type": "string"}},
+            },
+        },
         "Error": {
             "type": "object",
             "required": ["error"],
@@ -554,6 +632,72 @@ def _paths() -> dict[str, Any]:
                 },
             }
         },
+        "/api/import/preview": {
+            "post": {
+                "tags": ["Import"],
+                "summary": "Read an iCalendar file without saving anything",
+                "description": (
+                    "Says what the file holds, so a caller can show it before committing to it. "
+                    "Nothing is written and no calendar is chosen yet."
+                ),
+                "requestBody": _calendar_upload(),
+                "responses": {
+                    "200": {
+                        "description": "What was found in the file.",
+                        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ImportPreview"}}},
+                    },
+                    "400": invalid,
+                    "401": unauthenticated,
+                    "413": _error_response(f"The upload was larger than the {MAX_IMPORT_BYTES // 1024} KiB limit."),
+                },
+            }
+        },
+        "/api/import": {
+            "post": {
+                "tags": ["Import"],
+                "summary": "Import an iCalendar file as events",
+                "description": (
+                    "Every event in the file lands in the same calendar, given by `category`, "
+                    "`project` and `visibility`. Send them as form fields alongside the file, or "
+                    "as query parameters when posting the file as the request body.\n\n"
+                    "The import is all or nothing: every event is validated and the permission "
+                    "checked before any of them is written, and the batch is one transaction.\n\n"
+                    f"At most {MAX_IMPORT_EVENTS} events per file. Recurring events are imported as "
+                    "a single occurrence, and entries with no start time, or marked cancelled, are "
+                    "skipped; both are reported in `warnings`."
+                ),
+                "parameters": [
+                    {
+                        "name": "category",
+                        "in": "query",
+                        "description": "Required, unless sent as a form field.",
+                        "schema": {"type": "string", "enum": list(CATEGORIES)},
+                    },
+                    {
+                        "name": "project",
+                        "in": "query",
+                        "description": "Required for project events.",
+                        "schema": {"type": "string", "pattern": PROJECT_RE.pattern},
+                    },
+                    {
+                        "name": "visibility",
+                        "in": "query",
+                        "schema": {"type": "string", "enum": list(VISIBILITIES), "default": "public"},
+                    },
+                ],
+                "requestBody": _calendar_upload(with_settings=True),
+                "responses": {
+                    "201": {
+                        "description": "The events as stored.",
+                        "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ImportResult"}}},
+                    },
+                    "400": invalid,
+                    "401": unauthenticated,
+                    "403": forbidden,
+                    "413": _error_response(f"The upload was larger than the {MAX_IMPORT_BYTES // 1024} KiB limit."),
+                },
+            }
+        },
         "/api/openapi.json": {
             "get": {
                 "tags": ["Service"],
@@ -601,6 +745,7 @@ def build(cfg: Config, origin: str = "") -> dict[str, Any]:
         "servers": [{"url": server_url, "description": "This deployment"}],
         "tags": [
             {"name": "Events", "description": "Reading and changing calendar events."},
+            {"name": "Import", "description": "Turning an iCalendar file into events."},
             {"name": "Session", "description": "Who you are and what you may do."},
             {"name": "Service", "description": "Health and documentation."},
         ],
diff --git a/backend/asfcalendar/storage.py b/backend/asfcalendar/storage.py
index 1efbdd4..bcbaa98 100644
--- a/backend/asfcalendar/storage.py
+++ b/backend/asfcalendar/storage.py
@@ -160,7 +160,17 @@ class Storage:
         if not owner:
             raise ValueError("An event needs an owner")
         stamp = int(now if now is not None else time.time())
-        # Retry on the astronomically unlikely shortlink collision.
+        event_id = await self._insert(data, owner, stamp)
+        await self.db.commit()
+        created = await self.get(event_id)
+        assert created is not None
+        return created
+
+    async def _insert(self, data: EventInput, owner: str, stamp: int) -> int:
+        """Writes one row and returns its id, without committing.
+
+        Retries on the astronomically unlikely shortlink collision.
+        """
         for _attempt in range(8):
             token = shortlink.generate()
             try:
@@ -191,12 +201,38 @@ class Storage:
                 )
             except aiosqlite.IntegrityError:
                 continue
-            await self.db.commit()
-            created = await self.get(int(cursor.lastrowid or 0))
-            assert created is not None
-            return created
+            return int(cursor.lastrowid or 0)
         raise RuntimeError("Could not allocate a unique shortlink")
 
+    async def create_many(self, data: Sequence[EventInput], owner: str, *, now: int | None = None) -> list[Event]:
+        """Inserts several events in one transaction.
+
+        An import either lands completely or not at all: if any row fails, the
+        whole batch is rolled back rather than leaving somebody to work out
+        which half of their calendar arrived.
+        """
+        if not owner:
+            raise ValueError("An event needs an owner")
+        if not data:
+            return []
+
+        stamp = int(now if now is not None else time.time())
+        created_ids: list[int] = []
+        try:
+            for entry in data:
+                created_ids.append(await self._insert(entry, owner, stamp))
+        except Exception:
+            await self.db.rollback()
+            raise
+        await self.db.commit()
+
+        created: list[Event] = []
+        for event_id in created_ids:
+            event = await self.get(event_id)
+            assert event is not None
+            created.append(event)
+        return created
+
     async def get(self, event_id: int) -> Event | None:
         async with self.db.execute("SELECT * FROM events WHERE id = ?", (event_id,)) as cursor:
             row = await cursor.fetchone()
diff --git a/backend/tests/test_icsimport.py b/backend/tests/test_icsimport.py
new file mode 100644
index 0000000..65d4d17
--- /dev/null
+++ b/backend/tests/test_icsimport.py
@@ -0,0 +1,278 @@
+"""Reading events out of an uploaded iCalendar file."""
+
+from __future__ import annotations
+
+import pytest
+
+from asfcalendar.icsimport import (
+    MAX_IMPORT_BYTES,
+    UNTITLED,
+    ImportCandidate,
+    decode,
+    parse,
+)
+from asfcalendar.models import (
+    MAX_DESCRIPTION_LENGTH,
+    MAX_TITLE_LENGTH,
+    ValidationError,
+    parse_event_payload,
+    to_iso,
+)
+
+
+def calendar(*events: str) -> str:
+    body = "\r\n".join(events)
+    return f"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Test//EN\r\n{body}\r\nEND:VCALENDAR\r\n"
+
+
+def event(**properties: str) -> str:
+    lines = ["BEGIN:VEVENT"]
+    lines.extend(f"{name.replace('_', '-')}:{value}" for name, value in properties.items())
+    lines.append("END:VEVENT")
+    return "\r\n".join(lines)
+
+
+TIMED = event(UID="1@test", SUMMARY="Community call", DTSTART="20260710T090000Z", DTEND="20260710T100000Z")
+
+
+def only(document: str) -> ImportCandidate:
+    result = parse(document)
+    assert len(result.candidates) == 1
+    return result.candidates[0]
+
+
+class TestDecoding:
+    def test_plain_utf8(self) -> None:
+        assert decode(b"BEGIN:VCALENDAR") == "BEGIN:VCALENDAR"
+
+    def test_a_byte_order_mark_is_stripped(self) -> None:
+        assert decode("BEGIN".encode("utf-8-sig")) == "BEGIN"
+        assert decode("\ufeffBEGIN") == "BEGIN"
+
+    def test_latin1_survives(self) -> None:
+        # Not spec-compliant, but exporters do it.
+        assert "\u00c5sa" in decode("SUMMARY:\u00c5sa".encode("latin-1"))
+
+    def test_an_oversized_upload_is_refused(self) -> None:
+        with pytest.raises(ValidationError, match="import limit"):
+            decode(b"x" * (MAX_IMPORT_BYTES + 1))
+
+
+class TestRejectingRubbish:
+    def test_something_that_is_not_a_calendar(self) -> None:
+        with pytest.raises(ValidationError, match="iCalendar"):
+            parse("hello, I am a text file")
+
+    def test_a_calendar_with_no_events(self) -> None:
+        with pytest.raises(ValidationError, match="No events"):
+            parse(calendar())
+
+    def test_a_calendar_of_nothing_but_unusable_entries(self) -> None:
+        with pytest.raises(ValidationError, match="No events"):
+            parse(calendar(event(UID="1@t", SUMMARY="No start time at all")))
+
+    def test_more_events_than_the_limit(self) -> None:
+        many = calendar(
+            *[event(UID=f"{index}@t", SUMMARY=f"Event {index}", DTSTART="20260710T090000Z") for index in range(6)]
+        )
+        with pytest.raises(ValidationError, match="more than 5 events"):
+            parse(many, max_events=5)
+
+    def test_the_limit_itself_is_allowed(self) -> None:
+        many = calendar(
+            *[event(UID=f"{index}@t", SUMMARY=f"Event {index}", DTSTART="20260710T090000Z") for index in range(5)]
+        )
+        assert len(parse(many, max_events=5).candidates) == 5
+
+
+class TestTimes:
+    def test_a_zulu_timestamp(self) -> None:
+        candidate = only(calendar(TIMED))
+        assert to_iso(candidate.start) == "2026-07-10T09:00:00Z"
+        assert to_iso(candidate.end) == "2026-07-10T10:00:00Z"
+        assert candidate.all_day is False
+        assert candidate.timezone == "UTC"
+
+    def test_a_zone_is_kept_as_the_organisers_timezone(self) -> None:
+        document = calendar(
+            "BEGIN:VEVENT\r\nUID:1@t\r\nSUMMARY:Berlin\r\n"
+            "DTSTART;TZID=Europe/Berlin:20260710T150000\r\n"
+            "DTEND;TZID=Europe/Berlin:20260710T160000\r\nEND:VEVENT"
+        )
+        candidate = only(document)
+        assert candidate.timezone == "Europe/Berlin"
+        # 15:00 in Berlin in July is 13:00 UTC.
+        assert to_iso(candidate.start) == "2026-07-10T13:00:00Z"
+
+    def test_an_all_day_event(self) -> None:
+        document = calendar(
+            "BEGIN:VEVENT\r\nUID:1@t\r\nSUMMARY:ApacheCon\r\n"
+            "DTSTART;VALUE=DATE:20260710\r\nDTEND;VALUE=DATE:20260713\r\nEND:VEVENT"
+        )
+        candidate = only(document)
+        assert candidate.all_day is True
+        assert to_iso(candidate.start) == "2026-07-10T00:00:00Z"
+        assert to_iso(candidate.end) == "2026-07-13T00:00:00Z"
+        assert candidate.timezone == "UTC"
+
+    def test_a_duration_instead_of_an_end(self) -> None:
+        document = calendar(event(UID="1@t", SUMMARY="Sync", DTSTART="20260710T090000Z", DURATION="PT90M"))
+        assert only(document).end - only(document).start == 5400
+
+    def test_no_end_at_all_gets_an_hour(self) -> None:
+        document = calendar(event(UID="1@t", SUMMARY="Sync", DTSTART="20260710T090000Z"))
+        assert only(document).end - only(document).start == 3600
+
+    def test_an_all_day_event_with_no_end_gets_a_day(self) -> None:
+        document = calendar("BEGIN:VEVENT\r\nUID:1@t\r\nSUMMARY:x\r\nDTSTART;VALUE=DATE:20260710\r\nEND:VEVENT")
+        assert only(document).end - only(document).start == 86400
+
+    def test_a_floating_time_is_read_as_utc_and_says_so(self) -> None:
+        document = calendar(event(UID="1@t", SUMMARY="Floating", DTSTART="20260710T090000"))
+        candidate = only(document)
+        assert to_iso(candidate.start) == "2026-07-10T09:00:00Z"
+        assert any("no timezone" in warning for warning in candidate.warnings)
+
+    def test_an_end_before_the_start_is_repaired(self) -> None:
+        document = calendar(event(UID="1@t", SUMMARY="Backwards", DTSTART="20260710T100000Z", DTEND="20260710T090000Z"))
+        candidate = only(document)
+        assert candidate.end > candidate.start
+        assert any("ended before it started" in warning for warning in candidate.warnings)
+
+
+class TestFields:
+    def test_the_ordinary_ones(self) -> None:
+        document = calendar(
+            event(
+                UID="1@t",
+                SUMMARY="Community call",
+                DTSTART="20260710T090000Z",
+                LOCATION="Room 3",
+                DESCRIPTION="Agenda attached",
+                URL="https://apache.org",
+            )
+        )
+        candidate = only(document)
+        assert candidate.title == "Community call"
+        assert candidate.location == "Room 3"
+        assert candidate.description == "Agenda attached"
+        assert candidate.url == "https://apache.org"
+        assert candidate.uid == "1@t"
+
+    def test_escaped_text_is_unescaped(self) -> None:
+        document = calendar(
+            "BEGIN:VEVENT\r\nUID:1@t\r\nSUMMARY:Tea\\, biscuits\r\n"
+            "DESCRIPTION:Line one\\nLine two\r\nDTSTART:20260710T090000Z\r\nEND:VEVENT"
+        )
+        candidate = only(document)
+        assert candidate.title == "Tea, biscuits"
+        assert candidate.description == "Line one\nLine two"
+
+    def test_folded_lines_are_joined(self) -> None:
+        document = calendar(
+            "BEGIN:VEVENT\r\nUID:1@t\r\nSUMMARY:A title that was too long for one\r\n"
+            "  line in the file\r\nDTSTART:20260710T090000Z\r\nEND:VEVENT"
+        )
+        assert only(document).title == "A title that was too long for one line in the file"
+
+    def test_a_missing_title_gets_a_placeholder(self) -> None:
+        document = calendar(event(UID="1@t", DTSTART="20260710T090000Z"))
+        candidate = only(document)
+        assert candidate.title == UNTITLED
+        assert any("no title" in warning for warning in candidate.warnings)
+
+    def test_an_overlong_title_is_trimmed_rather_than_rejected(self) -> None:
+        document = calendar(event(UID="1@t", SUMMARY="x" * 500, DTSTART="20260710T090000Z"))
+        candidate = only(document)
+        assert len(candidate.title) <= MAX_TITLE_LENGTH
+        assert any("cut short" in warning for warning in candidate.warnings)
+
+    def test_an_overlong_description_is_trimmed_too(self) -> None:
+        document = calendar(event(UID="1@t", SUMMARY="x", DTSTART="20260710T090000Z", DESCRIPTION="y" * 30000))
+        assert len(only(document).description) <= MAX_DESCRIPTION_LENGTH
+
+    def test_a_link_that_is_not_http_is_dropped(self) -> None:
+        document = calendar(event(UID="1@t", SUMMARY="x", DTSTART="20260710T090000Z", URL="mailto:nobody@apache.org"))
+        candidate = only(document)
+        assert candidate.url == ""
+        assert any("not http" in warning for warning in candidate.warnings)
+
+
+class TestThingsThisCalendarCannotDo:
+    def test_a_repeating_event_comes_in_once_and_says_so(self) -> None:
+        document = calendar(event(UID="1@t", SUMMARY="Weekly", DTSTART="20260710T090000Z", RRULE="FREQ=WEEKLY;COUNT=5"))
+        result = parse(document)
+        assert len(result.candidates) == 1
+        assert any("repeats" in warning for warning in result.candidates[0].warnings)
+
+    def test_cancelled_events_are_left_out(self) -> None:
+        document = calendar(
+            TIMED,
+            event(UID="2@t", SUMMARY="Called off", DTSTART="20260710T090000Z", STATUS="CANCELLED"),
+        )
+        result = parse(document)
+        assert [candidate.title for candidate in result.candidates] == ["Community call"]
+        assert any("Skipped 1 entry" in warning for warning in result.warnings)
+
+    def test_entries_with_no_start_are_left_out(self) -> None:
+        result = parse(calendar(TIMED, event(UID="2@t", SUMMARY="No start")))
+        assert len(result.candidates) == 1
+        assert any("Skipped 1 entry" in warning for warning in result.warnings)
+
+    def test_several_skipped_entries_are_counted_together(self) -> None:
+        result = parse(calendar(TIMED, event(UID="2@t", SUMMARY="a"), event(UID="3@t", SUMMARY="b")))
+        assert any("Skipped 2 entries" in warning for warning in result.warnings)
+
+    def test_a_todo_or_journal_is_not_an_event(self) -> None:
+        document = (
+            "BEGIN:VCALENDAR\r\nVERSION:2.0\r\n"
+            "BEGIN:VTODO\r\nUID:1@t\r\nSUMMARY:Not an event\r\nEND:VTODO\r\n" + TIMED + "\r\nEND:VCALENDAR\r\n"
+        )
+        assert [candidate.title for candidate in parse(document).candidates] == ["Community call"]
+
+
+class TestHandingOverToTheNormalValidation:
+    """A candidate is only useful if the ordinary event validation accepts it."""
+
+    def test_a_candidate_becomes_a_valid_payload(self) -> None:
+        candidate = only(calendar(TIMED))
+        payload = parse_event_payload(candidate.to_payload("project", "public", "httpd"))
+        assert payload.title == "Community call"
+        assert payload.category == "project"
+        assert payload.project == "httpd"
+        assert payload.visibility == "public"
+
+    def test_every_candidate_from_an_awkward_file_still_validates(self) -> None:
+        document = calendar(
+            TIMED,
+            event(UID="2@t", SUMMARY="x" * 500, DTSTART="20260710T090000Z"),
+            event(UID="3@t", DTSTART="20260710T090000Z", URL="mailto:x@y"),
+            "BEGIN:VEVENT\r\nUID:4@t\r\nSUMMARY:All day\r\nDTSTART;VALUE=DATE:20260710\r\nEND:VEVENT",
+            event(UID="5@t", SUMMARY="Backwards", DTSTART="20260710T100000Z", DTEND="20260710T090000Z"),
+        )
+        for candidate in parse(document).candidates:
+            parse_event_payload(candidate.to_payload("foundation", "private", None))
+
+    def test_the_timezone_survives_into_the_payload(self) -> None:
+        document = calendar(
+            "BEGIN:VEVENT\r\nUID:1@t\r\nSUMMARY:Berlin\r\nDTSTART;TZID=Europe/Berlin:20260710T150000\r\nEND:VEVENT"
+        )
+        payload = parse_event_payload(only(document).to_payload("foundation", "public", None))
+        assert payload.timezone == "Europe/Berlin"
+        # The instant is unchanged by the round trip.
+        assert to_iso(payload.start) == "2026-07-10T13:00:00Z"
+
+    def test_the_preview_shape_is_what_the_ui_expects(self) -> None:
+        as_json = only(calendar(TIMED)).to_json()
+        assert set(as_json) == {
+            "title",
+            "start",
+            "end",
+            "all_day",
+            "description",
+            "location",
+            "url",
+            "timezone",
+            "uid",
+            "warnings",
+        }
diff --git a/backend/tests/test_import_api.py b/backend/tests/test_import_api.py
new file mode 100644
index 0000000..2dabc55
--- /dev/null
+++ b/backend/tests/test_import_api.py
@@ -0,0 +1,266 @@
+"""The import endpoints, over HTTP."""
+
+from __future__ import annotations
+
+import io
+from typing import Any
+
+import pytest
+from werkzeug.datastructures import FileStorage
+
+CALENDAR = (
+    "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Test//EN\r\n"
+    "BEGIN:VEVENT\r\nUID:1@t\r\nSUMMARY:Community call\r\n"
+    "DTSTART;TZID=Europe/Berlin:20260710T150000\r\nDTEND;TZID=Europe/Berlin:20260710T160000\r\n"
+    "LOCATION:Room 3\r\nEND:VEVENT\r\n"
+    "BEGIN:VEVENT\r\nUID:2@t\r\nSUMMARY:ApacheCon\r\n"
+    "DTSTART;VALUE=DATE:20260901\r\nDTEND;VALUE=DATE:20260904\r\nEND:VEVENT\r\n"
+    "END:VCALENDAR\r\n"
+)
+
+
+def upload(content: str = CALENDAR, **fields: str) -> dict[str, Any]:
+    """A multipart form the way a browser would send it.
+
+    Spread into the call: ``await client.post(path, **upload(category="..."))``.
+    """
+    storage = FileStorage(
+        stream=io.BytesIO(content.encode()),
+        filename="calendar.ics",
+        content_type="text/calendar",
+    )
+    return {"files": {"file": storage}, "form": dict(fields)}
+
+
+async def json_of(response: Any) -> Any:
+    return await response.get_json()
+
+
+class TestPreview:
+    async def test_it_needs_a_session(self, client: Any) -> None:
+        response = await client.post("/api/import/preview", **upload())
+        assert response.status_code == 401
+
+    async def test_it_reads_the_file(self, client: Any, login: Any) -> None:
+        await login("alice")
+        response = await client.post("/api/import/preview", **upload())
+        assert response.status_code == 200
+        body = await json_of(response)
+        assert body["count"] == 2
+        assert [event["title"] for event in body["events"]] == ["Community call", "ApacheCon"]
+
+    async def test_it_shows_the_times_it_worked_out(self, client: Any, login: Any) -> None:
+        await login("alice")
+        body = await json_of(await client.post("/api/import/preview", **upload()))
+        first = body["events"][0]
+        assert first["start"] == "2026-07-10T13:00:00Z"
+        assert first["timezone"] == "Europe/Berlin"
+        assert first["location"] == "Room 3"
+        assert body["events"][1]["all_day"] is True
+
+    async def test_it_writes_nothing(self, client: Any, login: Any) -> None:
+        await login("alice")
+        await client.post("/api/import/preview", **upload())
+        assert (await json_of(await client.get("/api/events")))["count"] == 0
+
+    async def test_it_does_not_ask_which_calendar(self, client: Any, login: Any) -> None:
+        # Choosing a calendar is the second step; a preview should work before
+        # the reader has decided.
+        await login("alice")
+        assert (await client.post("/api/import/preview", **upload())).status_code == 200
+
+    async def test_it_reports_what_it_had_to_change(self, client: Any, login: Any) -> None:
+        await login("alice")
+        document = (
+            "BEGIN:VCALENDAR\r\nVERSION:2.0\r\n"
+            "BEGIN:VEVENT\r\nUID:1@t\r\nSUMMARY:Weekly\r\nDTSTART:20260710T090000Z\r\n"
+            "RRULE:FREQ=WEEKLY;COUNT=5\r\nEND:VEVENT\r\n"
+            "BEGIN:VEVENT\r\nUID:2@t\r\nSUMMARY:No start\r\nEND:VEVENT\r\n"
+            "END:VCALENDAR\r\n"
+        )
+        body = await json_of(await client.post("/api/import/preview", **upload(document)))
+        assert body["count"] == 1
+        assert any("repeats" in warning for warning in body["events"][0]["warnings"])
+        assert any("Skipped 1 entry" in warning for warning in body["warnings"])
+
+    async def test_a_file_that_is_not_a_calendar(self, client: Any, login: Any) -> None:
+        await login("alice")
+        response = await client.post("/api/import/preview", **upload("just some text"))
+        assert response.status_code == 400
+        assert (await json_of(response))["field"] == "file"
+
+    async def test_a_missing_file_part(self, client: Any, login: Any) -> None:
+        await login("alice")
+        response = await client.post("/api/import/preview", form={"category": "foundation"})
+        assert response.status_code == 400
+        assert "file" in (await json_of(response))["error"]
+
+    async def test_the_raw_body_works_too(self, client: Any, login: Any) -> None:
+        await login("alice")
+        response = await client.post("/api/import/preview", data=CALENDAR, headers={"Content-Type": "text/calendar"})
+        assert response.status_code == 200
+        assert (await json_of(response))["count"] == 2
+
+    async def test_an_empty_body(self, client: Any, login: Any) -> None:
+        await login("alice")
+        response = await client.post("/api/import/preview", data="", headers={"Content-Type": "text/calendar"})
+        assert response.status_code == 400
+
+
+class TestImporting:
+    async def test_it_needs_a_session(self, client: Any) -> None:
+        response = await client.post("/api/import", **upload(category="foundation"))
+        assert response.status_code == 401
+
+    async def test_it_creates_every_event_in_the_file(self, client: Any, login: Any) -> None:
+        await login("alice")
+        response = await client.post("/api/import", **upload(category="project", project="httpd", visibility="public"))
+        assert response.status_code == 201
+        body = await json_of(response)
+        assert body["count"] == 2
+        assert {event["title"] for event in body["created"]} == {"Community call", "ApacheCon"}
+        assert all(event["project"] == "httpd" for event in body["created"])
+        assert all(event["owner"] == "alice" for event in body["created"])
+
+        listed = await json_of(await client.get("/api/events"))
+        assert listed["count"] == 2
+
+    async def test_the_imported_events_keep_their_own_timezone(self, client: Any, login: Any) -> None:
+        await login("alice")
+        body = await json_of(await client.post("/api/import", **upload(category="project", project="httpd")))
+        first = next(e for e in body["created"] if e["title"] == "Community call")
+        assert first["timezone"] == "Europe/Berlin"
+        assert first["start"] == "2026-07-10T13:00:00Z"
+
+    async def test_each_event_gets_its_own_shortlink(self, client: Any, login: Any) -> None:
+        await login("alice")
+        body = await json_of(await client.post("/api/import", **upload(category="project", project="httpd")))
+        tokens = {event["shortlink"] for event in body["created"]}
+        assert len(tokens) == 2
+
+    async def test_warnings_come_back_with_the_result(self, client: Any, login: Any) -> None:
+        await login("alice")
+        document = (
+            "BEGIN:VCALENDAR\r\nVERSION:2.0\r\n"
+            "BEGIN:VEVENT\r\nUID:1@t\r\nSUMMARY:x\r\nDTSTART:20260710T090000Z\r\nEND:VEVENT\r\n"
+            "BEGIN:VEVENT\r\nUID:2@t\r\nSUMMARY:No start\r\nEND:VEVENT\r\n"
+            "END:VCALENDAR\r\n"
+        )
+        body = await json_of(await client.post("/api/import", **upload(document, category="project", project="httpd")))
+        assert body["count"] == 1
+        assert any("Skipped" in warning for warning in body["warnings"])
+
+
+class TestWhereTheEventsLand:
+    async def test_a_category_is_required(self, client: Any, login: Any) -> None:
+        await login("alice")
+        response = await client.post("/api/import", **upload())
+        assert response.status_code == 400
+        assert (await json_of(response))["field"] == "category"
+
+    async def test_an_unknown_category(self, client: Any, login: Any) -> None:
+        await login("alice")
+        response = await client.post("/api/import", **upload(category="nonsense"))
+        assert response.status_code == 400
+
+    async def test_an_unknown_visibility(self, client: Any, login: Any) -> None:
+        await login("alice")
+        response = await client.post("/api/import", **upload(category="project", project="httpd", visibility="maybe"))
+        assert response.status_code == 400
+        assert (await json_of(response))["field"] == "visibility"
+
+    async def test_a_project_event_needs_a_project(self, client: Any, login: Any) -> None:
+        await login("alice")
+        response = await client.post("/api/import", **upload(category="project"))
+        assert response.status_code == 400
+        assert (await json_of(response))["field"] == "project"
+
+    async def test_settings_can_come_from_the_query_string(self, client: Any, login: Any) -> None:
+        # Which is how a script piping the file into the body has to send them.
+        await login("alice")
+        response = await client.post(
+            "/api/import?category=project&project=httpd",
+            data=CALENDAR,
+            headers={"Content-Type": "text/calendar"},
+        )
+        assert response.status_code == 201
+        assert (await json_of(response))["count"] == 2
+
+    async def test_visibility_defaults_the_same_way_a_single_event_does(self, client: Any, login: Any) -> None:
+        await login("alice")
+        body = await json_of(await client.post("/api/import", **upload(category="project", project="httpd")))
+        assert all(event["visibility"] == "public" for event in body["created"])
+
+    async def test_personal_events_are_forced_private(self, client: Any, login: Any) -> None:
+        await login("dave")
+        body = await json_of(await client.post("/api/import", **upload(category="personal", visibility="public")))
+        assert all(event["visibility"] == "private" for event in body["created"])
+
+
+class TestPermissions:
+    async def test_you_cannot_import_into_a_project_you_are_not_in(self, client: Any, login: Any) -> None:
+        await login("dave")
+        response = await client.post("/api/import", **upload(category="project", project="httpd"))
+        assert response.status_code == 403
+        assert "httpd" in (await json_of(response))["error"]
+
+    async def test_a_committer_cannot_import_private_project_events(self, client: Any, login: Any) -> None:
+        await login("alice")
+        response = await client.post("/api/import", **upload(category="project", project="httpd", visibility="private"))
+        assert response.status_code == 403
+        assert "committee" in (await json_of(response))["error"]
+
+    async def test_a_committee_member_can(self, client: Any, login: Any) -> None:
+        await login("bob")
+        response = await client.post("/api/import", **upload(category="project", project="httpd", visibility="private"))
+        assert response.status_code == 201
+
+    async def test_only_members_can_import_foundation_events(self, client: Any, login: Any) -> None:
+        await login("alice")
+        assert (await client.post("/api/import", **upload(category="foundation"))).status_code == 403
+        await login("carol")
+        assert (await client.post("/api/import", **upload(category="foundation"))).status_code == 201
+
+    async def test_a_refused_import_writes_nothing(self, client: Any, login: Any) -> None:
+        await login("dave")
+        await client.post("/api/import", **upload(category="project", project="httpd"))
+        await login("bob")
+        assert (await json_of(await client.get("/api/events")))["count"] == 0
+
+
+class TestItIsAllOrNothing:
+    async def test_a_file_with_one_bad_entry_imports_nothing(self, client: Any, login: Any) -> None:
+        # The parser repairs what it can, so reaching the validation step with a
+        # bad entry takes something it cannot fix: an event lasting over a year.
+        await login("alice")
+        document = (
+            "BEGIN:VCALENDAR\r\nVERSION:2.0\r\n"
+            "BEGIN:VEVENT\r\nUID:1@t\r\nSUMMARY:Fine\r\nDTSTART:20260710T090000Z\r\nEND:VEVENT\r\n"
+            "BEGIN:VEVENT\r\nUID:2@t\r\nSUMMARY:Endless\r\n"
+            "DTSTART:20260710T090000Z\r\nDTEND:20300710T090000Z\r\nEND:VEVENT\r\n"
+            "END:VCALENDAR\r\n"
+        )
+        response = await client.post("/api/import", **upload(document, category="project", project="httpd"))
+        assert response.status_code == 400
+        assert (await json_of(await client.get("/api/events")))["count"] == 0
+
+
+class TestSize:
+    async def test_an_oversized_upload_is_refused(self, client: Any, login: Any) -> None:
+        await login("alice")
+        giant = "BEGIN:VCALENDAR\r\n" + ("X-PADDING:" + "y" * 200 + "\r\n") * 8000 + "END:VCALENDAR\r\n"
+        response = await client.post("/api/import/preview", data=giant, headers={"Content-Type": "text/calendar"})
+        assert response.status_code in {400, 413}
+        body = await json_of(response)
+        assert "limit" in body["error"].lower()
+
+
+@pytest.mark.parametrize("path", ["/api/import", "/api/import/preview"])
+class TestBothEndpoints:
+    async def test_they_answer_in_json(self, client: Any, path: str) -> None:
+        response = await client.post(path, **upload(category="foundation"))
+        assert response.headers["Content-Type"].startswith("application/json")
+
+    async def test_they_do_not_redirect_an_anonymous_caller(self, client: Any, path: str) -> None:
+        response = await client.post(path, **upload(category="foundation"))
+        assert response.status_code == 401
diff --git a/frontend/dist/assets/index-Dbhcf4N0.css b/frontend/dist/assets/index-CXgtmuq1.css
similarity index 72%
rename from frontend/dist/assets/index-Dbhcf4N0.css
rename to frontend/dist/assets/index-CXgtmuq1.css
index d23679d..342b1d9 100644
--- a/frontend/dist/assets/index-Dbhcf4N0.css
+++ b/frontend/dist/assets/index-CXgtmuq1.css
@@ -1 +1 @@
-.zones.svelte-p7ai4p{display:flex;align-items:stretch;border:1px solid var(--border-strong);border-radius:var(--radius);overflow:hidden}.zone.svelte-p7ai4p{display:flex;flex-direction:column;justify-content:center;gap:0;background:var(--bg-panel);border:0;border-right:1px solid var(--border);padding:.15rem .6rem;font-size:12px;line-height:1.25;text-align:left;white-space:nowrap}.zone.svelte-p7ai4p:last-child{border-right:0}.zone.svelte-p7ai4p:hover{background:var(--bg-hover)}.zone.active [...]
+.zones.svelte-p7ai4p{display:flex;align-items:stretch;border:1px solid var(--border-strong);border-radius:var(--radius);overflow:hidden}.zone.svelte-p7ai4p{display:flex;flex-direction:column;justify-content:center;gap:0;background:var(--bg-panel);border:0;border-right:1px solid var(--border);padding:.15rem .6rem;font-size:12px;line-height:1.25;text-align:left;white-space:nowrap}.zone.svelte-p7ai4p:last-child{border-right:0}.zone.svelte-p7ai4p:hover{background:var(--bg-hover)}.zone.active [...]
diff --git a/frontend/dist/assets/index-CZgOqov1.js b/frontend/dist/assets/index-CZgOqov1.js
deleted file mode 100644
index 125a474..0000000
--- a/frontend/dist/assets/index-CZgOqov1.js
+++ /dev/null
@@ -1,61 +0,0 @@
-(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const l of s)if(l.type==="childList")for(const i of l.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(s){const l={};return s.integrity&&(l.integrity=s.integrity),s.referrerPolicy&&(l.referrerPolicy=s.referr [...]
-\r\f \v\uFEFF`];function Ei(e,t,n){var r=e==null?"":""+e;if(t&&(r=r?r+" "+t:t),n){for(var s of Object.keys(n))if(n[s])r=r?r+" "+s:s;else if(r.length)for(var l=s.length,i=0;(i=r.indexOf(s,i))>=0;){var c=i+l;(i===0||ga.includes(r[i-1]))&&(c===r.length||ga.includes(r[c]))?r=(i===0?"":r.substring(0,i))+r.substring(c+1):i=c}}return r===""?null:r}function Ti(e,t){return e==null?null:String(e)}function ze(e,t,n,r,s,l){var i=e[Dr];if(i!==n||i===void 0){var c=Ei(n,r,l);c==null?e.removeAttribute(" [...]
-      the page.</p> <!> <!> <p class="muted small svelte-x10slk">Comparison clocks appear beside the week and day grids, on agenda rows, and in an event's
-      details.</p></section> <section class="subscribe svelte-x10slk"><h3 class="svelte-x10slk">Subscribe</h3> <p class="muted svelte-x10slk">Add the events you can see to your own calendar application with this iCalendar feed.</p> <a class="btn">Download .ics</a></section></aside>`);function Oo(e,t){Xe(t,!0);let n=Fe(t,"maxCompareZones",3,3);function r(L){t.onchange({...t.filters,categories:Da(t.filters.categories,L)})}function s(L){t.onchange({...t.filters,projects:Da(t.filters.project [...]
-                     top: ${a(q).top*100}%;
-                     height: ${a(q).height*100}%;
-                     left: calc(${a(q).column/a(q).columns*100}% + 2px);
-                     width: calc(${1/a(q).columns*100}% - 4px);`),he(J,"title",a(q).event.title),O(ee,ie),O(Y,a(q).event.title)},[()=>kn(a(q).event),()=>Ie(Je(a(q).event,r()))]),Q("click",J,()=>t.onselect(a(q).event)),w(D,J)}),I((D,q)=>B=ze(F,1,"daycol svelte-5umrtz",null,B,{weekend:D,today:q}),[()=>Qn(a(b)),()=>qn(a(b),a(i))]),w(z,F)}),I(()=>{m=ze(h,1,"week svelte-5umrtz",null,m,{single:a(c).length===1}),Ct(h,`--cols: ${a(c).length??""}; --gutters: ${a(v).length??""}`)}),w(e,h),Qe()}it( [...]
-              their own clock.</small></label>`),ja=k('<input type="date" required=""/>'),Pa=k('<input type="datetime-local" required=""/>'),wc=k('<button type="button" class="btn danger">Delete</button>'),bc=k('<form><h2 class="svelte-qx7ml8"> </h2> <label class="row svelte-qx7ml8"><span class="svelte-qx7ml8">Title</span> <input required="" maxlength="200" placeholder="What is happening?"/></label> <div class="pair svelte-qx7ml8"><label class="row svelte-qx7ml8"><span class="svelte-qx7m [...]
-          are done, particularly on a shared machine.</p>`),Nc=k(`<p class="svelte-rmw6w0"><a>Log in</a> with your Apache account. You
-          will be sent to the foundation's OAuth service and back again. Nothing is stored here
-          beyond your username and the projects and committees you belong to.</p>`),Rc=k(`<div class="help svelte-rmw6w0"><div class="sheet svelte-rmw6w0"><header class="svelte-rmw6w0"><h2 class="svelte-rmw6w0">Using the ASF Community Calendar</h2> <button type="button" class="btn">Back to the calendar</button></header> <p class="status svelte-rmw6w0"> </p> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">The three calendars</h3> <p class="svelte-rmw6w0">Every event belongs to on [...]
-        who can change it.</p> <dl class="svelte-rmw6w0"><dt class="svelte-rmw6w0"><span class="swatch personal svelte-rmw6w0"></span> Personal</dt> <dd class="svelte-rmw6w0">Your own events. Nobody else can see them, and they are never public. Use them for the
-          things you want on the same grid as everything else without telling anyone about them.</dd> <dt class="svelte-rmw6w0"><span class="swatch project svelte-rmw6w0"></span> Project</dt> <dd class="svelte-rmw6w0">Events belonging to a project: release votes, community calls, meetups. Public ones are
-          visible to everyone, including people who are not signed in. Private ones are visible only
-          to the project's committee (its PMC).</dd> <dt class="svelte-rmw6w0"><span class="swatch foundation svelte-rmw6w0"></span> Foundation</dt> <dd class="svelte-rmw6w0">Events for the ASF as a whole: board meetings, ApacheCon, report deadlines. Public ones are
-          visible to everyone; private ones only to foundation members.</dd></dl></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Who can do what</h3> <p class="svelte-rmw6w0">The lists of projects and committees you belong to come from your Apache account, through the
-        same login the rest of the foundation's tools use. There is nothing to configure here: sign
-        in and the calendar knows.</p> <div class="tablewrap svelte-rmw6w0"><table class="svelte-rmw6w0"><thead class="svelte-rmw6w0"><tr><th scope="col" class="svelte-rmw6w0">&nbsp;</th><!></tr></thead><tbody class="svelte-rmw6w0"></tbody></table></div> <p class="muted small svelte-rmw6w0">"Own projects" means the projects you commit to; "own committees" means the PMCs you sit on.
-        Being on a committee also counts as being a member of that project. Any project member can
-        edit any of their project's events, not only the ones they added themselves.</p></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Getting around</h3> <ul class="svelte-rmw6w0"><li class="svelte-rmw6w0"><strong>Day, week, month, year and agenda</strong> are the five views. Pick one at the top.</li> <li class="svelte-rmw6w0">The <strong>&#8249;</strong> and <strong>&#8250;</strong> buttons move one view-sized step:
-          a day in the day view, a month in the month view, and so on. <strong>Today</strong> jumps
-          back to now.</li> <li class="svelte-rmw6w0">Clicking a date number in the month or year view opens that day. Clicking a month name in
-          the year view opens that month.</li> <li class="svelte-rmw6w0">A day with more events than fit shows <strong>+n more</strong>; click it to open the day.</li> <li class="svelte-rmw6w0">Clicking any event opens it, with its full details, shortlink and download link.</li></ul></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Filters and search</h3> <p class="svelte-rmw6w0">The panel on the left narrows what is drawn. It does not change what you have access to; it
-        only hides things you would rather not look at right now.</p> <ul class="svelte-rmw6w0"><li class="svelte-rmw6w0"><strong>Calendars</strong> switches the three categories on and off. When you sign in, all
-          three start switched on, along with every project you belong to.</li> <li class="svelte-rmw6w0"><strong>Projects</strong> lists your projects plus any others that appear in the events
-          currently loaded. Projects you are not a member of stay visible unless you narrow the list
-          yourself.</li> <li class="svelte-rmw6w0"><strong>Visibility</strong> lets you look at only the public or only the private events.</li> <li class="svelte-rmw6w0"><strong>Search</strong> matches the title, description, location and project name of the
-          events in view.</li> <li class="svelte-rmw6w0"><strong>Sort</strong> appears in the agenda view, where the order is yours to choose.</li></ul></section> <section id="timezones" class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Timezones</h3> <p class="svelte-rmw6w0">An event happens at one moment in time, but that moment has a different clock reading
-        depending on where you are. The calendar keeps those two things apart.</p> <ul class="svelte-rmw6w0"><li class="svelte-rmw6w0">The switch at the top of the page chooses the clock the calendar is <em>drawn</em> in. <strong>Local</strong> follows your browser, which right now says <strong> </strong> <strong> </strong>. Flipping it moves everything together: the
-          grid, the times on each event, and which day an event falls on.</li> <li class="svelte-rmw6w0"><strong>You can watch more than one clock at once.</strong> Under "Timezones" in the panel
-          on the left, add up to three comparison timezones. They appear as extra hour columns beside
-          the week and day grids, after the time on each agenda row, and in an event's details - so
-          you can see an event in the organiser's own time and in yours without doing the arithmetic. <!> The grid itself can only be drawn on one clock, so the extra ones are labels rather than
-          extra columns of events.</li> <li class="svelte-rmw6w0">When you add an event you also choose the timezone the times are <em>in</em>. If you are
-          organising a call at 15:00 Berlin time, pick Europe/Berlin and type 15:00, and everybody
-          else will see it at their own 15:00-equivalent. Changing the timezone in the form keeps the
-          clock reading and moves the moment, which is almost always what you meant.</li> <li class="svelte-rmw6w0">Zone names such as <code>Europe/Copenhagen</code> are how the timezone database identifies
-          a clock, not a guess about where you are sitting. The calendar shows the city and the
-          current offset together so it is obvious why a particular clock was chosen.</li> <li class="svelte-rmw6w0"><strong>All-day events are dates, not moments.</strong> An all-day event on 14 March is on
-          14 March for everyone, and does not shift when you change the switch.</li></ul></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Adding and changing events</h3> <p class="svelte-rmw6w0"><strong>New event</strong> appears at the top once you are signed in and have somewhere to
-        put an event. The form only offers the calendars you can actually write to, so if you cannot
-        see a "Foundation" option it is because you are not a foundation member.</p> <ul class="svelte-rmw6w0"><li class="svelte-rmw6w0">A title and a start time are the only things required. An event with no end lasts an hour.</li> <li class="svelte-rmw6w0"><strong>All day</strong> turns the time fields into date fields. A one-day event is a
-          single date; a conference is a range.</li> <li class="svelte-rmw6w0"><strong>Visibility</strong> is public or private. Private means the project committee for
-          project events, and foundation members for foundation events. Personal events are always
-          private, so there is no choice to make.</li> <li class="svelte-rmw6w0">To edit or delete, open the event and use <strong>Edit</strong>. It only appears if you are
-          allowed. You cannot move an event into a calendar you cannot write to, or out of one.</li></ul></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Shortlinks and subscribing</h3> <ul class="svelte-rmw6w0"><li class="svelte-rmw6w0">Every event has a short URL, shown in its details, that opens the event directly. It is
-          safe to paste anywhere: someone who cannot see the event gets told so rather than shown it.
-          Public events show their title in link previews; private ones deliberately do not.</li> <li class="svelte-rmw6w0"><strong>Download .ics</strong> in an event's details saves that one event for your own
-          calendar application.</li> <li class="svelte-rmw6w0"><strong>Download .ics</strong> at the bottom of the filter panel gives you everything
-          currently in view, filters and all.</li></ul></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Putting the agenda on your own site</h3> <p class="svelte-rmw6w0">A project website can carry a live list of its upcoming events with an iframe. No script and
-        no account are needed, and it stays up to date on its own.</p> <pre class="svelte-rmw6w0"> </pre> <p class="muted small svelte-rmw6w0">An embed always shows public events only, whoever is looking at it. Your session does not
-        travel to another site, which is exactly what you want. The project README lists the
-        parameters it takes and the headers a deployment needs.</p></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Talking to the calendar from a script</h3> <p class="svelte-rmw6w0">Everything the web interface does goes through a documented HTTP API, and so can anything
-        else. The <strong>API</strong> button at the top of the page opens the reference, with a
-        "try it out" button on each endpoint that calls this deployment for real.</p> <p class="muted small svelte-rmw6w0">The description is generated from the running service, so it always matches what is actually
-        deployed. Machine-readable copies live at <a>openapi.json</a> and <a>openapi.yaml</a>, ready for a client generator.</p></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Signing in</h3> <!> <p class="muted small svelte-rmw6w0">If your affiliations have changed recently and the calendar has not noticed, log out and back
-        in; the lists are read when you sign in.</p></section> <footer class="svelte-rmw6w0"><button type="button" class="btn primary">Back to the calendar</button></footer></div></div>`);function Fc(e,t){Xe(t,!0);let n=Fe(t,"compareZones",19,()=>[]);const r=["Anyone","Project member","Committee member","Foundation member"],s=[{what:"See public project events",cells:[!0,!0,!0,!0]},{what:"See public foundation events",cells:[!0,!0,!0,!0]},{what:"Subscribe to the iCalendar feed",cells:[!0, [...]
-          it holds any of the major timezones, starting on UTC. It is currently set to `),O(F,se),O(J,`<iframe src="${a(l)??""}" width="100%" height="420"></iframe>`),he(ee,"href",ae),he(L,"href",ue)},[()=>nn(),()=>mn("local"),()=>mn(t.zone),()=>Ft("/openapi.json"),()=>Ft("/openapi.yaml")]),Q("click",_,function(...W){t.onclose?.apply(this,W)}),Q("click",pe,function(...W){t.onclose?.apply(this,W)}),w(e,c),Qe()}it(["click"]);var Uc=k('<p class="note svelte-fzlhf">Loading the API documentat [...]
-        copies: <a>openapi.json</a> and <a>openapi.yaml</a>.</p></div> <button type="button" class="btn">Back to the calendar</button></header> <!> <div class="swagger svelte-fzlhf"></div></div>`);function Yc(e,t){Xe(t,!0);let n=de(null),r=de("loading"),s=de(null);const l="vendor/swagger-ui-bundle.js",i="vendor/swagger-ui.css";function c(S){const M=document.querySelector(`script[data-swagger="${S}"]`);return M?M.dataset.loaded==="yes"?Promise.resolve():new Promise((j,H)=>{M.addEventListe [...]
-//# sourceMappingURL=index-CZgOqov1.js.map
diff --git a/frontend/dist/assets/index-CZgOqov1.js.map b/frontend/dist/assets/index-CZgOqov1.js.map
deleted file mode 100644
index e3a486b..0000000
--- a/frontend/dist/assets/index-CZgOqov1.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"file":"index-CZgOqov1.js","sources":["../../node_modules/esm-env/false.js","../../node_modules/svelte/src/internal/shared/utils.js","../../node_modules/svelte/src/internal/client/constants.js","../../node_modules/svelte/src/constants.js","../../node_modules/svelte/src/internal/client/warnings.js","../../node_modules/svelte/src/internal/client/reactivity/equality.js","../../node_modules/svelte/src/internal/client/errors.js","../../node_modules/svelte/src/internal/flags/index [...]
\ No newline at end of file
diff --git a/frontend/dist/assets/index-DwsHFb2B.js b/frontend/dist/assets/index-DwsHFb2B.js
new file mode 100644
index 0000000..c67e8f2
--- /dev/null
+++ b/frontend/dist/assets/index-DwsHFb2B.js
@@ -0,0 +1,68 @@
+(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const l of s)if(l.type==="childList")for(const o of l.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(s){const l={};return s.integrity&&(l.integrity=s.integrity),s.referrerPolicy&&(l.referrerPolicy=s.referr [...]
+\r\f \v\uFEFF`];function Oo(e,t,n){var r=e==null?"":""+e;if(t&&(r=r?r+" "+t:t),n){for(var s of Object.keys(n))if(n[s])r=r?r+" "+s:s;else if(r.length)for(var l=s.length,o=0;(o=r.indexOf(s,o))>=0;){var c=o+l;(o===0||za.includes(r[o-1]))&&(c===r.length||za.includes(r[c]))?r=(o===0?"":r.substring(0,o))+r.substring(c+1):o=c}}return r===""?null:r}function Io(e,t){return e==null?null:String(e)}function Ie(e,t,n,r,s,l){var o=e[Rr];if(o!==n||o===void 0){var c=Oo(n,r,l);c==null?e.removeAttribute(" [...]
+      the page.</p> <!> <!> <p class="muted small svelte-x10slk">Comparison clocks appear beside the week and day grids, on agenda rows, and in an event's
+      details.</p></section> <section class="subscribe svelte-x10slk"><h3 class="svelte-x10slk">Subscribe</h3> <p class="muted svelte-x10slk">Add the events you can see to your own calendar application with this iCalendar feed.</p> <a class="btn">Download .ics</a></section></aside>`);function Bi(e,t){Je(t,!0);let n=Ye(t,"maxCompareZones",3,3);function r(q){t.onchange({...t.filters,categories:Ra(t.filters.categories,q)})}function s(q){t.onchange({...t.filters,projects:Ra(t.filters.project [...]
+                     top: ${a(R).top*100}%;
+                     height: ${a(R).height*100}%;
+                     left: calc(${a(R).column/a(R).columns*100}% + 2px);
+                     width: calc(${1/a(R).columns*100}% - 4px);`),ge(te,"title",a(R).event.title),C(ae,ve),C(X,a(R).event.title)},[()=>jn(a(R).event),()=>Ue(at(a(R).event,r()))]),Q("click",te,()=>t.onselect(a(R).event)),g(O,te)}),z((O,R)=>V=Ie(U,1,"daycol svelte-5umrtz",null,V,{weekend:O,today:R}),[()=>lr(a(x)),()=>Bn(a(x),a(o))]),g(L,U)}),z(()=>{y=Ie(h,1,"week svelte-5umrtz",null,y,{single:a(c).length===1}),Bt(h,`--cols: ${a(c).length??""}; --gutters: ${a(f).length??""}`)}),g(e,h),Xe()} [...]
+              their own clock.</small></label>`),Ya=b('<input type="date" required=""/>'),Za=b('<input type="datetime-local" required=""/>'),Dc=b('<button type="button" class="btn danger">Delete</button>'),Cc=b('<form><h2 class="svelte-qx7ml8"> </h2> <label class="row svelte-qx7ml8"><span class="svelte-qx7ml8">Title</span> <input required="" maxlength="200" placeholder="What is happening?"/></label> <div class="pair svelte-qx7ml8"><label class="row svelte-qx7ml8"><span class="svelte-qx7m [...]
+          are done, particularly on a shared machine.</p>`),Gc=b(`<p class="svelte-rmw6w0"><a>Log in</a> with your Apache account. You
+          will be sent to the foundation's OAuth service and back again. Nothing is stored here
+          beyond your username and the projects and committees you belong to.</p>`),Kc=b(`<div class="help svelte-rmw6w0"><div class="sheet svelte-rmw6w0"><header class="svelte-rmw6w0"><h2 class="svelte-rmw6w0">Using the ASF Community Calendar</h2> <button type="button" class="btn">Back to the calendar</button></header> <p class="status svelte-rmw6w0"> </p> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">The three calendars</h3> <p class="svelte-rmw6w0">Every event belongs to on [...]
+        who can change it.</p> <dl class="svelte-rmw6w0"><dt class="svelte-rmw6w0"><span class="swatch personal svelte-rmw6w0"></span> Personal</dt> <dd class="svelte-rmw6w0">Your own events. Nobody else can see them, and they are never public. Use them for the
+          things you want on the same grid as everything else without telling anyone about them.</dd> <dt class="svelte-rmw6w0"><span class="swatch project svelte-rmw6w0"></span> Project</dt> <dd class="svelte-rmw6w0">Events belonging to a project: release votes, community calls, meetups. Public ones are
+          visible to everyone, including people who are not signed in. Private ones are visible only
+          to the project's committee (its PMC).</dd> <dt class="svelte-rmw6w0"><span class="swatch foundation svelte-rmw6w0"></span> Foundation</dt> <dd class="svelte-rmw6w0">Events for the ASF as a whole: board meetings, ApacheCon, report deadlines. Public ones are
+          visible to everyone; private ones only to foundation members.</dd></dl></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Who can do what</h3> <p class="svelte-rmw6w0">The lists of projects and committees you belong to come from your Apache account, through the
+        same login the rest of the foundation's tools use. There is nothing to configure here: sign
+        in and the calendar knows.</p> <div class="tablewrap svelte-rmw6w0"><table class="svelte-rmw6w0"><thead class="svelte-rmw6w0"><tr><th scope="col" class="svelte-rmw6w0">&nbsp;</th><!></tr></thead><tbody class="svelte-rmw6w0"></tbody></table></div> <p class="muted small svelte-rmw6w0">"Own projects" means the projects you commit to; "own committees" means the PMCs you sit on.
+        Being on a committee also counts as being a member of that project. Any project member can
+        edit any of their project's events, not only the ones they added themselves.</p></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Getting around</h3> <ul class="svelte-rmw6w0"><li class="svelte-rmw6w0"><strong>Day, week, month, year and agenda</strong> are the five views. Pick one at the top.</li> <li class="svelte-rmw6w0">The <strong>&#8249;</strong> and <strong>&#8250;</strong> buttons move one view-sized step:
+          a day in the day view, a month in the month view, and so on. <strong>Today</strong> jumps
+          back to now.</li> <li class="svelte-rmw6w0">Clicking a date number in the month or year view opens that day. Clicking a month name in
+          the year view opens that month.</li> <li class="svelte-rmw6w0">A day with more events than fit shows <strong>+n more</strong>; click it to open the day.</li> <li class="svelte-rmw6w0">Clicking any event opens it, with its full details, shortlink and download link.</li></ul></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Filters and search</h3> <p class="svelte-rmw6w0">The panel on the left narrows what is drawn. It does not change what you have access to; it
+        only hides things you would rather not look at right now.</p> <ul class="svelte-rmw6w0"><li class="svelte-rmw6w0"><strong>Calendars</strong> switches the three categories on and off. When you sign in, all
+          three start switched on, along with every project you belong to.</li> <li class="svelte-rmw6w0"><strong>Projects</strong> lists your projects plus any others that appear in the events
+          currently loaded. Projects you are not a member of stay visible unless you narrow the list
+          yourself.</li> <li class="svelte-rmw6w0"><strong>Visibility</strong> lets you look at only the public or only the private events.</li> <li class="svelte-rmw6w0"><strong>Search</strong> matches the title, description, location and project name of the
+          events in view.</li> <li class="svelte-rmw6w0"><strong>Sort</strong> appears in the agenda view, where the order is yours to choose.</li></ul></section> <section id="timezones" class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Timezones</h3> <p class="svelte-rmw6w0">An event happens at one moment in time, but that moment has a different clock reading
+        depending on where you are. The calendar keeps those two things apart.</p> <ul class="svelte-rmw6w0"><li class="svelte-rmw6w0">The switch at the top of the page chooses the clock the calendar is <em>drawn</em> in. <strong>Local</strong> follows your browser, which right now says <strong> </strong> <strong> </strong>. Flipping it moves everything together: the
+          grid, the times on each event, and which day an event falls on.</li> <li class="svelte-rmw6w0"><strong>You can watch more than one clock at once.</strong> Under "Timezones" in the panel
+          on the left, add up to three comparison timezones. They appear as extra hour columns beside
+          the week and day grids, after the time on each agenda row, and in an event's details - so
+          you can see an event in the organiser's own time and in yours without doing the arithmetic. <!> The grid itself can only be drawn on one clock, so the extra ones are labels rather than
+          extra columns of events.</li> <li class="svelte-rmw6w0">When you add an event you also choose the timezone the times are <em>in</em>. If you are
+          organising a call at 15:00 Berlin time, pick Europe/Berlin and type 15:00, and everybody
+          else will see it at their own 15:00-equivalent. Changing the timezone in the form keeps the
+          clock reading and moves the moment, which is almost always what you meant.</li> <li class="svelte-rmw6w0">Zone names such as <code>Europe/Copenhagen</code> are how the timezone database identifies
+          a clock, not a guess about where you are sitting. The calendar shows the city and the
+          current offset together so it is obvious why a particular clock was chosen.</li> <li class="svelte-rmw6w0"><strong>All-day events are dates, not moments.</strong> An all-day event on 14 March is on
+          14 March for everyone, and does not shift when you change the switch.</li></ul></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Adding and changing events</h3> <p class="svelte-rmw6w0"><strong>New event</strong> appears at the top once you are signed in and have somewhere to
+        put an event. The form only offers the calendars you can actually write to, so if you cannot
+        see a "Foundation" option it is because you are not a foundation member.</p> <ul class="svelte-rmw6w0"><li class="svelte-rmw6w0">A title and a start time are the only things required. An event with no end lasts an hour.</li> <li class="svelte-rmw6w0"><strong>All day</strong> turns the time fields into date fields. A one-day event is a
+          single date; a conference is a range.</li> <li class="svelte-rmw6w0"><strong>Visibility</strong> is public or private. Private means the project committee for
+          project events, and foundation members for foundation events. Personal events are always
+          private, so there is no choice to make.</li> <li class="svelte-rmw6w0">To edit or delete, open the event and use <strong>Edit</strong>. It only appears if you are
+          allowed. You cannot move an event into a calendar you cannot write to, or out of one.</li></ul></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Bringing events in from another calendar</h3> <p class="svelte-rmw6w0"><strong>Import</strong>, next to New event, takes an <code>.ics</code> file and turns
+        everything in it into events. Most calendar applications can export one.</p> <ul class="svelte-rmw6w0"><li class="svelte-rmw6w0">Choose the file first and you get a preview of what was found, including anything the
+          importer had to change. Nothing is saved at this point.</li> <li class="svelte-rmw6w0">Then say which calendar the events belong to, and whether they are public or private. You
+          have to answer: an import can add a lot of events at once, so there is no default that
+          could quietly put them in the wrong place.</li> <li class="svelte-rmw6w0">Every event in the file goes to the same calendar. Import twice if some belong to a
+          project and others do not.</li> <li class="svelte-rmw6w0">Repeating events come in as a single occurrence, since the calendar has no recurrence.
+          Cancelled entries, and ones with no start time, are skipped and counted for you.</li></ul></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Shortlinks and subscribing</h3> <ul class="svelte-rmw6w0"><li class="svelte-rmw6w0">Every event has a short URL, shown in its details, that opens the event directly. It is
+          safe to paste anywhere: someone who cannot see the event gets told so rather than shown it.
+          Public events show their title in link previews; private ones deliberately do not.</li> <li class="svelte-rmw6w0"><strong>Download .ics</strong> in an event's details saves that one event for your own
+          calendar application.</li> <li class="svelte-rmw6w0"><strong>Download .ics</strong> at the bottom of the filter panel gives you everything
+          currently in view, filters and all.</li></ul></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Putting the agenda on your own site</h3> <p class="svelte-rmw6w0">A project website can carry a live list of its upcoming events with an iframe. No script and
+        no account are needed, and it stays up to date on its own.</p> <pre class="svelte-rmw6w0"> </pre> <p class="muted small svelte-rmw6w0">An embed always shows public events only, whoever is looking at it. Your session does not
+        travel to another site, which is exactly what you want. The project README lists the
+        parameters it takes and the headers a deployment needs.</p></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Talking to the calendar from a script</h3> <p class="svelte-rmw6w0">Everything the web interface does goes through a documented HTTP API, and so can anything
+        else. The <strong>API</strong> button at the top of the page opens the reference, with a
+        "try it out" button on each endpoint that calls this deployment for real.</p> <p class="muted small svelte-rmw6w0">The description is generated from the running service, so it always matches what is actually
+        deployed. Machine-readable copies live at <a>openapi.json</a> and <a>openapi.yaml</a>, ready for a client generator.</p></section> <section class="svelte-rmw6w0"><h3 class="svelte-rmw6w0">Signing in</h3> <!> <p class="muted small svelte-rmw6w0">If your affiliations have changed recently and the calendar has not noticed, log out and back
+        in; the lists are read when you sign in.</p></section> <footer class="svelte-rmw6w0"><button type="button" class="btn primary">Back to the calendar</button></footer></div></div>`);function Jc(e,t){Je(t,!0);let n=Ye(t,"compareZones",19,()=>[]);const r=["Anyone","Project member","Committee member","Foundation member"],s=[{what:"See public project events",cells:[!0,!0,!0,!0]},{what:"See public foundation events",cells:[!0,!0,!0,!0]},{what:"Subscribe to the iCalendar feed",cells:[!0, [...]
+          it holds any of the major timezones, starting on UTC. It is currently set to `),C(U,Y),C(te,`<iframe src="${a(l)??""}" width="100%" height="420"></iframe>`),ge(ae,"href",se),ge(q,"href",fe)},[()=>fn(),()=>An("local"),()=>An(t.zone),()=>Qt("/openapi.json"),()=>Qt("/openapi.yaml")]),Q("click",_,function(...K){t.onclose?.apply(this,K)}),Q("click",ye,function(...K){t.onclose?.apply(this,K)}),g(e,c),Xe()}ot(["click"]);var Xc=b('<p class="note svelte-fzlhf">Loading the API documentat [...]
+        copies: <a>openapi.json</a> and <a>openapi.yaml</a>.</p></div> <button type="button" class="btn">Back to the calendar</button></header> <!> <div class="swagger svelte-fzlhf"></div></div>`);function eu(e,t){Je(t,!0);let n=ce(null),r=ce("loading"),s=ce(null);const l="vendor/swagger-ui-bundle.js",o="vendor/swagger-ui.css";function c(D){const P=document.querySelector(`script[data-swagger="${D}"]`);return P?P.dataset.loaded==="yes"?Promise.resolve():new Promise((I,W)=>{P.addEventListe [...]
+          ${a(s).count===1?"event":"events"} found `),gt!==(gt=a(l).category??"")&&(Te.value=(Te.__value=gt)??"",Ot(Te,gt))}),Q("change",Te,H=>B({category:H.currentTarget.value||null})),g(m,Y)};J(ae,m=>{a(s)&&m(q)})}var X=u(ae,2),ie=u(p(X),2),ve=u(ie,2),we=p(ve);{var xe=m=>{var Y=Mn("Importing...");g(m,Y)},ye=m=>{var Y=Mn();z(()=>C(Y,`Import ${a(s).count??""} ${a(s).count===1?"event":"events"}`)),g(m,Y)},K=m=>{var Y=Mn("Import");g(m,Y)};J(we,m=>{a(c)?m(xe):a(s)?m(ye,1):m(K,-1)})}z(()=>{U [...]
+//# sourceMappingURL=index-DwsHFb2B.js.map
diff --git a/frontend/dist/assets/index-DwsHFb2B.js.map b/frontend/dist/assets/index-DwsHFb2B.js.map
new file mode 100644
index 0000000..e330903
--- /dev/null
+++ b/frontend/dist/assets/index-DwsHFb2B.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"index-DwsHFb2B.js","sources":["../../node_modules/esm-env/false.js","../../node_modules/svelte/src/internal/shared/utils.js","../../node_modules/svelte/src/internal/client/constants.js","../../node_modules/svelte/src/constants.js","../../node_modules/svelte/src/internal/client/warnings.js","../../node_modules/svelte/src/internal/client/reactivity/equality.js","../../node_modules/svelte/src/internal/client/errors.js","../../node_modules/svelte/src/internal/flags/index [...]
\ No newline at end of file
diff --git a/frontend/dist/index.html b/frontend/dist/index.html
index c9c8cf6..fef2bf9 100644
--- a/frontend/dist/index.html
+++ b/frontend/dist/index.html
@@ -16,8 +16,8 @@
       name="description"
       content="Personal, project and foundation events across the Apache Software Foundation."
     />
-    <script type="module" crossorigin src="./assets/index-CZgOqov1.js"></script>
-    <link rel="stylesheet" crossorigin href="./assets/index-Dbhcf4N0.css">
+    <script type="module" crossorigin src="./assets/index-DwsHFb2B.js"></script>
+    <link rel="stylesheet" crossorigin href="./assets/index-CXgtmuq1.css">
   </head>
   <body>
     <div id="app"></div>
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 3ab50ee..6ffdcf2 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -26,6 +26,7 @@
   import EventDialog from "./components/EventDialog.svelte";
   import HelpPage from "./components/HelpPage.svelte";
   import ApiDocs from "./components/ApiDocs.svelte";
+  import ImportDialog from "./components/ImportDialog.svelte";
 
   const VIEW_STORAGE_KEY = "asf-calendar-view";
   const ZONE_STORAGE_KEY = "asf-calendar-zone";
@@ -110,6 +111,7 @@
 
   let selected = $state<CalendarEvent | null>(null);
   let draft = $state<EventDraft | null>(null);
+  let importing = $state(false);
 
   let range = $derived(rangeForView(view, cursor));
   let knownProjects = $derived(projectsInPlay(events, calendars));
@@ -260,6 +262,23 @@
     draft = newDraft(fromWall(when, zone), calendars);
   }
 
+  function startImport() {
+    selected = null;
+    draft = null;
+    dialogError = null;
+    helpOpen = false;
+    docsOpen = false;
+    importing = true;
+  }
+
+  async function finishImport(count: number) {
+    importing = false;
+    // The imported events may be anywhere in time, so reload the window rather
+    // than trying to splice them in.
+    await loadEvents(fromWall(range.start, zone), fromWall(range.end, zone));
+    loadError = count === 0 ? "Nothing was imported." : null;
+  }
+
   function startEdit() {
     if (selected) draft = draftFromEvent(selected);
   }
@@ -353,6 +372,7 @@
     onstep={(direction) => (cursor = step(view, cursor, direction))}
     ontoday={() => (cursor = startOfDay(nowInZone(zone)))}
     oncreate={() => startCreate(cursor)}
+    onimport={startImport}
     ontogglefilters={() => (showFilters = !showFilters)}
     onzone={setZone}
     onalternatezone={(next) => (alternateZone = next)}
@@ -420,6 +440,15 @@
   </div>
 </div>
 
+{#if importing}
+  <ImportDialog
+    {calendars}
+    {zone}
+    onclose={() => (importing = false)}
+    onimported={finishImport}
+  />
+{/if}
+
 {#if selected || draft}
   <EventDialog
     event={selected}
diff --git a/frontend/src/components/Header.svelte b/frontend/src/components/Header.svelte
index c9869af..fda1d2a 100644
--- a/frontend/src/components/Header.svelte
+++ b/frontend/src/components/Header.svelte
@@ -22,6 +22,7 @@
     onstep: (direction: number) => void;
     ontoday: () => void;
     oncreate: () => void;
+    onimport: () => void;
     ontogglefilters: () => void;
     onzone: (zone: DisplayZone) => void;
     onalternatezone: (zone: DisplayZone) => void;
@@ -44,6 +45,7 @@
     onstep,
     ontoday,
     oncreate,
+    onimport,
     ontogglefilters,
     onzone,
     onalternatezone,
@@ -98,6 +100,9 @@
       API
     </button>
     {#if canCreate}
+      <button type="button" class="btn" onclick={onimport} title="Import events from an .ics file">
+        Import
+      </button>
       <button type="button" class="btn primary" onclick={oncreate}>New event</button>
     {/if}
     {#if session?.authenticated}
diff --git a/frontend/src/components/HelpPage.svelte b/frontend/src/components/HelpPage.svelte
index afb875c..9304da3 100644
--- a/frontend/src/components/HelpPage.svelte
+++ b/frontend/src/components/HelpPage.svelte
@@ -244,6 +244,33 @@
       </ul>
     </section>
 
+    <section>
+      <h3>Bringing events in from another calendar</h3>
+      <p>
+        <strong>Import</strong>, next to New event, takes an <code>.ics</code> file and turns
+        everything in it into events. Most calendar applications can export one.
+      </p>
+      <ul>
+        <li>
+          Choose the file first and you get a preview of what was found, including anything the
+          importer had to change. Nothing is saved at this point.
+        </li>
+        <li>
+          Then say which calendar the events belong to, and whether they are public or private. You
+          have to answer: an import can add a lot of events at once, so there is no default that
+          could quietly put them in the wrong place.
+        </li>
+        <li>
+          Every event in the file goes to the same calendar. Import twice if some belong to a
+          project and others do not.
+        </li>
+        <li>
+          Repeating events come in as a single occurrence, since the calendar has no recurrence.
+          Cancelled entries, and ones with no start time, are skipped and counted for you.
+        </li>
+      </ul>
+    </section>
+
     <section>
       <h3>Shortlinks and subscribing</h3>
       <ul>
diff --git a/frontend/src/components/ImportDialog.svelte b/frontend/src/components/ImportDialog.svelte
new file mode 100644
index 0000000..1ace122
--- /dev/null
+++ b/frontend/src/components/ImportDialog.svelte
@@ -0,0 +1,455 @@
+<script lang="ts">
+  import type { Calendars, Category, Visibility } from "../lib/types";
+  import type { DisplayZone } from "../lib/timezone";
+  import type { ImportCandidate, ImportPreview, ImportSettings } from "../lib/importing";
+  import {
+    emptySettings,
+    importReadiness,
+    importableCategories,
+    importableProjects,
+    importableVisibilities,
+    looksLikeCalendar,
+    reconcile,
+    resolveSettings,
+  } from "../lib/importing";
+  import { api, ApiError } from "../lib/api";
+  import { formatDate, formatTime } from "../lib/dates";
+  import { categoryLabel } from "../lib/events";
+  import { shortZoneLabel, toWall } from "../lib/timezone";
+
+  interface Props {
+    calendars: Calendars | null;
+    /** The clock the reader is using, so the preview matches the calendar. */
+    zone?: DisplayZone;
+    onclose: () => void;
+    /** Called with the number of events created, so the calendar can reload. */
+    onimported: (count: number) => void;
+  }
+
+  let { calendars, zone = "local", onclose, onimported }: Props = $props();
+
+  let file = $state<File | null>(null);
+  let preview = $state<ImportPreview | null>(null);
+  let settings = $state<ImportSettings>(emptySettings());
+  let reading = $state(false);
+  let saving = $state(false);
+  let error = $state<string | null>(null);
+  let dragging = $state(false);
+
+  let categories = $derived(importableCategories(calendars));
+  let visibilities = $derived(importableVisibilities(settings.category, calendars));
+  let projects = $derived(importableProjects(calendars, settings.visibility));
+  let readiness = $derived(importReadiness(settings, calendars));
+  let canSave = $derived(preview !== null && preview.count > 0 && readiness.ready && !saving);
+
+  function update(change: Partial<ImportSettings>) {
+    settings = reconcile({ ...settings, ...change }, calendars);
+  }
+
+  async function choose(chosen: File | null | undefined) {
+    if (!chosen) return;
+    file = chosen;
+    preview = null;
+    error = null;
+    reading = true;
+    try {
+      preview = await api.previewImport(chosen);
+      if (!looksLikeCalendar(chosen)) {
+        // It parsed, so the name was just unhelpful. Worth knowing, not worth
+        // refusing.
+        error = null;
+      }
+    } catch (failure) {
+      error = failure instanceof ApiError ? failure.message : "That file could not be read.";
+      file = null;
+    } finally {
+      reading = false;
+    }
+  }
+
+  async function save() {
+    if (!file || !canSave) return;
+    saving = true;
+    error = null;
+    try {
+      const result = await api.runImport(file, resolveSettings(settings));
+      onimported(result.count);
+    } catch (failure) {
+      error = failure instanceof ApiError ? failure.message : "Those events could not be saved.";
+    } finally {
+      saving = false;
+    }
+  }
+
+  function onDrop(event: DragEvent) {
+    event.preventDefault();
+    dragging = false;
+    void choose(event.dataTransfer?.files?.[0]);
+  }
+
+  function keydown(event: KeyboardEvent) {
+    if (event.key === "Escape") onclose();
+  }
+
+  function when(candidate: ImportCandidate): string {
+    const start = toWall(new Date(candidate.start), zone);
+    if (candidate.all_day) {
+      const last = toWall(new Date(new Date(candidate.end).getTime() - 1), zone);
+      return last.toDateString() === start.toDateString()
+        ? `${formatDate(start)} (all day)`
+        : `${formatDate(start)} - ${formatDate(last)} (all day)`;
+    }
+    const end = toWall(new Date(candidate.end), zone);
+    return `${formatDate(start)}, ${formatTime(start)} - ${formatTime(end)} ${shortZoneLabel(zone)}`;
+  }
+
+  let warningCount = $derived(
+    (preview?.warnings.length ?? 0) +
+      (preview?.events ?? []).reduce((total, event) => total + event.warnings.length, 0),
+  );
+</script>
+
+<svelte:window onkeydown={keydown} />
+
+<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
+<div class="backdrop" onclick={onclose}>
+  <!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
+  <div
+    class="dialog"
+    role="dialog"
+    tabindex="-1"
+    aria-modal="true"
+    aria-label="Import an iCalendar file"
+    onclick={(event) => event.stopPropagation()}
+  >
+    <h2>Import events from a calendar file</h2>
+
+    {#if error}
+      <p class="error" role="alert">{error}</p>
+    {/if}
+
+    <!-- svelte-ignore a11y_no_static_element_interactions -->
+    <div
+      class="dropzone"
+      class:dragging
+      ondragover={(event) => {
+        event.preventDefault();
+        dragging = true;
+      }}
+      ondragleave={() => (dragging = false)}
+      ondrop={onDrop}
+    >
+      <label class="btn">
+        Choose a file
+        <input
+          type="file"
+          accept=".ics,text/calendar"
+          onchange={(event) => choose(event.currentTarget.files?.[0])}
+        />
+      </label>
+      <span class="muted">
+        {#if file}{file.name}{:else}or drop an .ics file here{/if}
+      </span>
+    </div>
+
+    {#if reading}
+      <p class="note">Reading the file...</p>
+    {/if}
+
+    {#if preview}
+      <section class="preview">
+        <h3>
+          {preview.count}
+          {preview.count === 1 ? "event" : "events"} found
+          {#if warningCount > 0}
+            <span class="muted">- {warningCount} thing{warningCount === 1 ? "" : "s"} to note</span>
+          {/if}
+        </h3>
+
+        {#each preview.warnings as warning (warning)}
+          <p class="warning">{warning}</p>
+        {/each}
+
+        <ul>
+          {#each preview.events as candidate, index (candidate.uid ?? index)}
+            <li>
+              <span class="title">{candidate.title}</span>
+              <span class="when">{when(candidate)}</span>
+              {#if candidate.location}<span class="where muted">{candidate.location}</span>{/if}
+              {#each candidate.warnings as warning (warning)}
+                <span class="warning inline">{warning}</span>
+              {/each}
+            </li>
+          {/each}
+        </ul>
+      </section>
+
+      <section class="settings">
+        <h3>Where should they go?</h3>
+
+        <div class="pair">
+          <label class="row">
+            <span>Calendar</span>
+            <select
+              value={settings.category ?? ""}
+              onchange={(event) =>
+                update({ category: (event.currentTarget.value || null) as Category | null })}
+            >
+              <option value="">Choose...</option>
+              {#each categories as category (category)}
+                <option value={category}>{categoryLabel(category)}</option>
+              {/each}
+            </select>
+          </label>
+
+          {#if settings.category !== null && settings.category !== "personal"}
+            <label class="row">
+              <span>Visibility</span>
+              <select
+                value={settings.visibility ?? ""}
+                onchange={(event) =>
+                  update({ visibility: (event.currentTarget.value || null) as Visibility | null })}
+              >
+                <option value="">Choose...</option>
+                {#each visibilities as visibility (visibility)}
+                  <option value={visibility}>{visibility}</option>
+                {/each}
+              </select>
+            </label>
+          {/if}
+
+          {#if settings.category === "project"}
+            <label class="row">
+              <span>Project</span>
+              <select
+                value={settings.project ?? ""}
+                onchange={(event) => update({ project: event.currentTarget.value || null })}
+              >
+                <option value="">Choose...</option>
+                {#each projects as project (project)}
+                  <option value={project}>{project}</option>
+                {/each}
+              </select>
+            </label>
+          {/if}
+        </div>
+
+        {#if settings.category === "personal"}
+          <p class="muted small">Personal events are always private to you.</p>
+        {/if}
+
+        {#if !readiness.ready}
+          <p class="missing" role="status">
+            Still to choose: {readiness.missing.join(", ")}.
+          </p>
+        {/if}
+      </section>
+    {/if}
+
+    <footer>
+      <span class="spacer"></span>
+      <button type="button" class="btn" onclick={onclose} disabled={saving}>Cancel</button>
+      <button type="button" class="btn primary" onclick={save} disabled={!canSave}>
+        {#if saving}
+          Importing...
+        {:else if preview}
+          Import {preview.count} {preview.count === 1 ? "event" : "events"}
+        {:else}
+          Import
+        {/if}
+      </button>
+    </footer>
+  </div>
+</div>
+
+<style>
+  .backdrop {
+    position: fixed;
+    inset: 0;
+    background: rgba(10, 14, 20, 0.45);
+    display: flex;
+    align-items: flex-start;
+    justify-content: center;
+    padding: 3rem 1rem;
+    overflow-y: auto;
+    z-index: 50;
+  }
+
+  .dialog {
+    width: min(42rem, 100%);
+    background: var(--bg-panel);
+    border-radius: 10px;
+    border-top: 4px solid var(--asf-red);
+    box-shadow: var(--shadow-lg);
+    padding: 1.2rem 1.4rem 1rem;
+  }
+
+  h2 {
+    margin: 0 0 0.8rem;
+    font-size: 19px;
+  }
+
+  h3 {
+    margin: 0 0 0.4rem;
+    font-size: 12px;
+    font-weight: 700;
+    text-transform: uppercase;
+    letter-spacing: 0.05em;
+    color: var(--text-muted);
+  }
+
+  .error {
+    margin: 0 0 0.8rem;
+    padding: 0.5rem 0.7rem;
+    border-radius: var(--radius);
+    background: hsl(0 70% 95%);
+    border: 1px solid hsl(0 60% 75%);
+    color: hsl(0 65% 30%);
+  }
+
+  .dropzone {
+    display: flex;
+    align-items: center;
+    gap: 0.7rem;
+    padding: 1rem;
+    border: 2px dashed var(--border-strong);
+    border-radius: var(--radius);
+    background: var(--bg-subtle);
+  }
+
+  .dropzone.dragging {
+    border-color: var(--asf-red);
+    background: var(--bg-hover);
+  }
+
+  .dropzone input[type="file"] {
+    position: absolute;
+    width: 1px;
+    height: 1px;
+    opacity: 0;
+  }
+
+  .dropzone label {
+    cursor: pointer;
+  }
+
+  .note {
+    margin: 0.7rem 0 0;
+    color: var(--text-muted);
+  }
+
+  .preview,
+  .settings {
+    margin-top: 1.1rem;
+  }
+
+  .preview ul {
+    list-style: none;
+    margin: 0;
+    padding: 0;
+    max-height: 16rem;
+    overflow-y: auto;
+    border: 1px solid var(--border);
+    border-radius: var(--radius);
+  }
+
+  .preview li {
+    display: flex;
+    flex-direction: column;
+    gap: 1px;
+    padding: 0.4rem 0.6rem;
+    border-bottom: 1px solid var(--border);
+  }
+
+  .preview li:last-child {
+    border-bottom: 0;
+  }
+
+  .title {
+    font-weight: 600;
+  }
+
+  .when {
+    font-size: 12px;
+    color: var(--text-muted);
+    font-variant-numeric: tabular-nums;
+  }
+
+  .where {
+    font-size: 12px;
+  }
+
+  .warning {
+    margin: 0 0 0.4rem;
+    font-size: 12px;
+    color: hsl(28 70% 30%);
+    background: hsl(38 92% 92%);
+    border: 1px solid hsl(38 60% 78%);
+    border-radius: var(--radius);
+    padding: 0.3rem 0.5rem;
+  }
+
+  .warning.inline {
+    margin: 0.2rem 0 0;
+    display: block;
+  }
+
+  .pair {
+    display: flex;
+    gap: 0.7rem;
+    flex-wrap: wrap;
+  }
+
+  .row {
+    display: flex;
+    flex-direction: column;
+    gap: 0.2rem;
+    flex: 1 1 10rem;
+  }
+
+  .row > span {
+    font-size: 11px;
+    font-weight: 700;
+    text-transform: uppercase;
+    letter-spacing: 0.05em;
+    color: var(--text-muted);
+  }
+
+  .missing {
+    margin: 0.6rem 0 0;
+    font-size: 13px;
+    color: var(--asf-red);
+  }
+
+  .small {
+    font-size: 12px;
+    margin: 0.5rem 0 0;
+  }
+
+  footer {
+    display: flex;
+    align-items: center;
+    gap: 0.5rem;
+    margin-top: 1.2rem;
+    padding-top: 0.8rem;
+    border-top: 1px solid var(--border);
+  }
+
+  .spacer {
+    flex: 1;
+  }
+
+  @media (prefers-color-scheme: dark) {
+    .error {
+      background: hsl(0 40% 20%);
+      border-color: hsl(0 40% 40%);
+      color: hsl(0 70% 85%);
+    }
+
+    .warning {
+      background: hsl(38 40% 20%);
+      border-color: hsl(38 40% 35%);
+      color: hsl(38 80% 82%);
+    }
+  }
+</style>
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 3530475..1186ec1 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -10,6 +10,7 @@
  */
 
 import type { CalendarEvent, Calendars, EventDraft, SessionInfo } from "./types";
+import type { ImportPreview, ImportResult, ResolvedImportSettings } from "./importing";
 import { apiUrl } from "./base";
 
 export class ApiError extends Error {
@@ -30,6 +31,9 @@ export class ApiError extends Error {
 }
 
 async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
+  // FormData carries its own multipart boundary, so the browser has to set the
+  // content type; naming it ourselves would produce a body nothing can parse.
+  const isUpload = typeof FormData !== "undefined" && body instanceof FormData;
   let response: Response;
   try {
     response = await fetch(apiUrl(path), {
@@ -38,9 +42,9 @@ async function request<T>(method: string, path: string, body?: unknown): Promise
       headers: {
         Accept: "application/json",
         "X-No-Redirect": "1",
-        ...(body === undefined ? {} : { "Content-Type": "application/json" }),
+        ...(body === undefined || isUpload ? {} : { "Content-Type": "application/json" }),
       },
-      ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+      ...(body === undefined ? {} : { body: isUpload ? (body as FormData) : JSON.stringify(body) }),
     });
   } catch {
     throw new ApiError("Could not reach the calendar service.", 0);
@@ -130,6 +134,23 @@ export const api = {
 
   remove: (id: number) => request<{ deleted: number }>("DELETE", `/events/${id}`),
 
+  /** Reads an .ics file and says what is in it, without saving anything. */
+  previewImport: (file: File) => {
+    const body = new FormData();
+    body.append("file", file);
+    return request<ImportPreview>("POST", "/import/preview", body);
+  },
+
+  /** Turns an .ics file into events on the chosen calendar. */
+  runImport: (file: File, settings: ResolvedImportSettings) => {
+    const body = new FormData();
+    body.append("file", file);
+    body.append("category", settings.category);
+    if (settings.visibility) body.append("visibility", settings.visibility);
+    if (settings.project) body.append("project", settings.project);
+    return request<ImportResult>("POST", "/import", body);
+  },
+
   icsUrl: (id: number) => apiUrl(`/events/${id}.ics`),
 
   feedUrl: (query: EventQuery = {}) => apiUrl(`/events.ics${buildQuery(query)}`),
diff --git a/frontend/src/lib/importing.test.ts b/frontend/src/lib/importing.test.ts
new file mode 100644
index 0000000..4a3b605
--- /dev/null
+++ b/frontend/src/lib/importing.test.ts
@@ -0,0 +1,235 @@
+/**
+ * Deciding where imported events should land.
+ *
+ * Nothing here is defaulted on purpose: an import can create dozens of events
+ * at once, so the form makes the reader say which calendar, which project and
+ * whether they are public before it will save anything.
+ */
+
+import { describe, expect, it } from "vitest";
+import { anonymousCalendars, makeCalendars } from "../tests/factories";
+import {
+  emptySettings,
+  importReadiness,
+  importableCategories,
+  importableProjects,
+  importableVisibilities,
+  looksLikeCalendar,
+  reconcile,
+  resolveSettings,
+} from "./importing";
+import type { ImportSettings } from "./importing";
+
+const committer = makeCalendars({
+  uid: "alice",
+  projects: ["httpd", "tomcat"],
+  committees: [],
+  can_create: { personal: true, project: ["httpd", "tomcat"], project_private: [], foundation: false },
+});
+
+const pmcMember = makeCalendars({
+  uid: "bob",
+  projects: ["httpd"],
+  committees: ["httpd"],
+  can_create: { personal: true, project: ["httpd"], project_private: ["httpd"], foundation: false },
+});
+
+const member = makeCalendars({
+  uid: "carol",
+  is_member: true,
+  projects: ["tomcat"],
+  committees: ["tomcat"],
+  can_create: { personal: true, project: ["tomcat"], project_private: ["tomcat"], foundation: true },
+});
+
+function settings(overrides: Partial<ImportSettings> = {}): ImportSettings {
+  return { ...emptySettings(), ...overrides };
+}
+
+describe("nothing is chosen to begin with", () => {
+  it("starts empty", () => {
+    expect(emptySettings()).toEqual({ category: null, project: null, visibility: null });
+  });
+
+  it("is not ready, and says what is missing", () => {
+    const readiness = importReadiness(emptySettings(), committer);
+    expect(readiness.ready).toBe(false);
+    expect(readiness.missing).toEqual(["which calendar these events belong to"]);
+  });
+});
+
+describe("what is on offer", () => {
+  it("only the calendars this session may write", () => {
+    expect(importableCategories(committer)).toEqual(["personal", "project"]);
+    expect(importableCategories(member)).toEqual(["personal", "project", "foundation"]);
+    expect(importableCategories(anonymousCalendars)).toEqual([]);
+    expect(importableCategories(null)).toEqual([]);
+  });
+
+  it("private project events need the committee", () => {
+    expect(importableProjects(committer, "public")).toEqual(["httpd", "tomcat"]);
+    expect(importableProjects(committer, "private")).toEqual([]);
+    expect(importableProjects(pmcMember, "private")).toEqual(["httpd"]);
+  });
+
+  it("personal events have no visibility to choose", () => {
+    expect(importableVisibilities("personal", committer)).toEqual([]);
+  });
+
+  it("a committer with no committee can only import public project events", () => {
+    expect(importableVisibilities("project", committer)).toEqual(["public"]);
+  });
+
+  it("a committee member gets both", () => {
+    expect(importableVisibilities("project", pmcMember)).toEqual(["public", "private"]);
+  });
+
+  it("foundation events are members only", () => {
+    expect(importableVisibilities("foundation", committer)).toEqual([]);
+    expect(importableVisibilities("foundation", member)).toEqual(["public", "private"]);
+  });
+});
+
+describe("what still has to be answered", () => {
+  it("a project import needs a project and a visibility", () => {
+    const readiness = importReadiness(settings({ category: "project" }), committer);
+    expect(readiness.ready).toBe(false);
+    expect(readiness.missing).toEqual([
+      "whether they are public or private",
+      "which project they belong to",
+    ]);
+  });
+
+  it("choosing the visibility leaves only the project", () => {
+    const readiness = importReadiness(
+      settings({ category: "project", visibility: "public" }),
+      committer,
+    );
+    expect(readiness.missing).toEqual(["which project they belong to"]);
+  });
+
+  it("a fully answered project import is ready", () => {
+    const readiness = importReadiness(
+      settings({ category: "project", visibility: "public", project: "httpd" }),
+      committer,
+    );
+    expect(readiness).toEqual({ ready: true, missing: [] });
+  });
+
+  it("a personal import needs nothing more than the calendar", () => {
+    expect(importReadiness(settings({ category: "personal" }), committer).ready).toBe(true);
+  });
+
+  it("a foundation import still needs a visibility", () => {
+    expect(importReadiness(settings({ category: "foundation" }), member).ready).toBe(false);
+    expect(
+      importReadiness(settings({ category: "foundation", visibility: "private" }), member).ready,
+    ).toBe(true);
+  });
+});
+
+describe("it will not accept an answer the session is not allowed to give", () => {
+  it("a calendar the user cannot write to", () => {
+    const readiness = importReadiness(settings({ category: "foundation", visibility: "public" }), committer);
+    expect(readiness.ready).toBe(false);
+    expect(readiness.missing).toContain("a calendar you are allowed to add to");
+  });
+
+  it("a project the user is not a member of", () => {
+    const readiness = importReadiness(
+      settings({ category: "project", visibility: "public", project: "kafka" }),
+      committer,
+    );
+    expect(readiness.missing).toContain("a project you are allowed to add to");
+  });
+
+  it("a private project event without the committee", () => {
+    const readiness = importReadiness(
+      settings({ category: "project", visibility: "private", project: "httpd" }),
+      committer,
+    );
+    expect(readiness.ready).toBe(false);
+  });
+
+  it("...which the committee member may do", () => {
+    const readiness = importReadiness(
+      settings({ category: "project", visibility: "private", project: "httpd" }),
+      pmcMember,
+    );
+    expect(readiness.ready).toBe(true);
+  });
+
+  it("anonymous cannot import at all", () => {
+    expect(importReadiness(settings({ category: "personal" }), anonymousCalendars).ready).toBe(false);
+  });
+});
+
+describe("keeping the form consistent", () => {
+  it("drops the project when the calendar is not a project one", () => {
+    const next = reconcile(settings({ category: "personal", project: "httpd" }), committer);
+    expect(next.project).toBeNull();
+  });
+
+  it("drops the visibility for a personal calendar", () => {
+    const next = reconcile(settings({ category: "personal", visibility: "public" }), committer);
+    expect(next.visibility).toBeNull();
+  });
+
+  it("drops a project that switching to private has taken off the list", () => {
+    const chosen = settings({ category: "project", visibility: "public", project: "tomcat" });
+    const next = reconcile({ ...chosen, visibility: "private" }, committer);
+    expect(next.project).toBeNull();
+  });
+
+  it("keeps a project that is still allowed", () => {
+    const chosen = settings({ category: "project", visibility: "private", project: "httpd" });
+    expect(reconcile(chosen, pmcMember).project).toBe("httpd");
+  });
+
+  it("drops a visibility the new calendar does not offer", () => {
+    const chosen = settings({ category: "project", visibility: "private", project: "httpd" });
+    // A committer switching to a calendar where private is not on offer.
+    expect(reconcile(chosen, committer).visibility).toBeNull();
+  });
+});
+
+describe("handing the answers to the API", () => {
+  it("sends project and visibility for a project import", () => {
+    expect(
+      resolveSettings(settings({ category: "project", visibility: "public", project: "httpd" })),
+    ).toEqual({ category: "project", visibility: "public", project: "httpd" });
+  });
+
+  it("sends neither for a personal import", () => {
+    expect(resolveSettings(settings({ category: "personal" }))).toEqual({
+      category: "personal",
+      visibility: null,
+      project: null,
+    });
+  });
+
+  it("never sends a project on a foundation import", () => {
+    const resolved = resolveSettings(
+      settings({ category: "foundation", visibility: "public", project: "httpd" }),
+    );
+    expect(resolved.project).toBeNull();
+  });
+
+  it("refuses to resolve before a calendar is chosen", () => {
+    expect(() => resolveSettings(emptySettings())).toThrow();
+  });
+});
+
+describe("recognising a calendar file", () => {
+  const asFile = (name: string, type = "") => new File(["BEGIN:VCALENDAR"], name, { type });
+
+  it("by extension or by type", () => {
+    expect(looksLikeCalendar(asFile("events.ics"))).toBe(true);
+    expect(looksLikeCalendar(asFile("EVENTS.ICS"))).toBe(true);
+    expect(looksLikeCalendar(asFile("export", "text/calendar"))).toBe(true);
+  });
+
+  it("and not otherwise", () => {
+    expect(looksLikeCalendar(asFile("holiday.jpg", "image/jpeg"))).toBe(false);
+  });
+});
diff --git a/frontend/src/lib/importing.ts b/frontend/src/lib/importing.ts
new file mode 100644
index 0000000..5785dd2
--- /dev/null
+++ b/frontend/src/lib/importing.ts
@@ -0,0 +1,175 @@
+/**
+ * Importing an iCalendar file.
+ *
+ * The file itself is read by the backend, which knows how to cope with what
+ * Google, Outlook and Thunderbird produce. What lives here is the decision the
+ * backend cannot make: which calendar the events should land in.
+ *
+ * That decision is deliberately not defaulted. An import can create dozens of
+ * events at once, and a wrong default would publish somebody's private meetings
+ * or file them under the wrong project, so the form starts with nothing chosen
+ * and `importReadiness` reports what is still missing.
+ */
+
+import type { Calendars, Category, Visibility } from "./types";
+
+/** An event the backend found in the file, before it is given a calendar. */
+export interface ImportCandidate {
+  title: string;
+  start: string;
+  end: string;
+  all_day: boolean;
+  description: string;
+  location: string;
+  url: string;
+  timezone: string;
+  uid: string | null;
+  /** What the backend had to change to make this event importable. */
+  warnings: string[];
+}
+
+export interface ImportPreview {
+  events: ImportCandidate[];
+  count: number;
+  /** Problems with the file as a whole, such as entries that were skipped. */
+  warnings: string[];
+}
+
+export interface ImportResult {
+  created: import("./types").CalendarEvent[];
+  count: number;
+  warnings: string[];
+}
+
+/** What the form collects. Null means "not chosen yet", not "default". */
+export interface ImportSettings {
+  category: Category | null;
+  project: string | null;
+  visibility: Visibility | null;
+}
+
+/** The same thing once every required answer is in. */
+export interface ResolvedImportSettings {
+  category: Category;
+  project: string | null;
+  visibility: Visibility | null;
+}
+
+export function emptySettings(): ImportSettings {
+  return { category: null, project: null, visibility: null };
+}
+
+/** The calendars this session may import into, in the order to offer them. */
+export function importableCategories(calendars: Calendars | null): Category[] {
+  const can = calendars?.can_create;
+  if (!can) return [];
+  const categories: Category[] = [];
+  if (can.personal) categories.push("personal");
+  if (can.project.length > 0) categories.push("project");
+  if (can.foundation) categories.push("foundation");
+  return categories;
+}
+
+/**
+ * The projects that can take an import, which depends on the visibility: a
+ * committer can add public events to their projects, but a private one needs
+ * the committee.
+ */
+export function importableProjects(
+  calendars: Calendars | null,
+  visibility: Visibility | null,
+): string[] {
+  const can = calendars?.can_create;
+  if (!can) return [];
+  return visibility === "private" ? can.project_private : can.project;
+}
+
+export function importableVisibilities(
+  category: Category | null,
+  calendars: Calendars | null,
+): Visibility[] {
+  if (category === "personal") return [];
+  if (category === "foundation") return calendars?.can_create.foundation ? ["public", "private"] : [];
+  if (category === "project") {
+    const can = calendars?.can_create;
+    if (!can) return [];
+    return can.project_private.length > 0 ? ["public", "private"] : ["public"];
+  }
+  return [];
+}
+
+export interface Readiness {
+  ready: boolean;
+  /** What the reader still has to answer, in words fit for a hint. */
+  missing: string[];
+}
+
+/**
+ * Whether the form has enough to save, and what is missing if not.
+ *
+ * Personal events have no project and no visibility to choose - they are
+ * always private to their owner - so those are not asked for.
+ */
+export function importReadiness(settings: ImportSettings, calendars: Calendars | null): Readiness {
+  const missing: string[] = [];
+
+  const categories = importableCategories(calendars);
+  if (settings.category === null) {
+    missing.push("which calendar these events belong to");
+  } else if (!categories.includes(settings.category)) {
+    missing.push("a calendar you are allowed to add to");
+  }
+
+  if (settings.category !== null && settings.category !== "personal") {
+    if (settings.visibility === null) {
+      missing.push("whether they are public or private");
+    } else if (!importableVisibilities(settings.category, calendars).includes(settings.visibility)) {
+      missing.push("a visibility you are allowed to use");
+    }
+  }
+
+  if (settings.category === "project") {
+    const projects = importableProjects(calendars, settings.visibility);
+    if (settings.project === null) {
+      missing.push("which project they belong to");
+    } else if (!projects.includes(settings.project)) {
+      missing.push("a project you are allowed to add to");
+    }
+  }
+
+  return { ready: missing.length === 0, missing };
+}
+
+/** The settings, once ready, in the shape the API takes. */
+export function resolveSettings(settings: ImportSettings): ResolvedImportSettings {
+  if (settings.category === null) throw new Error("resolveSettings called before a category was chosen");
+  return {
+    category: settings.category,
+    project: settings.category === "project" ? settings.project : null,
+    visibility: settings.category === "personal" ? null : settings.visibility,
+  };
+}
+
+/**
+ * Keeps the form consistent when the category or visibility changes: a project
+ * that is no longer offered should not stay quietly selected.
+ */
+export function reconcile(settings: ImportSettings, calendars: Calendars | null): ImportSettings {
+  const next: ImportSettings = { ...settings };
+  if (next.category !== "project") next.project = null;
+  if (next.category === "personal") next.visibility = null;
+  if (next.category === "project" && next.project !== null) {
+    if (!importableProjects(calendars, next.visibility).includes(next.project)) next.project = null;
+  }
+  if (next.visibility !== null && next.category !== null) {
+    if (!importableVisibilities(next.category, calendars).includes(next.visibility)) {
+      next.visibility = null;
+    }
+  }
+  return next;
+}
+
+/** True if the file looks like something worth sending. */
+export function looksLikeCalendar(file: File): boolean {
+  return /\.ics$/i.test(file.name) || file.type === "text/calendar";
+}
diff --git a/frontend/src/tests/components.test.ts b/frontend/src/tests/components.test.ts
index a9047d6..b535e8f 100644
--- a/frontend/src/tests/components.test.ts
+++ b/frontend/src/tests/components.test.ts
@@ -338,6 +338,7 @@ describe("Header", () => {
       onstep: noop,
       ontoday: noop,
       oncreate: noop,
+      onimport: noop,
       ontogglefilters: noop,
       onzone: noop,
       onalternatezone: noop,
diff --git a/frontend/src/tests/importdialog.test.ts b/frontend/src/tests/importdialog.test.ts
new file mode 100644
index 0000000..84b28bf
--- /dev/null
+++ b/frontend/src/tests/importdialog.test.ts
@@ -0,0 +1,300 @@
+/** The import form: preview first, then say where the events go. */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor, within } from "@testing-library/svelte";
+
+import ImportDialog from "../components/ImportDialog.svelte";
+import { makeCalendars, makeEvent } from "./factories";
+
+const noop = () => {};
+const fetchMock = vi.fn();
+
+const CANDIDATE = {
+  title: "Community call",
+  start: "2026-07-10T13:00:00Z",
+  end: "2026-07-10T14:00:00Z",
+  all_day: false,
+  description: "",
+  location: "Room 3",
+  url: "",
+  timezone: "Europe/Berlin",
+  uid: "1@t",
+  warnings: [] as string[],
+};
+
+function respond(body: unknown, status = 200) {
+  return new Response(JSON.stringify(body), {
+    status,
+    headers: { "Content-Type": "application/json" },
+  });
+}
+
+function previewOf(events = [CANDIDATE], warnings: string[] = []) {
+  return { events, count: events.length, warnings };
+}
+
+const pmcMember = makeCalendars({
+  uid: "bob",
+  projects: ["httpd"],
+  committees: ["httpd"],
+  can_create: { personal: true, project: ["httpd"], project_private: ["httpd"], foundation: false },
+});
+
+function props(overrides: Record<string, unknown> = {}) {
+  return {
+    calendars: pmcMember,
+    zone: "UTC",
+    onclose: noop,
+    onimported: noop,
+    ...overrides,
+  };
+}
+
+function icsFile(name = "events.ics") {
+  return new File(["BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n"], name, { type: "text/calendar" });
+}
+
+/** Puts a file into the dialog's file input the way a picker would. */
+async function attach(container: HTMLElement, file = icsFile()) {
+  const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;
+  Object.defineProperty(input, "files", { value: [file], configurable: true });
+  await fireEvent.change(input);
+}
+
+function importButton(): HTMLButtonElement {
+  return screen.getByRole("button", { name: /^Import/ }) as HTMLButtonElement;
+}
+
+beforeEach(() => {
+  fetchMock.mockReset();
+  vi.stubGlobal("fetch", fetchMock);
+});
+
+afterEach(() => {
+  vi.unstubAllGlobals();
+});
+
+describe("before a file is chosen", () => {
+  it("asks for one", () => {
+    render(ImportDialog, { props: props() });
+    expect(screen.getByText("Choose a file")).toBeInTheDocument();
+    expect(screen.getByText(/drop an .ics file here/)).toBeInTheDocument();
+  });
+
+  it("cannot import anything yet", () => {
+    render(ImportDialog, { props: props() });
+    expect(importButton()).toBeDisabled();
+  });
+
+  it("asks nothing about calendars yet", () => {
+    render(ImportDialog, { props: props() });
+    expect(screen.queryByLabelText("Calendar")).not.toBeInTheDocument();
+  });
+});
+
+describe("the preview", () => {
+  it("reads the file without saving it", async () => {
+    fetchMock.mockResolvedValue(respond(previewOf()));
+    const { container } = render(ImportDialog, { props: props() });
+    await attach(container);
+    await waitFor(() => expect(screen.getByText("Community call")).toBeInTheDocument());
+
+    expect(fetchMock).toHaveBeenCalledTimes(1);
+    const [url, init] = fetchMock.mock.calls[0];
+    expect(url).toBe("/api/import/preview");
+    expect(init.method).toBe("POST");
+    expect(init.body).toBeInstanceOf(FormData);
+  });
+
+  it("sends the file as multipart, letting the browser set the boundary", async () => {
+    fetchMock.mockResolvedValue(respond(previewOf()));
+    const { container } = render(ImportDialog, { props: props() });
+    await attach(container);
+    await waitFor(() => expect(fetchMock).toHaveBeenCalled());
+    const init = fetchMock.mock.calls[0][1];
+    expect(init.headers["Content-Type"]).toBeUndefined();
+    expect((init.body as FormData).get("file")).toBeInstanceOf(File);
+  });
+
+  it("shows what was found, on the reader's clock", async () => {
+    fetchMock.mockResolvedValue(respond(previewOf()));
+    const { container } = render(ImportDialog, { props: props() });
+    await attach(container);
+    await waitFor(() => expect(screen.getByText("Community call")).toBeInTheDocument());
+    expect(screen.getByText("1 event found")).toBeInTheDocument();
+    expect(screen.getByText(/10 July 2026, 13:00 - 14:00/)).toBeInTheDocument();
+    expect(screen.getByText("Room 3")).toBeInTheDocument();
+  });
+
+  it("counts several events", async () => {
+    fetchMock.mockResolvedValue(
+      respond(previewOf([CANDIDATE, { ...CANDIDATE, uid: "2@t", title: "ApacheCon" }])),
+    );
+    const { container } = render(ImportDialog, { props: props() });
+    await attach(container);
+    await waitFor(() => expect(screen.getByText("2 events found")).toBeInTheDocument());
+  });
+
+  it("shows the file's own warnings", async () => {
+    fetchMock.mockResolvedValue(respond(previewOf([CANDIDATE], ["Skipped 1 entry with no start time."])));
+    const { container } = render(ImportDialog, { props: props() });
+    await attach(container);
+    await waitFor(() =>
+      expect(screen.getByText("Skipped 1 entry with no start time.")).toBeInTheDocument(),
+    );
+  });
+
+  it("shows a warning attached to one event", async () => {
+    const repeating = { ...CANDIDATE, warnings: ["This event repeats."] };
+    fetchMock.mockResolvedValue(respond(previewOf([repeating])));
+    const { container } = render(ImportDialog, { props: props() });
+    await attach(container);
+    await waitFor(() => expect(screen.getByText("This event repeats.")).toBeInTheDocument());
+    expect(screen.getByText(/1 thing to note/)).toBeInTheDocument();
+  });
+
+  it("reports a file it cannot read", async () => {
+    fetchMock.mockResolvedValue(
+      respond({ error: "That does not look like an iCalendar (.ics) file.", field: "file" }, 400),
+    );
+    const { container } = render(ImportDialog, { props: props() });
+    await attach(container, new File(["nope"], "holiday.jpg", { type: "image/jpeg" }));
+    expect(await screen.findByRole("alert")).toHaveTextContent("does not look like an iCalendar");
+    expect(importButton()).toBeDisabled();
+  });
+});
+
+describe("choosing where the events go", () => {
+  async function withPreview() {
+    fetchMock.mockResolvedValue(respond(previewOf()));
+    const rendered = render(ImportDialog, { props: props() });
+    await attach(rendered.container);
+    await waitFor(() => expect(screen.getByText("Community call")).toBeInTheDocument());
+    return rendered;
+  }
+
+  it("will not save until a calendar is chosen", async () => {
+    await withPreview();
+    expect(importButton()).toBeDisabled();
+    expect(screen.getByRole("status")).toHaveTextContent("which calendar these events belong to");
+  });
+
+  it("offers only the calendars this session may write to", async () => {
+    await withPreview();
+    const picker = screen.getByLabelText<HTMLSelectElement>("Calendar");
+    const options = [...picker.querySelectorAll("option")].map((option) => option.value);
+    expect(options).toEqual(["", "personal", "project"]);
+  });
+
+  it("insists on a project and a visibility for a project import", async () => {
+    await withPreview();
+    await fireEvent.change(screen.getByLabelText("Calendar"), { target: { value: "project" } });
+    expect(importButton()).toBeDisabled();
+    expect(screen.getByRole("status")).toHaveTextContent("whether they are public or private");
+    expect(screen.getByRole("status")).toHaveTextContent("which project they belong to");
+  });
+
+  it("enables saving once everything is answered", async () => {
+    await withPreview();
+    await fireEvent.change(screen.getByLabelText("Calendar"), { target: { value: "project" } });
+    await fireEvent.change(screen.getByLabelText("Visibility"), { target: { value: "public" } });
+    expect(importButton()).toBeDisabled();
+    await fireEvent.change(screen.getByLabelText("Project"), { target: { value: "httpd" } });
+    expect(importButton()).toBeEnabled();
+    expect(screen.queryByRole("status")).not.toBeInTheDocument();
+  });
+
+  it("asks nothing more for a personal import", async () => {
+    await withPreview();
+    await fireEvent.change(screen.getByLabelText("Calendar"), { target: { value: "personal" } });
+    expect(screen.queryByLabelText("Visibility")).not.toBeInTheDocument();
+    expect(screen.queryByLabelText("Project")).not.toBeInTheDocument();
+    expect(screen.getByText(/always private to you/)).toBeInTheDocument();
+    expect(importButton()).toBeEnabled();
+  });
+
+  it("nothing is pre-selected, so a wrong default cannot be saved by accident", async () => {
+    await withPreview();
+    expect(screen.getByLabelText<HTMLSelectElement>("Calendar").value).toBe("");
+    await fireEvent.change(screen.getByLabelText("Calendar"), { target: { value: "project" } });
+    expect(screen.getByLabelText<HTMLSelectElement>("Visibility").value).toBe("");
+    expect(screen.getByLabelText<HTMLSelectElement>("Project").value).toBe("");
+  });
+
+  it("forgets a project that switching visibility has taken off the list", async () => {
+    const committer = makeCalendars({
+      can_create: { personal: true, project: ["httpd"], project_private: [], foundation: false },
+    });
+    fetchMock.mockResolvedValue(respond(previewOf()));
+    const { container } = render(ImportDialog, { props: props({ calendars: committer }) });
+    await attach(container);
+    await waitFor(() => expect(screen.getByText("Community call")).toBeInTheDocument());
+
+    await fireEvent.change(screen.getByLabelText("Calendar"), { target: { value: "project" } });
+    await fireEvent.change(screen.getByLabelText("Visibility"), { target: { value: "public" } });
+    await fireEvent.change(screen.getByLabelText("Project"), { target: { value: "httpd" } });
+    expect(importButton()).toBeEnabled();
+  });
+});
+
+describe("saving", () => {
+  async function readyToSave() {
+    fetchMock.mockResolvedValue(respond(previewOf()));
+    const onimported = vi.fn();
+    const rendered = render(ImportDialog, { props: props({ onimported }) });
+    await attach(rendered.container);
+    await waitFor(() => expect(screen.getByText("Community call")).toBeInTheDocument());
+    await fireEvent.change(screen.getByLabelText("Calendar"), { target: { value: "project" } });
+    await fireEvent.change(screen.getByLabelText("Visibility"), { target: { value: "private" } });
+    await fireEvent.change(screen.getByLabelText("Project"), { target: { value: "httpd" } });
+    return { ...rendered, onimported };
+  }
+
+  it("posts the file with the chosen settings", async () => {
+    const { onimported } = await readyToSave();
+    fetchMock.mockResolvedValue(respond({ created: [makeEvent()], count: 1, warnings: [] }, 201));
+    await fireEvent.click(importButton());
+    await waitFor(() => expect(onimported).toHaveBeenCalledWith(1));
+
+    const [url, init] = fetchMock.mock.calls[fetchMock.mock.calls.length - 1];
+    expect(url).toBe("/api/import");
+    const body = init.body as FormData;
+    expect(body.get("category")).toBe("project");
+    expect(body.get("visibility")).toBe("private");
+    expect(body.get("project")).toBe("httpd");
+    expect(body.get("file")).toBeInstanceOf(File);
+  });
+
+  it("says how many will be imported", async () => {
+    await readyToSave();
+    expect(importButton()).toHaveTextContent("Import 1 event");
+  });
+
+  it("reports a refusal from the server without closing", async () => {
+    const { onimported } = await readyToSave();
+    fetchMock.mockResolvedValue(
+      respond({ error: "You are not a member of the httpd project." }, 403),
+    );
+    await fireEvent.click(importButton());
+    expect(await screen.findByRole("alert")).toHaveTextContent("not a member of the httpd project");
+    expect(onimported).not.toHaveBeenCalled();
+  });
+});
+
+describe("getting out", () => {
+  it("closes on Cancel and on Escape", async () => {
+    const onclose = vi.fn();
+    render(ImportDialog, { props: props({ onclose }) });
+    await fireEvent.click(screen.getByText("Cancel"));
+    expect(onclose).toHaveBeenCalledOnce();
+    await fireEvent.keyDown(window, { key: "Escape" });
+    expect(onclose).toHaveBeenCalledTimes(2);
+  });
+
+  it("stays open when the dialog itself is clicked", async () => {
+    const onclose = vi.fn();
+    render(ImportDialog, { props: props({ onclose }) });
+    await fireEvent.click(within(screen.getByRole("dialog")).getByText(/Import events from/));
+    expect(onclose).not.toHaveBeenCalled();
+  });
+});
diff --git a/pyproject.toml b/pyproject.toml
index b36b1dd..f43f1ee 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -12,6 +12,7 @@ dependencies = [
     "aiosqlite>=0.20,<1",
     "PyYAML>=6.0.1,<7",
     "hypercorn>=0.17,<1",
+    "icalendar>=6,<8",
 ]
 
 [project.scripts]
diff --git a/uv.lock b/uv.lock
index 4749ed2..ed713cd 100644
--- a/uv.lock
+++ b/uv.lock
@@ -195,6 +195,7 @@ dependencies = [
     { name = "aiosqlite" },
     { name = "asfquart" },
     { name = "hypercorn" },
+    { name = "icalendar" },
     { name = "pyyaml" },
     { name = "tzdata" },
 ]
@@ -215,6 +216,7 @@ requires-dist = [
     { name = "aiosqlite", specifier = ">=0.20,<1" },
     { name = "asfquart", specifier = ">=0.1.12,<1" },
     { name = "hypercorn", specifier = ">=0.17,<1" },
+    { name = "icalendar", specifier = ">=6,<8" },
     { name = "pyyaml", specifier = ">=6.0.1,<7" },
     { name = "tzdata", specifier = ">=2024.1" },
 ]
@@ -992,6 +994,20 @@ wheels = [
     { url = "https://files.pythonhosted.org/packages/48/30/47d0bf6072f7252e6521f3447ccfa40b421b6824517f82854703d0f5a98b/hyperframe-6.1.0-py3-none-any.whl", hash = "sha256:b03380493a519fce58ea5af42e4a42317bf9bd425596f7a0835ffce80f1a42e5", size = 13007, upload-time = "2025-01-22T21:41:47.295Z" },
 ]
 
+[[package]]
+name = "icalendar"
+version = "7.3.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+    { name = "python-dateutil" },
+    { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+    { name = "tzdata" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/47/2b/1bbf82d316df18c3331d9a06228819c8a5814ceda545a3e9980e52ffce1b/icalendar-7.3.0.tar.gz", hash = "sha256:7bd001c8e648205e1bde5c6a5b77096598e8d0893dcf57755c6c597635620132", size = 525811, upload-time = "2026-08-19T15:10:21.05Z" }
+wheels = [
+    { url = "https://files.pythonhosted.org/packages/bb/82/50bff78b0bb0c7d7c0cb39e0ee189b92f611fff6bd7cf57f25e92d5a7551/icalendar-7.3.0-py3-none-any.whl", hash = "sha256:8355acfe17be81b368f0b1e3740817cea9b56ea889931f8f1a87c62f2d28db0b", size = 542540, upload-time = "2026-08-19T15:10:19.525Z" },
+]
+
 [[package]]
 name = "idna"
 version = "3.19"
@@ -1911,6 +1927,18 @@ wheels = [
     { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" },
 ]
 
+[[package]]
+name = "python-dateutil"
+version = "2.9.0.post0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+    { name = "six" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }
+wheels = [
+    { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },
+]
+
 [[package]]
 name = "python-dotenv"
 version = "1.2.3"