summaryrefslogtreecommitdiff
path: root/internal/api/ics_client.go
blob: 857fa8f8a8d50ee0a407ecb73de3d7c124113e00 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
	}
}