Files

665 lines
18 KiB
Go

package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"image"
"image/color"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/disintegration/imaging"
_ "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 getParamFloat(p map[string]interface{}, key string, def float64) float64 {
if v, ok := p[key]; ok {
switch val := v.(type) {
case float64:
return val
case float32:
return float64(val)
case int:
return float64(val)
case int64:
return float64(val)
case string:
if f, err := strconv.ParseFloat(val, 64); err == nil {
return f
}
}
}
return def
}
func getParamInt(p map[string]interface{}, key string, def int) int {
if v, ok := p[key]; ok {
switch val := v.(type) {
case float64:
return int(val)
case float32:
return int(val)
case int:
return val
case int64:
return int(val)
case string:
if i, err := strconv.Atoi(val); err == nil {
return i
}
if f, err := strconv.ParseFloat(val, 64); err == nil {
return int(f)
}
}
}
return def
}
func getParamBool(p map[string]interface{}, key string, def bool) bool {
if v, ok := p[key]; ok {
switch val := v.(type) {
case bool:
return val
case string:
valLower := strings.ToLower(val)
return valLower == "true" || valLower == "1" || valLower == "yes"
case int:
return val != 0
case float64:
return val != 0
}
}
return def
}
func getParamString(p map[string]interface{}, key string, def string) string {
if v, ok := p[key]; ok {
if s, ok := v.(string); ok && s != "" {
return s
}
}
return def
}
func processSingleBatchFile(file string, operation string, params map[string]interface{}, uploadsDir string, resultsDir string) (int64, int64, error) {
stat, err := os.Stat(file)
if err != nil {
return 0, 0, err
}
origSize := stat.Size()
fileReader, err := os.Open(file)
if err != nil {
return 0, 0, err
}
img, format, err := image.Decode(fileReader)
fileReader.Close()
if err != nil {
return 0, 0, err
}
if format == "" {
format = "PNG"
}
var buf []byte
var finalFmt = format
switch operation {
case "resize":
width := getParamInt(params, "width", 0)
height := getParamInt(params, "height", 0)
maintain := getParamBool(params, "maintain_aspect", true)
if !maintain {
maintain = getParamBool(params, "maintain", false)
}
processed := resizeImage(img, width, height, maintain)
buf, finalFmt = compressLogic(processed, format, 95)
case "convert":
targetFmt := getParamString(params, "format", "png")
quality := getParamInt(params, "quality", 95)
if quality <= 0 {
quality = 95
}
buf, finalFmt = compressLogic(img, targetFmt, quality)
case "compress":
targetFmt := getParamString(params, "format", "original")
if targetFmt == "original" {
targetFmt = format
}
q := getParamInt(params, "quality", 85)
if q <= 0 {
q = 85
}
targetMB := getParamFloat(params, "target_size_mb", 0)
currentMB := getParamFloat(params, "current_size_mb", 0)
if targetMB > 0 && currentMB > targetMB {
ratio := targetMB / currentMB
calculatedQuality := int(float64(q) * ratio)
if calculatedQuality < 5 {
calculatedQuality = 5
}
if calculatedQuality > 95 {
calculatedQuality = 95
}
q = calculatedQuality
}
buf, finalFmt = compressLogic(img, targetFmt, q)
case "crop":
bounds := img.Bounds()
origW := bounds.Dx()
origH := bounds.Dy()
leftPct := getParamFloat(params, "left_pct", 0)
topPct := getParamFloat(params, "top_pct", 0)
rightPct := getParamFloat(params, "right_pct", 100)
bottomPct := getParamFloat(params, "bottom_pct", 100)
x := int(float64(origW) * leftPct / 100.0)
y := int(float64(origH) * topPct / 100.0)
w := int(float64(origW) * (rightPct - leftPct) / 100.0)
h := int(float64(origH) * (bottomPct - topPct) / 100.0)
processed := cropImage(img, x, y, w, h)
buf, finalFmt = compressLogic(processed, format, 95)
case "filter":
filterType := getParamString(params, "filter", "GRAYSCALE")
processed := filterImage(img, filterType)
buf, finalFmt = compressLogic(processed, format, 95)
case "rotate":
rotOp := getParamString(params, "operation", "90")
processed := rotateImage(img, rotOp)
buf, finalFmt = compressLogic(processed, format, 95)
case "round_corners":
radius := getParamInt(params, "radius", 20)
isCircle := getParamBool(params, "is_circle", false)
processed := roundCorners(img, radius, isCircle)
buf, finalFmt = compressLogic(processed, "PNG", 95)
case "border":
borderWidth := getParamInt(params, "border_width", 10)
borderColorHex := getParamString(params, "border_color", "#000000")
padAspect := getParamString(params, "pad_aspect", "none")
processed := addBorderCanvas(img, borderWidth, borderColorHex, padAspect)
buf, finalFmt = compressLogic(processed, format, 95)
case "strip_metadata":
targetFmt := getParamString(params, "format", "original")
if targetFmt == "original" {
targetFmt = format
}
quality := getParamInt(params, "quality", 95)
buf, finalFmt = compressLogic(img, targetFmt, quality)
case "adjust":
brightness := getParamFloat(params, "brightness", 0)
contrast := getParamFloat(params, "contrast", 0)
saturation := getParamFloat(params, "saturation", 0)
gamma := getParamFloat(params, "gamma", 1.0)
processed := adjustColor(img, brightness, contrast, saturation, gamma)
buf, finalFmt = compressLogic(processed, format, 95)
case "watermark":
var wmImg image.Image
wmBase64 := getParamString(params, "watermark_base64", "")
if wmBase64 != "" {
if commaIdx := strings.Index(wmBase64, ","); commaIdx != -1 {
wmBase64 = wmBase64[commaIdx+1:]
}
if decoded, err := base64.StdEncoding.DecodeString(wmBase64); err == nil {
wmImg, _, _ = image.Decode(bytes.NewReader(decoded))
}
}
position := getParamString(params, "position", "bottom_right")
opacity := getParamFloat(params, "opacity", 0.7)
if wmImg != nil {
processed := watermarkImage(img, wmImg, position, int(opacity*100))
buf, finalFmt = compressLogic(processed, format, 95)
} else {
buf, finalFmt = compressLogic(img, format, 95)
}
case "masker", "mask":
var maskImg image.Image
maskBase64 := getParamString(params, "mask_base64", "")
if maskBase64 != "" {
if commaIdx := strings.Index(maskBase64, ","); commaIdx != -1 {
maskBase64 = maskBase64[commaIdx+1:]
}
if decoded, err := base64.StdEncoding.DecodeString(maskBase64); err == nil {
maskImg, _, _ = image.Decode(bytes.NewReader(decoded))
}
}
if maskImg != nil {
resizedMask := imaging.Resize(maskImg, img.Bounds().Dx(), img.Bounds().Dy(), imaging.Lanczos)
buf, finalFmt = compressLogic(resizedMask, "PNG", 95)
} else {
blackCanvas := imaging.New(img.Bounds().Dx(), img.Bounds().Dy(), color.Black)
buf, finalFmt = compressLogic(blackCanvas, "PNG", 95)
}
default:
buf, finalFmt = compressLogic(img, format, 95)
}
relPath, _ := filepath.Rel(uploadsDir, file)
if operation == "convert" || operation == "round_corners" || (operation == "compress" && params["format"] != nil && params["format"] != "original" && 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)
if err := os.WriteFile(targetFilePath, buf, 0644); err != nil {
return origSize, 0, err
}
return origSize, int64(len(buf)), nil
}
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++
origSize, newSize, err := processSingleBatchFile(file, data.Operation, data.Params, uploadsDir, resultsDir)
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
}
totalOriginalSize += origSize
totalCompressedSize += newSize
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(newSize) / 1024
if origSize > 0 {
pd["reduction"] = (1.0 - float64(newSize)/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)
}