package api import ( "context" "fmt" "io" "net/http" "time" "task-dashboard/internal/models" ) // ICSFetcher retrieves and parses a remote iCalendar feed. type ICSFetcher struct { client *http.Client } // NewICSFetcher builds a fetcher with a bounded timeout. func NewICSFetcher(timeout time.Duration) *ICSFetcher { return &ICSFetcher{client: &http.Client{Timeout: timeout}} } // maxICSBytes caps how much of a feed is read. A calendar is small; anything // enormous is a misconfigured URL pointing at something else, and reading it // all into memory would be the only harm it does. const maxICSBytes = 8 << 20 // 8 MiB // Fetch downloads the feed at url and returns its events. // // The context is threaded into the request, so a hung feed cannot outlive the // refresh that started it — see internal/api/context_audit_test.go for why that // matters here. func (f *ICSFetcher) Fetch(ctx context.Context, url string) ([]ICSEvent, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, fmt.Errorf("building request: %w", err) } // Some publishers serve HTML to unknown agents and the calendar only to // something that looks like a calendar client. req.Header.Set("Accept", "text/calendar, text/plain;q=0.9, */*;q=0.8") req.Header.Set("User-Agent", "doot/1.0 (+https://doot.terst.org)") resp, err := f.client.Do(req) if err != nil { return nil, fmt.Errorf("fetching feed: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("feed returned HTTP %d", resp.StatusCode) } events, err := ParseICS(io.LimitReader(resp.Body, maxICSBytes)) if err != nil { return nil, fmt.Errorf("parsing feed: %w", err) } return events, nil } // ToCalendarEvents converts parsed ICS events into the model the timeline // already renders, so feed events need no special handling downstream. // // feedID scopes the generated ids; feedName is prefixed to each title so a // bare fixture like "Seahawks at 49ers" is identifiable on a mixed timeline. func ToCalendarEvents(feedID, feedName string, events []ICSEvent) []models.CalendarEvent { out := make([]models.CalendarEvent, 0, len(events)) for _, e := range events { summary := e.Summary if summary == "" { summary = feedName } out = append(out, models.CalendarEvent{ ID: e.StableID(feedID), Summary: summary, Description: descriptionWithLocation(e), Start: e.Start, End: e.End, }) } return out } func descriptionWithLocation(e ICSEvent) string { switch { case e.Location == "": return e.Description case e.Description == "": return e.Location default: return e.Description + "\n" + e.Location } }