aboutsummaryrefslogtreecommitdiff
path: root/web/rides.go
blob: 1eea98e733944bf9ffb14e18b10ae79f4c161a56 (plain) (blame)
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231

package web

import (
	"errors"
	"log/slog"
	"net/http"
	"strconv"

	"github.com/martinlehoux/biking_home/climb"
	"github.com/martinlehoux/biking_home/mountain_pass"
	"github.com/martinlehoux/biking_home/official_climb"
	"github.com/martinlehoux/biking_home/ride"
	"github.com/martinlehoux/biking_home/rideanalysis"
	"github.com/martinlehoux/kagamigo/kcore"
)

func (s *Server) handleRides(w http.ResponseWriter, r *http.Request) {
	rideSort := parseRideSort(r.URL.Query())
	rideFilters := parseRideFilters(r.URL.Query())
	items, err := s.listRides(rideSort)
	if err != nil {
		slog.Error("Failed to load rides", "sort", rideSort.Column, "descending", rideSort.Descending, "error", err)
		http.Error(w, "failed to load rides", http.StatusInternalServerError)
		return
	}
	items = filterRides(items, rideFilters)
	if rideFilters.Active() {
		slog.Info("Applied ride library filters", "matches", len(items))
	}
	views := buildRideViews(items)
	kcore.RenderPage(r.Context(), RidesPage(RidesPageData{
		Items:   views,
		Headers: rideSortHeadersWithFilters(rideSort, rideFilters),
		Filters: buildRideFilterView(rideFilters, rideSort),
		Sort:    rideSort,
	}), w)
}

func (s *Server) handleRide(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil || id <= 0 {
		http.NotFound(w, r)
		return
	}
	item, found, err := ride.GetByID(s.db, id)
	if err != nil {
		slog.Error("Failed to load ride", "ride_id", id, "error", err)
		http.Error(w, "failed to load ride", http.StatusInternalServerError)
		return
	}
	if !found {
		http.NotFound(w, r)
		return
	}
	if item.FitPath == "" && item.GPXPath == "" {
		slog.Info("Loaded ride detail without route", "ride_id", id)
		kcore.RenderPage(r.Context(), RideDetailPage(RideDetailView{RideView: buildRideView(item), ExternalURL: externalRideURL(item.ExternalID), Notice: rideDetailNotice(r)}), w)
		return
	}
	// Prefer FIT; fallback to GPX for legacy rides pending backfill.
	var parsed ride.Ride
	if item.FitPath != "" {
		parsed, err = ride.ParseFile(ride.FITRideParser{}, item.FitPath)
		if err != nil {
			slog.Error("Failed to load ride route", "ride_id", id, "file", item.FitPath, "error", err)
		}
	} else {
		parsed, err = ride.ParseFile(ride.GPXRideParser{}, item.GPXPath)
		if err != nil {
			slog.Error("Failed to load ride route", "ride_id", id, "file", item.GPXPath, "error", err)
		}
	}
	if err != nil {
		kcore.RenderPage(r.Context(), RideDetailPage(RideDetailView{
			RideView:    buildRideView(item),
			ExternalURL: externalRideURL(item.ExternalID),
			RouteError:  "The recorded route is unavailable.",
			Notice:      rideDetailNotice(r),
		}), w)
		return
	}
	passes, err := mountain_pass.LoadMountainPassesAroundRide(s.db, parsed.Coords, rideanalysis.PassMarginM)
	if err != nil {
		slog.Warn("Failed to load nearby mountain passes for ride detail", "ride_id", id, "error", err)
	}
	officialClimbs, err := official_climb.List(s.db)
	if err != nil {
		slog.Warn("Failed to load official climbs for ride detail", "ride_id", id, "error", err)
	}
	matchPolicy := s.officialClimbMatchPolicy()
	s.recordOfficialClimbAttempts(id, parsed, analysisFor(parsed, passes, officialClimbs, matchPolicy))
	slog.Info("Loaded ride detail", "ride_id", id)
	view := buildRideDetailView(buildRideView(item), parsed, passes, officialClimbs, matchPolicy)
	view.Notice = rideDetailNotice(r)
	kcore.RenderPage(r.Context(), RideDetailPage(view), w)
}

func (s *Server) handleAnalytics(w http.ResponseWriter, r *http.Request) {
	items, err := s.listRides(RideSort{})
	if err != nil {
		slog.Error("Failed to load rides for analytics", "error", err)
		http.Error(w, "failed to load rides", http.StatusInternalServerError)
		return
	}
	filters := parseRideFilters(r.URL.Query())
	eligible := filterRides(items, filters)
	filterView := buildRideFilterView(filters, RideSort{})
	filterView.ResetURL = "/analytics"
	slog.Info("Loaded ride analytics", "rides", len(eligible))
	kcore.RenderPage(r.Context(), AnalyticsPage(AnalyticsPageData{
		Points: buildAnalyticsPoints(eligible),
		Filter: filterView,
	}), w)
}

