fyp/logic/models/delete.go

112 lines
2.6 KiB
Go

package models
import (
"fmt"
"net/http"
"os"
"path"
"strconv"
. "git.andr3h3nriqu3s.com/andr3/fyp/logic/models/utils"
. "git.andr3h3nriqu3s.com/andr3/fyp/logic/utils"
)
func deleteModel(handle *Handle, id string, w http.ResponseWriter, c *Context, model BaseModel) {
fmt.Printf("Removing model with id: %s\n", id)
_, err := handle.Db.Exec("delete from models where id=$1;", id)
if err != nil {
fmt.Println(err)
panic("TODO handle better deleteModel failed delete database query")
}
model_path := path.Join("./savedData", id)
fmt.Printf("Removing folder of model with id: %s at %s\n", id, model_path)
err = os.RemoveAll(model_path)
if err != nil {
fmt.Println(err)
panic("TODO handle better deleteModel failed to delete folder")
}
if c.Mode == HTML {
// TODO move this to a constant so i don't forget
w.WriteHeader(309)
c.Mode = HTMLFULL
}
LoadBasedOnAnswer(c.Mode, w, "/models/delete.html", c.AddMap(AnyMap{
"Model": model,
}))
}
func handleDelete(handle *Handle) {
handle.Delete("/models/delete", func(w http.ResponseWriter, r *http.Request, c *Context) *Error {
if c.Mode == JSON {
panic("TODO handle json on models/delete")
}
f, err := MyParseForm(r)
if err != nil {
return ErrorCode(err, 400, nil)
}
if !CheckId(f, "id") {
return ErrorCode(nil, http.StatusNotFound, AnyMap{
"NotFoundMessage": "Model not found",
"GoBackLink": "/models",
})
}
id := f.Get("id")
// TODO handle admin users
rows, err := handle.Db.Query("select name, status from models where id=$1 and user_id=$2;", id, c.User.Id)
if err != nil {
return Error500(err)
}
defer rows.Close()
if !rows.Next() {
return ErrorCode(nil, http.StatusNotFound, AnyMap{
"NotFoundMessage": "Model not found",
"GoBackLink": "/models",
})
}
model := BaseModel{}
model.Id = id
err = rows.Scan(&model.Name, &model.Status)
if err != nil {
return Error500(err)
}
switch model.Status {
case FAILED_PREPARING_TRAINING:
fallthrough
case FAILED_PREPARING:
deleteModel(handle, id, w, c, model)
return nil
case CONFIRM_PRE_TRAINING:
if CheckEmpty(f, "name") {
// TODO improve result
return ErrorCode(nil, http.StatusBadRequest, nil)
}
name := f.Get("name")
if name != model.Name {
LoadDefineTemplate(w, "/models/edit.html", "delete-model-card", c.AddMap(AnyMap{
"NameDoesNotMatch": true,
"Model": model,
}))
return nil
}
deleteModel(handle, id, w, c, model)
return nil
default:
panic("Do not know how to handle model in status:" + strconv.Itoa(model.Status))
}
})
}