GET /api/info reports name/tabs/mount types (empty - state lives in Postgres, no shared file mounts) so ProjectConfigurator's Projects workspace can register this instance from just a URL. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
332 lines
12 KiB
Go
332 lines
12 KiB
Go
package server
|
|
|
|
// CarrierNode client: every non-CarrierNode service serves and stores media by calling CarrierNode's
|
|
// HTTP API through the helpers in this file instead of touching MediaRoots/ThumbnailRoot/
|
|
// OutputRoot/DownloadsRoot/InputRoot/CopyRoot locally. CarrierNode's own handlers keep using those
|
|
// roots directly (see media.go, admin_storage.go) - this file is never called from CarrierNode's
|
|
// own code path.
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// carrierNodeHTTPClient has no blanket timeout since it streams large media files; callers bound
|
|
// individual calls with a context deadline instead.
|
|
var carrierNodeHTTPClient = &http.Client{}
|
|
|
|
func (s *Server) carrierNodeClient() *http.Client {
|
|
return carrierNodeHTTPClient
|
|
}
|
|
|
|
// carrierNodeBaseURL is configured in ProjectConfigurator and stored in the settings table (key
|
|
// "carriernode_url", the same "{projectKey}_url" convention ConfigWorkspace.svelte uses for
|
|
// every project's connection URL) - not a static env var, so a change in ProjectConfigurator
|
|
// takes effect on every service's very next request without a restart. CARRIERNODE_URL is only the
|
|
// bootstrap fallback before that setting has ever been saved.
|
|
func (s *Server) carrierNodeBaseURL(ctx context.Context) string {
|
|
return strings.TrimRight(s.settingValue(ctx, "carriernode_url", s.cfg.CarrierNodeURL), "/")
|
|
}
|
|
|
|
func (s *Server) newCarrierNodeRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
|
|
request, err := http.NewRequestWithContext(ctx, method, s.carrierNodeBaseURL(ctx)+path, body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if s.cfg.InternalServiceSecret != "" {
|
|
request.Header.Set("X-Internal-Auth", s.cfg.InternalServiceSecret)
|
|
}
|
|
return request, nil
|
|
}
|
|
|
|
var carrierNodeForwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
|
|
var carrierNodeForwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
|
|
|
|
// proxyCarrierNode streams a CarrierNode response straight through to the original client, preserving
|
|
// range/conditional-request semantics so video scrubbing keeps working without reimplementing
|
|
// http.ServeContent on this side.
|
|
func (s *Server) proxyCarrierNode(w http.ResponseWriter, r *http.Request, carrierNodePath string) {
|
|
request, err := s.newCarrierNodeRequest(r.Context(), r.Method, carrierNodePath, nil)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadGateway, "media service unavailable")
|
|
return
|
|
}
|
|
for _, header := range carrierNodeForwardRequestHeaders {
|
|
if value := r.Header.Get(header); value != "" {
|
|
request.Header.Set(header, value)
|
|
}
|
|
}
|
|
response, err := s.carrierNodeClient().Do(request)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadGateway, "media service unavailable")
|
|
return
|
|
}
|
|
defer response.Body.Close()
|
|
for _, header := range carrierNodeForwardResponseHeaders {
|
|
if value := response.Header.Get(header); value != "" {
|
|
w.Header().Set(header, value)
|
|
}
|
|
}
|
|
w.WriteHeader(response.StatusCode)
|
|
if r.Method != http.MethodHead {
|
|
_, _ = io.Copy(w, response.Body)
|
|
}
|
|
}
|
|
|
|
// probeCarrierNode checks whether a CarrierNode-served path exists without fetching its bytes.
|
|
// A 404 is reported as exists=false with a nil error, not a failure - only transport/5xx
|
|
// problems are surfaced as errors.
|
|
func (s *Server) probeCarrierNode(ctx context.Context, carrierNodePath string) (bool, int64, time.Time, error) {
|
|
request, err := s.newCarrierNodeRequest(ctx, http.MethodHead, carrierNodePath, nil)
|
|
if err != nil {
|
|
return false, 0, time.Time{}, err
|
|
}
|
|
response, err := s.carrierNodeClient().Do(request)
|
|
if err != nil {
|
|
return false, 0, time.Time{}, err
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode == http.StatusNotFound {
|
|
return false, 0, time.Time{}, nil
|
|
}
|
|
if response.StatusCode >= 400 {
|
|
return false, 0, time.Time{}, fmt.Errorf("carriernode probe failed: %s", response.Status)
|
|
}
|
|
size, _ := strconv.ParseInt(response.Header.Get("Content-Length"), 10, 64)
|
|
modTime, _ := http.ParseTime(response.Header.Get("Last-Modified"))
|
|
return true, size, modTime, nil
|
|
}
|
|
|
|
// fetchCarrierNodeToScratch downloads a CarrierNode-served path into an ephemeral temp file for local
|
|
// processing (ffmpeg/ffprobe/yt-dlp all need a real file handle). Callers must invoke the
|
|
// returned cleanup once done; it removes the scratch file unconditionally.
|
|
func (s *Server) fetchCarrierNodeToScratch(ctx context.Context, carrierNodePath, suffix string) (string, func(), error) {
|
|
request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, carrierNodePath, nil)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
response, err := s.carrierNodeClient().Do(request)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode != http.StatusOK {
|
|
return "", nil, fmt.Errorf("carriernode fetch failed: %s", response.Status)
|
|
}
|
|
scratch, err := os.CreateTemp("", "carriernode-src-*"+suffix)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
cleanup := func() { _ = os.Remove(scratch.Name()) }
|
|
if _, err := io.Copy(scratch, response.Body); err != nil {
|
|
scratch.Close()
|
|
cleanup()
|
|
return "", nil, err
|
|
}
|
|
if err := scratch.Close(); err != nil {
|
|
cleanup()
|
|
return "", nil, err
|
|
}
|
|
return scratch.Name(), cleanup, nil
|
|
}
|
|
|
|
// pushToCarrierNode streams a local file as the request body without buffering it in memory.
|
|
func (s *Server) pushToCarrierNode(ctx context.Context, method, carrierNodePath, localPath string) (*http.Response, error) {
|
|
file, err := os.Open(localPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer file.Close()
|
|
request, err := s.newCarrierNodeRequest(ctx, method, carrierNodePath, file)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if info, statErr := file.Stat(); statErr == nil {
|
|
request.ContentLength = info.Size()
|
|
}
|
|
response, err := s.carrierNodeClient().Do(request)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if response.StatusCode >= 400 {
|
|
body, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
|
|
response.Body.Close()
|
|
return nil, fmt.Errorf("carriernode push failed: %s: %s", response.Status, string(body))
|
|
}
|
|
return response, nil
|
|
}
|
|
|
|
func carrierNodePushedSize(response *http.Response) int64 {
|
|
defer response.Body.Close()
|
|
var payload struct {
|
|
Size int64 `json:"size"`
|
|
}
|
|
_ = json.NewDecoder(response.Body).Decode(&payload)
|
|
return payload.Size
|
|
}
|
|
|
|
func (s *Server) carrierNodePushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
|
|
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return carrierNodePushedSize(response), nil
|
|
}
|
|
|
|
func (s *Server) carrierNodeDeleteThumbnail(ctx context.Context, id string) error {
|
|
request, err := s.newCarrierNodeRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
response, err := s.carrierNodeClient().Do(request)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound {
|
|
return fmt.Errorf("carriernode delete thumbnail failed: %s", response.Status)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) carrierNodePushOutput(ctx context.Context, name, localPath string) (int64, error) {
|
|
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return carrierNodePushedSize(response), nil
|
|
}
|
|
|
|
func (s *Server) carrierNodePushInput(ctx context.Context, name, localPath string) (int64, error) {
|
|
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return carrierNodePushedSize(response), nil
|
|
}
|
|
|
|
func (s *Server) carrierNodePushCopy(ctx context.Context, name, localPath string) (int64, error) {
|
|
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return carrierNodePushedSize(response), nil
|
|
}
|
|
|
|
// carrierNodeUploadDownload streams a locally-produced file (e.g. a completed yt-dlp download
|
|
// staged in a scratch dir) into CarrierNode's DownloadsRoot via its existing raw-upload endpoint.
|
|
func (s *Server) carrierNodeUploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) {
|
|
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/upload?filename="+url.QueryEscape(filename), localPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer response.Body.Close()
|
|
var payload map[string]any
|
|
_ = json.NewDecoder(response.Body).Decode(&payload)
|
|
return payload, nil
|
|
}
|
|
|
|
// carrierNodeStoreDownload catalogs an already-uploaded file into CarrierNode's media/downloaded_media
|
|
// tables via its existing /api/store endpoint - callers should stop duplicating that DB write
|
|
// locally once they migrate to this.
|
|
func (s *Server) carrierNodeStoreDownload(ctx context.Context, filePath, sourceURL, tool, status string) (map[string]any, error) {
|
|
body, err := json.Marshal(map[string]any{"filePath": filePath, "sourceUrl": sourceURL, "tool": tool, "status": status})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
request, err := s.newCarrierNodeRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
request.Header.Set("Content-Type", "application/json")
|
|
response, err := s.carrierNodeClient().Do(request)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode >= 400 {
|
|
errorBody, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
|
|
return nil, fmt.Errorf("carriernode store failed: %s: %s", response.Status, string(errorBody))
|
|
}
|
|
var payload map[string]any
|
|
_ = json.NewDecoder(response.Body).Decode(&payload)
|
|
return payload, nil
|
|
}
|
|
|
|
// carrierNodeListFiles lists files under CarrierNode's MediaRoots via its existing /api/files(/recent)
|
|
// endpoints - the replacement for a local filepath.WalkDir over MediaRoots.
|
|
func (s *Server) carrierNodeListFiles(ctx context.Context, relative string, recent bool, limit int) ([]fileEntry, error) {
|
|
endpoint := "/api/files"
|
|
if recent {
|
|
endpoint = "/api/files/recent"
|
|
}
|
|
query := url.Values{}
|
|
if relative != "" {
|
|
query.Set("path", relative)
|
|
}
|
|
if limit > 0 {
|
|
query.Set("limit", strconv.Itoa(limit))
|
|
}
|
|
if encoded := query.Encode(); encoded != "" {
|
|
endpoint += "?" + encoded
|
|
}
|
|
request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, endpoint, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
response, err := s.carrierNodeClient().Do(request)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("carriernode file listing failed: %s", response.Status)
|
|
}
|
|
var payload struct {
|
|
Files []fileEntry `json:"files"`
|
|
}
|
|
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
|
|
return nil, err
|
|
}
|
|
return payload.Files, nil
|
|
}
|
|
|
|
type carrierNodeProbeResult struct {
|
|
DurationMs int64 `json:"durationMs"`
|
|
Width int `json:"width"`
|
|
Height int `json:"height"`
|
|
}
|
|
|
|
// carrierNodeProbe runs ffprobe on CarrierNode against a MediaRoots-relative path and returns just the
|
|
// metadata fields - bytes never leave CarrierNode, unlike every other helper in this file.
|
|
func (s *Server) carrierNodeProbe(ctx context.Context, relative string) (carrierNodeProbeResult, error) {
|
|
query := url.Values{}
|
|
query.Set("path", relative)
|
|
request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil)
|
|
if err != nil {
|
|
return carrierNodeProbeResult{}, err
|
|
}
|
|
response, err := s.carrierNodeClient().Do(request)
|
|
if err != nil {
|
|
return carrierNodeProbeResult{}, err
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode != http.StatusOK {
|
|
return carrierNodeProbeResult{}, fmt.Errorf("carriernode probe failed: %s", response.Status)
|
|
}
|
|
var result carrierNodeProbeResult
|
|
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
|
|
return carrierNodeProbeResult{}, err
|
|
}
|
|
return result, nil
|
|
}
|