feat(modpacks): implement simple zip importer and API
This commit is contained in:
68
internal/api/modpack_handler.go
Normal file
68
internal/api/modpack_handler.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"gitea.mrixs.me/minecraft-platform/backend/internal/core/importer"
|
||||
"gitea.mrixs.me/minecraft-platform/backend/internal/database"
|
||||
"gitea.mrixs.me/minecraft-platform/backend/internal/models"
|
||||
)
|
||||
|
||||
type ModpackHandler struct {
|
||||
ModpackRepo *database.ModpackRepository
|
||||
}
|
||||
|
||||
func (h *ModpackHandler) ImportModpack(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseMultipartForm(512 << 20); err != nil { // 512 MB лимит
|
||||
http.Error(w, "File too large", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
file, _, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid file upload", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
tempFile, err := os.CreateTemp("", "modpack-*.zip")
|
||||
if err != nil {
|
||||
http.Error(w, "Could not create temp file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer os.Remove(tempFile.Name())
|
||||
defer tempFile.Close()
|
||||
|
||||
_, err = io.Copy(tempFile, file)
|
||||
if err != nil {
|
||||
http.Error(w, "Could not save temp file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
storagePath := os.Getenv("MODPACKS_STORAGE_PATH")
|
||||
imp := &importer.SimpleZipImporter{StoragePath: storagePath}
|
||||
|
||||
files, err := imp.Import(tempFile.Name())
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Import failed: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
modpack := &models.Modpack{
|
||||
Name: r.FormValue("name"),
|
||||
DisplayName: r.FormValue("displayName"),
|
||||
MinecraftVersion: r.FormValue("mcVersion"),
|
||||
}
|
||||
|
||||
err = h.ModpackRepo.CreateModpackTx(r.Context(), modpack, files)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Database save failed: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
fmt.Fprintf(w, "Modpack '%s' imported successfully with %d files.", modpack.DisplayName, len(files))
|
||||
}
|
||||
Reference in New Issue
Block a user