1006 lines
35 KiB
Go
1006 lines
35 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"mediacollection/internal/auth"
|
|
)
|
|
|
|
func (s *Server) mountToolsRoutes(r chi.Router) {
|
|
r.Get("/generator/label", func(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]string{"label": "Generator"})
|
|
})
|
|
r.Get("/downloader/label", func(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]string{"label": "Downloader"})
|
|
})
|
|
r.Get("/converter/label", func(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]string{"label": "Converter"})
|
|
})
|
|
r.Get("/workflows/list", s.workflowList)
|
|
r.Get("/input/*", func(w http.ResponseWriter, req *http.Request) { s.toolFile(w, req, "/mount/inputs/") })
|
|
r.Get("/copy/*", func(w http.ResponseWriter, req *http.Request) { s.toolFile(w, req, "/mount/copies/") })
|
|
r.Get("/output/*", func(w http.ResponseWriter, req *http.Request) { s.toolFile(w, req, "/mount/generated/") })
|
|
r.With(s.auth.RequireIfLoginRequired).Post("/upload", s.toolUpload)
|
|
r.Get("/converter/formats", s.converterFormats)
|
|
r.Get("/converter/breakdown", s.converterBreakdown)
|
|
r.Get("/converter/settings", s.converterSettings)
|
|
r.With(s.auth.RequireIfLoginRequired).Put("/converter/settings", s.saveConverterSettings)
|
|
r.Get("/jobs", s.workflowJobs)
|
|
r.Get("/queue", s.workflowQueue)
|
|
r.Get("/jobs/{id}", s.workflowJob)
|
|
r.With(s.auth.RequireIfLoginRequired).Post("/jobs/{tool}/start", s.startWorkflowJob)
|
|
r.With(s.auth.RequireIfLoginRequired).Delete("/jobs/{id}", s.deleteWorkflowJob)
|
|
r.Get("/schedules", s.workflowSchedules)
|
|
r.With(s.auth.RequireIfLoginRequired).Post("/schedules/{id}/run", s.runWorkflowSchedule)
|
|
r.With(s.auth.RequireIfLoginRequired).Post("/schedules", s.createWorkflowSchedule)
|
|
r.With(s.auth.RequireIfLoginRequired).Delete("/schedules/{id}", s.deleteWorkflowSchedule)
|
|
|
|
r.Get("/generator/schedules", s.workflowSchedules)
|
|
r.Get("/downloader/schedules", s.workflowSchedules)
|
|
r.Get("/converter/schedules", s.workflowSchedules)
|
|
r.With(s.auth.RequireIfLoginRequired).Post("/generator/upload-copy", s.uploadCopy)
|
|
r.With(s.auth.RequireIfLoginRequired).Post("/downloader/single", s.startSingleDownload)
|
|
r.Get("/downloader/queue", s.workflowJobs)
|
|
r.Get("/library/unified", s.unifiedLibrary)
|
|
r.Get("/generator/workflows/meta", s.workflowMeta)
|
|
r.Get("/generator/my-generations", s.myGenerations)
|
|
r.With(s.auth.RequireIfLoginRequired).Post("/converter/start", s.startWorkflowJob)
|
|
r.With(s.auth.RequireIfLoginRequired).Post("/converter/start-group", s.startWorkflowJob)
|
|
r.With(s.auth.RequireIfLoginRequired).Post("/converter/start-discovered", s.startWorkflowJob)
|
|
r.Get("/converter/jobs", s.workflowJobs)
|
|
r.Get("/converter/jobs/{id}", s.workflowJob)
|
|
r.With(s.auth.RequireIfLoginRequired).Get("/converter/download/{id}", s.downloadWorkflowResult)
|
|
|
|
}
|
|
|
|
func (s *Server) converterFormats(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{"formats": []map[string]any{
|
|
{"id": "mp4", "label": "MP4", "extension": ".mp4", "video": true, "audio": true},
|
|
{"id": "webm", "label": "WebM", "extension": ".webm", "video": true, "audio": true},
|
|
{"id": "mkv", "label": "Matroska", "extension": ".mkv", "video": true, "audio": true},
|
|
{"id": "mp3", "label": "MP3", "extension": ".mp3", "video": false, "audio": true},
|
|
}})
|
|
}
|
|
|
|
func (s *Server) converterBreakdown(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": []any{}, "total": 0})
|
|
}
|
|
|
|
func (s *Server) converterSettings(w http.ResponseWriter, r *http.Request) {
|
|
settings := map[string]string{}
|
|
rows, err := s.db.Query(r.Context(), `SELECT key, value FROM settings WHERE key LIKE 'converter_%' OR key LIKE 'mediatools_%' ORDER BY key`)
|
|
if err == nil {
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var key, value string
|
|
if rows.Scan(&key, &value) == nil {
|
|
settings[key] = value
|
|
}
|
|
}
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"settings": settings})
|
|
}
|
|
|
|
func (s *Server) saveConverterSettings(w http.ResponseWriter, r *http.Request) {
|
|
var settings map[string]any
|
|
if err := decodeRequestJSON(r, &settings); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
|
return
|
|
}
|
|
for key, value := range settings {
|
|
if !strings.HasPrefix(key, "converter_") && !strings.HasPrefix(key, "mediatools_") {
|
|
continue
|
|
}
|
|
encoded, _ := json.Marshal(value)
|
|
_, _ = s.db.Exec(r.Context(), `INSERT INTO settings (key, value, updated_at) VALUES ($1, $2, NOW()) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`, key, strings.Trim(string(encoded), `"`))
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
|
}
|
|
|
|
func (s *Server) workflowJobs(w http.ResponseWriter, r *http.Request) {
|
|
tool := strings.TrimSpace(r.URL.Query().Get("tool"))
|
|
query := `SELECT id, service, tool, status, progress, request, result, COALESCE(error_message, ''), created_at, started_at, finished_at FROM workflow_jobs WHERE service = $1`
|
|
args := []any{s.cfg.ServiceName}
|
|
if tool != "" {
|
|
query += " AND tool = $2"
|
|
args = append(args, tool)
|
|
}
|
|
query += " ORDER BY created_at DESC LIMIT 100"
|
|
rows, err := s.db.Query(r.Context(), query, args...)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "workflow jobs unavailable")
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
jobs := make([]WorkflowJob, 0)
|
|
for rows.Next() {
|
|
job, err := scanWorkflowJob(rows)
|
|
if err == nil {
|
|
jobs = append(jobs, job)
|
|
}
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"jobs": jobs, "items": jobs})
|
|
}
|
|
|
|
func (s *Server) workflowQueue(w http.ResponseWriter, r *http.Request) {
|
|
tool := strings.TrimSpace(r.URL.Query().Get("tool"))
|
|
query := `SELECT id, service, tool, status, progress, request, result, COALESCE(error_message, ''), created_at, started_at, finished_at FROM workflow_jobs WHERE service = $1 AND status IN ('queued', 'processing')`
|
|
args := []any{s.cfg.ServiceName}
|
|
if tool != "" {
|
|
query += " AND tool = $2"
|
|
args = append(args, tool)
|
|
}
|
|
query += " ORDER BY created_at ASC LIMIT 100"
|
|
rows, err := s.db.Query(r.Context(), query, args...)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "workflow queue unavailable")
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
jobs := make([]WorkflowJob, 0)
|
|
for rows.Next() {
|
|
if job, scanErr := scanWorkflowJob(rows); scanErr == nil {
|
|
jobs = append(jobs, job)
|
|
}
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"queue": jobs, "jobs": jobs, "items": jobs})
|
|
}
|
|
|
|
func (s *Server) workflowJob(w http.ResponseWriter, r *http.Request) {
|
|
job, err := s.findWorkflowJob(r.Context(), chi.URLParam(r, "id"))
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "job not found")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, job)
|
|
}
|
|
|
|
func (s *Server) startWorkflowJob(w http.ResponseWriter, r *http.Request) {
|
|
tool := strings.TrimSpace(chi.URLParam(r, "tool"))
|
|
if tool == "" {
|
|
tool = inferToolFromPath(r.URL.Path)
|
|
}
|
|
var request map[string]any
|
|
if r.Body != nil && r.ContentLength != 0 {
|
|
if err := decodeRequestJSON(r, &request); err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, io.EOF) {
|
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
|
return
|
|
}
|
|
}
|
|
if request == nil {
|
|
request = map[string]any{}
|
|
}
|
|
job, err := s.createWorkflowJob(r.Context(), tool, request)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "job could not be queued")
|
|
return
|
|
}
|
|
s.enqueueWorkflowJob(job.ID)
|
|
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "job": job, "id": job.ID})
|
|
}
|
|
|
|
func (s *Server) startSingleDownload(w http.ResponseWriter, r *http.Request) {
|
|
var request map[string]any
|
|
if err := decodeRequestJSON(r, &request); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
|
return
|
|
}
|
|
rawURL, _ := request["url"].(string)
|
|
if err := validateDownloadURL(rawURL); err != nil {
|
|
writeError(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
job, err := s.createWorkflowJob(r.Context(), "downloader", request)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "download could not be queued")
|
|
return
|
|
}
|
|
s.enqueueWorkflowJob(job.ID)
|
|
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "job": job, "queueId": job.ID})
|
|
}
|
|
|
|
func (s *Server) createWorkflowJob(ctx context.Context, tool string, request map[string]any) (*WorkflowJob, error) {
|
|
jobID, err := randomID()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
requestJSON, err := json.Marshal(request)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var userID any
|
|
if user := auth.UserFromContext(ctx); user != nil {
|
|
userID = user.ID
|
|
}
|
|
_, err = s.db.Exec(ctx, `INSERT INTO workflow_jobs (id, service, tool, request, user_id) VALUES ($1, $2, $3, $4, $5)`, jobID, s.cfg.ServiceName, tool, requestJSON, userID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
job := &WorkflowJob{ID: jobID, Service: s.cfg.ServiceName, Tool: tool, Status: "queued", Request: request, Result: map[string]any{}, CreatedAt: time.Now()}
|
|
s.jobsMu.Lock()
|
|
s.jobs[job.ID] = job
|
|
s.jobsMu.Unlock()
|
|
return job, nil
|
|
}
|
|
|
|
func (s *Server) enqueueWorkflowJob(id string) {
|
|
go func() {
|
|
s.workflowSem <- struct{}{}
|
|
defer func() { <-s.workflowSem }()
|
|
s.processWorkflowJob(id)
|
|
}()
|
|
}
|
|
|
|
func (s *Server) processWorkflowJob(id string) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
|
defer cancel()
|
|
job, err := s.findWorkflowJob(ctx, id)
|
|
if err != nil {
|
|
return
|
|
}
|
|
started := time.Now()
|
|
_, _ = s.db.Exec(ctx, `UPDATE workflow_jobs SET status='processing', progress=5, started_at=$2, error_message=NULL WHERE id=$1`, id, started)
|
|
|
|
result, executionErr := s.executeWorkflow(ctx, job)
|
|
status := "completed"
|
|
progress := 100
|
|
message := ""
|
|
if executionErr != nil {
|
|
status = "failed"
|
|
progress = 0
|
|
message = executionErr.Error()
|
|
if result == nil {
|
|
result = map[string]any{}
|
|
}
|
|
}
|
|
finished := time.Now()
|
|
_, _ = s.db.Exec(ctx, `UPDATE workflow_jobs SET status=$2, progress=$3, result=$4, error_message=NULLIF($5, ''), finished_at=$6 WHERE id=$1`, id, status, progress, mustJSON(result), message, finished)
|
|
if job, err := s.findWorkflowJob(ctx, id); err == nil {
|
|
s.jobsMu.Lock()
|
|
s.jobs[id] = &job
|
|
s.jobsMu.Unlock()
|
|
}
|
|
}
|
|
|
|
func (s *Server) executeWorkflow(ctx context.Context, job WorkflowJob) (map[string]any, error) {
|
|
switch strings.ToLower(job.Tool) {
|
|
case "converter":
|
|
return s.executeConversion(ctx, job)
|
|
case "downloader":
|
|
return s.executeDownload(ctx, job)
|
|
case "generator":
|
|
return s.executeGeneration(ctx, job)
|
|
default:
|
|
return nil, fmt.Errorf("unsupported workflow tool: %s", job.Tool)
|
|
}
|
|
}
|
|
|
|
func (s *Server) executeConversion(ctx context.Context, job WorkflowJob) (map[string]any, error) {
|
|
sourceName := firstString(job.Request, "sourcePath", "input", "path")
|
|
if sourceName == "" {
|
|
return nil, fmt.Errorf("converter input path is required")
|
|
}
|
|
source, cleanupSource, err := s.fetchWorkflowFileFromServant(ctx, sourceName)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("converter input is not an allowed file: %w", err)
|
|
}
|
|
defer cleanupSource()
|
|
target := strings.ToLower(strings.TrimPrefix(firstString(job.Request, "targetFormat", "format", "extension"), "."))
|
|
if target == "" {
|
|
target = strings.TrimPrefix(strings.ToLower(filepath.Ext(sourceName)), ".")
|
|
}
|
|
if !supportedConversionFormat(target) {
|
|
return nil, fmt.Errorf("unsupported converter target format: %s", target)
|
|
}
|
|
base := safeOutputBase(filepath.Base(sourceName))
|
|
outputName := fmt.Sprintf("%s-%s.%s", base, shortID(job.ID), target)
|
|
temporary, err := os.CreateTemp("", ".convert-*."+target)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("converter scratch file unavailable: %w", err)
|
|
}
|
|
outputPath := temporary.Name()
|
|
if err := temporary.Close(); err != nil {
|
|
_ = os.Remove(outputPath)
|
|
return nil, err
|
|
}
|
|
defer os.Remove(outputPath)
|
|
args := conversionArgs(source, outputPath, target, firstString(job.Request, "encoding", "encodingProfile"))
|
|
var output bytes.Buffer
|
|
command := exec.CommandContext(ctx, s.cfg.FFmpeg, args...)
|
|
command.Stdout = &output
|
|
command.Stderr = &output
|
|
if err := command.Run(); err != nil {
|
|
return nil, fmt.Errorf("ffmpeg conversion failed: %s", tailOutput(output.String(), 600))
|
|
}
|
|
info, err := os.Stat(outputPath)
|
|
if err != nil || info.IsDir() {
|
|
return nil, fmt.Errorf("ffmpeg did not produce an output file")
|
|
}
|
|
size, err := s.servantPushOutput(ctx, outputName, outputPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("converted output could not be stored: %w", err)
|
|
}
|
|
return map[string]any{"backend": "go", "outputFile": outputName, "outputSize": size, "sourceFile": filepath.Base(sourceName), "targetFormat": target}, nil
|
|
}
|
|
|
|
func (s *Server) executeDownload(ctx context.Context, job WorkflowJob) (map[string]any, error) {
|
|
sourceURL := firstString(job.Request, "url", "sourceUrl", "sourceURL")
|
|
if err := validateDownloadURL(sourceURL); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := ensurePublicDownloadHost(ctx, sourceURL); err != nil {
|
|
return nil, err
|
|
}
|
|
scratchDir, err := os.MkdirTemp("", "yt-dlp-*")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("download scratch directory unavailable: %w", err)
|
|
}
|
|
defer os.RemoveAll(scratchDir)
|
|
template := filepath.Join(scratchDir, "%(title).200B.%(ext)s")
|
|
command := exec.CommandContext(ctx, s.cfg.YTDLP, "--no-playlist", "--no-part", "--newline", "--print", "after_move:filepath", "-o", template, "--", sourceURL)
|
|
var output bytes.Buffer
|
|
command.Stdout = &output
|
|
command.Stderr = &output
|
|
if err := command.Run(); err != nil {
|
|
return nil, fmt.Errorf("download failed: %s", tailOutput(output.String(), 600))
|
|
}
|
|
filePath := newestDownloadedFile(scratchDir, output.String())
|
|
if filePath == "" {
|
|
return nil, fmt.Errorf("downloader completed without producing a file")
|
|
}
|
|
info, err := os.Stat(filePath)
|
|
if err != nil || info.IsDir() {
|
|
return nil, fmt.Errorf("downloaded file is unavailable")
|
|
}
|
|
filename := filepath.Base(filePath)
|
|
// Pushing through Servant's upload endpoint also catalogs the file into media/media_worker_jobs
|
|
// (see servantRawUpload) - no separate indexMediaFile call needed here.
|
|
if _, err := s.servantUploadDownload(ctx, filePath, filename); err != nil {
|
|
return nil, fmt.Errorf("downloaded file could not be stored: %w", err)
|
|
}
|
|
_, _ = s.db.Exec(ctx, `INSERT INTO downloaded_media (source_url, tool, file_path, file_name, file_size_bytes, status, started_at, finished_at) VALUES ($1,'yt-dlp',$2,$3,$4,'completed',$5,NOW())`, sourceURL, filename, filename, info.Size(), job.CreatedAt)
|
|
return map[string]any{"backend": "go", "file": filename, "filename": filename, "size": info.Size(), "sourceUrl": sourceURL}, nil
|
|
}
|
|
|
|
func (s *Server) executeGeneration(ctx context.Context, job WorkflowJob) (map[string]any, error) {
|
|
workflow, ok := job.Request["workflow"].(map[string]any)
|
|
if !ok {
|
|
workflow, ok = job.Request["prompt"].(map[string]any)
|
|
}
|
|
if !ok || len(workflow) == 0 {
|
|
return nil, fmt.Errorf("generator workflow graph is required")
|
|
}
|
|
applyGeneratorPrompt(workflow, firstString(job.Request, "promptText"))
|
|
body, _ := json.Marshal(map[string]any{"prompt": workflow, "client_id": job.ID})
|
|
request, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(s.cfg.ComfyURL, "/")+"/prompt", bytes.NewReader(body))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
request.Header.Set("Content-Type", "application/json")
|
|
response, err := http.DefaultClient.Do(request)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("ComfyUI request failed: %w", err)
|
|
}
|
|
defer response.Body.Close()
|
|
var payload struct {
|
|
PromptID string `json:"prompt_id"`
|
|
Error string `json:"error"`
|
|
}
|
|
if err := json.NewDecoder(io.LimitReader(response.Body, 512*1024)).Decode(&payload); err != nil {
|
|
return nil, fmt.Errorf("invalid ComfyUI response: %w", err)
|
|
}
|
|
if response.StatusCode >= 300 || payload.PromptID == "" {
|
|
if payload.Error == "" {
|
|
payload.Error = response.Status
|
|
}
|
|
return nil, fmt.Errorf("ComfyUI rejected workflow: %s", payload.Error)
|
|
}
|
|
return map[string]any{"backend": "go", "promptId": payload.PromptID, "status": "submitted"}, nil
|
|
}
|
|
|
|
func (s *Server) resumeWorkflowJobs(ctx context.Context) {
|
|
rows, err := s.db.Query(ctx, `SELECT id FROM workflow_jobs WHERE service=$1 AND status IN ('queued','processing') ORDER BY created_at`, s.cfg.ServiceName)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var id string
|
|
if rows.Scan(&id) == nil {
|
|
s.enqueueWorkflowJob(id)
|
|
}
|
|
}
|
|
}
|
|
|
|
func firstString(values map[string]any, keys ...string) string {
|
|
for _, key := range keys {
|
|
if value, ok := values[key].(string); ok && strings.TrimSpace(value) != "" {
|
|
return strings.TrimSpace(value)
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// workflowFileServantPaths mirrors the search order resolveWorkflowFile used to walk locally
|
|
// (InputRoot, MediaRoots, DownloadsRoot, OutputRoot) but as Servant-side mount prefixes, since
|
|
// MediaTools no longer has any of those roots mounted on its own filesystem.
|
|
var workflowFileServantPaths = []string{"/mount/inputs/", "/media/", "/media/downloads/", "/mount/generated/"}
|
|
|
|
// fetchWorkflowFileFromServant locates a converter input under any of Servant's mounts and
|
|
// downloads it into an ephemeral scratch file for ffmpeg to read; the caller must invoke the
|
|
// returned cleanup once done.
|
|
func (s *Server) fetchWorkflowFileFromServant(ctx context.Context, value string) (string, func(), error) {
|
|
value = strings.TrimSpace(value)
|
|
if !safeRelative(value) {
|
|
return "", nil, os.ErrNotExist
|
|
}
|
|
for _, prefix := range workflowFileServantPaths {
|
|
servantPath := prefix + urlPath(value)
|
|
if exists, _, _, err := s.probeServant(ctx, servantPath); err != nil || !exists {
|
|
continue
|
|
}
|
|
return s.fetchServantToScratch(ctx, servantPath, filepath.Ext(value))
|
|
}
|
|
return "", nil, os.ErrNotExist
|
|
}
|
|
|
|
func safeOutputBase(value string) string {
|
|
base := strings.TrimSuffix(filepath.Base(value), filepath.Ext(value))
|
|
var builder strings.Builder
|
|
for _, character := range base {
|
|
if (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || (character >= '0' && character <= '9') || character == '-' || character == '_' {
|
|
builder.WriteRune(character)
|
|
} else {
|
|
builder.WriteByte('_')
|
|
}
|
|
}
|
|
result := strings.Trim(builder.String(), "_.-")
|
|
if result == "" {
|
|
return "converted"
|
|
}
|
|
if len(result) > 100 {
|
|
return result[:100]
|
|
}
|
|
return result
|
|
}
|
|
|
|
func shortID(value string) string {
|
|
if len(value) > 8 {
|
|
return value[:8]
|
|
}
|
|
if value == "" {
|
|
return "job"
|
|
}
|
|
return value
|
|
}
|
|
|
|
func supportedConversionFormat(value string) bool {
|
|
switch value {
|
|
case "mp4", "mkv", "mov", "webm", "avi", "flv", "wmv", "ts", "3gp", "mpg", "gif", "mp3", "flac", "wav", "aac", "ogg", "opus", "m4a", "jpg", "jpeg", "png", "webp", "bmp", "tiff", "avif":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func conversionArgs(source, output, target, encoding string) []string {
|
|
args := []string{"-hide_banner", "-loglevel", "error", "-y", "-i", source}
|
|
switch target {
|
|
case "mp3":
|
|
args = append(args, "-vn", "-c:a", "libmp3lame", "-q:a", "2")
|
|
case "flac":
|
|
args = append(args, "-vn", "-c:a", "flac")
|
|
case "wav":
|
|
args = append(args, "-vn", "-c:a", "pcm_s16le")
|
|
case "aac", "m4a":
|
|
args = append(args, "-vn", "-c:a", "aac", "-b:a", "192k")
|
|
case "ogg", "opus":
|
|
args = append(args, "-vn", "-c:a", "libopus", "-b:a", "160k")
|
|
case "jpg", "jpeg", "png", "webp", "bmp", "tiff", "avif":
|
|
args = append(args, "-frames:v", "1")
|
|
case "webm":
|
|
args = append(args, "-c:v", "libvpx-vp9", "-crf", "32", "-b:v", "0", "-c:a", "libopus")
|
|
default:
|
|
preset, crf := "medium", "23"
|
|
switch strings.ToLower(strings.TrimSpace(encoding)) {
|
|
case "fast":
|
|
preset, crf = "veryfast", "28"
|
|
case "quality":
|
|
preset, crf = "slow", "18"
|
|
}
|
|
args = append(args, "-c:v", "libx264", "-preset", preset, "-crf", crf, "-c:a", "aac", "-b:a", "192k")
|
|
if target == "mp4" {
|
|
args = append(args, "-movflags", "+faststart")
|
|
}
|
|
}
|
|
return append(args, output)
|
|
}
|
|
|
|
func applyGeneratorPrompt(workflow map[string]any, prompt string) {
|
|
prompt = strings.TrimSpace(prompt)
|
|
if prompt == "" {
|
|
return
|
|
}
|
|
for _, rawNode := range workflow {
|
|
node, ok := rawNode.(map[string]any)
|
|
if !ok {
|
|
continue
|
|
}
|
|
classType, _ := node["class_type"].(string)
|
|
inputs, ok := node["inputs"].(map[string]any)
|
|
if ok && classType == "CLIPTextEncode" {
|
|
inputs["text"] = prompt
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func tailOutput(value string, limit int) string {
|
|
value = strings.TrimSpace(value)
|
|
if len(value) <= limit {
|
|
return value
|
|
}
|
|
return value[len(value)-limit:]
|
|
}
|
|
|
|
func newestDownloadedFile(root, commandOutput string) string {
|
|
candidates := make([]string, 0)
|
|
for _, line := range strings.Split(commandOutput, "\n") {
|
|
line = strings.Trim(strings.TrimSpace(line), "\"")
|
|
if line == "" || strings.HasPrefix(line, "[download]") || strings.HasPrefix(line, "WARNING:") {
|
|
continue
|
|
}
|
|
candidate := filepath.FromSlash(line)
|
|
if !filepath.IsAbs(candidate) {
|
|
candidate = filepath.Join(root, candidate)
|
|
}
|
|
if info, err := os.Stat(candidate); err == nil && !info.IsDir() && sameRealRoot(root, candidate) {
|
|
candidates = append(candidates, candidate)
|
|
}
|
|
}
|
|
entries, _ := os.ReadDir(root)
|
|
for _, entry := range entries {
|
|
if entry.IsDir() {
|
|
continue
|
|
}
|
|
candidates = append(candidates, filepath.Join(root, entry.Name()))
|
|
}
|
|
if len(candidates) == 0 {
|
|
return ""
|
|
}
|
|
sort.Slice(candidates, func(i, j int) bool {
|
|
left, _ := os.Stat(candidates[i])
|
|
right, _ := os.Stat(candidates[j])
|
|
if left == nil || right == nil {
|
|
return false
|
|
}
|
|
return left.ModTime().After(right.ModTime())
|
|
})
|
|
return candidates[0]
|
|
}
|
|
|
|
func ensurePublicDownloadHost(ctx context.Context, raw string) error {
|
|
parsed, err := url.Parse(raw)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
addresses, err := net.DefaultResolver.LookupIPAddr(ctx, parsed.Hostname())
|
|
if err != nil {
|
|
return fmt.Errorf("download host could not be resolved")
|
|
}
|
|
for _, address := range addresses {
|
|
if isPrivateIP(address.IP) {
|
|
return fmt.Errorf("private and local download hosts are not allowed")
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) deleteWorkflowJob(w http.ResponseWriter, r *http.Request) {
|
|
result, err := s.db.Exec(r.Context(), `DELETE FROM workflow_jobs WHERE id=$1 AND service=$2`, chi.URLParam(r, "id"), s.cfg.ServiceName)
|
|
if err != nil || result.RowsAffected() == 0 {
|
|
writeError(w, http.StatusNotFound, "job not found")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (s *Server) workflowSchedules(w http.ResponseWriter, r *http.Request) {
|
|
rows, err := s.db.Query(r.Context(), `SELECT id, service, tool, name, interval_minutes, enabled, settings, last_run_at, last_status, next_run_at FROM workflow_schedules WHERE service=$1 ORDER BY created_at DESC`, s.cfg.ServiceName)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "schedules unavailable")
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
schedules := make([]map[string]any, 0)
|
|
for rows.Next() {
|
|
var id, service, tool, name string
|
|
var lastStatus *string
|
|
var interval int
|
|
var enabled bool
|
|
var settings []byte
|
|
var lastRun, nextRun *time.Time
|
|
if rows.Scan(&id, &service, &tool, &name, &interval, &enabled, &settings, &lastRun, &lastStatus, &nextRun) != nil {
|
|
continue
|
|
}
|
|
var parsed any
|
|
_ = json.Unmarshal(settings, &parsed)
|
|
schedules = append(schedules, map[string]any{"id": id, "service": service, "tool": tool, "name": name, "intervalMinutes": interval, "enabled": enabled, "settings": parsed, "lastRunAt": lastRun, "lastStatus": lastStatus, "nextRunAt": nextRun})
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"schedules": schedules, "items": schedules})
|
|
}
|
|
|
|
func (s *Server) createWorkflowSchedule(w http.ResponseWriter, r *http.Request) {
|
|
var input struct {
|
|
ID string `json:"id"`
|
|
Tool string `json:"tool"`
|
|
Name string `json:"name"`
|
|
IntervalMinutes int `json:"intervalMinutes"`
|
|
Enabled *bool `json:"enabled"`
|
|
Settings map[string]any `json:"settings"`
|
|
}
|
|
if err := decodeRequestJSON(r, &input); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
|
return
|
|
}
|
|
if input.Name == "" {
|
|
input.Name = input.Tool + " schedule"
|
|
}
|
|
if input.Tool == "" {
|
|
input.Tool = "workflow"
|
|
}
|
|
if input.IntervalMinutes <= 0 {
|
|
input.IntervalMinutes = 60
|
|
}
|
|
id := input.ID
|
|
if id == "" {
|
|
id, _ = randomID()
|
|
}
|
|
enabled := true
|
|
if input.Enabled != nil {
|
|
enabled = *input.Enabled
|
|
}
|
|
var userID any
|
|
if user := auth.UserFromContext(r.Context()); user != nil {
|
|
userID = user.ID
|
|
}
|
|
_, err := s.db.Exec(r.Context(), `INSERT INTO workflow_schedules (id, service, tool, name, interval_minutes, enabled, settings, user_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT (id) DO UPDATE SET name=EXCLUDED.name, interval_minutes=EXCLUDED.interval_minutes, enabled=EXCLUDED.enabled, settings=EXCLUDED.settings, updated_at=NOW()`, id, s.cfg.ServiceName, input.Tool, input.Name, input.IntervalMinutes, enabled, mustJSON(input.Settings), userID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "schedule could not be saved")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "id": id})
|
|
}
|
|
|
|
func (s *Server) runWorkflowSchedule(w http.ResponseWriter, r *http.Request) {
|
|
id := chi.URLParam(r, "id")
|
|
var tool string
|
|
var settings []byte
|
|
if err := s.db.QueryRow(r.Context(), `SELECT tool, settings FROM workflow_schedules WHERE id=$1 AND service=$2`, id, s.cfg.ServiceName).Scan(&tool, &settings); err != nil {
|
|
writeError(w, http.StatusNotFound, "schedule not found")
|
|
return
|
|
}
|
|
var request map[string]any
|
|
_ = json.Unmarshal(settings, &request)
|
|
job, err := s.createWorkflowJob(r.Context(), tool, request)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "scheduled job could not be queued")
|
|
return
|
|
}
|
|
_, _ = s.db.Exec(r.Context(), `UPDATE workflow_schedules SET last_run_at=NOW(), last_status='queued', next_run_at=NOW() + make_interval(mins => interval_minutes), updated_at=NOW() WHERE id=$1`, id)
|
|
s.enqueueWorkflowJob(job.ID)
|
|
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "job": job})
|
|
}
|
|
|
|
func (s *Server) deleteWorkflowSchedule(w http.ResponseWriter, r *http.Request) {
|
|
result, err := s.db.Exec(r.Context(), `DELETE FROM workflow_schedules WHERE id=$1 AND service=$2`, chi.URLParam(r, "id"), s.cfg.ServiceName)
|
|
if err != nil || result.RowsAffected() == 0 {
|
|
writeError(w, http.StatusNotFound, "schedule not found")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
}
|
|
|
|
func (s *Server) uploadCopy(w http.ResponseWriter, r *http.Request) {
|
|
if s.cfg.MaxUploadBytes > 0 {
|
|
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes)
|
|
}
|
|
filename, size, err := s.saveMultipartUpload(r, s.servantPushCopy)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
file := map[string]any{"filename": filename, "path": filename, "size": size}
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": true, "filename": filename, "file": file, "files": []any{file}, "uploadCopyDir": "/copy"})
|
|
}
|
|
|
|
func (s *Server) toolUpload(w http.ResponseWriter, r *http.Request) {
|
|
if s.cfg.MaxUploadBytes > 0 {
|
|
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes)
|
|
}
|
|
filename, size, err := s.saveMultipartUpload(r, s.servantPushInput)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusAccepted, map[string]any{"success": true, "filename": filename, "file": map[string]any{"filename": filename, "path": filename, "size": size}, "inputDir": "/input"})
|
|
}
|
|
|
|
func (s *Server) saveMultipartUpload(r *http.Request, push func(ctx context.Context, name, localPath string) (int64, error)) (string, int64, error) {
|
|
if err := r.ParseMultipartForm(8 << 20); err != nil {
|
|
return "", 0, errors.New("invalid multipart upload")
|
|
}
|
|
file, header, err := r.FormFile("file")
|
|
if err != nil {
|
|
file, header, err = r.FormFile("image")
|
|
}
|
|
if err != nil || file == nil || header == nil {
|
|
return "", 0, errors.New("file is required")
|
|
}
|
|
defer file.Close()
|
|
filename := uploadFilename(header.Filename)
|
|
temporary, err := os.CreateTemp("", "upload-*")
|
|
if err != nil {
|
|
return "", 0, errors.New("upload could not be stored")
|
|
}
|
|
temporaryPath := temporary.Name()
|
|
defer os.Remove(temporaryPath)
|
|
_, copyErr := io.Copy(temporary, file)
|
|
closeErr := temporary.Close()
|
|
if copyErr != nil || closeErr != nil {
|
|
return "", 0, errors.New("upload could not be stored")
|
|
}
|
|
size, err := push(r.Context(), filename, temporaryPath)
|
|
if err != nil {
|
|
return "", 0, errors.New("upload could not be stored")
|
|
}
|
|
return filename, size, nil
|
|
}
|
|
|
|
func uploadFilename(original string) string {
|
|
name := filepath.Base(strings.TrimSpace(original))
|
|
extension := filepath.Ext(name)
|
|
stem := strings.TrimSuffix(name, extension)
|
|
stem = sanitizeUploadPart(stem)
|
|
extension = sanitizeUploadPart(extension)
|
|
if stem == "" {
|
|
stem = "upload"
|
|
}
|
|
if extension != "" && !strings.HasPrefix(extension, ".") {
|
|
extension = "." + extension
|
|
}
|
|
id, err := randomID()
|
|
if err != nil || len(id) < 8 {
|
|
id = "upload00000000"
|
|
}
|
|
return id[:8] + "-" + stem[:minInt(len(stem), 160)] + extension
|
|
}
|
|
|
|
func sanitizeUploadPart(value string) string {
|
|
var builder strings.Builder
|
|
for _, char := range value {
|
|
if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9') || char == '.' || char == '_' || char == '-' {
|
|
builder.WriteRune(char)
|
|
} else {
|
|
builder.WriteByte('_')
|
|
}
|
|
}
|
|
return strings.Trim(builder.String(), "._-")
|
|
}
|
|
|
|
func (s *Server) toolFile(w http.ResponseWriter, r *http.Request, mountPrefix string) {
|
|
relative := chi.URLParam(r, "*")
|
|
if relative == "" {
|
|
relative = strings.TrimPrefix(r.URL.Path, "/")
|
|
}
|
|
if !safeRelative(relative) {
|
|
writeError(w, http.StatusNotFound, "file not found")
|
|
return
|
|
}
|
|
s.proxyServant(w, r, mountPrefix+urlPath(relative))
|
|
}
|
|
|
|
func (s *Server) workflowList(w http.ResponseWriter, _ *http.Request) {
|
|
entries, err := os.ReadDir(s.cfg.WorkflowsRoot)
|
|
if err != nil {
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": true, "builtIn": []string{}, "mine": []string{}, "data": []string{}})
|
|
return
|
|
}
|
|
workflows := make([]string, 0, len(entries))
|
|
for _, entry := range entries {
|
|
if entry.IsDir() {
|
|
continue
|
|
}
|
|
ext := strings.ToLower(filepath.Ext(entry.Name()))
|
|
if ext == ".json" || ext == ".png" {
|
|
workflows = append(workflows, entry.Name())
|
|
}
|
|
}
|
|
sort.Strings(workflows)
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": true, "builtIn": workflows, "mine": []string{}, "data": workflows})
|
|
}
|
|
|
|
func (s *Server) workflowMeta(w http.ResponseWriter, r *http.Request) {
|
|
name := filepath.Base(strings.TrimSpace(r.URL.Query().Get("name")))
|
|
if name == "." || name == "" || !safeRelative(name) {
|
|
writeError(w, http.StatusBadRequest, "missing workflow name")
|
|
return
|
|
}
|
|
full, err := s.resolveUnderRoots(name, []string{s.cfg.WorkflowsRoot})
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "workflow not found")
|
|
return
|
|
}
|
|
data, err := os.ReadFile(full)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "workflow could not be read")
|
|
return
|
|
}
|
|
var graph map[string]map[string]any
|
|
if json.Unmarshal(data, &graph) != nil {
|
|
writeError(w, http.StatusBadRequest, "workflow JSON is invalid")
|
|
return
|
|
}
|
|
videoLength := false
|
|
for _, node := range graph {
|
|
if classType, _ := node["class_type"].(string); classType == "WanImageToVideo" {
|
|
videoLength = true
|
|
break
|
|
}
|
|
}
|
|
defaults := map[string]any{}
|
|
var videoFPS any
|
|
if videoLength {
|
|
defaults["videoLength"] = 5
|
|
videoFPS = 16
|
|
}
|
|
info, _ := os.Stat(full)
|
|
writeJSON(w, http.StatusOK, map[string]any{"success": true, "workflow": name, "graph": graph, "supports": map[string]bool{"videoLength": videoLength}, "defaults": defaults, "videoFps": videoFPS, "data": map[string]any{"name": name, "bytes": infoSize(info), "modifiedAt": infoTime(info)}})
|
|
}
|
|
|
|
func (s *Server) myGenerations(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": []any{}, "generations": []any{}})
|
|
}
|
|
|
|
func (s *Server) downloadWorkflowResult(w http.ResponseWriter, r *http.Request) {
|
|
job, err := s.findWorkflowJob(r.Context(), chi.URLParam(r, "id"))
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "job not found")
|
|
return
|
|
}
|
|
if job.Status != "completed" {
|
|
writeError(w, http.StatusConflict, "job is not complete")
|
|
return
|
|
}
|
|
filename, _ := job.Result["outputFile"].(string)
|
|
if !safeRelative(filename) {
|
|
writeError(w, http.StatusNotFound, "job result not found")
|
|
return
|
|
}
|
|
servantPath := "/mount/generated/" + urlPath(filename)
|
|
if exists, _, _, err := s.probeServant(r.Context(), servantPath); err != nil || !exists {
|
|
writeError(w, http.StatusGone, "job result is no longer available")
|
|
return
|
|
}
|
|
w.Header().Set("Content-Disposition", `attachment; filename="`+filepath.Base(filename)+`"`)
|
|
s.proxyServant(w, r, servantPath)
|
|
}
|
|
|
|
func scanWorkflowJob(row interface{ Scan(...any) error }) (WorkflowJob, error) {
|
|
var job WorkflowJob
|
|
var request, result []byte
|
|
var errorMessage string
|
|
if err := row.Scan(&job.ID, &job.Service, &job.Tool, &job.Status, &job.Progress, &request, &result, &errorMessage, &job.CreatedAt, &job.StartedAt, &job.FinishedAt); err != nil {
|
|
return job, err
|
|
}
|
|
_ = json.Unmarshal(request, &job.Request)
|
|
_ = json.Unmarshal(result, &job.Result)
|
|
job.Error = errorMessage
|
|
return job, nil
|
|
}
|
|
|
|
func minInt(left, right int) int {
|
|
if left < right {
|
|
return left
|
|
}
|
|
return right
|
|
}
|
|
|
|
func infoTime(info os.FileInfo) any {
|
|
if info == nil {
|
|
return nil
|
|
}
|
|
return info.ModTime()
|
|
}
|
|
|
|
func (s *Server) findWorkflowJob(ctx context.Context, id string) (WorkflowJob, error) {
|
|
return scanWorkflowJob(s.db.QueryRow(ctx, `SELECT id, service, tool, status, progress, request, result, COALESCE(error_message, ''), created_at, started_at, finished_at FROM workflow_jobs WHERE id=$1 AND service=$2`, id, s.cfg.ServiceName))
|
|
}
|
|
|
|
func randomID() (string, error) {
|
|
data := make([]byte, 16)
|
|
if _, err := rand.Read(data); err != nil {
|
|
return "", err
|
|
}
|
|
return hex.EncodeToString(data), nil
|
|
}
|
|
|
|
func mustJSON(value any) []byte {
|
|
if value == nil {
|
|
return []byte(`{}`)
|
|
}
|
|
data, err := json.Marshal(value)
|
|
if err != nil {
|
|
return []byte(`{}`)
|
|
}
|
|
return data
|
|
}
|
|
|
|
func inferToolFromPath(value string) string {
|
|
for _, tool := range []string{"generator", "downloader", "converter"} {
|
|
if strings.Contains(value, tool) {
|
|
return tool
|
|
}
|
|
}
|
|
return "workflow"
|
|
}
|
|
|
|
func validateDownloadURL(raw string) error {
|
|
parsed, err := url.Parse(strings.TrimSpace(raw))
|
|
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Hostname() == "" {
|
|
return fmt.Errorf("url must be an absolute http(s) URL")
|
|
}
|
|
if parsed.User != nil {
|
|
return fmt.Errorf("URL credentials are not allowed")
|
|
}
|
|
host := parsed.Hostname()
|
|
if ip := net.ParseIP(host); ip != nil && isPrivateIP(ip) {
|
|
return fmt.Errorf("private and local download hosts are not allowed")
|
|
}
|
|
if strings.EqualFold(host, "localhost") || strings.HasSuffix(strings.ToLower(host), ".localhost") || strings.EqualFold(host, "metadata.google.internal") {
|
|
return fmt.Errorf("private and local download hosts are not allowed")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func isPrivateIP(ip net.IP) bool {
|
|
if ip == nil {
|
|
return true
|
|
}
|
|
if ip.IsLoopback() || ip.IsUnspecified() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsMulticast() || ip.IsPrivate() {
|
|
return true
|
|
}
|
|
if v4 := ip.To4(); v4 != nil {
|
|
ip = v4
|
|
}
|
|
private := []*net.IPNet{}
|
|
for _, cidr := range []string{"0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.168.0.0/16", "198.18.0.0/15", "::1/128", "fc00::/7", "fe80::/10"} {
|
|
_, network, _ := net.ParseCIDR(cidr)
|
|
private = append(private, network)
|
|
}
|
|
for _, network := range private {
|
|
if network.Contains(ip) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|