package routes import ( "database/sql" "encoding/json" "io" "log" "net/http" "os" "path/filepath" ) func (rt *Router) UploadSimulationResource(w http.ResponseWriter, r *http.Request, idStr string) { w.Header().Set("Access-Control-Allow-Origin", "*") var simName string err := rt.DB.QueryRow("SELECT name FROM simulations WHERE id = ?", idStr).Scan(&simName) if err != nil { if err == sql.ErrNoRows { http.Error(w, "Simulation not found", http.StatusNotFound) } else { http.Error(w, err.Error(), http.StatusInternalServerError) } return } err = r.ParseMultipartForm(500 << 20) // 500 MB max memory/file bounds if err != nil { http.Error(w, "Error parsing form: "+err.Error(), http.StatusBadRequest) return } file, handler, err := r.FormFile("file") if err != nil { http.Error(w, "Error retrieving the file", http.StatusBadRequest) return } defer file.Close() destPath := filepath.Join("../results", simName, handler.Filename) dst, err := os.Create(destPath) if err != nil { http.Error(w, "Error creating destination file: "+err.Error(), http.StatusInternalServerError) return } defer dst.Close() _, err = io.Copy(dst, file) if err != nil { http.Error(w, "Error saving file: "+err.Error(), http.StatusInternalServerError) return } finalFilename := TranscodeIfNeeded(filepath.Join("../results", simName), handler.Filename) var resID int err = rt.DB.QueryRow("SELECT id FROM resources WHERE simulation_id = ? AND filename = ?", idStr, finalFilename).Scan(&resID) if err == sql.ErrNoRows { _, err = rt.DB.Exec("INSERT INTO resources(simulation_id, filename) VALUES(?, ?)", idStr, finalFilename) if err != nil { log.Println("Error inserting uploaded resource into db:", err) } } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{ "status": "success", "filename": finalFilename, }) } func (rt *Router) DeleteSimulationResource(w http.ResponseWriter, r *http.Request, idStr string, fileName string) { w.Header().Set("Access-Control-Allow-Origin", "*") var simName string err := rt.DB.QueryRow("SELECT name FROM simulations WHERE id = ?", idStr).Scan(&simName) if err != nil { if err == sql.ErrNoRows { http.Error(w, "Simulation not found", http.StatusNotFound) } else { http.Error(w, err.Error(), http.StatusInternalServerError) } return } _, err = rt.DB.Exec("DELETE FROM resources WHERE simulation_id = ? AND filename = ?", idStr, fileName) if err != nil { log.Println("Error deleting resource from DB:", err) http.Error(w, "Failed to delete from database", http.StatusInternalServerError) return } filePath := filepath.Join("../results", simName, fileName) if _, statErr := os.Stat(filePath); statErr == nil { err = os.Remove(filePath) if err != nil { log.Println("Warning: Failed deleting physical file:", err) } } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{"status": "success"}) }