feat: improve ArtCraft integration and configurable file opening
This commit is contained in:
1 parent
3bc62d2b69
commit
80bc2c458d
60 files changed
+1738
-232
No files matched your search
+133
@@ -0,0 +1,133 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var mediaStreams = make(chan struct{}, 2)
|
||||
|
||||
var mediaStatusHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
status := struct {
|
||||
Available bool `json:"available"`
|
||||
Version string `json:"version,omitempty"`
|
||||
}{}
|
||||
binary, err := exec.LookPath("ffmpeg")
|
||||
if err == nil {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
output, runErr := exec.CommandContext(ctx, binary, "-version").Output()
|
||||
if runErr == nil && strings.HasPrefix(string(output), "ffmpeg version ") {
|
||||
status.Available = true
|
||||
status.Version = strings.SplitN(string(output), "\n", 2)[0]
|
||||
}
|
||||
}
|
||||
return renderJSON(w, r, status)
|
||||
})
|
||||
|
||||
// The browser uses the original file first. This optional fallback converts
|
||||
// codecs the browser cannot decode, without changing or copying the original.
|
||||
var mediaHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
||||
if !d.user.Perm.Download {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
name := r.URL.Query().Get("path")
|
||||
if name == "" || !strings.HasPrefix(name, "/") || path.Clean(name) != name || strings.ContainsAny(name, "\\\x00") {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
if !d.Check(name) {
|
||||
return http.StatusForbidden, nil
|
||||
}
|
||||
ext := strings.ToLower(path.Ext(name))
|
||||
if !strings.Contains("|.mp4|.m4v|.mkv|.webm|.mov|.avi|.wmv|.mpg|.mpeg|.ts|.mts|.m2ts|.flv|.ogv|.mp3|.wav|.ogg|.oga|.flac|.m4a|.aac|.opus|.aif|.aiff|.wma|.ac3|.dts|", "|"+ext+"|") {
|
||||
return http.StatusUnsupportedMediaType, nil
|
||||
}
|
||||
input, err := d.user.Fs.Open(name)
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
defer input.Close()
|
||||
info, err := input.Stat()
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
return http.StatusBadRequest, nil
|
||||
}
|
||||
binary, err := exec.LookPath("ffmpeg")
|
||||
if err != nil {
|
||||
return http.StatusServiceUnavailable, errors.New("install FFmpeg on the server to play this codec")
|
||||
}
|
||||
select {
|
||||
case mediaStreams <- struct{}{}:
|
||||
defer func() { <-mediaStreams }()
|
||||
default:
|
||||
return http.StatusTooManyRequests, nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Hour)
|
||||
defer cancel()
|
||||
// Give FFmpeg seekable HTTP access to this already authorized, open handle.
|
||||
// No filesystem path, credentials or caller-controlled URL enters its args.
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
secret := make([]byte, 32)
|
||||
if _, err = rand.Read(secret); err != nil {
|
||||
listener.Close()
|
||||
return 500, err
|
||||
}
|
||||
token := "/" + hex.EncodeToString(secret)
|
||||
var readMu sync.Mutex
|
||||
relay := &http.Server{ReadHeaderTimeout: 5 * time.Second, Handler: http.HandlerFunc(func(out http.ResponseWriter, request *http.Request) {
|
||||
if request.URL.Path != token || (request.Method != "GET" && request.Method != "HEAD") {
|
||||
http.NotFound(out, request)
|
||||
return
|
||||
}
|
||||
// ServeContent seeks the shared handle; FFmpeg issues sequential range requests.
|
||||
readMu.Lock()
|
||||
defer readMu.Unlock()
|
||||
http.ServeContent(out, request, info.Name(), info.ModTime(), input)
|
||||
})}
|
||||
go relay.Serve(listener) //nolint:errcheck
|
||||
defer relay.Close()
|
||||
args := []string{"-nostdin", "-hide_banner", "-loglevel", "error", "-protocol_whitelist", "http,tcp", "-format_whitelist", "mov,matroska,webm,avi,asf,mpeg,mpegts,flv,ogg,wav,mp3,flac,aac,aiff,ac3,eac3,dts", "-threads", "2", "-i", "http://" + listener.Addr().String() + token}
|
||||
if r.URL.Query().Get("audio") == "true" {
|
||||
args = append(args, "-map", "0:a:0", "-vn", "-c:a", "libmp3lame", "-b:a", "192k", "-f", "mp3", "pipe:1")
|
||||
w.Header().Set("Content-Type", "audio/mpeg")
|
||||
} else {
|
||||
args = append(args, "-map", "0:v:0", "-map", "0:a:0?", "-c:v", "libx264", "-threads", "2", "-preset", "veryfast", "-crf", "23", "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2", "-pix_fmt", "yuv420p", "-c:a", "aac", "-movflags", "frag_keyframe+empty_moov+default_base_moof", "-f", "mp4", "pipe:1")
|
||||
w.Header().Set("Content-Type", "video/mp4")
|
||||
}
|
||||
command := exec.CommandContext(ctx, binary, args...)
|
||||
stream, err := command.StdoutPipe()
|
||||
if err != nil {
|
||||
return 500, err
|
||||
}
|
||||
if err = command.Start(); err != nil {
|
||||
return http.StatusServiceUnavailable, err
|
||||
}
|
||||
defer command.Wait() //nolint:errcheck
|
||||
// Do not report success when FFmpeg rejects the container or codec.
|
||||
first := make([]byte, 32*1024)
|
||||
n, err := stream.Read(first)
|
||||
if n == 0 {
|
||||
return http.StatusUnsupportedMediaType, errors.New("FFmpeg could not decode this media file")
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
if _, err = w.Write(first[:n]); err == nil {
|
||||
_, err = io.Copy(w, stream)
|
||||
}
|
||||
if err != nil {
|
||||
cancel()
|
||||
}
|
||||
return 0, err
|
||||
})
|
||||
Reference in new issue
Block a user