Drop narration, history and restated-code comments across the repo, keep short ones for security boundaries, upstream quirks and ordering constraints, and record the convention in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
188 lines
5.5 KiB
Go
188 lines
5.5 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/rwcarlsen/goexif/exif"
|
|
|
|
"adam-french.co.uk/backend/models"
|
|
"adam-french.co.uk/backend/services"
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// CreateRowing reads a photo of the rowing machine display. The Claude call
|
|
// is in python/app/rowing.py; auth, EXIF, dedup and bounds checks stay here.
|
|
|
|
// ExtractedRowingData matches RowingReading in python/app/rowing.py.
|
|
type ExtractedRowingData struct {
|
|
TimeMinutes uint64 `json:"timeMinutes"`
|
|
TimeSeconds uint64 `json:"timeSeconds"`
|
|
Distance uint64 `json:"distance"`
|
|
}
|
|
|
|
// Internal: Caddy refuses /py/internal/, so only a direct container call works.
|
|
const rowingReadPath = "/internal/rowing/read"
|
|
|
|
func (store *Store) readRowingDisplay(ctx context.Context, mediaType string, image []byte) (ExtractedRowingData, error) {
|
|
// []byte marshals as standard base64, as the Anthropic API expects.
|
|
return services.CallPython[ExtractedRowingData](ctx, store.PythonURL, rowingReadPath, struct {
|
|
MediaType string `json:"media_type"`
|
|
Data []byte `json:"data"`
|
|
}{mediaType, image})
|
|
}
|
|
|
|
func (store *Store) GetRowing(ctx *gin.Context) {
|
|
var rowing []models.Rowing
|
|
if err := store.DB.Order("created_at DESC").Find(&rowing).Error; err != nil {
|
|
log.Println(err)
|
|
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
|
return
|
|
}
|
|
ctx.JSON(http.StatusOK, rowing)
|
|
}
|
|
|
|
// CreateRowing is admin-only, so its checks target misreadings, not hostile
|
|
// input.
|
|
func (store *Store) CreateRowing(ctx *gin.Context) {
|
|
file, err := ctx.FormFile("image")
|
|
if err != nil {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "image is required"})
|
|
return
|
|
}
|
|
|
|
f, err := file.Open()
|
|
if err != nil {
|
|
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to open image"})
|
|
return
|
|
}
|
|
defer f.Close()
|
|
|
|
// EXIF is required: it is both the session date and the duplicate key.
|
|
exifData, err := exif.Decode(f)
|
|
if err != nil {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "no EXIF data found"})
|
|
return
|
|
}
|
|
|
|
dateTaken, err := exifData.DateTime()
|
|
if err != nil {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "no date found in EXIF data"})
|
|
return
|
|
}
|
|
|
|
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
|
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to seek image"})
|
|
return
|
|
}
|
|
|
|
// Bounded before buffering, to cap memory and the paid API call.
|
|
const maxPhotoSize = 10 << 20
|
|
if file.Size > maxPhotoSize {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "image too large (max 10MB)"})
|
|
return
|
|
}
|
|
|
|
data, err := io.ReadAll(f)
|
|
if err != nil {
|
|
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read image"})
|
|
return
|
|
}
|
|
|
|
allowedMediaTypes := map[string]bool{
|
|
"image/jpeg": true,
|
|
"image/png": true,
|
|
"image/gif": true,
|
|
"image/webp": true,
|
|
}
|
|
// The browser's claimed type, checked only to keep the API call
|
|
// well-formed and give a clear 400.
|
|
mediaType := file.Header.Get("Content-Type")
|
|
if !allowedMediaTypes[mediaType] {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image type"})
|
|
return
|
|
}
|
|
|
|
// Checked before the paid call. Fails closed: only ErrRecordNotFound
|
|
// means "no duplicate".
|
|
var existing models.Rowing
|
|
err = store.DB.Where("date = ?", dateTaken).First(&existing).Error
|
|
switch {
|
|
case err == nil:
|
|
ctx.JSON(http.StatusConflict, gin.H{"error": "duplicate entry for this date"})
|
|
return
|
|
case !errors.Is(err, gorm.ErrRecordNotFound):
|
|
log.Println(err)
|
|
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
|
return
|
|
}
|
|
|
|
extractedData, err := store.readRowingDisplay(ctx.Request.Context(), mediaType, data)
|
|
if err != nil {
|
|
log.Println(err)
|
|
// Pass on the reader's own messages; hide plumbing failures.
|
|
msg := "failed to process image"
|
|
var readErr *services.PythonError
|
|
if errors.As(err, &readErr) {
|
|
msg = readErr.Detail
|
|
}
|
|
ctx.JSON(http.StatusInternalServerError, gin.H{"error": msg})
|
|
return
|
|
}
|
|
|
|
if extractedData.Distance == 0 {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid distance in image"})
|
|
return
|
|
}
|
|
|
|
totalSeconds := extractedData.TimeMinutes*60 + extractedData.TimeSeconds
|
|
|
|
// A misread digit usually lands outside human performance; the pace check
|
|
// catches plausible time and distance that disagree.
|
|
const (
|
|
minDistance = 100 // metres
|
|
maxDistance = 100000 // metres
|
|
minTotalSecs = 30 // 30 seconds
|
|
maxTotalSecs = 7200 // 2 hours
|
|
minPacePer500m = 80 // ~1:20 /500m (faster than any human)
|
|
maxPacePer500m = 150 // ~2:30 /500m (slow, not important)
|
|
)
|
|
if extractedData.Distance < minDistance || extractedData.Distance > maxDistance {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "anomalous distance value"})
|
|
return
|
|
}
|
|
if totalSeconds < minTotalSecs || totalSeconds > maxTotalSecs {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "anomalous time value"})
|
|
return
|
|
}
|
|
|
|
per500m := float64(totalSeconds) / float64(extractedData.Distance) * 500.0
|
|
if per500m < minPacePer500m || per500m > maxPacePer500m {
|
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "anomalous pace value"})
|
|
return
|
|
}
|
|
|
|
// A display-only estimate, ~500 kcal per 7500 m.
|
|
const kcalPerMetre = 500.0 / 7500.0
|
|
calories := float64(extractedData.Distance) * kcalPerMetre
|
|
|
|
rowing := models.Rowing{
|
|
Date: dateTaken,
|
|
Time: totalSeconds,
|
|
TimePer500m: per500m,
|
|
Distance: extractedData.Distance,
|
|
Calories: calories,
|
|
}
|
|
|
|
if err := store.DB.Create(&rowing).Error; err != nil {
|
|
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save rowing"})
|
|
return
|
|
}
|
|
|
|
ctx.JSON(http.StatusCreated, rowing)
|
|
}
|