85 lines
2.3 KiB
Go
85 lines
2.3 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"net/url"
|
|
"pageswiki/internal/calendar"
|
|
"sort"
|
|
"time"
|
|
)
|
|
|
|
func (s *Server) handleCalendarUpcoming(w http.ResponseWriter, r *http.Request, repo *calendar.Repository, domain, actor string) {
|
|
w.Header().Set("Cache-Control", "private, no-store")
|
|
if r.Method != http.MethodGet {
|
|
w.Header().Set("Allow", "GET")
|
|
w.WriteHeader(405)
|
|
return
|
|
}
|
|
if actor == "" {
|
|
calendarError(w, calendar.ErrForbidden)
|
|
return
|
|
}
|
|
cs, err := repo.List(domain, actor)
|
|
if err != nil {
|
|
calendarError(w, err)
|
|
return
|
|
}
|
|
defaults, err := repo.Defaults(domain, actor)
|
|
if err != nil {
|
|
calendarError(w, err)
|
|
return
|
|
}
|
|
if len(defaults) == 0 && len(cs) > 0 {
|
|
defaults = []string{cs[0].ID}
|
|
}
|
|
selected := map[string]bool{}
|
|
for _, id := range defaults {
|
|
selected[id] = true
|
|
}
|
|
type entry struct {
|
|
calendar.Event
|
|
Calendar string `json:"calendar"`
|
|
Href string `json:"href"`
|
|
}
|
|
events := []entry{}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
|
defer cancel()
|
|
// Calendar day boundaries use the configured Domain timezone, including
|
|
// 23/25-hour DST days. The browser sends a civil date only as a hint.
|
|
location := s.getLocation(domain)
|
|
now := time.Now().In(location)
|
|
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, location)
|
|
start := today
|
|
if raw := r.URL.Query().Get("date"); raw != "" {
|
|
day, e := time.ParseInLocation("2006-01-02", raw, location)
|
|
if e != nil || day.Before(today.AddDate(0, 0, -2)) || day.After(today.AddDate(0, 0, 1)) {
|
|
calendarError(w, calendar.ErrInvalid)
|
|
return
|
|
}
|
|
start = day
|
|
}
|
|
end := start.AddDate(0, 0, 31)
|
|
if r.URL.Query().Get("period") == "day" {
|
|
end = start.AddDate(0, 0, 1)
|
|
}
|
|
for _, c := range cs {
|
|
if !selected[c.ID] {
|
|
continue
|
|
}
|
|
items, e := repo.Upcoming(ctx, domain, c.ID, actor, start, end)
|
|
if e != nil {
|
|
calendarError(w, e)
|
|
return
|
|
}
|
|
for _, event := range items {
|
|
events = append(events, entry{Event: event, Calendar: c.Name, Href: "/v/plan/event/" + url.PathEscape(event.UID) + "?calendar=" + url.QueryEscape(c.PrettyName)})
|
|
}
|
|
}
|
|
sort.SliceStable(events, func(i, j int) bool { return events[i].Start.Before(events[j].Start) })
|
|
if len(events) > 20 {
|
|
events = events[:20]
|
|
}
|
|
writeEventJSON(w, 200, map[string]any{"events": events})
|
|
}
|