func (s *Server) handleCreateOfficialClimb(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil || id <= 0 {
		http.NotFound(w, r)
		return
	}
	item, found, err := ride.GetByID(s.db, id)
	if err != nil {
		slog.Error("Failed to load ride for official climb creation", "ride_id", id, "error", err)
		http.Error(w, "failed to load ride", http.StatusInternalServerError)
		return
	}
	if !found {
		http.NotFound(w, r)
		return
	}
	if item.FitPath == "" && item.GPXPath == "" {
		http.Error(w, "a recorded route is required to create an official climb", http.StatusBadRequest)
		return
	}
	if err := r.ParseForm(); err != nil {
		http.Error(w, "invalid form", http.StatusBadRequest)
		return
	}
	startIndex, err := parseRouteIndex(r.FormValue("start_index"))
	if err != nil {
		http.Error(w, "a valid start route point is required", http.StatusBadRequest)
		return
	}
	endIndex, err := parseRouteIndex(r.FormValue("end_index"))
	if err != nil {
		http.Error(w, "a valid end route point is required", http.StatusBadRequest)
		return
	}
	var parsed ride.Ride
	if item.FitPath != "" {
		parsed, err = ride.ParseFile(ride.FITRideParser{}, item.FitPath)
		if err != nil {
			slog.Error("Failed to load ride route for official climb creation", "ride_id", id, "file", item.FitPath, "error", err)
		}
	} else {
		parsed, err = ride.ParseFile(ride.GPXRideParser{}, item.GPXPath)
		if err != nil {
			slog.Error("Failed to load ride route for official climb creation", "ride_id", id, "file", item.GPXPath, "error", err)
		}
	}
	if err != nil {
		http.Error(w, "the recorded route is unavailable", http.StatusBadRequest)
		return
	}
	bounds := parsed.Coords
	if startIndex >= endIndex || endIndex >= len(bounds) {
		http.Error(w, "the official climb boundaries must be ordered route points", http.StatusBadRequest)
		return
	}
	sample := parsed.Sample(startIndex, endIndex)
	created, err := official_climb.Create(s.db, official_climb.OfficialClimb{
		Name:       r.FormValue("name"),
		StartCoord: bounds[startIndex],
		EndCoord:   bounds[endIndex],
		Sample:     sample,
	})
	if err != nil {
		slog.Warn("Failed to create official climb", "ride_id", id, "error", err)
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	slog.Info("Created official climb", "official_climb_id", created.ID, "ride_id", id, "start_index", startIndex, "end_index", endIndex)
	http.Redirect(w, r, rideDetailURL(id)+"?official_climb=created", http.StatusSeeOther)
}

// officialClimbMatchPolicy loads the configured endpoint radius, falling back to the default.
func (s *Server) officialClimbMatchPolicy() official_climb.MatchPolicy {
	matchPolicy := official_climb.DefaultMatchPolicy()
	appConfig, err := s.loadConfig()
	if err != nil {
		slog.Warn("Failed to load official climb matching configuration", "error", err)
		return matchPolicy
	}
	matchPolicy.EndpointRadiusM = appConfig.OfficialClimb.MatchRadiusM
	return matchPolicy
}

func parseRouteIndex(value string) (int, error) {
	index, err := strconv.Atoi(value)
	if err != nil || index < 0 {
		return 0, errors.New("invalid route point index")
	}
	return index, nil
}

func (s *Server) listRides(rideSort RideSort) ([]ride.StoredRide, error) {
	column, found := rideSort.databaseColumn()
	if !found {
		return ride.List(s.db)
	}
	return ride.ListSorted(s.db, column, rideSort.Descending)
}

func buildRideViews(items []ride.StoredRide) []RideView {
	views := make([]RideView, 0, len(items))
	for _, item := range items {
		views = append(views, buildRideView(item))
	}
	return views
}

func buildRideView(item ride.StoredRide) RideView {
	view := RideView{Ride: item, Cotacol: "-", CotacolPer100Km: "-", MovingTime: formatDuration(item.EffectiveMovingTimeS())}
	cotacol, ready := item.CotacolScore()
	if ready && item.CotacolAlgorithmVersion() == climb.CotacolAlgorithmVersion && item.DistanceM > 0 {
		view.Cotacol = formatCotacol(cotacol)
		view.CotacolPer100Km = formatCotacolPer100Km(cotacol, item.DistanceM)
	}
	return view
}