package handlers import ( "bytes" "context" "encoding/json" "errors" "io" "log" "net/http" "os" "path/filepath" "regexp" "strings" "time" "github.com/gin-gonic/gin" "adam-french.co.uk/usaco-site/internal/audiostore" "adam-french.co.uk/usaco-site/internal/claude" "adam-french.co.uk/usaco-site/internal/index" "adam-french.co.uk/usaco-site/internal/review" "adam-french.co.uk/usaco-site/internal/transcribe" ) // Transcriber is the part of transcribe.Client the handlers use, so tests // can fake it. type Transcriber interface { Transcribe(ctx context.Context, filename string, audio []byte) (*transcribe.Transcript, error) Model() string } // AudioStore is the part of audiostore.Store the handlers use. type AudioStore interface { Put(ctx context.Context, key, contentType string, b []byte) error Get(ctx context.Context, key string) (*audiostore.Object, error) Delete(ctx context.Context, key string) error } // The formats OpenAI's transcription endpoint takes, by extension, with the // type the recording is stored and played back as. var audioTypes = map[string]string{ ".mp3": "audio/mpeg", ".mpga": "audio/mpeg", ".mpeg": "audio/mpeg", ".m4a": "audio/mp4", ".mp4": "audio/mp4", ".wav": "audio/wav", ".webm": "audio/webm", ".ogg": "audio/ogg", ".oga": "audio/ogg", ".flac": "audio/flac", } // A review's id is the UTC time it was started. Checking the shape keeps // anything path-like out of the filesystem and the bucket. const reviewIDLayout = "2006-01-02-150405" var validReviewID = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}-\d{6}$`) // Transcription and a long recording's review both take minutes. const reviewTimeout = 10 * time.Minute // startReview takes the recording and starts the review; the page polls // reviewStatus. Like startExplain, everything Claude sees about the problem // is taken from the index now. func (s *Server) startReview(ctx *gin.Context) { p, ok := s.lookup(ctx, true) if !ok { return } if !s.claudeReady(ctx) { return } if s.Transcriber == nil { ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "transcription is not configured on this server (TRANSCRIBE_API_KEY)"}) return } // The form's other fields are tiny; the slack is for them and the // multipart framing. ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, transcribe.MaxBytes+64<<10) fh, err := ctx.FormFile("audio") if err != nil { var tooBig *http.MaxBytesError if errors.As(err, &tooBig) { ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the recording is over 25 MB; export it at a lower bitrate"}) return } ctx.JSON(http.StatusBadRequest, gin.H{"error": "attach the recording as audio"}) return } ext := strings.ToLower(filepath.Ext(fh.Filename)) contentType, ok := audioTypes[ext] if !ok { ctx.JSON(http.StatusBadRequest, gin.H{"error": "the recording must be mp3, m4a, wav, webm, ogg or flac"}) return } if fh.Size > transcribe.MaxBytes { ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the recording is over 25 MB; export it at a lower bitrate"}) return } f, err := fh.Open() if err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "the recording could not be read"}) return } audio, err := io.ReadAll(f) f.Close() if err != nil || len(audio) == 0 { ctx.JSON(http.StatusBadRequest, gin.H{"error": "the recording is empty"}) return } note := ctx.PostForm("note") if len(note) > maxNote { ctx.JSON(http.StatusBadRequest, gin.H{"error": "the note is too long"}) return } if strings.TrimSpace(p.Statement) == "" && p.URL == "" { ctx.JSON(http.StatusBadRequest, gin.H{"error": "add the problem statement or a link to it first"}) return } in := review.Input{Name: p.Name, Statement: p.Statement, Note: note, Examples: examples(p)} if ctx.PostForm("includeCode") == "true" { in.Code = mainFile(p) } // Chosen now rather than in the job's edit, which Mutate may replay: // a replay must write the same file. id := time.Now().UTC().Format(reviewIDLayout) rec := recording{name: id + ext, contentType: contentType, data: audio} link := p.URL if startJob(ctx, s.reviewJobs, p.Name, "a recording is already being reviewed", func() (any, error) { return s.review(in, link, id, rec) }) { ctx.JSON(http.StatusAccepted, s.reviewJobs.Get(p.Name)) } } func (s *Server) reviewStatus(ctx *gin.Context) { if p, ok := s.lookup(ctx, true); ok { ctx.JSON(http.StatusOK, s.reviewJobs.Get(p.Name)) } } type recording struct { name, contentType string data []byte } // reviewDraft is a written review waiting to be committed. Audio is the // recording's key in the store, kept until the review is saved or replaced. type reviewDraft struct { Name string `json:"name"` ID string `json:"id"` Fetched string `json:"fetched,omitempty"` Markdown string `json:"markdown"` Audio string `json:"audio,omitempty"` } // review is one job's work. Its error is shown to the admin, so every path // returns a message meant for them and logs the detail. func (s *Server) review(in review.Input, link, id string, rec recording) (draft any, err error) { ctx, cancel := context.WithTimeout(context.Background(), reviewTimeout) defer cancel() name := in.Name fetched, err := s.ensureStatement(ctx, "review", name, &in.Statement, link) if err != nil { return nil, err } tr, err := s.Transcriber.Transcribe(ctx, rec.name, rec.data) if err != nil { var f *transcribe.Failure if errors.As(err, &f) { log.Printf("[review] %s: %s: %v", name, f.Msg, f.Err) return nil, f } log.Printf("[review] %s: transcribing: %v", name, err) return nil, errors.New("the recording could not be transcribed") } in.Transcript, in.Metrics = tr, tr.Metrics() // The recording is kept only if there is somewhere to keep it, and a // failure to keep it costs the playback, not the review. It is stored // before Claude runs so the review can point at it, and removed again // if Claude fails. Once there is a review it stays with the draft: a // failed commit can be retried, and discardReview removes it if a new // recording replaces the draft instead. key := "" if s.Audio != nil { k := name + "/" + rec.name if perr := s.Audio.Put(ctx, k, rec.contentType, rec.data); perr != nil { log.Printf("[review] %s: storing the recording: %v", name, perr) } else { key = k // err is the job's result: set by the return statements below. defer func() { if err != nil { if derr := s.Audio.Delete(context.Background(), key); derr != nil { log.Printf("[review] %s: removing the unused recording: %v", name, derr) } } }() } } md, err := review.Generate(ctx, s.Claude, in, review.Meta{Now: time.Now(), Transcriber: s.Transcriber.Model(), Audio: key}) if err != nil { var f *claude.Failure if errors.As(err, &f) { log.Printf("[review] %s: %s: %v", name, f.Msg, f.Err) return nil, f } log.Printf("[review] %s: %v", name, err) return nil, errors.New("the review could not be written") } return reviewDraft{Name: name, ID: id, Fetched: fetched, Markdown: md, Audio: key}, nil } // saveReview commits a review. The id was chosen when the recording came // in, so running it again for a draft already pushed rewrites the same // file and commits nothing. func (s *Server) saveReview(raw json.RawMessage) (any, error) { var d reviewDraft if err := json.Unmarshal(raw, &d); err != nil { return nil, err } ctx, cancel := context.WithTimeout(context.Background(), saveTimeout) defer cancel() err := s.Repo.Mutate(ctx, "Review "+d.Name, func(dir string) error { status, err := findOnDisk(dir, d.Name) if err != nil { return err } pdir := filepath.Join(dir, status, d.Name) if err := saveFetched(pdir, d.Fetched); err != nil { return err } if err := os.MkdirAll(filepath.Join(pdir, "reviews"), 0o755); err != nil { return err } return writeOrRemove(filepath.Join(pdir, "reviews", d.ID+".md"), d.Markdown) }) return nil, jobSaveError("review", d.Name, "the review was written but could not be saved to git", err) } // discardReview removes the recording of a review that was never saved and // has been replaced by a new one. func (s *Server) discardReview(raw json.RawMessage) { var d reviewDraft if json.Unmarshal(raw, &d) != nil || d.Audio == "" || s.Audio == nil { return } if err := s.Audio.Delete(context.Background(), d.Audio); err != nil { log.Printf("[review] %s: removing the unsaved review's recording: %v", d.Name, err) } } // findReview is the problem's review with the URL's id. func findReview(ctx *gin.Context, p *index.Problem) (*index.Review, bool) { id := ctx.Param("id") if validReviewID.MatchString(id) { for i := range p.Reviews { if p.Reviews[i].ID == id { return &p.Reviews[i], true } } } ctx.JSON(http.StatusNotFound, gin.H{"error": "no such review"}) return nil, false } // reviewAudio plays a review's recording back. It is read whole and served // with ServeContent so the player can seek (range requests); recordings are // at most 25 MB. func (s *Server) reviewAudio(ctx *gin.Context) { p, ok := s.lookup(ctx, true) if !ok { return } r, ok := findReview(ctx, p) if !ok { return } if s.Audio == nil || r.Audio == "" { ctx.JSON(http.StatusNotFound, gin.H{"error": "this review's recording was not kept"}) return } c, cancel := context.WithTimeout(ctx.Request.Context(), time.Minute) defer cancel() obj, err := s.Audio.Get(c, r.Audio) if errors.Is(err, audiostore.ErrNotFound) { ctx.JSON(http.StatusNotFound, gin.H{"error": "the recording is gone from storage"}) return } if err != nil { log.Printf("[review] %s: reading %s: %v", p.Name, r.Audio, err) ctx.JSON(http.StatusBadGateway, gin.H{"error": "the recording could not be read"}) return } defer obj.Body.Close() b, err := io.ReadAll(io.LimitReader(obj.Body, transcribe.MaxBytes+1)) if err != nil { log.Printf("[review] %s: reading %s: %v", p.Name, r.Audio, err) ctx.JSON(http.StatusBadGateway, gin.H{"error": "the recording could not be read"}) return } if obj.ContentType != "" { ctx.Header("Content-Type", obj.ContentType) } ctx.Header("Cache-Control", "private, max-age=3600") http.ServeContent(ctx.Writer, ctx.Request, filepath.Base(r.Audio), time.Time{}, bytes.NewReader(b)) } // deleteReview removes a review and, once that is committed, its recording. func (s *Server) deleteReview(ctx *gin.Context) { p, ok := s.lookup(ctx, true) if !ok { return } r, ok := findReview(ctx, p) if !ok { return } name, id, audio := p.Name, r.ID, r.Audio s.mutate(ctx, name, "Remove review "+name, func(dir string) error { status, err := findOnDisk(dir, name) if err != nil { return err } rdir := filepath.Join(dir, status, name, "reviews") if err := os.Remove(filepath.Join(rdir, id+".md")); err != nil { if os.IsNotExist(err) { return &requestError{http.StatusNotFound, "no such review"} } return err } // Only succeeds when it was the last review; git does not keep // empty directories anyway. os.Remove(rdir) return nil }) if ctx.Writer.Status() == http.StatusOK && audio != "" && s.Audio != nil { if err := s.Audio.Delete(context.Background(), audio); err != nil { log.Printf("[review] %s: removing %s: %v", name, audio, err) } } }