Fix proxied download by removing approx filesize

This commit is contained in:
Evan Fiordeliso 2024-02-17 11:05:49 -05:00
parent dd84590ac7
commit 8e4a9cb4f1
2 changed files with 32 additions and 8 deletions

View File

@ -3,7 +3,7 @@ testdata_dir = "testdata"
tmp_dir = "tmp"
[build]
args_bin = ["-l", "0.0.0.0"]
args_bin = ["-l", "0.0.0.0", "-p", "3000"]
bin = "./out/ytdl-web"
cmd = "build"
delay = 1000

View File

@ -2,8 +2,10 @@ package controllers
import (
"fmt"
"io"
"net/http"
"net/url"
"sync"
"github.com/go-chi/chi/v5"
"github.com/samber/lo"
@ -147,17 +149,39 @@ func (c *DownloadController) ProxyDownload(w http.ResponseWriter, r *http.Reques
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s-%s.%s\"", meta.ID, format.Resolution, format.Ext))
if format.Filesize != nil {
w.Header().Set("Content-Length", fmt.Sprint(*format.Filesize))
} else if format.FilesizeApprox != nil {
w.Header().Set("Content-Length", fmt.Sprint(*format.FilesizeApprox))
}
if len(videos) == 1 {
index = -1
}
if err := c.ytdl.Download(w, videoUrl, format.FormatID, index); err != nil {
slog.Error("Failed to download", slog.String("error", err.Error()))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
pread, pwrite := io.Pipe()
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
if err := c.ytdl.Download(pwrite, videoUrl, format.FormatID, index); err != nil {
slog.Error("Failed to download", slog.String("error", err.Error()))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
pwrite.CloseWithError(err)
return
} else {
pwrite.Close()
}
}()
go func() {
defer wg.Done()
_, err = io.Copy(w, pread)
if err != nil {
slog.Error("Failed to copy", slog.String("error", err.Error()))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}()
wg.Wait()
}