Skip to content

[Bug] Calendar parsed prior to filtering - unable to load large ics file #4103

Closed

Description

@Evarda

Environment

Hi, long time user. Don't think you need my system info for this one, so I'm going to skip this. I updated recently and pulled the code below from the main version of the Git Repo.
I have an issue with a calendar I've used for many years, has many events. All my other calendars work fine, all of my new calendars work fine. I run this on a raspberry pi with decent specs but also run my homebridge on it. This calendar used to be the slowest to load - one day it just stopped loading and has not loaded since.
I noticed the calendar fetcher parses the entire ical and then filters the events.
Can we fix this to make the filter happen when the calendar is loaded rather than loading the information first then filtering it?
I am fairly certain my calendar not loading is related to this. I have also seen others report calendar not loading issues, and I wonder if this is the root cause (I'm not sure what limits the size of parsed).

This is in calendarfetcher.js, see how it loads the ics and then parses after:

try {

			const responseData = await response.text();
			const parsed = ical.parseICS(responseData);

			Log.debug(`Parsed iCal data from ${this.url} with ${Object.keys(parsed).length} entries.`);

			this.events = CalendarFetcherUtils.filterEvents(parsed, {
				excludedEvents: this.excludedEvents,
				includePastEvents: this.includePastEvents,
				maximumEntries: this.maximumEntries,
				maximumNumberOfDays: this.maximumNumberOfDays
			});

I feel like this is what is causing the problem.
Hopefully this is possible to do and wouldn't be problematic to implement!

Which start option are you using?

node --run server

Are you using PM2?

No

Module

None

Have you tried disabling other modules?

  • Yes
  • No

Have you searched if someone else has already reported the issue on the forum or in the issues?

  • Yes

What did you do?

Reproduce:
Have big old calendar file; try to load; have it never load.
Have many new calendar files; no problems loading

To be fair, I haven't checked the size of the big old calendar file, but I know it has a lot of events on it...

What did you expect to happen?

I expect calendar to load.

What actually happened?

Calendar events do not load. No error.

Additional comments

Sorry I'm not doing a great job filling out the fields with all my system information for this. If this is not the reason, I'm back to the drawing board on this issue... I'm hoping that pointing out the issue in data handling I believe is causing this issue will fix the bug I'm running into.

Also thank you!! :)

Participation

  • I am willing to submit a pull request for this change.

Activity

  1. KristjanESPERANTO commented on Apr 25, 2026

    @KristjanESPERANTO
    Collaborator

    @Evarda Thank you for the report, and also for offering to open a PR. That would be welcome! 🙂

    Your idea about improving handling for large ICS files makes sense. If you’d like, feel free to try an initial approach. It doesn't have to be perfect right away; the main thing is that the general approach is clear and works as a proof of concept.

  2. sdetweil commented on May 1, 2026

    @sdetweil
    Collaborator

    some food for thought
    the blob we load is all text .

    you can see it and count the events with

    curl -sL your_calendar_url_here >cal.txt
    

    then you can count how many begin and end events there are

    grep -i "begin:vevent" cal.txt | wc -l
    grep -i "end:vevent" cal.txt | wc -l
    

    my personal calendar has 1112 events. over 13 years.
    an event looks like this

    BEGIN:VEVENT
    DTSTART:20221215T164500Z
    DTEND:20221215T220000Z
    DTSTAMP:20260501T221936Z
    UID:cdijap9icpj3ib9oc4r3gb9k6cojebb26lgjibb2cdijed1i68om2or66k@google.com
    CREATED:20221201T222727Z
    LAST-MODIFIED:20221215T162845Z
    SEQUENCE:0
    STATUS:CONFIRMED
    SUMMARY:wharever the text was 
    TRANSP:OPAQUE
    X-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC
    BEGIN:VALARM
    ACTION:NONE
    TRIGGER;VALUE=DATE-TIME:19760401T005545Z
    X-WR-ALARMUID:484D273D-D427-4C1A-9A28-D9324037E051
    UID:484D273D-D427-4C1A-9A28-D9324037E051
    ACKNOWLEDGED:20221215T162845Z
    X-APPLE-DEFAULT-ALARM:TRUE
    END:VALARM
    END:VEVENT
    

    to filter, we need to use the

    DTSTART:20221215T164500Z
    

    line, in each event
    a search and AI conversation produced a function like this

    /**
     * Filters a large ics string without creating new large arrays.
     * @param {string} icsString - The raw ics text already in memory.
     *  @param {string} first_event_date - text YYYYMMDD string of the beginning of the accepted event dates
     */
    function* filterIcsGenerator(icsString, first_event_date) {
        // 1. Find the header (everything before the first VEVENT)
        const firstEventIndex = icsString.indexOf("BEGIN:VEVENT");
        // if we didn't find any events, return the full input text
        if (firstEventIndex === -1) {
            yield icsString;
            return;
        }
        // send all the text before the 1st event
        yield icsString.slice(0, firstEventIndex);
    
        // 2. Scan for VEVENT blocks using a global regex
       
        const eventRegex = /BEGIN:VEVENT[\s\S]*?END:VEVENT/g;
        let match;
    
         // get each event content thru END:VEVENT
        while ((match = eventRegex.exec(icsString)) !== null) {
            const eventBody = match[0];
    
            // if the event has an RRULE, always pass it on 
            if(eventBody.indexOf("RRULE:")>0({ 
                yield eventBody + "\n";
                continue
            }
               
            // Find DTSTART within this specific event block
            // no  RRULE, extract the start date
            const dtMatch = eventBody.match(/DTSTART[;:][^:]*(\d{8})/);
            
            // if we found it, some events don't have start dates.. 
            if (dtMatch) {
                const dateValue = parseInt(dtMatch[1], 10);   <--- 
                // if the event date is on or after the input start of filter date
                if (dateValue >= first_event_date) {  <----  I added the start date text string,, need to get into proper compare format
                    // add it to the output
                    yield eventBody + "\n";
                }
            }
        }
    
        // no more events
        // 3. Add footer
        yield "END:VCALENDAR";
    }
    
    let start_date="20240701"
    // Usage:
    const largeIcsText = "..."; // Your text in memory  <---- text from fetch request 
    let result =  "";
    
    for (const chunk of filterIcsGenerator(largeIcsText, start_date)) {
        // Append to a result string, write to a stream, or log
        result += chunk; 
    }
    

    this will add another complete pass of the text to get all the requested events.. as the source (google, et al) does not provide a mechanism to pre-filter before download
    then the ics parser will do a complete pass to turn the text into object before we can process it

    this filtered my cal from 1112 events to 177

  3. sdetweil commented on May 4, 2026

    @sdetweil
    Collaborator

    There is a problem with this approach

    If there is an event that starts outside the filter range, but has a repeating cycle that presents an event inside the calendar view range. It will be dropped from the processing list, because we are not yet processing rrule events (until after parse)

    Consider your new child’s birthday, added 5 yrs ago
    Anniversary, etc.

  4. sdetweil commented on May 4, 2026

    @sdetweil
    Collaborator

    I actually had a couple in my cal with this condition, and updated the filter (see edit above) to send all events with RRULE thru.
    changed the count from 177 to 217, still a lot less than 1112

    on my AMD 5950x the filter took 1243 ms
    on my pi4 (running MM) it took 8624 ms
    using this little script, the events were previously downloaded, so this doesn't count extract from source or transmission time

    #!/bin/bash
    full_count=$(grep "BEGIN:VEVENT" cal.txt | wc -l)
    start=$(date +%s%3N)
    node filter_ical.js >somefile.txt
    end=$(date +%s%3N)
    filtered_count=$(grep "BEGIN:VEVENT" somefile.txt | wc -l)
    echo "Duration: $((end - start)) ms from $full_count to $filtered_count"
    

    this will output the before and after filter count of events and the elapsed time to run the filter
    the downloaded event list is called cal.txt

    this did count the filesystem time to read the file into memory

  5. KristjanESPERANTO commented on May 6, 2026

    @KristjanESPERANTO
    Collaborator

    @Evarda Are you working on this? 🙂

  6. sdetweil commented on May 6, 2026

    @sdetweil
    Collaborator

    the CPU elapsed time cost for the filter is bad.
    so I thought of another approach, which doesn't cleanly work with a regex..

    search for the 1st occurrence of the date, and take that match.index as the start of the events to copy.

    but after looking at my ical data, the events are not in date order

    BEGIN:VEVENT
    DTSTART:20250410T220000Z <--- 2025
    DTEND:20250410T230000Z
    DTSTAMP:20260501T221936Z
    ORGANIZER;[email protected]:mailto:[email protected]
    UID:[email protected]
    ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;CN=sdetwe
     [email protected];X-NUM-GUESTS=0:mailto:[email protected]
    ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;CN=kkenne
     [email protected];X-NUM-GUESTS=0:mailto:[email protected]
    ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;CN=junewo
     [email protected];X-NUM-GUESTS=0:mailto:[email protected]
    X-GOOGLE-CONFERENCE:https://meet.google.com/mfu-xjbq-epk
    CREATED:20250319T152935Z
    DESCRIPTION:Join with Google Meet: https://meet.google.com/mfu-xjbq-epk\n\n
     Learn more about Meet at: https://support.google.com/a/users/answer/9282720
    LAST-MODIFIED:20250319T153216Z
    LOCATION:1408 Cora Marie Cove\, Pflugerville\, TX 78660\, USA
    SEQUENCE:1
    STATUS:CONFIRMED
    SUMMARY:dinner
    TRANSP:OPAQUE
    END:VEVENT
    
    BEGIN:VEVENT
    DTSTART:20241001T230000Z  <2024,  after 2025 <----- 
    
  7. KristjanESPERANTO commented on May 25, 2026

    @KristjanESPERANTO
    Collaborator

    I was eager to work on a solution myself, and since @Evarda didn't opened a PR, I've now created one: #4168.

    It's a bit complex, and I'm not sure if it's worth increasing the complexity of our codebase,

  8. sdetweil commented on May 25, 2026

    @sdetweil
    Collaborator

    I don’t think this is a cpu issue, I think this is a memory issue.

    I’ve only seen this reported 3 times now over the years.

    One solution was to build an external scraper (cron job) to fetch and filter to a file which was read by calendar. At least this removes the processing time delay out of the main path

  9. KristjanESPERANTO commented on May 25, 2026

    @KristjanESPERANTO
    Collaborator

    An external scraper would have a real advantage for users who restart MM often - the file is already there, no download needed. But since this problem seems rare and most users don't restart frequently, the added complexity of managing a cron job outside of MagicMirror probably isn't worth it.

    I think pre-filtering during the fetch cycle would solve the issue good enough - the question is only whether we use our own implementation (like PR #4168) or an external package (like ics-filter) - both with zero additional setup for the user.

  10. sdetweil commented on May 26, 2026

    @sdetweil
    Collaborator

    an external scraper has to download every time, as the calendar events will change..

    as you said before, do we want to carry the code burden of this..

    pm2 supports cron now too..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions