Uploaded Media File Delete Update

This commit is contained in:
2026-02-22 13:04:04 -05:00
parent 3d936d8a6f
commit 3b4d5e4080
16 changed files with 701 additions and 451 deletions

12
server/routes/models.go Normal file
View File

@@ -0,0 +1,12 @@
package routes
type Simulation struct {
ID int `json:"id"`
Name string `json:"name"`
Resources []string `json:"resources"`
CreatedAt string `json:"created_at"`
Config *string `json:"config"`
SearchTime *float64 `json:"search_time"`
TotalTime *float64 `json:"total_time"`
TotalSizeBytes int64 `json:"total_size_bytes"`
}

103
server/routes/resources.go Normal file
View File

@@ -0,0 +1,103 @@
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"})
}

93
server/routes/router.go Normal file
View File

@@ -0,0 +1,93 @@
package routes
import (
"database/sql"
"net/http"
"strings"
"net/url"
)
type Router struct {
DB *sql.DB
}
func NewRouter(db *sql.DB) *Router {
return &Router{DB: db}
}
func (rt *Router) Register(mux *http.ServeMux) {
mux.HandleFunc("/api/simulations", rt.handleSimulationsBase)
mux.HandleFunc("/api/simulations/", rt.handleSimulationsPath)
}
func (rt *Router) handleSimulationsBase(w http.ResponseWriter, r *http.Request) {
if r.Method == "OPTIONS" {
rt.OptionsHandler(w, r)
return
}
if r.Method == "GET" {
rt.GetSimulations(w, r)
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func (rt *Router) handleSimulationsPath(w http.ResponseWriter, r *http.Request) {
if r.Method == "OPTIONS" {
rt.OptionsHandler(w, r)
return
}
pathParts := strings.Split(strings.Trim(r.URL.Path[len("/api/simulations/"):], "/"), "/")
if len(pathParts) == 0 || pathParts[0] == "" {
http.Error(w, "Not found", http.StatusNotFound)
return
}
if pathParts[0] == "create" && r.Method == "POST" {
rt.CreateSimulation(w, r)
return
}
idStr := pathParts[0]
if len(pathParts) == 1 {
if r.Method == "GET" {
rt.GetSimulationDetails(w, r, idStr)
} else if r.Method == "DELETE" {
rt.DeleteSimulation(w, r, idStr)
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
return
}
if len(pathParts) > 1 {
action := pathParts[1]
if r.Method == "PUT" && action == "time" {
rt.UpdateSimulationTime(w, r, idStr)
return
}
if r.Method == "PUT" && action == "rename" {
rt.RenameSimulation(w, r, idStr)
return
}
if r.Method == "POST" && action == "upload" {
rt.UploadSimulationResource(w, r, idStr)
return
}
if r.Method == "DELETE" && action == "resources" && len(pathParts) > 2 {
fileName, _ := url.PathUnescape(pathParts[2])
rt.DeleteSimulationResource(w, r, idStr, fileName)
return
}
}
http.Error(w, "Not found", http.StatusNotFound)
}
func (rt *Router) OptionsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS")
w.WriteHeader(http.StatusOK)
}

View File

@@ -0,0 +1,265 @@
package routes
import (
"database/sql"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
func (rt *Router) CreateSimulation(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
configStr := string(bodyBytes)
if configStr == "" {
http.Error(w, "Config cannot be empty", http.StatusBadRequest)
return
}
hasPattern := false
var jsonParsed map[string]interface{}
err = json.Unmarshal(bodyBytes, &jsonParsed)
if err != nil {
http.Error(w, "Invalid configuration format: must be valid JSON", http.StatusBadRequest)
return
}
for k, v := range jsonParsed {
if k == "search.yaml" || k == "search" {
if searchMap, ok := v.(map[string]interface{}); ok {
if _, ok := searchMap["spiral"]; ok {
hasPattern = true
}
if _, ok := searchMap["lawnmower"]; ok {
hasPattern = true
}
if _, ok := searchMap["levy"]; ok {
hasPattern = true
}
}
}
}
if !hasPattern {
http.Error(w, "Simulation configuration must include a search pattern (spiral, lawnmower, or levy)", http.StatusBadRequest)
return
}
var existingID int
var existingName string
err = rt.DB.QueryRow("SELECT id, name FROM simulations WHERE config = ?", configStr).Scan(&existingID, &existingName)
if err == nil {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"id": existingID,
"name": existingName,
})
return
}
var count int
rt.DB.QueryRow("SELECT COUNT(*) FROM simulations").Scan(&count)
newName := fmt.Sprintf("simulation_%d", count+1)
for {
var temp int
err := rt.DB.QueryRow("SELECT id FROM simulations WHERE name = ?", newName).Scan(&temp)
if err == sql.ErrNoRows {
break
}
count++
newName = fmt.Sprintf("simulation_%d", count+1)
}
res, err := rt.DB.Exec("INSERT INTO simulations(name, config) VALUES(?, ?)", newName, configStr)
if err != nil {
log.Println("Insert simulation error:", err)
http.Error(w, "Failed to create", http.StatusInternalServerError)
return
}
newID, _ := res.LastInsertId()
resultsDir := filepath.Join("../results", newName)
os.MkdirAll(resultsDir, 0755)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"id": newID,
"name": newName,
})
}
func (rt *Router) GetSimulations(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
rows, err := rt.DB.Query("SELECT id, name, config, created_at, search_time, total_time FROM simulations")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
var sims []Simulation
for rows.Next() {
var s Simulation
err = rows.Scan(&s.ID, &s.Name, &s.Config, &s.CreatedAt, &s.SearchTime, &s.TotalTime)
if err != nil {
log.Println("Row scan error:", err)
continue
}
sims = append(sims, s)
}
if sims == nil {
sims = []Simulation{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(sims)
}
func (rt *Router) GetSimulationDetails(w http.ResponseWriter, r *http.Request, idStr string) {
w.Header().Set("Access-Control-Allow-Origin", "*")
var s Simulation
err := rt.DB.QueryRow("SELECT id, name, config, created_at, search_time, total_time FROM simulations WHERE id = ?", idStr).Scan(&s.ID, &s.Name, &s.Config, &s.CreatedAt, &s.SearchTime, &s.TotalTime)
if err != nil {
if err == sql.ErrNoRows {
http.Error(w, "Simulation not found", http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
rows, err := rt.DB.Query("SELECT filename FROM resources WHERE simulation_id = ?", s.ID)
if err == nil {
defer rows.Close()
for rows.Next() {
var fname string
if err := rows.Scan(&fname); err == nil {
s.Resources = append(s.Resources, fname)
if stat, err := os.Stat(filepath.Join("../results", s.Name, fname)); err == nil {
s.TotalSizeBytes += stat.Size()
}
}
}
}
if s.Resources == nil {
s.Resources = []string{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(s)
}
func (rt *Router) RenameSimulation(w http.ResponseWriter, r *http.Request, idStr string) {
w.Header().Set("Access-Control-Allow-Origin", "*")
var reqBody struct {
Name string `json:"name"`
}
err := json.NewDecoder(r.Body).Decode(&reqBody)
if err != nil || strings.TrimSpace(reqBody.Name) == "" {
http.Error(w, "Invalid request body or missing name", http.StatusBadRequest)
return
}
defer r.Body.Close()
newName := strings.TrimSpace(reqBody.Name)
var oldName string
err = rt.DB.QueryRow("SELECT name FROM simulations WHERE id = ?", idStr).Scan(&oldName)
if err != nil {
http.Error(w, "Simulation not found", http.StatusNotFound)
return
}
// Make sure the new name doesn't already exist
var tempID int
err = rt.DB.QueryRow("SELECT id FROM simulations WHERE name = ?", newName).Scan(&tempID)
if err == nil {
http.Error(w, "A simulation with that name already exists", http.StatusConflict)
return
}
// Rename the physical storage folder to maintain link parity
oldDirPath := filepath.Join("../results", oldName)
newDirPath := filepath.Join("../results", newName)
if _, statErr := os.Stat(oldDirPath); statErr == nil {
err = os.Rename(oldDirPath, newDirPath)
if err != nil {
log.Println("Error renaming directory:", err)
http.Error(w, "Failed to rename results directory", http.StatusInternalServerError)
return
}
} else {
// Just ensure target dir exists
os.MkdirAll(newDirPath, 0755)
}
_, err = rt.DB.Exec("UPDATE simulations SET name = ? WHERE id = ?", newName, idStr)
if err != nil {
// Attempt revert if DB dies halfway
os.Rename(newDirPath, oldDirPath)
log.Println("Update simulation name error:", err)
http.Error(w, "Failed to update database", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "success", "new_name": newName})
}
func (rt *Router) DeleteSimulation(w http.ResponseWriter, r *http.Request, idStr string) {
w.Header().Set("Access-Control-Allow-Origin", "*")
var name string
err := rt.DB.QueryRow("SELECT name FROM simulations WHERE id = ?", idStr).Scan(&name)
if err != nil {
if err == sql.ErrNoRows {
http.Error(w, "Simulation not found", http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
// Attempt dropping resource map hooks first
_, err = rt.DB.Exec("DELETE FROM resources WHERE simulation_id = ?", idStr)
if err != nil {
log.Println("Warning: Error deleting resources map from DB:", err)
}
_, err = rt.DB.Exec("DELETE FROM simulations WHERE id = ?", idStr)
if err != nil {
log.Println("Error deleting simulation from DB:", err)
http.Error(w, "Failed to delete from database", http.StatusInternalServerError)
return
}
// Physically destroy data payload mapped onto it
dirPath := filepath.Join("../results", name)
if _, statErr := os.Stat(dirPath); statErr == nil {
err = os.RemoveAll(dirPath)
if err != nil {
log.Println("Warning: Failed fully deleting physical directory items:", err)
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "success"})
}

38
server/routes/time.go Normal file
View File

@@ -0,0 +1,38 @@
package routes
import (
"encoding/json"
"log"
"net/http"
)
func (rt *Router) UpdateSimulationTime(w http.ResponseWriter, r *http.Request, idStr string) {
w.Header().Set("Access-Control-Allow-Origin", "*")
var reqBody struct {
SearchTime *float64 `json:"search_time"`
TotalTime *float64 `json:"total_time"`
}
err := json.NewDecoder(r.Body).Decode(&reqBody)
if err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
if reqBody.SearchTime == nil || reqBody.TotalTime == nil {
http.Error(w, "Missing search_time or total_time", http.StatusBadRequest)
return
}
_, err = rt.DB.Exec("UPDATE simulations SET search_time = ?, total_time = ? WHERE id = ?", *reqBody.SearchTime, *reqBody.TotalTime, idStr)
if err != nil {
log.Println("Update simulation error:", err)
http.Error(w, "Failed to update", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "success"})
}

View File

@@ -0,0 +1,45 @@
package routes
import (
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
func TranscodeIfNeeded(simDir, filename string) string {
ext := strings.ToLower(filepath.Ext(filename))
if ext != ".avi" {
return filename
}
baseName := strings.TrimSuffix(filename, filepath.Ext(filename))
mp4Filename := baseName + ".mp4"
aviPath := filepath.Join(simDir, filename)
mp4Path := filepath.Join(simDir, mp4Filename)
if _, err := os.Stat(mp4Path); err == nil {
os.Remove(aviPath)
return mp4Filename
}
log.Printf("Attempting GPU Transcoding (h264_nvenc) %s to %s...\n", aviPath, mp4Path)
cmdGPU := exec.Command("ffmpeg", "-y", "-i", aviPath, "-c:v", "h264_nvenc", "-pix_fmt", "yuv420p", "-movflags", "+faststart", mp4Path)
if err := cmdGPU.Run(); err == nil {
os.Remove(aviPath)
return mp4Filename
}
log.Printf("GPU transcoding failed/unavailable, falling back to CPU (libx264) for %s...\n", aviPath)
cmdCPU := exec.Command("ffmpeg", "-y", "-i", aviPath, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-movflags", "+faststart", mp4Path)
if err := cmdCPU.Run(); err == nil {
os.Remove(aviPath)
return mp4Filename
} else {
log.Println("Failed to transcode (both GPU and CPU):", err)
return filename
}
}