package handlers import ( dbgen "Rezina-Backend/gen/db" "Rezina-Backend/internal/domain" minioservice "Rezina-Backend/internal/services/minio" "Rezina-Backend/internal/web_server/fileurls" "bytes" "encoding/json" "errors" "fmt" "io" "net/http" "path" "strconv" "strings" "time" "github.com/gofiber/fiber/v2" ) type uploadMediaRes struct { ObjectKey string `json:"object_key"` URL string `json:"url"` ContentType string `json:"content_type"` MediaType string `json:"media_type"` Provider string `json:"provider"` VimeoID string `json:"vimeo_id,omitempty"` EmbedURL string `json:"embed_url,omitempty"` } type uploadMediaByURLReq struct { MediaType string `json:"media_type"` SourceURL string `json:"source_url"` Title string `json:"title"` Description string `json:"description"` } type presignedUploadReq struct { MediaType string `json:"media_type"` Filename string `json:"filename"` ContentType string `json:"content_type"` FileSize int64 `json:"file_size"` } type presignedUploadRes struct { ObjectKey string `json:"object_key"` UploadURL string `json:"upload_url"` Reference string `json:"reference"` ContentType string `json:"content_type"` MediaType string `json:"media_type"` Provider string `json:"provider"` ExpiresIn int `json:"expires_in"` } type completePresignedUploadReq struct { ObjectKey string `json:"object_key"` MediaType string `json:"media_type"` FileSize int64 `json:"file_size,omitempty"` } type refreshFileURLReq struct { Reference string `json:"reference"` } // resolveFileURL converts a stored file path to a usable URL. // If the path is a MinIO reference, it generates a presigned URL. // Otherwise it returns the path as-is (e.g. "/static/..."). func (h *Handler) resolveFileURL(c *fiber.Ctx, storedPath string) string { return fileurls.New(h.minioSvc).Resolve(c.Context(), storedPath) } // GetFileURL resolves a MinIO object key to a presigned download URL. // @Summary Get presigned URL for a file // @Tags files // @Param key query string true "MinIO object key (e.g. profile_pictures/uuid.jpg)" // @Success 200 {object} domain.Response{data=GetFileURLData} // @Router /api/v1/admin/files/url [get] // @Router /api/v1/files/url [get] // @Security Bearer // @Produce json // @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 503 {object} domain.ErrorResponse "Service unavailable" func (h *Handler) GetFileURL(c *fiber.Ctx) error { key := strings.TrimSpace(c.Query("key")) if key == "" { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Missing 'key' query parameter", }) } if h.minioSvc == nil { return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{ Message: "File storage service is not available", }) } url, err := h.minioSvc.GetURL(c.Context(), key, 1*time.Hour) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to generate file URL", Error: err.Error(), }) } return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "File URL generated", Data: map[string]string{"url": url}, Success: true, StatusCode: fiber.StatusOK, }) } func (h *Handler) extractObjectKeyFromReference(reference string) (string, error) { bucket := "" if h.minioSvc != nil { bucket = h.minioSvc.BucketName() } return fileurls.ExtractObjectKey(reference, bucket) } // RefreshFileURL generates a new presigned URL from an object key, minio:// URI, or stale presigned URL. // @Summary Refresh presigned URL for a file // @Tags files // @Accept json // @Produce json // @Param body body refreshFileURLReq true "reference (object key, minio://..., or existing presigned URL)" // @Success 200 {object} domain.Response{data=RefreshFileURLData} // @Router /api/v1/admin/files/refresh-url [post] // @Router /api/v1/files/refresh-url [post] // @Security Bearer // @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 503 {object} domain.ErrorResponse "Service unavailable" func (h *Handler) RefreshFileURL(c *fiber.Ctx) error { if h.minioSvc == nil { return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{ Message: "File storage service is not available", }) } var req refreshFileURLReq if err := c.BodyParser(&req); err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid request body", Error: err.Error(), }) } objectKey, err := h.extractObjectKeyFromReference(req.Reference) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid file reference", Error: err.Error(), }) } freshURL, err := h.minioSvc.GetURL(c.Context(), objectKey, 1*time.Hour) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to refresh file URL", Error: err.Error(), }) } return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "File URL refreshed", Data: map[string]interface{}{ "object_key": objectKey, "url": freshURL, "expires_in": int((1 * time.Hour).Seconds()), }, Success: true, StatusCode: fiber.StatusOK, }) } // CreatePresignedUpload returns a presigned PUT URL so the client can upload directly to MinIO with progress tracking. // @Summary Create presigned MinIO upload URL // @Description Returns a short-lived PUT URL and object key. Upload the file with HTTP PUT to upload_url using the same Content-Type, then call POST /files/complete-upload. // @Tags files // @Accept json // @Produce json // @Param body body presignedUploadReq true "Presigned upload request" // @Success 201 {object} domain.Response{data=presignedUploadRes} // @Router /api/v1/admin/files/presign-upload [post] // @Router /api/v1/files/presign-upload [post] // @Security Bearer // @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 503 {object} domain.ErrorResponse "Service unavailable" func (h *Handler) CreatePresignedUpload(c *fiber.Ctx) error { if h.minioSvc == nil { return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{ Message: "File storage service is not available", }) } var req presignedUploadReq if err := c.BodyParser(&req); err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid request body", Error: err.Error(), }) } mediaType := strings.ToLower(strings.TrimSpace(req.MediaType)) filename := strings.TrimSpace(req.Filename) contentType := strings.TrimSpace(req.ContentType) if mediaType == "" || filename == "" || contentType == "" || req.FileSize <= 0 { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid request body", Error: "media_type, filename, content_type, and file_size are required", }) } if mediaType == "video" { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Use Vimeo TUS for video uploads", Error: "POST /api/v1/vimeo/uploads/tus for video files", }) } if !isPresignedMinIOMediaType(mediaType) { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid media_type", Error: "media_type must be one of: image, audio, pdf", }) } maxSize := maxUploadSizeForMediaType(mediaType) if req.FileSize > maxSize { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "File too large", Error: "File exceeds size limit for selected media_type", }) } normalizedType, err := normalizeAndValidateMediaContentType(mediaType, contentType, filename) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid file type", Error: err.Error(), }) } result, err := h.minioSvc.CreatePresignedUpload(c.Context(), mediaType, filename, normalizedType) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to create presigned upload URL", Error: err.Error(), }) } reference := "minio://" + result.ObjectKey meta, _ := json.Marshal(map[string]interface{}{"object_key": result.ObjectKey, "media_type": mediaType}) h.recordActivity(c, domain.ActionFilePresignCreated, domain.ResourceFile, nil, "Created presigned upload URL", meta) return c.Status(fiber.StatusCreated).JSON(domain.Response{ Message: "Presigned upload URL created successfully", Data: presignedUploadRes{ ObjectKey: result.ObjectKey, UploadURL: result.UploadURL, Reference: reference, ContentType: result.ContentType, MediaType: mediaType, Provider: "MINIO", ExpiresIn: result.ExpiresIn, }, Success: true, StatusCode: fiber.StatusCreated, }) } // CompletePresignedUpload verifies a client-direct MinIO upload and returns the stored file reference. // @Summary Complete presigned MinIO upload // @Description Call after PUT upload to upload_url. Returns the same file metadata shape as POST /files/upload. // @Tags files // @Accept json // @Produce json // @Param body body completePresignedUploadReq true "Complete upload request" // @Success 200 {object} domain.Response{data=uploadMediaRes} // @Router /api/v1/admin/files/complete-upload [post] // @Router /api/v1/files/complete-upload [post] // @Security Bearer // @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 404 {object} domain.ErrorResponse "Resource not found" // @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 503 {object} domain.ErrorResponse "Service unavailable" func (h *Handler) CompletePresignedUpload(c *fiber.Ctx) error { if h.minioSvc == nil { return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{ Message: "File storage service is not available", }) } var req completePresignedUploadReq if err := c.BodyParser(&req); err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid request body", Error: err.Error(), }) } objectKey := strings.TrimSpace(req.ObjectKey) mediaType := strings.ToLower(strings.TrimSpace(req.MediaType)) if objectKey == "" || mediaType == "" { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid request body", Error: "object_key and media_type are required", }) } if !isPresignedMinIOMediaType(mediaType) { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid media_type", Error: "media_type must be one of: image, audio, pdf", }) } if !objectKeyMatchesMediaType(objectKey, mediaType) { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid object_key", Error: "object_key does not match media_type", }) } size, contentType, err := h.minioSvc.ConfirmUploadedObject(c.Context(), objectKey) if err != nil { if errors.Is(err, minioservice.ErrUploadedObjectNotFound) { return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{ Message: "Uploaded file not found", Error: "Complete the PUT upload to MinIO before calling this endpoint", }) } return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to verify uploaded file", Error: err.Error(), }) } if req.FileSize > 0 && size != req.FileSize { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Uploaded file size mismatch", Error: fmt.Sprintf("expected %d bytes, got %d", req.FileSize, size), }) } if maxSize := maxUploadSizeForMediaType(mediaType); size > maxSize { _ = h.minioSvc.Delete(c.Context(), objectKey) return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Uploaded file too large", Error: "File exceeds size limit for selected media_type", }) } storedPath := "minio://" + objectKey meta, _ := json.Marshal(map[string]interface{}{"object_key": objectKey, "media_type": mediaType}) h.recordActivity(c, domain.ActionFileUploaded, domain.ResourceFile, nil, "Completed presigned file upload", meta) return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "File uploaded successfully", Data: uploadMediaRes{ ObjectKey: objectKey, URL: h.resolveFileURL(c, storedPath), ContentType: contentType, MediaType: mediaType, Provider: "MINIO", }, Success: true, StatusCode: fiber.StatusOK, }) } func isPresignedMinIOMediaType(mediaType string) bool { switch mediaType { case "image", "audio", "pdf": return true default: return false } } func maxUploadSizeForMediaType(mediaType string) int64 { switch mediaType { case "image": return 10 * 1024 * 1024 case "audio": return 50 * 1024 * 1024 case "pdf": return 25 * 1024 * 1024 default: return 100 * 1024 * 1024 } } func objectKeyMatchesMediaType(objectKey, mediaType string) bool { prefix := mediaType + "/" if !strings.HasPrefix(objectKey, prefix) { return false } rest := strings.TrimPrefix(objectKey, prefix) return rest != "" && !strings.Contains(rest, "/") } // UploadMedia uploads an image/audio/video/pdf file and returns its URL and key. // @Summary Upload media file // @Tags files // @Accept multipart/form-data // @Param media_type formData string true "Media type: image|audio|video|pdf" // @Param file formData file true "Media file" // @Success 200 {object} domain.Response{data=uploadMediaRes} // @Router /api/v1/admin/files/upload [post] // @Router /api/v1/files/upload [post] // @Security Bearer // @Produce json // @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 503 {object} domain.ErrorResponse "Service unavailable" func (h *Handler) UploadMedia(c *fiber.Ctx) error { mediaType := strings.ToLower(strings.TrimSpace(c.FormValue("media_type"))) sourceURL := strings.TrimSpace(c.FormValue("source_url")) title := strings.TrimSpace(c.FormValue("title")) description := strings.TrimSpace(c.FormValue("description")) if strings.Contains(strings.ToLower(c.Get("Content-Type")), "application/json") { var req uploadMediaByURLReq if err := c.BodyParser(&req); err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid request body", Error: err.Error(), }) } mediaType = strings.ToLower(strings.TrimSpace(req.MediaType)) sourceURL = strings.TrimSpace(req.SourceURL) title = strings.TrimSpace(req.Title) description = strings.TrimSpace(req.Description) } if mediaType == "" { mediaType = "file" } if mediaType != "image" && mediaType != "audio" && mediaType != "video" && mediaType != "pdf" { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid media_type", Error: "media_type must be one of: image, audio, video, pdf", }) } maxSize := int64(100 * 1024 * 1024) // default 100MB switch mediaType { case "image": maxSize = 10 * 1024 * 1024 case "audio": maxSize = 50 * 1024 * 1024 case "pdf": maxSize = 25 * 1024 * 1024 case "video": maxSize = 500 * 1024 * 1024 } if mediaType == "video" && h.vimeoSvc == nil { return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{ Message: "Vimeo service is not available for video uploads", }) } if (mediaType == "image" || mediaType == "audio" || mediaType == "pdf") && h.minioSvc == nil { return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{ Message: "MinIO service is not available for image/audio/pdf uploads", }) } var ( fileName string contentType string data []byte ) if sourceURL != "" { fetched, err := fetchMediaFromSourceURL(c.Context(), sourceURL, mediaType, maxSize) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Failed to fetch source URL", Error: err.Error(), }) } fileName = fetched.FileName contentType = fetched.ContentType data = fetched.Data } else { fileHeader, err := c.FormFile("file") if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "File is required", Error: err.Error(), }) } if fileHeader.Size > maxSize { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "File too large", Error: "File exceeds size limit for selected media_type", }) } fh, err := fileHeader.Open() if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to read file", Error: err.Error(), }) } defer fh.Close() head := make([]byte, 512) n, _ := fh.Read(head) contentType = http.DetectContentType(head[:n]) rest, err := io.ReadAll(fh) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to read file", Error: err.Error(), }) } data = append(head[:n], rest...) fileName = fileHeader.Filename } var err error contentType, err = normalizeAndValidateMediaContentType(mediaType, contentType, fileName) if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid file type", Error: err.Error(), }) } if mediaType == "video" { if title == "" { title = fileName } vimeoUpload, err := h.vimeoSvc.UploadVideoFile(c.Context(), title, description, bytes.NewReader(data), int64(len(data))) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to upload video to Vimeo", Error: err.Error(), }) } meta, _ := json.Marshal(map[string]interface{}{"media_type": mediaType, "vimeo_id": vimeoUpload.VimeoID}) h.recordActivity(c, domain.ActionFileUploaded, domain.ResourceFile, nil, "Uploaded video file", meta) return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Video uploaded successfully", Data: uploadMediaRes{ URL: vimeoUpload.Link, ContentType: contentType, MediaType: mediaType, Provider: "VIMEO", VimeoID: vimeoUpload.VimeoID, EmbedURL: "https://player.vimeo.com/video/" + vimeoUpload.VimeoID, }, Success: true, StatusCode: fiber.StatusOK, }) } uploadResult, err := h.minioSvc.Upload( c.Context(), mediaType, fileName, bytes.NewReader(data), int64(len(data)), contentType, ) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to upload file", Error: err.Error(), }) } storedPath := "minio://" + uploadResult.ObjectKey meta, _ := json.Marshal(map[string]interface{}{"object_key": uploadResult.ObjectKey, "media_type": mediaType}) h.recordActivity(c, domain.ActionFileUploaded, domain.ResourceFile, nil, "Uploaded file", meta) return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "File uploaded successfully", Data: uploadMediaRes{ ObjectKey: uploadResult.ObjectKey, URL: h.resolveFileURL(c, storedPath), ContentType: contentType, MediaType: mediaType, Provider: "MINIO", }, Success: true, StatusCode: fiber.StatusOK, }) } func normalizeAndValidateMediaContentType(mediaType, contentType, fileName string) (string, error) { contentType = strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0])) if contentType == "" { contentType = "application/octet-stream" } switch mediaType { case "image": if contentType != "image/jpeg" && contentType != "image/png" && contentType != "image/webp" { return "", fmt.Errorf("only jpg, png, and webp images are allowed") } case "audio": allowedAudio := map[string]bool{ "audio/mpeg": true, "audio/wav": true, "audio/ogg": true, "audio/mp4": true, "audio/aac": true, "audio/webm": true, "video/ogg": true, "video/webm": true, "audio/x-wav": true, "audio/x-m4a": true, "audio/flac": true, } if contentType == "application/octet-stream" { filenameLower := strings.ToLower(fileName) lastDot := strings.LastIndex(filenameLower, ".") ext := "" if lastDot != -1 && lastDot+1 < len(filenameLower) { ext = filenameLower[lastDot+1:] } extMap := map[string]string{ "mp3": "audio/mpeg", "wav": "audio/wav", "ogg": "audio/ogg", "m4a": "audio/mp4", "aac": "audio/aac", "webm": "audio/webm", "flac": "audio/flac", } if ct, ok := extMap[ext]; ok { contentType = ct } } if !allowedAudio[contentType] { return "", fmt.Errorf("only supported audio formats are allowed") } case "video": if !strings.HasPrefix(contentType, "video/") { return "", fmt.Errorf("only video files are allowed") } case "pdf": if contentType == "application/octet-stream" { if ext := strings.ToLower(path.Ext(fileName)); ext == ".pdf" { contentType = "application/pdf" } } if contentType != "application/pdf" { return "", fmt.Errorf("only PDF files are allowed") } } return contentType, nil } // UploadAudio uploads an audio file to MinIO and returns the object key. // @Summary Upload an audio file // @Tags files // @Accept multipart/form-data // @Param file formData file true "Audio file (mp3, wav, ogg, m4a, aac, webm)" // @Success 200 {object} domain.Response{data=UploadAudioData} // @Router /api/v1/admin/files/audio [post] // @Router /api/v1/files/audio [post] // @Security Bearer // @Produce json // @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 503 {object} domain.ErrorResponse "Service unavailable" func (h *Handler) UploadAudio(c *fiber.Ctx) error { if h.minioSvc == nil { return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{ Message: "File storage service is not available", }) } fileHeader, err := c.FormFile("file") if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Audio file is required", Error: err.Error(), }) } const maxSize = 50 * 1024 * 1024 // 50 MB if fileHeader.Size > maxSize { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "File too large", Error: "Audio file must be <= 50MB", }) } fh, err := fileHeader.Open() if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to read file", Error: err.Error(), }) } defer fh.Close() head := make([]byte, 512) n, _ := fh.Read(head) contentType := http.DetectContentType(head[:n]) allowedTypes := map[string]bool{ "audio/mpeg": true, // mp3 "audio/wav": true, "audio/ogg": true, "audio/mp4": true, // m4a "audio/aac": true, "audio/webm": true, "video/ogg": true, // ogg sometimes detected as video/ogg "video/webm": true, // webm audio sometimes detected as video/webm "audio/x-wav": true, "audio/x-m4a": true, "audio/flac": true, } // DetectContentType may return "application/octet-stream" for some audio formats. // In that case, fall back to extension-based detection. if contentType == "application/octet-stream" { ext := strings.ToLower(strings.TrimLeft(strings.ToLower(fileHeader.Filename[strings.LastIndex(fileHeader.Filename, "."):]), ".")) extMap := map[string]string{ "mp3": "audio/mpeg", "wav": "audio/wav", "ogg": "audio/ogg", "m4a": "audio/mp4", "aac": "audio/aac", "webm": "audio/webm", "flac": "audio/flac", } if ct, ok := extMap[ext]; ok { contentType = ct } } if !allowedTypes[contentType] { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid file type", Error: "Only audio files are allowed (mp3, wav, ogg, m4a, aac, webm, flac)", }) } rest, err := io.ReadAll(fh) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to read file", Error: err.Error(), }) } data := append(head[:n], rest...) result, err := h.minioSvc.Upload(c.Context(), "audio", fileHeader.Filename, bytes.NewReader(data), int64(len(data)), contentType) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to upload audio file", Error: err.Error(), }) } storedPath := "minio://" + result.ObjectKey meta, _ := json.Marshal(map[string]interface{}{"object_key": result.ObjectKey, "media_type": "audio"}) h.recordActivity(c, domain.ActionFileUploaded, domain.ResourceFile, nil, "Uploaded audio file", meta) return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Audio file uploaded successfully", Data: map[string]string{ "object_key": result.ObjectKey, "url": h.resolveFileURL(c, storedPath), "content_type": contentType, }, Success: true, StatusCode: fiber.StatusOK, }) } // SubmitAudioAnswer allows a learner to upload an audio recording as their answer // to an AUDIO-type question within a question set (practice). // @Summary Submit audio answer for a question // @Tags questions // @Accept multipart/form-data // @Param question_id formData int true "Question ID" // @Param question_set_id formData int true "Question Set ID" // @Param file formData file true "Audio recording" // @Success 200 {object} domain.Response{data=SubmitAudioAnswerData} // @Router /api/v1/questions/audio-answer [post] // @Security Bearer // @Produce json // @Failure 401 {string} string "Missing, invalid, or expired Bearer token" // @Failure 403 {string} string "Account audience, status, permission, or subscription does not allow this operation" // @Failure 400 {object} domain.ErrorResponse "Invalid request" // @Failure 500 {object} domain.ErrorResponse "Internal server error" // @Failure 503 {object} domain.ErrorResponse "Service unavailable" func (h *Handler) SubmitAudioAnswer(c *fiber.Ctx) error { if h.minioSvc == nil { return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{ Message: "File storage service is not available", }) } userID, ok := c.Locals("user_id").(int64) if !ok { return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{ Message: "Unauthorized", }) } // JSON mode: store reference to previously uploaded media key if strings.Contains(strings.ToLower(c.Get("Content-Type")), "application/json") { var req struct { QuestionID int64 `json:"question_id"` QuestionSetID int64 `json:"question_set_id"` ObjectKey string `json:"object_key"` } if err := c.BodyParser(&req); err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid request body", Error: err.Error(), }) } if req.QuestionID <= 0 || req.QuestionSetID <= 0 || strings.TrimSpace(req.ObjectKey) == "" { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "question_id, question_set_id and object_key are required", }) } row, err := h.analyticsDB.CreateUserAudioResponse(c.Context(), dbgen.CreateUserAudioResponseParams{ UserID: userID, QuestionID: req.QuestionID, QuestionSetID: req.QuestionSetID, AudioObjectKey: req.ObjectKey, }) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to save audio answer", Error: err.Error(), }) } audioURL := h.resolveFileURL(c, "minio://"+req.ObjectKey) qid := req.QuestionID h.recordActivity(c, domain.ActionQuestionAudioAnswerSubmitted, domain.ResourceQuestion, &qid, fmt.Sprintf("Submitted audio answer for question %d", req.QuestionID), nil) return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Audio answer submitted successfully", Data: map[string]interface{}{ "id": row.ID, "question_id": row.QuestionID, "question_set_id": row.QuestionSetID, "audio_url": audioURL, "created_at": row.CreatedAt, }, Success: true, StatusCode: fiber.StatusOK, }) } questionID, err := strconv.ParseInt(c.FormValue("question_id"), 10, 64) if err != nil || questionID <= 0 { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid question_id", }) } questionSetID, err := strconv.ParseInt(c.FormValue("question_set_id"), 10, 64) if err != nil || questionSetID <= 0 { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Invalid question_set_id", }) } fileHeader, err := c.FormFile("file") if err != nil { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "Audio file is required", Error: err.Error(), }) } const maxSize = 50 * 1024 * 1024 // 50 MB if fileHeader.Size > maxSize { return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ Message: "File too large", Error: "Audio file must be <= 50MB", }) } fh, err := fileHeader.Open() if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to read file", Error: err.Error(), }) } defer fh.Close() head := make([]byte, 512) n, _ := fh.Read(head) contentType := http.DetectContentType(head[:n]) // Fallback for audio formats that DetectContentType can't identify if contentType == "application/octet-stream" { dotIdx := strings.LastIndex(fileHeader.Filename, ".") if dotIdx >= 0 { ext := strings.ToLower(fileHeader.Filename[dotIdx+1:]) extMap := map[string]string{ "mp3": "audio/mpeg", "wav": "audio/wav", "ogg": "audio/ogg", "m4a": "audio/mp4", "aac": "audio/aac", "webm": "audio/webm", "flac": "audio/flac", } if ct, ok := extMap[ext]; ok { contentType = ct } } } rest, err := io.ReadAll(fh) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to read file", Error: err.Error(), }) } data := append(head[:n], rest...) uploadResult, err := h.minioSvc.Upload(c.Context(), "audio_answers", fileHeader.Filename, bytes.NewReader(data), int64(len(data)), contentType) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to upload audio answer", Error: err.Error(), }) } row, err := h.analyticsDB.CreateUserAudioResponse(c.Context(), dbgen.CreateUserAudioResponseParams{ UserID: userID, QuestionID: questionID, QuestionSetID: questionSetID, AudioObjectKey: uploadResult.ObjectKey, }) if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{ Message: "Failed to save audio answer", Error: err.Error(), }) } audioURL := h.resolveFileURL(c, "minio://"+uploadResult.ObjectKey) qid := questionID h.recordActivity(c, domain.ActionQuestionAudioAnswerSubmitted, domain.ResourceQuestion, &qid, fmt.Sprintf("Submitted audio answer for question %d", questionID), nil) return c.Status(fiber.StatusOK).JSON(domain.Response{ Message: "Audio answer submitted successfully", Data: map[string]interface{}{ "id": row.ID, "question_id": row.QuestionID, "question_set_id": row.QuestionSetID, "audio_url": audioURL, "created_at": row.CreatedAt, }, Success: true, StatusCode: fiber.StatusOK, }) }