Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ may want to subscribe to `GitHub's tag feed
0.14.2
======
unreleased
* FIX importing a ``METHOD:CANCEL`` for one recurrence no longer replaces the full series
* FIX ``khal import --format``/``-f`` was accepted and then ignored, always
falling back to ``view.event_format``

Expand Down
53 changes: 49 additions & 4 deletions khal/controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,14 +697,53 @@ def import_ics(collection, conf, ics, batch=False, random_uid=False, format=None
if format is None:
format = conf["view"]["event_format"]
try:
method = str(cal_from_ics(ics).get("METHOD", "")).upper()
vevents = split_ics(ics, random_uid, conf["locale"]["default_timezone"])
except Exception as error:
raise FatalError(error)
for vevent in vevents:
import_event(vevent, collection, conf["locale"], batch, format, env)
import_event(vevent, collection, conf["locale"], batch, format, env, method)


def import_event(vevent, collection, locale, batch, format=None, env=None):
def _merge_cancelled_recurrences(existing_ics, cancellation_ics):
existing_calendar = cal_from_ics(existing_ics)
cancellation_calendar = cal_from_ics(cancellation_ics)
cancellations = [
component for component in cancellation_calendar.walk() if component.name == "VEVENT"
]
if not cancellations or any("RECURRENCE-ID" not in event for event in cancellations):
return None

timezone_ids = {
str(component["TZID"])
for component in existing_calendar.subcomponents
if component.name == "VTIMEZONE"
}
for component in cancellation_calendar.subcomponents:
if component.name == "VTIMEZONE" and str(component["TZID"]) not in timezone_ids:
existing_calendar.add_component(component)
timezone_ids.add(str(component["TZID"]))

for event in cancellations:
event["STATUS"] = "CANCELLED"

existing_calendar.subcomponents[:] = [
component
for component in existing_calendar.subcomponents
if component.name != "VEVENT"
or "RECURRENCE-ID" not in component
or not any(
component["RECURRENCE-ID"].dt == cancellation["RECURRENCE-ID"].dt
and component["RECURRENCE-ID"].params == cancellation["RECURRENCE-ID"].params
for cancellation in cancellations
)
]
for event in cancellations:
existing_calendar.add_component(event)
return existing_calendar.to_ical().decode("utf-8")


def import_event(vevent, collection, locale, batch, format=None, env=None, method=None):
"""import one event into collection, let user choose the collection

:type vevent: list of vevents, which can be more than one VEVENT, i.e., the
Expand Down Expand Up @@ -749,11 +788,17 @@ def import_event(vevent, collection, locale, batch, format=None, env=None):
if batch or confirm(f"Do you want to import this event into `{calendar_name}`?"):
try:
collection.insert(Item(vevent), collection=calendar_name)
except DuplicateUid:
except DuplicateUid as error:
if batch or confirm(
"An event with the same UID already exists. Do you want to update it?"
):
collection.force_update(Item(vevent), collection=calendar_name)
item = Item(vevent)
if method == "CANCEL" and error.args:
existing_event = collection.get_event(error.args[0], calendar_name)
merged = _merge_cancelled_recurrences(existing_event.raw, vevent)
if merged is not None:
item = Item(merged)
collection.force_update(item, collection=calendar_name)
else:
logger.warning(f"Not importing event with UID `{event.uid}`")

Expand Down
44 changes: 44 additions & 0 deletions tests/controller_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,50 @@ def test_import(self, coll_vdirs):
ev.start_local for ev in events
]

def test_import_cancelled_single_recurrence(self, coll_vdirs):
coll, _vdirs = coll_vdirs
conf = {"locale": utils.LOCALE_BERLIN, "view": {"event_format": "{title}"}}
series = """BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:cancel-single-instance
DTSTAMP:20260419T120000Z
DTSTART;TZID=Europe/Berlin:20260420T130000
DTEND;TZID=Europe/Berlin:20260420T134000
RRULE:FREQ=DAILY;COUNT=3
SUMMARY:Test2
END:VEVENT
END:VCALENDAR
"""
cancellation = """BEGIN:VCALENDAR
VERSION:2.0
METHOD:CANCEL
BEGIN:VEVENT
UID:cancel-single-instance
DTSTAMP:20260419T120000Z
RECURRENCE-ID;TZID=Europe/Berlin:20260421T130000
DTSTART;TZID=Europe/Berlin:20260421T130000
DTEND;TZID=Europe/Berlin:20260421T134000
SUMMARY:Test2
STATUS:CANCELLED
END:VEVENT
END:VCALENDAR
"""

import_ics(coll, conf, series, batch=True)
import_ics(coll, conf, cancellation, batch=True)
import_ics(coll, conf, cancellation, batch=True)

start = utils.BERLIN.localize(dt.datetime(2026, 4, 20))
end = utils.BERLIN.localize(dt.datetime(2026, 4, 23))
events = sorted(coll.get_localized(start, end))
assert [event.start_local for event in events] == [
utils.BERLIN.localize(dt.datetime(2026, 4, 20, 13)),
utils.BERLIN.localize(dt.datetime(2026, 4, 21, 13)),
utils.BERLIN.localize(dt.datetime(2026, 4, 22, 13)),
]
assert [event.status for event in events] == ["", "CANCELLED", ""]

def test_mix_datetime_types(self, coll_vdirs):
"""
Test importing events with mixed tz-aware and tz-naive datetimes.
Expand Down