204 lines
6.1 KiB
Go
204 lines
6.1 KiB
Go
package universal
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/debridmediamanager/zurg/internal/config"
|
|
intTor "github.com/debridmediamanager/zurg/internal/torrent"
|
|
zurghttp "github.com/debridmediamanager/zurg/pkg/http"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
type GetFile struct {
|
|
client *zurghttp.HTTPClient
|
|
}
|
|
|
|
func NewGetFile(client *zurghttp.HTTPClient) *GetFile {
|
|
return &GetFile{client: client}
|
|
}
|
|
|
|
// HandleGetRequest handles a GET request universally for both WebDAV and HTTP
|
|
func (gf *GetFile) HandleGetRequest(directory, torrentName, fileName string, resp http.ResponseWriter, req *http.Request, torMgr *intTor.TorrentManager, cfg config.ConfigInterface, log *zap.SugaredLogger) {
|
|
torrents, ok := torMgr.DirectoryMap.Get(directory)
|
|
if !ok {
|
|
log.Warnf("Cannot find directory %s", directory)
|
|
http.Error(resp, "File not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
torrent, ok := torrents.Get(torrentName)
|
|
if !ok {
|
|
log.Warnf("Cannot find torrent %sfrom path %s", torrentName, req.URL.Path)
|
|
http.Error(resp, "File not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
file, ok := torrent.SelectedFiles.Get(fileName)
|
|
if !ok {
|
|
log.Warnf("Cannot find file %s from path %s", fileName, req.URL.Path)
|
|
http.Error(resp, "File not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
if !strings.HasPrefix(file.Link, "http") {
|
|
// This is a dead file, serve an alternate file
|
|
log.Warnf("File %s is not available", fileName)
|
|
http.Error(resp, "File is not available", http.StatusNotFound)
|
|
return
|
|
}
|
|
link := file.Link
|
|
|
|
if download, exists := torMgr.DownloadCache.Get(link); exists {
|
|
if cfg.ShouldServeFromRclone() && torMgr.Api.CanFetchFirstByte(download.Download) {
|
|
redirect(resp, req, download.Download, cfg)
|
|
return
|
|
} else {
|
|
err := gf.streamCachedLinkToResponse(download.Download, resp, req, torMgr, cfg, log)
|
|
if err == nil {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
unrestrict := torMgr.UnrestrictUntilOk(link)
|
|
if unrestrict == nil {
|
|
// log.Warnf("File %s is no longer available, link %s", filepath.Base(file.Path), link)
|
|
file.Link = "repair"
|
|
if cfg.EnableRepair() {
|
|
// log.Debugf("File %s is marked for repair", filepath.Base(file.Path))
|
|
torMgr.ScheduleForRefresh() // force a recheck
|
|
}
|
|
http.Error(resp, "File is not available", http.StatusNotFound)
|
|
return
|
|
} else {
|
|
if unrestrict.Filename != fileName {
|
|
// this is possible if there's only 1 streamable file in the torrent
|
|
// and then suddenly it's a rar file
|
|
actualExt := filepath.Ext(unrestrict.Filename)
|
|
expectedExt := filepath.Ext(fileName)
|
|
if actualExt != expectedExt && unrestrict.Streamable != 1 {
|
|
log.Warnf("File was changed and is not streamable: %s and %s", fileName, unrestrict.Filename)
|
|
http.Error(resp, "File is not available", http.StatusNotFound)
|
|
return
|
|
} else {
|
|
log.Warnf("Filename mismatch: %s and %s", fileName, unrestrict.Filename)
|
|
}
|
|
}
|
|
torMgr.DownloadCache.Set(link, unrestrict)
|
|
if cfg.ShouldServeFromRclone() {
|
|
redirect(resp, req, unrestrict.Download, cfg)
|
|
} else {
|
|
gf.streamFileToResponse(file, unrestrict.Download, resp, req, torMgr, cfg, log)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
func (gf *GetFile) streamCachedLinkToResponse(url string, resp http.ResponseWriter, req *http.Request, torMgr *intTor.TorrentManager, cfg config.ConfigInterface, log *zap.SugaredLogger) error {
|
|
// Create a new dlReq for the file download.
|
|
dlReq, err := http.NewRequest(http.MethodGet, url, nil)
|
|
if err != nil {
|
|
return fmt.Errorf("file is not available")
|
|
}
|
|
|
|
// copy range header if it exists
|
|
if req.Header.Get("Range") != "" {
|
|
dlReq.Header.Add("Range", req.Header.Get("Range"))
|
|
}
|
|
|
|
download, err := gf.client.Do(dlReq)
|
|
if err != nil {
|
|
return fmt.Errorf("file is not available")
|
|
}
|
|
defer download.Body.Close()
|
|
|
|
if download.StatusCode != http.StatusOK && download.StatusCode != http.StatusPartialContent {
|
|
return fmt.Errorf("file is not available")
|
|
}
|
|
|
|
for k, vv := range download.Header {
|
|
for _, v := range vv {
|
|
resp.Header().Add(k, v)
|
|
}
|
|
}
|
|
|
|
buf := make([]byte, cfg.GetNetworkBufferSize())
|
|
io.CopyBuffer(resp, download.Body, buf)
|
|
return nil
|
|
}
|
|
|
|
func (gf *GetFile) streamFileToResponse(file *intTor.File, url string, resp http.ResponseWriter, req *http.Request, torMgr *intTor.TorrentManager, cfg config.ConfigInterface, log *zap.SugaredLogger) {
|
|
// Create a new request for the file download.
|
|
dlReq, err := http.NewRequest(http.MethodGet, url, nil)
|
|
if err != nil {
|
|
if file != nil {
|
|
log.Errorf("Error creating new request for file %s: %v", file.Path, err)
|
|
}
|
|
http.Error(resp, "File is not available", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
// copy range header if it exists
|
|
if req.Header.Get("Range") != "" {
|
|
dlReq.Header.Add("Range", req.Header.Get("Range"))
|
|
}
|
|
|
|
download, err := gf.client.Do(dlReq)
|
|
if err != nil {
|
|
if file != nil {
|
|
log.Warnf("Cannot download file %s: %v", file.Path, err)
|
|
file.Link = "repair"
|
|
if cfg.EnableRepair() {
|
|
// log.Debugf("File %s is marked for repair", filepath.Base(file.Path))
|
|
torMgr.ScheduleForRefresh() // force a recheck
|
|
}
|
|
}
|
|
http.Error(resp, "File is not available", http.StatusNotFound)
|
|
return
|
|
}
|
|
defer download.Body.Close()
|
|
|
|
if download.StatusCode != http.StatusOK && download.StatusCode != http.StatusPartialContent {
|
|
if file != nil {
|
|
log.Warnf("Received a %s status code for file %s", download.Status, file.Path)
|
|
file.Link = "repair"
|
|
if cfg.EnableRepair() {
|
|
// log.Debugf("File %s is marked for repair", filepath.Base(file.Path))
|
|
torMgr.ScheduleForRefresh() // force a recheck
|
|
}
|
|
}
|
|
http.Error(resp, "File is not available", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
for k, vv := range download.Header {
|
|
for _, v := range vv {
|
|
resp.Header().Add(k, v)
|
|
}
|
|
}
|
|
|
|
buf := make([]byte, cfg.GetNetworkBufferSize())
|
|
io.CopyBuffer(resp, download.Body, buf)
|
|
}
|
|
|
|
func redirect(resp http.ResponseWriter, req *http.Request, url string, cfg config.ConfigInterface) {
|
|
prefHost := cfg.GetRandomPreferredHost()
|
|
if prefHost != "" {
|
|
url = replaceHostInURL(url, prefHost)
|
|
}
|
|
http.Redirect(resp, req, url, http.StatusFound)
|
|
}
|
|
|
|
func replaceHostInURL(inputURL string, newHost string) string {
|
|
u, err := url.Parse(inputURL)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
u.Host = newHost
|
|
return u.String()
|
|
}
|