585 lines
16 KiB
Go
585 lines
16 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"image"
|
|
_ "image/gif"
|
|
_ "image/jpeg"
|
|
_ "image/png"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
_ "golang.org/x/image/bmp"
|
|
_ "golang.org/x/image/tiff"
|
|
_ "golang.org/x/image/webp"
|
|
)
|
|
|
|
func createSessionHandler(w http.ResponseWriter, r *http.Request) {
|
|
sessionID := createSession()
|
|
setSessionData(w, &SessionData{
|
|
SessionID: sessionID,
|
|
CreatedAt: time.Now(),
|
|
})
|
|
slog.Info("created manipulation session", "session_id", sessionID)
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]string{
|
|
"session_id": sessionID,
|
|
"status": "created",
|
|
})
|
|
}
|
|
|
|
func uploadBatchHandler(w http.ResponseWriter, r *http.Request) {
|
|
sessionData := getSessionData(r)
|
|
if sessionData == nil || !validateSession(sessionData.SessionID) {
|
|
sessionID := createSession()
|
|
sessionData = &SessionData{
|
|
SessionID: sessionID,
|
|
CreatedAt: time.Now(),
|
|
}
|
|
setSessionData(w, sessionData)
|
|
}
|
|
|
|
if err := r.ParseMultipartForm(1024 * 1024 * 1024); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
chunkIndex := 0
|
|
if cStr := r.FormValue("chunk_index"); cStr != "" {
|
|
if c, err := strconv.Atoi(cStr); err == nil {
|
|
chunkIndex = c
|
|
}
|
|
}
|
|
totalChunks := 1
|
|
if tStr := r.FormValue("total_chunks"); tStr != "" {
|
|
if t, err := strconv.Atoi(tStr); err == nil {
|
|
totalChunks = t
|
|
}
|
|
}
|
|
reset := (chunkIndex == 0)
|
|
if rStr := r.FormValue("reset"); rStr == "true" {
|
|
reset = true
|
|
} else if rStr == "false" {
|
|
reset = false
|
|
}
|
|
|
|
files := r.MultipartForm.File["files"]
|
|
if len(files) == 0 {
|
|
http.Error(w, "No files provided in chunk", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
relativePaths := r.MultipartForm.Value["relative_paths"]
|
|
|
|
uploadsDir := getSessionDir(sessionData.SessionID, "uploads")
|
|
resultsDir := getSessionDir(sessionData.SessionID, "results")
|
|
if reset {
|
|
os.RemoveAll(uploadsDir)
|
|
os.RemoveAll(resultsDir)
|
|
os.MkdirAll(uploadsDir, 0755)
|
|
os.MkdirAll(resultsDir, 0755)
|
|
} else {
|
|
os.MkdirAll(uploadsDir, 0755)
|
|
os.MkdirAll(resultsDir, 0755)
|
|
}
|
|
|
|
var rootFolderName string
|
|
if len(relativePaths) > 0 && relativePaths[0] != "" {
|
|
parts := strings.Split(filepath.ToSlash(relativePaths[0]), "/")
|
|
if len(parts) > 1 {
|
|
rootFolderName = parts[0]
|
|
}
|
|
}
|
|
if rootFolderName != "" || sessionData.BatchRootFolder == "" {
|
|
sessionData.BatchRootFolder = rootFolderName
|
|
}
|
|
setSessionData(w, sessionData) // Update store
|
|
|
|
var fileInfos []map[string]interface{}
|
|
var chunkTotalSize int64
|
|
|
|
for i, fileHeader := range files {
|
|
var targetPath string
|
|
if i < len(relativePaths) && relativePaths[i] != "" {
|
|
relPath := filepath.ToSlash(relativePaths[i])
|
|
parts := strings.Split(relPath, "/")
|
|
if len(parts) > 1 {
|
|
subPath := filepath.Join(parts[1:]...)
|
|
targetPath = filepath.Join(uploadsDir, subPath)
|
|
} else {
|
|
targetPath = filepath.Join(uploadsDir, parts[0])
|
|
}
|
|
} else {
|
|
targetPath = filepath.Join(uploadsDir, fileHeader.Filename)
|
|
}
|
|
|
|
os.MkdirAll(filepath.Dir(targetPath), 0755)
|
|
|
|
file, err := fileHeader.Open()
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
out, err := os.Create(targetPath)
|
|
if err != nil {
|
|
file.Close()
|
|
continue
|
|
}
|
|
|
|
io.Copy(out, file)
|
|
out.Close()
|
|
file.Close()
|
|
|
|
stat, _ := os.Stat(targetPath)
|
|
size := stat.Size()
|
|
chunkTotalSize += size
|
|
|
|
fileInfos = append(fileInfos, map[string]interface{}{
|
|
"filename": filepath.Base(targetPath),
|
|
"size": size,
|
|
"size_mb": float64(size) / (1024 * 1024),
|
|
})
|
|
}
|
|
|
|
// Calculate accumulated total files and size across all chunks in uploadsDir
|
|
var allFilesCount int
|
|
var allFilesTotalSize int64
|
|
filepath.Walk(uploadsDir, func(path string, info os.FileInfo, err error) error {
|
|
if err == nil && !info.IsDir() {
|
|
allFilesCount++
|
|
allFilesTotalSize += info.Size()
|
|
}
|
|
return nil
|
|
})
|
|
|
|
slog.Info("batch chunk processed", "session_id", sessionData.SessionID, "chunk_index", chunkIndex, "total_chunks", totalChunks, "chunk_files", len(fileInfos), "total_uploaded_files", allFilesCount, "total_size_mb", float64(allFilesTotalSize)/(1024*1024), "root_folder", sessionData.BatchRootFolder)
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
|
"success": true,
|
|
"session_id": sessionData.SessionID,
|
|
"chunk_index": chunkIndex,
|
|
"total_chunks": totalChunks,
|
|
"chunk_files": len(fileInfos),
|
|
"total_files": allFilesCount,
|
|
"total_size_mb": float64(allFilesTotalSize) / (1024 * 1024),
|
|
"root_folder": sessionData.BatchRootFolder,
|
|
})
|
|
}
|
|
|
|
func previewBatchHandler(w http.ResponseWriter, r *http.Request) {
|
|
sessionData := getSessionData(r)
|
|
if sessionData == nil || !validateSession(sessionData.SessionID) {
|
|
http.Error(w, "No active session", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
uploadsDir := getSessionDir(sessionData.SessionID, "uploads")
|
|
var fileList []map[string]interface{}
|
|
var totalSize int64
|
|
|
|
filepath.Walk(uploadsDir, func(path string, info os.FileInfo, err error) error {
|
|
if err == nil && !info.IsDir() {
|
|
size := info.Size()
|
|
totalSize += size
|
|
fileList = append(fileList, map[string]interface{}{
|
|
"filename": info.Name(),
|
|
"size": size,
|
|
"size_kb": float64(size) / 1024,
|
|
})
|
|
}
|
|
return nil
|
|
})
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
|
"files": fileList,
|
|
"count": len(fileList),
|
|
"total_size": totalSize,
|
|
"total_size_mb": float64(totalSize) / (1024 * 1024),
|
|
})
|
|
}
|
|
|
|
func batchProcessSessionHandler(w http.ResponseWriter, r *http.Request) {
|
|
sessionData := getSessionData(r)
|
|
|
|
var rawMap map[string]interface{}
|
|
if err := json.NewDecoder(r.Body).Decode(&rawMap); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if sessionData == nil {
|
|
if sid, ok := rawMap["session_id"].(string); ok && sid != "" && validateSession(sid) {
|
|
sessionData = &SessionData{SessionID: sid, CreatedAt: time.Now()}
|
|
setSessionData(w, sessionData)
|
|
}
|
|
}
|
|
if sessionData == nil || !validateSession(sessionData.SessionID) {
|
|
http.Error(w, "Invalid or expired session. Please re-upload your files.", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
var data struct {
|
|
Operation string
|
|
Params map[string]interface{}
|
|
}
|
|
if op, ok := rawMap["operation"].(string); ok {
|
|
data.Operation = op
|
|
}
|
|
if p, ok := rawMap["params"].(map[string]interface{}); ok {
|
|
data.Params = p
|
|
} else {
|
|
data.Params = rawMap
|
|
}
|
|
|
|
uploadsDir := getSessionDir(sessionData.SessionID, "uploads")
|
|
resultsDir := getSessionDir(sessionData.SessionID, "results")
|
|
|
|
os.RemoveAll(resultsDir)
|
|
os.MkdirAll(resultsDir, 0755)
|
|
|
|
var allFiles []string
|
|
filepath.Walk(uploadsDir, func(path string, info os.FileInfo, err error) error {
|
|
if err == nil && !info.IsDir() {
|
|
allFiles = append(allFiles, path)
|
|
}
|
|
return nil
|
|
})
|
|
|
|
if len(allFiles) == 0 {
|
|
http.Error(w, "No files found in upload session. Please select and upload images first.", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
rootFolder := sessionData.BatchRootFolder
|
|
manipulatedFolder := "processed_manipulated"
|
|
if rootFolder != "" {
|
|
manipulatedFolder = rootFolder + "_manipulated"
|
|
}
|
|
zipName := manipulatedFolder + ".zip"
|
|
|
|
sessionData.BatchZipName = zipName
|
|
setSessionData(w, sessionData)
|
|
|
|
// Setup SSE
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.Header().Set("Cache-Control", "no-cache, no-transform")
|
|
w.Header().Set("Connection", "keep-alive")
|
|
w.Header().Set("X-Accel-Buffering", "no")
|
|
flusher, ok := w.(http.Flusher)
|
|
if !ok {
|
|
http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
var sseMu sync.Mutex
|
|
heartbeatTicker := time.NewTicker(8 * time.Second)
|
|
defer heartbeatTicker.Stop()
|
|
heartbeatDone := make(chan struct{})
|
|
defer close(heartbeatDone)
|
|
|
|
// Keep-alive goroutine to prevent reverse proxy / Cloudflare 524 timeouts
|
|
go func() {
|
|
for {
|
|
select {
|
|
case <-heartbeatTicker.C:
|
|
sseMu.Lock()
|
|
fmt.Fprintf(w, ": ping\n\n")
|
|
flusher.Flush()
|
|
sseMu.Unlock()
|
|
case <-heartbeatDone:
|
|
return
|
|
case <-r.Context().Done():
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
|
|
emitSSE := func(data any) {
|
|
jsonBytes, err := json.Marshal(data)
|
|
if err == nil {
|
|
sseMu.Lock()
|
|
fmt.Fprintf(w, "data: %s\n\n", string(jsonBytes))
|
|
flusher.Flush()
|
|
sseMu.Unlock()
|
|
}
|
|
}
|
|
|
|
totalFiles := len(allFiles)
|
|
processedCount := 0
|
|
errorCount := 0
|
|
var errors []string
|
|
var totalOriginalSize, totalCompressedSize int64
|
|
completed := 0
|
|
|
|
for _, file := range allFiles {
|
|
// Check for client disconnect
|
|
select {
|
|
case <-r.Context().Done():
|
|
slog.Warn("client cancelled batch processing", "session_id", sessionData.SessionID, "completed", completed, "total", totalFiles)
|
|
return
|
|
default:
|
|
}
|
|
|
|
completed++
|
|
|
|
stat, err := os.Stat(file)
|
|
if err != nil {
|
|
errorCount++
|
|
errors = append(errors, fmt.Sprintf("Error: %s: %v", filepath.Base(file), err))
|
|
emitSSE(map[string]interface{}{
|
|
"type": "progress",
|
|
"current": completed,
|
|
"total": totalFiles,
|
|
"filename": filepath.Base(file),
|
|
"error": true,
|
|
})
|
|
continue
|
|
}
|
|
origSize := stat.Size()
|
|
totalOriginalSize += origSize
|
|
|
|
fileReader, err := os.Open(file)
|
|
if err != nil {
|
|
errorCount++
|
|
errors = append(errors, fmt.Sprintf("Error: %s: %v", filepath.Base(file), err))
|
|
emitSSE(map[string]interface{}{
|
|
"type": "progress",
|
|
"current": completed,
|
|
"total": totalFiles,
|
|
"filename": filepath.Base(file),
|
|
"error": true,
|
|
})
|
|
continue
|
|
}
|
|
|
|
img, format, err := image.Decode(fileReader)
|
|
fileReader.Close()
|
|
|
|
if err != nil {
|
|
errorCount++
|
|
errors = append(errors, fmt.Sprintf("Error: %s: %v", filepath.Base(file), err))
|
|
emitSSE(map[string]interface{}{
|
|
"type": "progress",
|
|
"current": completed,
|
|
"total": totalFiles,
|
|
"filename": filepath.Base(file),
|
|
"error": true,
|
|
})
|
|
continue
|
|
}
|
|
if format == "" {
|
|
format = "PNG"
|
|
}
|
|
|
|
var buf []byte
|
|
var finalFmt = format
|
|
|
|
switch data.Operation {
|
|
case "resize":
|
|
width := 0
|
|
if w, ok := data.Params["width"].(float64); ok { width = int(w) }
|
|
height := 0
|
|
if h, ok := data.Params["height"].(float64); ok { height = int(h) }
|
|
maintain := true
|
|
if m, ok := data.Params["maintain_aspect"].(bool); ok { maintain = m }
|
|
if m, ok := data.Params["maintain"].(bool); ok { maintain = m }
|
|
processed := resizeImage(img, width, height, maintain)
|
|
buf, finalFmt = compressLogic(processed, format, 95)
|
|
case "convert":
|
|
targetFmt := "png"
|
|
if f, ok := data.Params["format"].(string); ok && f != "" {
|
|
targetFmt = f
|
|
}
|
|
buf, finalFmt = compressLogic(img, targetFmt, 95)
|
|
case "compress":
|
|
targetFmt := format
|
|
if f, ok := data.Params["format"].(string); ok && f != "" && f != "original" {
|
|
targetFmt = f
|
|
}
|
|
q := 80
|
|
if qval, ok := data.Params["quality"].(float64); ok { q = int(qval) }
|
|
|
|
// Smart Target Size Compression
|
|
var targetSizeMB, currentSizeMB float64
|
|
if t, ok := data.Params["target_size_mb"].(float64); ok { targetSizeMB = t }
|
|
if tstr, ok := data.Params["target_size_mb"].(string); ok { targetSizeMB, _ = strconv.ParseFloat(tstr, 64) }
|
|
if c, ok := data.Params["current_size_mb"].(float64); ok { currentSizeMB = c }
|
|
if cstr, ok := data.Params["current_size_mb"].(string); ok { currentSizeMB, _ = strconv.ParseFloat(cstr, 64) }
|
|
|
|
if targetSizeMB > 0 && currentSizeMB > 0 {
|
|
ratio := targetSizeMB / currentSizeMB
|
|
if ratio >= 1.0 {
|
|
buf, finalFmt = compressLogic(img, targetFmt, 92)
|
|
} else {
|
|
perFileTarget := int64(float64(origSize) * ratio)
|
|
initQ := int(ratio * 90)
|
|
if initQ < 10 { initQ = 10 }
|
|
if initQ > 90 { initQ = 90 }
|
|
|
|
trialBuf, trialFmt := compressLogic(img, targetFmt, initQ)
|
|
trialSize := int64(len(trialBuf))
|
|
if trialSize <= perFileTarget && trialSize >= int64(float64(perFileTarget)*0.85) {
|
|
buf, finalFmt = trialBuf, trialFmt
|
|
} else {
|
|
lo, hi := 5, 95
|
|
if trialSize <= perFileTarget {
|
|
lo = initQ
|
|
} else {
|
|
hi = initQ
|
|
}
|
|
bestBuf := trialBuf
|
|
bestFmt := trialFmt
|
|
// Fast bounded bisection (max 4 iterations)
|
|
for iter := 0; iter < 4; iter++ {
|
|
mid := (lo + hi) / 2
|
|
tBuf, tFmt := compressLogic(img, targetFmt, mid)
|
|
tSize := int64(len(tBuf))
|
|
if tSize <= perFileTarget {
|
|
bestBuf, bestFmt = tBuf, tFmt
|
|
lo = mid + 1
|
|
} else {
|
|
hi = mid - 1
|
|
}
|
|
}
|
|
buf, finalFmt = bestBuf, bestFmt
|
|
}
|
|
}
|
|
} else {
|
|
buf, finalFmt = compressLogic(img, targetFmt, q)
|
|
}
|
|
case "crop":
|
|
l, t, r, b := 0, 0, 800, 600
|
|
if val, ok := data.Params["left"].(float64); ok { l = int(val) }
|
|
if val, ok := data.Params["top"].(float64); ok { t = int(val) }
|
|
if val, ok := data.Params["right"].(float64); ok { r = int(val) }
|
|
if val, ok := data.Params["bottom"].(float64); ok { b = int(val) }
|
|
processed := cropImage(img, l, t, r, b)
|
|
buf, finalFmt = compressLogic(processed, format, 95)
|
|
case "filter":
|
|
f := "BLUR"
|
|
if val, ok := data.Params["filter"].(string); ok && val != "" { f = val }
|
|
if val, ok := data.Params["filter_type"].(string); ok && val != "" { f = val }
|
|
processed := filterImage(img, f)
|
|
buf, finalFmt = compressLogic(processed, format, 95)
|
|
case "rotate":
|
|
op := "90"
|
|
if val, ok := data.Params["operation"].(string); ok { op = val }
|
|
processed := rotateImage(img, op)
|
|
buf, finalFmt = compressLogic(processed, format, 95)
|
|
case "watermark":
|
|
wmPath, _ := data.Params["watermark_path"].(string)
|
|
pos := "bottom_right"
|
|
if p, ok := data.Params["position"].(string); ok && p != "" { pos = p }
|
|
op := 50
|
|
if o, ok := data.Params["opacity"].(float64); ok { op = int(o) }
|
|
if wmPath != "" {
|
|
if wmFile, err := os.Open(wmPath); err == nil {
|
|
if wmImg, _, err := image.Decode(wmFile); err == nil {
|
|
img = watermarkImage(img, wmImg, pos, op)
|
|
}
|
|
wmFile.Close()
|
|
}
|
|
}
|
|
buf, finalFmt = compressLogic(img, format, 95)
|
|
default:
|
|
buf, finalFmt = compressLogic(img, format, 95)
|
|
}
|
|
|
|
relPath, _ := filepath.Rel(uploadsDir, file)
|
|
if data.Operation == "convert" || (data.Operation == "compress" && data.Params["format"] != nil && data.Params["format"] != "original" && data.Params["format"] != "") {
|
|
ext := strings.ToLower(finalFmt)
|
|
if ext == "jpeg" {
|
|
ext = "jpg"
|
|
}
|
|
relPath = strings.TrimSuffix(relPath, filepath.Ext(relPath)) + "." + ext
|
|
}
|
|
|
|
targetFilePath := filepath.Join(resultsDir, relPath)
|
|
os.MkdirAll(filepath.Dir(targetFilePath), 0755)
|
|
|
|
os.WriteFile(targetFilePath, buf, 0644)
|
|
totalCompressedSize += int64(len(buf))
|
|
processedCount++
|
|
|
|
pd := map[string]interface{}{
|
|
"type": "progress",
|
|
"current": completed,
|
|
"total": totalFiles,
|
|
"filename": filepath.Base(file),
|
|
}
|
|
|
|
if data.Operation == "compress" {
|
|
pd["original_kb"] = float64(origSize) / 1024
|
|
pd["compressed_kb"] = float64(len(buf)) / 1024
|
|
if origSize > 0 {
|
|
pd["reduction"] = (1.0 - float64(len(buf))/float64(origSize)) * 100.0
|
|
}
|
|
}
|
|
|
|
emitSSE(pd)
|
|
}
|
|
|
|
createZip(sessionData.SessionID, "results", zipName, manipulatedFolder)
|
|
|
|
slog.Info("completed batch processing", "session_id", sessionData.SessionID, "operation", data.Operation, "processed", processedCount, "errors", errorCount, "zip_name", zipName)
|
|
|
|
finalRes := map[string]interface{}{
|
|
"type": "complete",
|
|
"status": "success",
|
|
"processed_count": processedCount,
|
|
"error_count": errorCount,
|
|
"errors": errors,
|
|
"download_ready": true,
|
|
"session_id": sessionData.SessionID,
|
|
"zip_name": zipName,
|
|
"total_original_mb": float64(totalOriginalSize) / (1024 * 1024),
|
|
"total_compressed_mb": float64(totalCompressedSize) / (1024 * 1024),
|
|
}
|
|
emitSSE(finalRes)
|
|
}
|
|
|
|
func downloadBatchHandler(w http.ResponseWriter, r *http.Request) {
|
|
sessionData := getSessionData(r)
|
|
var sessionID, zipName string
|
|
if sessionData != nil {
|
|
sessionID = sessionData.SessionID
|
|
zipName = sessionData.BatchZipName
|
|
}
|
|
if sessionID == "" {
|
|
sessionID = r.URL.Query().Get("session_id")
|
|
}
|
|
if zipName == "" {
|
|
zipName = r.URL.Query().Get("zip_name")
|
|
}
|
|
|
|
if sessionID == "" || !validateSession(sessionID) {
|
|
http.Error(w, "Invalid session", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if zipName == "" {
|
|
zipName = "processed_images.zip"
|
|
}
|
|
|
|
zipPath := filepath.Join(getSessionDir(sessionID), zipName)
|
|
if _, err := os.Stat(zipPath); os.IsNotExist(err) {
|
|
zipPath = filepath.Join(getSessionDir(sessionID), "processed_images.zip")
|
|
}
|
|
|
|
slog.Info("serving batch zip download", "session_id", sessionID, "zip", filepath.Base(zipPath))
|
|
w.Header().Set("Content-Type", "application/zip")
|
|
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filepath.Base(zipPath)))
|
|
http.ServeFile(w, r, zipPath)
|
|
}
|