240 lines
7.2 KiB
Go
240 lines
7.2 KiB
Go
package main
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"encoding/base64"
|
||
|
|
"encoding/json"
|
||
|
|
"fmt"
|
||
|
|
"log/slog"
|
||
|
|
"net/http"
|
||
|
|
"os"
|
||
|
|
"os/exec"
|
||
|
|
"path/filepath"
|
||
|
|
"strings"
|
||
|
|
)
|
||
|
|
|
||
|
|
func browseFolderHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
|
// Try zenity
|
||
|
|
cmd := exec.Command("zenity", "--file-selection", "--directory", "--title=Select Output Folder")
|
||
|
|
out, err := cmd.Output()
|
||
|
|
path := strings.TrimSpace(string(out))
|
||
|
|
|
||
|
|
if err == nil && path != "" {
|
||
|
|
slog.Info("folder selected via zenity", "path", path)
|
||
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": true, "path": path})
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
// Try tkinter fallback
|
||
|
|
pyCode := `import tkinter as tk; from tkinter import filedialog; root = tk.Tk(); root.withdraw(); root.attributes("-topmost", True); print(filedialog.askdirectory()); root.destroy()`
|
||
|
|
cmd = exec.Command("python3", "-c", pyCode)
|
||
|
|
out, err = cmd.Output()
|
||
|
|
path = strings.TrimSpace(string(out))
|
||
|
|
|
||
|
|
if err == nil && path != "" {
|
||
|
|
slog.Info("folder selected via tkinter", "path", path)
|
||
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": true, "path": path})
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
slog.Warn("no folder selected")
|
||
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": false, "error": "No folder selected"})
|
||
|
|
}
|
||
|
|
|
||
|
|
func saveFolderHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
|
var data map[string]any
|
||
|
|
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
|
||
|
|
slog.Error("invalid save folder payload", "error", err)
|
||
|
|
writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": err.Error()})
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
targetDir, _ := data["path"].(string)
|
||
|
|
if targetDir == "" {
|
||
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": false, "error": "Invalid path"})
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
if _, err := os.Stat(targetDir); os.IsNotExist(err) {
|
||
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": false, "error": "Path does not exist"})
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
results, _ := data["results"].([]any)
|
||
|
|
savedCount := 0
|
||
|
|
var errors []string
|
||
|
|
|
||
|
|
for _, resAny := range results {
|
||
|
|
res, ok := resAny.(map[string]any)
|
||
|
|
if !ok {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
|
||
|
|
filename, _ := res["filename"].(string)
|
||
|
|
if filename == "" {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
|
||
|
|
fullPath := filepath.Join(targetDir, filepath.Base(filename))
|
||
|
|
if strings.Contains(filename, "/") || strings.Contains(filename, string(os.PathSeparator)) {
|
||
|
|
fullPath = filepath.Join(targetDir, filename)
|
||
|
|
if err := os.MkdirAll(filepath.Dir(fullPath), 0755); err != nil {
|
||
|
|
errors = append(errors, err.Error())
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
isBinary, _ := res["is_binary"].(bool)
|
||
|
|
binaryData, _ := res["binary_data"].(string)
|
||
|
|
content, hasContent := res["content"]
|
||
|
|
|
||
|
|
if isBinary && binaryData != "" {
|
||
|
|
binaryBytes, err := base64.StdEncoding.DecodeString(binaryData)
|
||
|
|
if err != nil {
|
||
|
|
errors = append(errors, fmt.Sprintf("%s: invalid base64", filename))
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
if err := os.WriteFile(fullPath, binaryBytes, 0644); err != nil {
|
||
|
|
errors = append(errors, fmt.Sprintf("%s: %s", filename, err.Error()))
|
||
|
|
} else {
|
||
|
|
savedCount++
|
||
|
|
}
|
||
|
|
} else if hasContent {
|
||
|
|
contentStr := ""
|
||
|
|
switch v := content.(type) {
|
||
|
|
case string:
|
||
|
|
contentStr = v
|
||
|
|
default:
|
||
|
|
bytes, _ := json.Marshal(v)
|
||
|
|
contentStr = string(bytes)
|
||
|
|
}
|
||
|
|
if err := os.WriteFile(fullPath, []byte(contentStr), 0644); err != nil {
|
||
|
|
errors = append(errors, fmt.Sprintf("%s: %s", filename, err.Error()))
|
||
|
|
} else {
|
||
|
|
savedCount++
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
slog.Info("saved bulk results to folder", "path", targetDir, "saved_count", savedCount, "errors_count", len(errors))
|
||
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": true, "count": savedCount, "errors": errors})
|
||
|
|
}
|
||
|
|
|
||
|
|
func saveFolderFromLastrunHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
|
var data map[string]any
|
||
|
|
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
|
||
|
|
slog.Error("invalid saveFolderFromLastrun payload", "error", err)
|
||
|
|
writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": err.Error()})
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
targetDir, _ := data["path"].(string)
|
||
|
|
if targetDir == "" {
|
||
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": false, "error": "Invalid path"})
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
indicesAny, _ := data["indices"].([]any)
|
||
|
|
indicesMap := make(map[float64]bool)
|
||
|
|
useIndices := false
|
||
|
|
if len(indicesAny) > 0 {
|
||
|
|
useIndices = true
|
||
|
|
for _, idx := range indicesAny {
|
||
|
|
if f, ok := idx.(float64); ok {
|
||
|
|
indicesMap[f] = true
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
var lastRun map[string]any
|
||
|
|
if err := readJSON(LastRunFile, &lastRun); err != nil {
|
||
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": false, "error": "No saved run data found"})
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
// Python looks at last_run.get('bulk', {}).get('results', [])
|
||
|
|
bulkAny, ok := lastRun["bulk"].(map[string]any)
|
||
|
|
if !ok {
|
||
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": false, "error": "No batch results found"})
|
||
|
|
return
|
||
|
|
}
|
||
|
|
resultsAny, ok := bulkAny["results"].([]any)
|
||
|
|
if !ok {
|
||
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": false, "error": "No batch results found"})
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
savedCount := 0
|
||
|
|
var errors []string
|
||
|
|
|
||
|
|
for _, resAny := range resultsAny {
|
||
|
|
res, ok := resAny.(map[string]any)
|
||
|
|
if !ok {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
|
||
|
|
idx, _ := res["index"].(float64)
|
||
|
|
if useIndices && !indicesMap[idx] {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
|
||
|
|
inputFilename, _ := res["inputFilename"].(string)
|
||
|
|
if inputFilename == "" {
|
||
|
|
inputFilename = fmt.Sprintf("result_%v", res["index"])
|
||
|
|
}
|
||
|
|
|
||
|
|
contentType, _ := res["contentType"].(string)
|
||
|
|
ext := filepath.Ext(inputFilename)
|
||
|
|
if ext == "" {
|
||
|
|
ct := strings.ToLower(contentType)
|
||
|
|
if strings.Contains(ct, "image/png") { ext = ".png" } else
|
||
|
|
if strings.Contains(ct, "image/jpeg") || strings.Contains(ct, "image/jpg") { ext = ".jpg" } else
|
||
|
|
if strings.Contains(ct, "image/gif") { ext = ".gif" } else
|
||
|
|
if strings.Contains(ct, "image/webp") { ext = ".webp" } else
|
||
|
|
if strings.Contains(ct, "image/svg") { ext = ".svg" } else
|
||
|
|
if strings.Contains(ct, "application/pdf") { ext = ".pdf" } else
|
||
|
|
if strings.Contains(ct, "application/json") { ext = ".json" } else
|
||
|
|
if strings.Contains(ct, "text/html") { ext = ".html" } else
|
||
|
|
if strings.Contains(ct, "text/plain") { ext = ".txt" }
|
||
|
|
}
|
||
|
|
|
||
|
|
finalFilename := inputFilename
|
||
|
|
if ext != "" && filepath.Ext(inputFilename) == "" {
|
||
|
|
finalFilename += ext
|
||
|
|
}
|
||
|
|
fullPath := filepath.Join(targetDir, filepath.Base(finalFilename))
|
||
|
|
|
||
|
|
binaryData, _ := res["binaryData"].(string)
|
||
|
|
fullContent, hasFullContent := res["fullContent"]
|
||
|
|
|
||
|
|
if binaryData != "" {
|
||
|
|
binaryBytes, err := base64.StdEncoding.DecodeString(binaryData)
|
||
|
|
if err != nil {
|
||
|
|
errors = append(errors, fmt.Sprintf("%s: invalid base64", finalFilename))
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
if err := os.WriteFile(fullPath, binaryBytes, 0644); err != nil {
|
||
|
|
errors = append(errors, fmt.Sprintf("%s: %s", finalFilename, err.Error()))
|
||
|
|
} else {
|
||
|
|
savedCount++
|
||
|
|
}
|
||
|
|
} else if hasFullContent {
|
||
|
|
contentStr := ""
|
||
|
|
switch v := fullContent.(type) {
|
||
|
|
case string:
|
||
|
|
contentStr = v
|
||
|
|
default:
|
||
|
|
bytes, _ := json.Marshal(v)
|
||
|
|
contentStr = string(bytes)
|
||
|
|
}
|
||
|
|
if err := os.WriteFile(fullPath, []byte(contentStr), 0644); err != nil {
|
||
|
|
errors = append(errors, fmt.Sprintf("%s: %s", finalFilename, err.Error()))
|
||
|
|
} else {
|
||
|
|
savedCount++
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
slog.Info("saved last run results to folder", "path", targetDir, "saved_count", savedCount, "errors_count", len(errors))
|
||
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": true, "count": savedCount, "errors": errors})
|
||
|
|
}
|