Files
zurg/internal/universal/get.go
2023-10-28 06:18:47 +02:00

136 lines
3.9 KiB
Go

package universal
import (
"io"
"log"
"net/http"
"path"
"path/filepath"
"strings"
"sync"
"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/davextra"
"github.com/debridmediamanager.com/zurg/pkg/realdebrid"
"github.com/hashicorp/golang-lru/v2/expirable"
)
// 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]) {
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 {
http.Redirect(w, r, data, http.StatusFound)
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.Println("Cannot find torrent", requestPath)
http.Error(w, "Cannot find file", http.StatusNotFound)
return
}
filenameV2, linkFragment := davextra.ExtractLinkFragment(filename)
torrent, file := getFile(torrents, filenameV2, linkFragment)
if file == nil {
log.Println("Cannot find file (get)", requestPath)
http.Error(w, "Cannot find file", http.StatusNotFound)
return
}
if file.Link == "" {
log.Println("Link not found (get)", filename)
http.Error(w, "Cannot find file", http.StatusNotFound)
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.Println("Cannot unrestrict link", link, filenameV2)
t.HideTheFile(torrent, file)
}
http.Redirect(w, r, "https://send.nukes.wtf/tDeTd0", http.StatusFound)
} else if resp.Filename != filenameV2 {
actualExt := filepath.Ext(resp.Filename)
expectedExt := filepath.Ext(filenameV2)
if actualExt != expectedExt {
log.Println("File extension mismatch", resp.Filename, filenameV2)
} else {
log.Println("Filename mismatch", resp.Filename, filenameV2)
}
} else {
cache.Add(requestPath, resp.Download)
streamFileToResponse(resp.Download, w)
}
}
func streamFileToResponse(url string, w http.ResponseWriter) {
resp, err := http.Get(url) // HTTP/2 is used by default if the server supports it
if err != nil {
log.Println("Error downloading file:", err)
http.Error(w, "Error downloading file", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Printf("Received a non-OK status code: %d", resp.StatusCode)
http.Error(w, "Error downloading file", http.StatusInternalServerError)
return
}
// Parallelize header copying to reduce waiting time
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for k, vv := range resp.Header {
for _, v := range vv {
w.Header().Add(k, v)
}
}
}()
// If Content-Length is available from the original response, set it
if val, ok := resp.Header["Content-Length"]; ok {
w.Header().Set("Content-Length", val[0])
}
// Wait for the header copying to complete
// Stream the response with a buffer for better performance
bufferSize := 32 * 1024 // 16KB buffer
buf := make([]byte, bufferSize)
wg.Wait()
io.CopyBuffer(w, resp.Body, buf)
}