Initial commit
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type debugCheck struct {
|
||||
OK bool `json:"ok"`
|
||||
Status string `json:"status"`
|
||||
DurationMS int64 `json:"duration_ms,omitempty"`
|
||||
HTTPStatus int `json:"http_status,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Details map[string]any `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) debugStatus(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"request_id": requestID(r),
|
||||
"debug": map[string]any{
|
||||
"enabled": true,
|
||||
"verbose": s.cfg.DebugVerbose,
|
||||
"log_level": s.cfg.LogLevel.String(),
|
||||
},
|
||||
"config": s.debugConfig(),
|
||||
"checks": map[string]any{
|
||||
"db": s.store.DebugStatus(r.Context()),
|
||||
"azure": s.azureStatus(),
|
||||
"flowise": s.flowiseStatus(r.Context()),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) debugDB(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"request_id": requestID(r),
|
||||
"db": s.store.DebugStatus(r.Context()),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) debugFlowise(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"request_id": requestID(r),
|
||||
"flowise": s.flowiseStatus(r.Context()),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) debugAzure(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"request_id": requestID(r),
|
||||
"azure": s.azureStatus(),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) debugRuntime(w http.ResponseWriter, r *http.Request) {
|
||||
hostname, _ := os.Hostname()
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"request_id": requestID(r),
|
||||
"runtime": map[string]any{
|
||||
"hostname": hostname,
|
||||
"go_version": runtime.Version(),
|
||||
"go_os": runtime.GOOS,
|
||||
"go_arch": runtime.GOARCH,
|
||||
"goroutines": runtime.NumGoroutine(),
|
||||
"uptime_seconds": int64(time.Since(s.started).Seconds()),
|
||||
"started_at": s.started.UTC().Format(time.RFC3339),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) debugConfig() map[string]any {
|
||||
return map[string]any{
|
||||
"api_port": s.cfg.Port,
|
||||
"cors_origins": s.cfg.CORSOrigins,
|
||||
"azure_mock": s.cfg.AzureMock,
|
||||
"azure_region": valueOr(s.cfg.AzureRegion, "not-set"),
|
||||
"azure_speech_key_set": s.cfg.AzureSpeechKey != "",
|
||||
"flowise_base_url": valueOr(s.cfg.FlowiseBaseURL, "not-set"),
|
||||
"flowise_chatflow_set": s.cfg.FlowiseChatflow != "",
|
||||
"flowise_api_key_set": s.cfg.FlowiseAPIKey != "",
|
||||
"jwt_secret_configured": s.cfg.JWTSecret != "" && s.cfg.JWTSecret != "dev-secret-change-me",
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) azureStatus() debugCheck {
|
||||
details := map[string]any{
|
||||
"mock_enabled": s.cfg.AzureMock,
|
||||
"region": valueOr(s.cfg.AzureRegion, "not-set"),
|
||||
"speech_key_set": s.cfg.AzureSpeechKey != "",
|
||||
}
|
||||
if s.cfg.AzureMock {
|
||||
return debugCheck{OK: true, Status: "mock", Details: details}
|
||||
}
|
||||
if s.cfg.AzureSpeechKey == "" || s.cfg.AzureRegion == "" {
|
||||
return debugCheck{OK: false, Status: "not_configured", Details: details}
|
||||
}
|
||||
details["stt_endpoint"] = "https://" + s.cfg.AzureRegion + ".stt.speech.microsoft.com"
|
||||
details["tts_endpoint"] = "https://" + s.cfg.AzureRegion + ".tts.speech.microsoft.com"
|
||||
return debugCheck{OK: true, Status: "configured", Details: details}
|
||||
}
|
||||
|
||||
func (s *Server) flowiseStatus(ctx context.Context) debugCheck {
|
||||
baseURL := strings.TrimRight(s.cfg.FlowiseBaseURL, "/")
|
||||
details := map[string]any{
|
||||
"base_url": valueOr(baseURL, "not-set"),
|
||||
"chatflow_set": s.cfg.FlowiseChatflow != "",
|
||||
"api_key_set": s.cfg.FlowiseAPIKey != "",
|
||||
}
|
||||
if baseURL == "" {
|
||||
return debugCheck{OK: false, Status: "not_configured", Details: details}
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
checkCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(checkCtx, http.MethodGet, baseURL, nil)
|
||||
if err != nil {
|
||||
return debugCheck{OK: false, Status: "invalid_url", Error: err.Error(), Details: details}
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return debugCheck{OK: false, Status: "unreachable", Error: err.Error(), DurationMS: time.Since(start).Milliseconds(), Details: details}
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
ok := resp.StatusCode < 500
|
||||
status := "reachable"
|
||||
if !ok {
|
||||
status = "server_error"
|
||||
}
|
||||
return debugCheck{
|
||||
OK: ok,
|
||||
Status: status,
|
||||
HTTPStatus: resp.StatusCode,
|
||||
DurationMS: time.Since(start).Milliseconds(),
|
||||
Details: details,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const userIDKey contextKey = "user_id"
|
||||
const requestIDKey contextKey = "request_id"
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
bytes int
|
||||
}
|
||||
|
||||
func (r *statusRecorder) WriteHeader(status int) {
|
||||
r.status = status
|
||||
r.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (r *statusRecorder) Write(body []byte) (int, error) {
|
||||
if r.status == 0 {
|
||||
r.status = http.StatusOK
|
||||
}
|
||||
n, err := r.ResponseWriter.Write(body)
|
||||
r.bytes += n
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (s *Server) requestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := strings.TrimSpace(r.Header.Get("X-Request-ID"))
|
||||
if requestID == "" || len(requestID) > 128 {
|
||||
requestID = newRequestID()
|
||||
}
|
||||
w.Header().Set("X-Request-ID", requestID)
|
||||
ctx := context.WithValue(r.Context(), requestIDKey, requestID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) requestLogging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
recorder := &statusRecorder{ResponseWriter: w}
|
||||
next.ServeHTTP(recorder, r)
|
||||
status := recorder.status
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
attrs := []any{
|
||||
"request_id", requestID(r),
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", status,
|
||||
"bytes", recorder.bytes,
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
"remote", r.RemoteAddr,
|
||||
}
|
||||
if userID := currentUserID(r); userID != "" {
|
||||
attrs = append(attrs, "user_id", userID)
|
||||
}
|
||||
if status >= 500 {
|
||||
s.logger.Error("http request", attrs...)
|
||||
return
|
||||
}
|
||||
s.logger.Info("http request", attrs...)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) cors(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
origin := r.Header.Get("Origin")
|
||||
if s.isAllowedOrigin(origin) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Vary", "Origin")
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "X-Request-ID")
|
||||
}
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) isAllowedOrigin(origin string) bool {
|
||||
if origin == "" {
|
||||
return false
|
||||
}
|
||||
for _, allowed := range s.cfg.CORSOrigins {
|
||||
if allowed == "*" || strings.EqualFold(allowed, origin) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) requireAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
token := strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer "))
|
||||
if token == "" || token == authHeader {
|
||||
writeError(w, http.StatusUnauthorized, nil)
|
||||
return
|
||||
}
|
||||
userID, err := s.auth.VerifyToken(token)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, err)
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), userIDKey, userID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func currentUserID(r *http.Request) string {
|
||||
value, _ := r.Context().Value(userIDKey).(string)
|
||||
return value
|
||||
}
|
||||
|
||||
func requestID(r *http.Request) string {
|
||||
value, _ := r.Context().Value(requestIDKey).(string)
|
||||
return value
|
||||
}
|
||||
|
||||
func newRequestID() string {
|
||||
var b [12]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type errorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, err error) {
|
||||
if err == nil {
|
||||
err = errors.New(http.StatusText(status))
|
||||
}
|
||||
writeJSON(w, status, errorResponse{Error: err.Error()})
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, dst any) error {
|
||||
defer r.Body.Close()
|
||||
return json.NewDecoder(r.Body).Decode(dst)
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"speech-learning-api/internal/config"
|
||||
"speech-learning-api/internal/domain"
|
||||
"speech-learning-api/internal/services"
|
||||
)
|
||||
|
||||
type DataStore interface {
|
||||
GetUser(ctx context.Context, id string) (domain.User, error)
|
||||
GetPrimaryProfile(ctx context.Context, userID string) (domain.LearnerProfile, error)
|
||||
UpdatePreferences(ctx context.Context, userID, uiLanguage, targetLanguage, cefrLevel string, dailyGoalMinutes int) (domain.LearnerProfile, error)
|
||||
ListLanguages(ctx context.Context) ([]domain.LanguageProfile, error)
|
||||
GetLanguage(ctx context.Context, code string) (domain.LanguageProfile, error)
|
||||
NextLessonAndExercise(ctx context.Context, profile domain.LearnerProfile) (domain.Lesson, domain.Exercise, error)
|
||||
GetExercise(ctx context.Context, id string) (domain.Exercise, error)
|
||||
SaveAttempt(ctx context.Context, attempt domain.Attempt) (domain.Attempt, error)
|
||||
Progress(ctx context.Context, userID string, limit int) (domain.ProgressSummary, error)
|
||||
CreateConversationSession(ctx context.Context, userID, targetLanguage, cefrLevel string) (domain.ConversationSession, error)
|
||||
SaveConversationTurn(ctx context.Context, turn domain.ConversationTurn) (domain.ConversationTurn, error)
|
||||
DebugStatus(ctx context.Context) domain.DebugDBStatus
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
cfg config.Config
|
||||
logger *slog.Logger
|
||||
store DataStore
|
||||
auth *services.AuthService
|
||||
speech services.SpeechService
|
||||
teacher services.TeacherAgent
|
||||
started time.Time
|
||||
}
|
||||
|
||||
func NewServer(cfg config.Config, logger *slog.Logger, store DataStore, auth *services.AuthService, speech services.SpeechService, teacher services.TeacherAgent) *Server {
|
||||
return &Server{cfg: cfg, logger: logger, store: store, auth: auth, speech: speech, teacher: teacher, started: time.Now()}
|
||||
}
|
||||
|
||||
func (s *Server) Routes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health", s.health)
|
||||
mux.HandleFunc("POST /auth/register", s.register)
|
||||
mux.HandleFunc("POST /auth/login", s.login)
|
||||
mux.HandleFunc("POST /auth/logout", s.logout)
|
||||
|
||||
mux.Handle("GET /me", s.requireAuth(http.HandlerFunc(s.me)))
|
||||
mux.Handle("PATCH /me/preferences", s.requireAuth(http.HandlerFunc(s.updatePreferences)))
|
||||
mux.Handle("GET /languages", s.requireAuth(http.HandlerFunc(s.languages)))
|
||||
mux.Handle("GET /languages/{code}/voices", s.requireAuth(http.HandlerFunc(s.languageVoices)))
|
||||
mux.Handle("GET /dashboard", s.requireAuth(http.HandlerFunc(s.dashboard)))
|
||||
mux.Handle("GET /progress", s.requireAuth(http.HandlerFunc(s.progress)))
|
||||
mux.Handle("POST /lessons/next", s.requireAuth(http.HandlerFunc(s.nextLesson)))
|
||||
mux.Handle("POST /practice/attempts", s.requireAuth(http.HandlerFunc(s.createAttempt)))
|
||||
mux.Handle("POST /conversation/start", s.requireAuth(http.HandlerFunc(s.startConversation)))
|
||||
mux.Handle("POST /conversation/{id}/turn", s.requireAuth(http.HandlerFunc(s.conversationTurn)))
|
||||
if s.cfg.DebugEnabled {
|
||||
mux.Handle("GET /debug/status", s.requireAuth(http.HandlerFunc(s.debugStatus)))
|
||||
mux.Handle("GET /debug/db", s.requireAuth(http.HandlerFunc(s.debugDB)))
|
||||
mux.Handle("GET /debug/flowise", s.requireAuth(http.HandlerFunc(s.debugFlowise)))
|
||||
mux.Handle("GET /debug/azure", s.requireAuth(http.HandlerFunc(s.debugAzure)))
|
||||
mux.Handle("GET /debug/runtime", s.requireAuth(http.HandlerFunc(s.debugRuntime)))
|
||||
}
|
||||
|
||||
return s.requestID(s.requestLogging(s.cors(mux)))
|
||||
}
|
||||
|
||||
func (s *Server) health(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) register(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
UILanguage string `json:"ui_language"`
|
||||
TargetLanguage string `json:"target_language"`
|
||||
DailyGoalMinutes int `json:"daily_goal_minutes"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
result, err := s.auth.Register(r.Context(), req.Email, req.Password, req.UILanguage, req.TargetLanguage, req.DailyGoalMinutes)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, result)
|
||||
}
|
||||
|
||||
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
result, err := s.auth.Login(r.Context(), req.Email, req.Password)
|
||||
if err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
if errors.Is(err, services.ErrInvalidCredentials) {
|
||||
status = http.StatusUnauthorized
|
||||
}
|
||||
writeError(w, status, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) me(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := s.store.GetUser(r.Context(), currentUserID(r))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
profile, err := s.store.GetPrimaryProfile(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"user": user, "profile": profile})
|
||||
}
|
||||
|
||||
func (s *Server) updatePreferences(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
UILanguage string `json:"ui_language"`
|
||||
TargetLanguage string `json:"target_language"`
|
||||
CEFRLevel string `json:"cefr_level"`
|
||||
DailyGoalMinutes int `json:"daily_goal_minutes"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
profile, err := s.store.UpdatePreferences(r.Context(), currentUserID(r), req.UILanguage, req.TargetLanguage, valueOr(req.CEFRLevel, "A1"), req.DailyGoalMinutes)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, profile)
|
||||
}
|
||||
|
||||
func (s *Server) languages(w http.ResponseWriter, r *http.Request) {
|
||||
languages, err := s.store.ListLanguages(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, languages)
|
||||
}
|
||||
|
||||
func (s *Server) languageVoices(w http.ResponseWriter, r *http.Request) {
|
||||
lang, err := s.store.GetLanguage(r.Context(), r.PathValue("code"))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"code": lang.Code, "voices": lang.Voices, "default_voice": lang.DefaultTTSVoice})
|
||||
}
|
||||
|
||||
func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) {
|
||||
userID := currentUserID(r)
|
||||
user, err := s.store.GetUser(r.Context(), userID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
profile, err := s.store.GetPrimaryProfile(r.Context(), userID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
progress, err := s.store.Progress(r.Context(), userID, 5)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
lesson, exercise, err := s.store.NextLessonAndExercise(r.Context(), profile)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, domain.Dashboard{
|
||||
User: user, Profile: profile, Progress: progress, NextLesson: lesson, NextExercise: exercise,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) progress(w http.ResponseWriter, r *http.Request) {
|
||||
progress, err := s.store.Progress(r.Context(), currentUserID(r), 20)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, progress)
|
||||
}
|
||||
|
||||
func (s *Server) nextLesson(w http.ResponseWriter, r *http.Request) {
|
||||
profile, err := s.store.GetPrimaryProfile(r.Context(), currentUserID(r))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
lesson, exercise, err := s.store.NextLessonAndExercise(r.Context(), profile)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"lesson": lesson, "exercise": exercise})
|
||||
}
|
||||
|
||||
func (s *Server) createAttempt(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseMultipartForm(24 << 20); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
exerciseID := r.FormValue("exercise_id")
|
||||
exercise, err := s.store.GetExercise(r.Context(), exerciseID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
file, header, err := r.FormFile("audio")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, errors.New("audio file is required"))
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
audio, err := io.ReadAll(io.LimitReader(file, 20<<20))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
contentType := header.Header.Get("Content-Type")
|
||||
if contentType == "" {
|
||||
contentType = "audio/wav"
|
||||
}
|
||||
|
||||
result, err := s.speech.AssessPronunciation(r.Context(), services.PronunciationInput{
|
||||
Audio: audio, ContentType: contentType, TargetText: exercise.TargetText, Locale: exercise.TargetLanguage,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadGateway, err)
|
||||
return
|
||||
}
|
||||
teacher, err := s.teacher.FeedbackForAttempt(r.Context(), exercise.TargetText, result, weakWords(result.WordScores))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadGateway, err)
|
||||
return
|
||||
}
|
||||
attempt, err := s.store.SaveAttempt(r.Context(), domain.Attempt{
|
||||
UserID: currentUserID(r),
|
||||
ExerciseID: exercise.ID,
|
||||
TargetLanguage: exercise.TargetLanguage,
|
||||
RecognizedText: result.RecognizedText,
|
||||
OverallScore: result.OverallScore,
|
||||
AccuracyScore: result.AccuracyScore,
|
||||
FluencyScore: result.FluencyScore,
|
||||
CompletenessScore: result.CompletenessScore,
|
||||
ProsodyScore: result.ProsodyScore,
|
||||
WordScores: result.WordScores,
|
||||
TeacherFeedback: teacher.TeacherFeedback,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"attempt": attempt, "teacher": teacher, "provider": result.Provider})
|
||||
}
|
||||
|
||||
func (s *Server) startConversation(w http.ResponseWriter, r *http.Request) {
|
||||
profile, err := s.store.GetPrimaryProfile(r.Context(), currentUserID(r))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
session, err := s.store.CreateConversationSession(r.Context(), currentUserID(r), profile.TargetLanguage, profile.CEFRLevel)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
teacher, err := s.teacher.StartConversation(r.Context(), profile.TargetLanguage, profile.CEFRLevel)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadGateway, err)
|
||||
return
|
||||
}
|
||||
lang, _ := s.store.GetLanguage(r.Context(), profile.TargetLanguage)
|
||||
audio, mime, _ := s.speech.Synthesize(r.Context(), lang.AzureLocale, lang.DefaultTTSVoice, firstNonEmpty(teacher.TTSText, teacher.TargetText))
|
||||
turn, _ := s.store.SaveConversationTurn(r.Context(), domain.ConversationTurn{SessionID: session.ID, Speaker: "teacher", Text: firstNonEmpty(teacher.TTSText, teacher.TargetText)})
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"session": session,
|
||||
"turn": turn,
|
||||
"teacher": teacher,
|
||||
"audio": encodeAudio(audio, mime),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) conversationTurn(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
profile, err := s.store.GetPrimaryProfile(r.Context(), currentUserID(r))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
sessionID := r.PathValue("id")
|
||||
userTurn, err := s.store.SaveConversationTurn(r.Context(), domain.ConversationTurn{SessionID: sessionID, Speaker: "learner", Text: req.Text})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
teacher, err := s.teacher.ContinueConversation(r.Context(), profile.TargetLanguage, profile.CEFRLevel, req.Text)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadGateway, err)
|
||||
return
|
||||
}
|
||||
lang, _ := s.store.GetLanguage(r.Context(), profile.TargetLanguage)
|
||||
audio, mime, _ := s.speech.Synthesize(r.Context(), lang.AzureLocale, lang.DefaultTTSVoice, firstNonEmpty(teacher.TTSText, teacher.TargetText))
|
||||
teacherTurn, _ := s.store.SaveConversationTurn(r.Context(), domain.ConversationTurn{SessionID: sessionID, Speaker: "teacher", Text: firstNonEmpty(teacher.TTSText, teacher.TargetText)})
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"user_turn": userTurn,
|
||||
"teacher_turn": teacherTurn,
|
||||
"teacher": teacher,
|
||||
"audio": encodeAudio(audio, mime),
|
||||
})
|
||||
}
|
||||
|
||||
func weakWords(words []domain.WordScore) []domain.WordScore {
|
||||
out := make([]domain.WordScore, 0)
|
||||
for _, word := range words {
|
||||
if word.Accuracy < 75 {
|
||||
out = append(out, word)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func encodeAudio(audio []byte, mime string) map[string]string {
|
||||
if len(audio) == 0 {
|
||||
return nil
|
||||
}
|
||||
return map[string]string{
|
||||
"mime_type": mime,
|
||||
"base64": base64.StdEncoding.EncodeToString(audio),
|
||||
}
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func valueOr(value, fallback string) string {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return fallback
|
||||
}
|
||||
return value
|
||||
}
|
||||
Reference in New Issue
Block a user