Add OpenAPI docs, frontend, migrations, and API updates
- OpenAPI: add missing endpoints (add-from-url, subscriptions, public availability) - OpenAPI: CalendarSubscription schema, Subscriptions tag - Frontend app - Migrations: count_for_availability, subscriptions_sync, user_preferences, calendar_settings - Config, rate limit, auth, calendar, booking, ICS, availability, user service updates Made-with: Cursor
This commit is contained in:
@@ -2,9 +2,11 @@ package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -59,7 +61,7 @@ func (h *ICSHandler) PublicFeed(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
cal, err := h.queries.GetCalendarByPublicToken(r.Context(), pgtype.Text{String: token, Valid: true})
|
||||
cal, err := h.queries.GetCalendarByToken(r.Context(), pgtype.Text{String: token, Valid: true})
|
||||
if err != nil {
|
||||
utils.WriteError(w, models.ErrNotFound)
|
||||
return
|
||||
@@ -243,32 +245,23 @@ func (h *ICSHandler) ImportURL(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(fetchURL, "webcal://") {
|
||||
fetchURL = "https://" + strings.TrimPrefix(fetchURL, "webcal://")
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Get(fetchURL)
|
||||
if err != nil {
|
||||
utils.WriteError(w, models.NewValidationError("failed to fetch URL: "+err.Error()))
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
utils.WriteError(w, models.NewValidationError(fmt.Sprintf("URL returned status %d", resp.StatusCode)))
|
||||
return
|
||||
if normalized, ok := normalizeGoogleCalendarURL(fetchURL); ok {
|
||||
fetchURL = normalized
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20))
|
||||
if err != nil {
|
||||
utils.WriteError(w, models.ErrInternal)
|
||||
body, fetchErr := fetchICSURL(fetchURL)
|
||||
if fetchErr != nil {
|
||||
utils.WriteError(w, models.NewValidationError(fetchErr.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
count := h.importICSData(r.Context(), string(body), calID, userID)
|
||||
|
||||
h.queries.CreateCalendarSubscription(r.Context(), repository.CreateCalendarSubscriptionParams{
|
||||
ID: utils.ToPgUUID(uuid.New()),
|
||||
CalendarID: utils.ToPgUUID(calID),
|
||||
SourceUrl: req.URL,
|
||||
ID: utils.ToPgUUID(uuid.New()),
|
||||
CalendarID: utils.ToPgUUID(calID),
|
||||
SourceUrl: req.URL,
|
||||
SyncIntervalMinutes: pgtype.Int4{Valid: false},
|
||||
})
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, map[string]interface{}{
|
||||
@@ -278,6 +271,428 @@ func (h *ICSHandler) ImportURL(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ICSHandler) AddFromURL(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := middleware.GetUserID(r.Context())
|
||||
|
||||
var req struct {
|
||||
URL string `json:"url"`
|
||||
Name *string `json:"name"`
|
||||
Color *string `json:"color"`
|
||||
}
|
||||
if err := utils.DecodeJSON(r, &req); err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
req.URL = strings.TrimSpace(req.URL)
|
||||
if req.URL == "" {
|
||||
utils.WriteError(w, models.NewValidationError("url is required"))
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(req.URL, "http://") && !strings.HasPrefix(req.URL, "https://") && !strings.HasPrefix(req.URL, "webcal://") {
|
||||
utils.WriteError(w, models.NewValidationError("url must be http, https, or webcal"))
|
||||
return
|
||||
}
|
||||
|
||||
fetchURL := req.URL
|
||||
if strings.HasPrefix(fetchURL, "webcal://") {
|
||||
fetchURL = "https://" + strings.TrimPrefix(fetchURL, "webcal://")
|
||||
}
|
||||
if normalized, ok := normalizeGoogleCalendarURL(fetchURL); ok {
|
||||
fetchURL = normalized
|
||||
}
|
||||
|
||||
body, fetchErr := fetchICSURL(fetchURL)
|
||||
if fetchErr != nil {
|
||||
utils.WriteError(w, models.NewValidationError(fetchErr.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
name := "Imported Calendar"
|
||||
if req.Name != nil && *req.Name != "" {
|
||||
name = *req.Name
|
||||
}
|
||||
color := "#3B82F6"
|
||||
if req.Color != nil && *req.Color != "" {
|
||||
if err := utils.ValidateColor(*req.Color); err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
color = *req.Color
|
||||
}
|
||||
|
||||
cal, err := h.calSvc.Create(r.Context(), userID, name, color)
|
||||
if err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
calID := cal.ID
|
||||
|
||||
count := h.importICSData(r.Context(), string(body), calID, userID)
|
||||
|
||||
h.queries.CreateCalendarSubscription(r.Context(), repository.CreateCalendarSubscriptionParams{
|
||||
ID: utils.ToPgUUID(uuid.New()),
|
||||
CalendarID: utils.ToPgUUID(calID),
|
||||
SourceUrl: req.URL,
|
||||
SyncIntervalMinutes: pgtype.Int4{Valid: false},
|
||||
})
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"ok": true,
|
||||
"calendar": cal,
|
||||
"imported": map[string]int{"events": count},
|
||||
"source": req.URL,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ICSHandler) ListSubscriptions(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := middleware.GetUserID(r.Context())
|
||||
calID, err := utils.ValidateUUID(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.calSvc.GetRole(r.Context(), calID, userID); err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
subs, err := h.queries.ListSubscriptionsByCalendar(r.Context(), utils.ToPgUUID(calID))
|
||||
if err != nil {
|
||||
utils.WriteError(w, models.ErrInternal)
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]map[string]interface{}, len(subs))
|
||||
for i, s := range subs {
|
||||
syncMins := (*int32)(nil)
|
||||
if s.SyncIntervalMinutes.Valid {
|
||||
syncMins = &s.SyncIntervalMinutes.Int32
|
||||
}
|
||||
lastSynced := ""
|
||||
if s.LastSyncedAt.Valid {
|
||||
lastSynced = s.LastSyncedAt.Time.Format(time.RFC3339)
|
||||
}
|
||||
items[i] = map[string]interface{}{
|
||||
"id": utils.FromPgUUID(s.ID),
|
||||
"calendar_id": utils.FromPgUUID(s.CalendarID),
|
||||
"source_url": s.SourceUrl,
|
||||
"last_synced_at": lastSynced,
|
||||
"sync_interval_minutes": syncMins,
|
||||
"created_at": s.CreatedAt.Time.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"items": items,
|
||||
"page": map[string]interface{}{"limit": 100, "next_cursor": nil},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ICSHandler) AddSubscription(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := middleware.GetUserID(r.Context())
|
||||
calID, err := utils.ValidateUUID(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
role, err := h.calSvc.GetRole(r.Context(), calID, userID)
|
||||
if err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
if role != "owner" && role != "editor" {
|
||||
utils.WriteError(w, models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
URL string `json:"url"`
|
||||
SyncIntervalMinutes *int32 `json:"sync_interval_minutes"`
|
||||
}
|
||||
if err := utils.DecodeJSON(r, &req); err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
if req.URL == "" {
|
||||
utils.WriteError(w, models.NewValidationError("url is required"))
|
||||
return
|
||||
}
|
||||
if !strings.HasPrefix(req.URL, "http://") && !strings.HasPrefix(req.URL, "https://") && !strings.HasPrefix(req.URL, "webcal://") {
|
||||
utils.WriteError(w, models.NewValidationError("url must be http, https, or webcal"))
|
||||
return
|
||||
}
|
||||
|
||||
fetchURL := req.URL
|
||||
if strings.HasPrefix(fetchURL, "webcal://") {
|
||||
fetchURL = "https://" + strings.TrimPrefix(fetchURL, "webcal://")
|
||||
}
|
||||
if normalized, ok := normalizeGoogleCalendarURL(fetchURL); ok {
|
||||
fetchURL = normalized
|
||||
}
|
||||
|
||||
body, fetchErr := fetchICSURL(fetchURL)
|
||||
if fetchErr != nil {
|
||||
utils.WriteError(w, models.NewValidationError(fetchErr.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
count := h.importICSData(r.Context(), string(body), calID, userID)
|
||||
|
||||
syncMins := pgtype.Int4{Valid: false}
|
||||
if req.SyncIntervalMinutes != nil && *req.SyncIntervalMinutes > 0 {
|
||||
syncMins = pgtype.Int4{Int32: *req.SyncIntervalMinutes, Valid: true}
|
||||
}
|
||||
|
||||
h.queries.CreateCalendarSubscription(r.Context(), repository.CreateCalendarSubscriptionParams{
|
||||
ID: utils.ToPgUUID(uuid.New()),
|
||||
CalendarID: utils.ToPgUUID(calID),
|
||||
SourceUrl: req.URL,
|
||||
SyncIntervalMinutes: syncMins,
|
||||
})
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"ok": true,
|
||||
"imported": map[string]int{"events": count},
|
||||
"source": req.URL,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *ICSHandler) DeleteSubscription(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := middleware.GetUserID(r.Context())
|
||||
calID, err := utils.ValidateUUID(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
subID, err := utils.ValidateUUID(chi.URLParam(r, "subId"))
|
||||
if err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.calSvc.GetRole(r.Context(), calID, userID); err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
sub, err := h.queries.GetSubscriptionByID(r.Context(), utils.ToPgUUID(subID))
|
||||
if err != nil {
|
||||
utils.WriteError(w, models.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if utils.FromPgUUID(sub.CalendarID) != calID {
|
||||
utils.WriteError(w, models.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.queries.DeleteSubscription(r.Context(), utils.ToPgUUID(subID)); err != nil {
|
||||
utils.WriteError(w, models.ErrInternal)
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteOK(w)
|
||||
}
|
||||
|
||||
func (h *ICSHandler) SyncSubscription(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := middleware.GetUserID(r.Context())
|
||||
calID, err := utils.ValidateUUID(chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
subID, err := utils.ValidateUUID(chi.URLParam(r, "subId"))
|
||||
if err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
role, err := h.calSvc.GetRole(r.Context(), calID, userID)
|
||||
if err != nil {
|
||||
utils.WriteError(w, err)
|
||||
return
|
||||
}
|
||||
if role != "owner" && role != "editor" {
|
||||
utils.WriteError(w, models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
sub, err := h.queries.GetSubscriptionByID(r.Context(), utils.ToPgUUID(subID))
|
||||
if err != nil {
|
||||
utils.WriteError(w, models.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if utils.FromPgUUID(sub.CalendarID) != calID {
|
||||
utils.WriteError(w, models.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
fetchURL := sub.SourceUrl
|
||||
if strings.HasPrefix(fetchURL, "webcal://") {
|
||||
fetchURL = "https://" + strings.TrimPrefix(fetchURL, "webcal://")
|
||||
}
|
||||
if normalized, ok := normalizeGoogleCalendarURL(fetchURL); ok {
|
||||
fetchURL = normalized
|
||||
}
|
||||
|
||||
body, fetchErr := fetchICSURL(fetchURL)
|
||||
if fetchErr != nil {
|
||||
utils.WriteError(w, models.NewValidationError(fetchErr.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
count := h.importICSData(r.Context(), string(body), calID, userID)
|
||||
|
||||
if err := h.queries.UpdateSubscriptionLastSynced(r.Context(), utils.ToPgUUID(subID)); err != nil {
|
||||
utils.WriteError(w, models.ErrInternal)
|
||||
return
|
||||
}
|
||||
|
||||
utils.WriteJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"ok": true,
|
||||
"imported": map[string]int{"events": count},
|
||||
})
|
||||
}
|
||||
|
||||
// SyncSubscriptionBackground performs a subscription sync (used by background worker).
|
||||
func (h *ICSHandler) SyncSubscriptionBackground(ctx context.Context, subscriptionID string) error {
|
||||
subID, err := uuid.Parse(subscriptionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sub, err := h.queries.GetSubscriptionByID(ctx, utils.ToPgUUID(subID))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
calID := utils.FromPgUUID(sub.CalendarID)
|
||||
cal, err := h.queries.GetCalendarByID(ctx, sub.CalendarID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ownerID := utils.FromPgUUID(cal.OwnerID)
|
||||
|
||||
fetchURL := sub.SourceUrl
|
||||
if strings.HasPrefix(fetchURL, "webcal://") {
|
||||
fetchURL = "https://" + strings.TrimPrefix(fetchURL, "webcal://")
|
||||
}
|
||||
if normalized, ok := normalizeGoogleCalendarURL(fetchURL); ok {
|
||||
fetchURL = normalized
|
||||
}
|
||||
|
||||
body, err := fetchICSURL(fetchURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_ = h.importICSData(ctx, string(body), calID, ownerID)
|
||||
return h.queries.UpdateSubscriptionLastSynced(ctx, utils.ToPgUUID(subID))
|
||||
}
|
||||
|
||||
// normalizeGoogleCalendarURL converts Google Calendar embed/share URLs to the iCal feed format.
|
||||
// Returns (fetchURL, true) if the URL was converted or is already a Google iCal URL.
|
||||
func normalizeGoogleCalendarURL(raw string) (string, bool) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if !strings.Contains(raw, "calendar.google.com") {
|
||||
return raw, false
|
||||
}
|
||||
|
||||
// Already an iCal URL - use as-is (may be public or private)
|
||||
if strings.Contains(raw, "/calendar/ical/") && strings.HasSuffix(raw, ".ics") {
|
||||
return raw, true
|
||||
}
|
||||
|
||||
// Embed URL: https://calendar.google.com/calendar/embed?src=CALENDAR_ID
|
||||
if strings.Contains(raw, "/calendar/embed") {
|
||||
if u, err := url.Parse(raw); err == nil {
|
||||
if src := u.Query().Get("src"); src != "" {
|
||||
decoded, _ := url.QueryUnescape(src)
|
||||
icalURL := "https://calendar.google.com/calendar/ical/" + url.PathEscape(decoded) + "/public/basic.ics"
|
||||
return icalURL, true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calendar link with cid: https://calendar.google.com/calendar?cid=BASE64_CALENDAR_ID
|
||||
if strings.Contains(raw, "cid=") {
|
||||
if u, err := url.Parse(raw); err == nil {
|
||||
if cid := u.Query().Get("cid"); cid != "" {
|
||||
// cid can be base64, base64url, or base64url without padding
|
||||
var decoded []byte
|
||||
for _, enc := range []*base64.Encoding{base64.URLEncoding, base64.RawURLEncoding, base64.StdEncoding} {
|
||||
d, decodeErr := enc.DecodeString(cid)
|
||||
if decodeErr == nil && len(d) > 0 {
|
||||
decoded = d
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(decoded) > 0 {
|
||||
calID := string(decoded)
|
||||
icalURL := "https://calendar.google.com/calendar/ical/" + url.PathEscape(calID) + "/public/basic.ics"
|
||||
return icalURL, true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return raw, true
|
||||
}
|
||||
|
||||
// googleCalendarHelp is the error hint shown when Google Calendar requests fail.
|
||||
const googleCalendarHelp = "Use the iCal link from Google: Settings → your calendar → Integrate calendar → copy \"Secret address in iCal format\" (not the embed or share URL)"
|
||||
|
||||
// fetchICSURL fetches an ICS file from a URL. Google Calendar blocks non-browser User-Agents,
|
||||
// so we use a full Chrome User-Agent. Other providers generally accept it.
|
||||
func fetchICSURL(fetchURL string) ([]byte, error) {
|
||||
req, err := http.NewRequest(http.MethodGet, fetchURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid URL: %w", err)
|
||||
}
|
||||
// Google Calendar returns 403 for non-browser User-Agents; use a real Chrome UA
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
|
||||
req.Header.Set("Accept", "text/calendar,text/plain,*/*")
|
||||
if strings.Contains(fetchURL, "calendar.google.com") {
|
||||
req.Header.Set("Referer", "https://calendar.google.com/")
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to fetch URL: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
if strings.Contains(fetchURL, "calendar.google.com") {
|
||||
switch resp.StatusCode {
|
||||
case http.StatusNotFound:
|
||||
return nil, fmt.Errorf("Google Calendar returned 404. %s", googleCalendarHelp)
|
||||
case http.StatusForbidden:
|
||||
return nil, fmt.Errorf("Google Calendar returned 403 (access denied). %s", googleCalendarHelp)
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("URL returned HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Google may return 200 with an HTML login/error page instead of ICS
|
||||
bodyStr := string(body)
|
||||
if len(body) > 10 && (body[0] == '<' || strings.HasPrefix(bodyStr, "<!") || strings.Contains(bodyStr[:min(500, len(bodyStr))], "<html")) {
|
||||
if strings.Contains(fetchURL, "calendar.google.com") {
|
||||
return nil, fmt.Errorf("Google returned HTML instead of calendar data. %s", googleCalendarHelp)
|
||||
}
|
||||
return nil, fmt.Errorf("URL returned HTML instead of calendar data (ICS)")
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func (h *ICSHandler) importICSData(ctx context.Context, data string, calID, userID uuid.UUID) int {
|
||||
cal, err := ics.ParseCalendar(strings.NewReader(data))
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user