package tasks import ( "bytes" "io" "net/http" "os" "path" . "git.andr3h3nriqu3s.com/andr3/fyp/logic/db_types" . "git.andr3h3nriqu3s.com/andr3/fyp/logic/models" . "git.andr3h3nriqu3s.com/andr3/fyp/logic/models/utils" . "git.andr3h3nriqu3s.com/andr3/fyp/logic/tasks/utils" . "git.andr3h3nriqu3s.com/andr3/fyp/logic/utils" ) func handleUpload(handler *Handle) { handler.PostAuth("/tasks/start/image", 1, func(c *Context) *Error { read_form, err := c.R.MultipartReader() if err != nil { return c.JsonBadRequest("Please provide a valid form data request!") } var json_data string var file []byte for { part, err_part := read_form.NextPart() if err_part == io.EOF { break } else if err_part != nil { return c.JsonBadRequest("Please provide a valid form data request!") } if part.FormName() == "json_data" { buf := new(bytes.Buffer) buf.ReadFrom(part) json_data = buf.String() } if part.FormName() == "file" { buf := new(bytes.Buffer) buf.ReadFrom(part) file = buf.Bytes() } } var requestData struct { ModelId string `json:"id" validate:"required"` } _err := c.ParseJson(&requestData, json_data) if _err != nil { return _err } model, err := GetBaseModel(c.Db, requestData.ModelId) if err != nil { return c.Error500(err) } switch model.Status { case READY: case READY_RETRAIN: case READY_ALTERATION: case READY_ALTERATION_FAILED: case READY_RETRAIN_FAILED: // Model can run default: return c.SendJSONStatus(http.StatusBadRequest, "Model not in the correct status to be able to evaludate a model") } // TODO Check if the user can use this model type CreateNewTask struct { UserId string `db:"user_id"` ModelId string `db:"model_id"` TaskType int `db:"task_type"` Status int `db:"status"` } newTask := CreateNewTask{ UserId: c.User.Id, ModelId: model.Id, // TODO move this to an enum TaskType: 1, Status: 0, } id, err := InsertReturnId(c, &newTask, "tasks", "id") if err != nil { return c.E500M("Error 500", err) } save_path := path.Join("savedData", model.Id, "tasks") os.MkdirAll(save_path, os.ModePerm) img_path := path.Join(save_path, id+"."+model.Format) img_file, err := os.Create(img_path) if err != nil { if _err := UpdateTaskStatus(c,id, -1, "Failed to create the file"); _err != nil { c.Logger.Error("Failed to update tasks") } return c.E500M("Failed to create the file", err) } defer img_file.Close() img_file.Write(file) if !TestImgForModel(c, model, img_path) { if _err := UpdateTaskStatus(c, id, -1, "The provided image is not a valid image for this model"); _err != nil { c.Logger.Error("Failed to update tasks") } return c.JsonBadRequest(struct { Message string `json:"message"` Id string `json:"task_id"` } { "Provided image does not match the model", id}) } UpdateStatus(c, "tasks", id, 1) return c.SendJSON(struct {Id string `json:"id"`}{id}) }) }