Files
zurg/internal/universal/get.go
2023-11-07 17:20:54 +01:00

149 lines
4.6 KiB
Go

package universal
import (
"io"
"net/http"
"path"
"path/filepath"
"strings"
"github.com/debridmediamanager.com/zurg/internal/config"
"github.com/debridmediamanager.com/zurg/internal/dav"
intHttp "github.com/debridmediamanager.com/zurg/internal/http"
"github.com/debridmediamanager.com/zurg/internal/torrent"
"github.com/debridmediamanager.com/zurg/pkg/logutil"
"github.com/debridmediamanager.com/zurg/pkg/realdebrid"
"github.com/hashicorp/golang-lru/v2/expirable"
"go.uber.org/zap"
)
// HandleGetRequest handles a GET request universally for both WebDAV and HTTP
func HandleGetRequest(w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager, c config.ConfigInterface, cache *expirable.LRU[string, string]) {
rlog := logutil.NewLogger()
log := rlog.Named("uniget")
requestPath := path.Clean(r.URL.Path)
isDav := true
if strings.Contains(requestPath, "/http") {
requestPath = strings.Replace(requestPath, "/http", "/", 1)
isDav = false
}
if requestPath == "/favicon.ico" {
return
}
segments := strings.Split(requestPath, "/")
// If there are less than 3 segments, return an error or adjust as needed
if len(segments) <= 3 {
if isDav {
dav.HandlePropfindRequest(w, r, t, c, cache)
} else {
intHttp.HandleDirectoryListing(w, r, t, c, cache)
}
return
}
if data, exists := cache.Get(requestPath); exists {
streamFileToResponse(data, w, r, c, log)
return
}
baseDirectory := segments[len(segments)-3]
torrentName := segments[len(segments)-2]
filename := segments[len(segments)-1]
torrents := t.FindAllTorrentsWithName(baseDirectory, torrentName)
if torrents == nil {
log.Errorf("Cannot find torrent %s in the directory %s", requestPath, baseDirectory)
http.Error(w, "File not found", http.StatusNotFound)
return
}
torrent, file := getFile(torrents, filename)
if file == nil {
log.Errorf("Cannot find file from path %s", requestPath)
http.Error(w, "File not found", http.StatusNotFound)
return
}
if file.Link == "" {
// This is a dead file, serve an alternate file
log.Errorf("File %s is no longer available", filename)
streamErrorVideo("https://www.youtube.com/watch?v=bGTqwt6vdcY", w, r, c, log)
return
}
link := file.Link
unrestrictFn := func() (*realdebrid.UnrestrictResponse, error) {
return realdebrid.UnrestrictLink(c.GetToken(), link)
}
resp := realdebrid.RetryUntilOk(unrestrictFn)
if resp == nil {
if !file.Unavailable {
log.Errorf("Cannot unrestrict file %s %s", filename, link)
t.HideTheFile(torrent, file)
}
streamErrorVideo("https://www.youtube.com/watch?v=gea_FJrtFVA", w, r, c, log)
return
} else if resp.Filename != filename {
actualExt := filepath.Ext(resp.Filename)
expectedExt := filepath.Ext(filename)
if actualExt != expectedExt && resp.Streamable != 1 {
log.Errorf("File extension mismatch: %s and %s", filename, resp.Filename)
streamErrorVideo("https://www.youtube.com/watch?v=t9VgOriBHwE", w, r, c, log)
return
} else {
log.Errorf("Filename mismatch: %s and %s", filename, resp.Filename)
}
}
cache.Add(requestPath, resp.Download)
streamFileToResponse(resp.Download, w, r, c, log)
}
func streamFileToResponse(url string, w http.ResponseWriter, r *http.Request, c config.ConfigInterface, log *zap.SugaredLogger) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Errorf("Error creating new request %v", err)
streamErrorVideo("https://www.youtube.com/watch?v=H3NSrObyAxM", w, r, c, log)
return
}
for k, values := range r.Header {
for _, v := range values {
req.Header.Add(k, v)
}
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Errorf("Error downloading file %v", err)
streamErrorVideo("https://www.youtube.com/watch?v=FSSd8cponAA", w, r, c, log)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
log.Errorf("Received a nonOK status code %d", resp.StatusCode)
streamErrorVideo("https://www.youtube.com/watch?v=BcseUxviVqE", w, r, c, log)
return
}
for k, vv := range resp.Header {
for _, v := range vv {
w.Header().Add(k, v)
}
}
buf := make([]byte, c.GetNetworkBufferSize())
io.CopyBuffer(w, resp.Body, buf)
}
func streamErrorVideo(link string, w http.ResponseWriter, r *http.Request, c config.ConfigInterface, log *zap.SugaredLogger) {
unrestrictFn := func() (*realdebrid.UnrestrictResponse, error) {
return realdebrid.UnrestrictLink(c.GetToken(), link)
}
resp := realdebrid.RetryUntilOk(unrestrictFn)
if resp == nil {
http.Error(w, "REAL-DEBRID IS DOWN", http.StatusInternalServerError)
return
}
streamFileToResponse(resp.Download, w, r, c, log)
}