Client-side backup of caldav/carddav?

Suppose I am an unprivileged user of Nextcloud instance that has the Contacts and Calendar apps enabled. (That is, I am not an administrator of the instance, nor do I have SSH access to the server.)

I can manually download a backup of my contacts and calendar through the web GUI. However, I would like to do this programmatically (e.g. from a cron job). How can I do this?

I am looking for solutions on all platforms that support the official Nextcloud client app (so Windows, Mac, and Linux).

If you are on the link, you can show the link, for contacts:
https://nextcloud.example.net/remote.php/dav/addressbooks/users/username/default/?export

Can’t you use that?

Alternative: Use a script language that can handle calDAV/cardDAV. chatGPT and others can help you, but be sure to test it.

chatGPT with a python solution (untested):

import caldav
from caldav.elements import dav, cdav
from icalendar import Calendar
from datetime import datetime

# Replace these values with your CalDAV server details
caldav_url = "https://example.com/path/to/caldav/"
username = "your_username"
password = "your_password"

# Connect to CalDAV server
client = caldav.DAVClient(url=caldav_url, username=username, password=password)
principal = client.principal()

# Replace this with your calendar URL
calendar_url = "https://example.com/path/to/calendar.ics"
calendar = principal.calendar(url=calendar_url)

# Function to backup all calendar data
def backup_calendar_data(output_folder):
    # Create the output folder if it doesn't exist
    os.makedirs(output_folder, exist_ok=True)

    # Get all events in the calendar
    all_events = calendar.date_search(datetime(1970, 1, 1), datetime(2030, 1, 1))

    for event in all_events:
        # Get the event data
        event_data = event.data
        event_ical = Calendar.from_ical(event_data)

        # Extract event details
        event_component = event_ical.subcomponents[0]
        event_summary = event_component.get('summary', 'Untitled')
        event_uid = event_component.get('uid')

        # Save the event to a file
        output_file_path = os.path.join(output_folder, f"{event_uid}.ics")
        with open(output_file_path, 'wb') as output_file:
            output_file.write(event_data)

# Example usage:
# Replace this with the desired output folder
backup_folder = "path/to/backup"
backup_calendar_data(backup_folder)

Check out calcardbackup. I’ve been using it for several yerars. I’ve even written a cron job to update it from time to time.

2 Likes