package universal import ( "io" "net/http" "path/filepath" "strings" "github.com/debridmediamanager/zurg/internal/config" intTor "github.com/debridmediamanager/zurg/internal/torrent" zurghttp "github.com/debridmediamanager/zurg/pkg/http" "github.com/debridmediamanager/zurg/pkg/logutil" "github.com/debridmediamanager/zurg/pkg/realdebrid" ) type Downloader struct { client *zurghttp.HTTPClient } func NewDownloader(client *zurghttp.HTTPClient) *Downloader { return &Downloader{ client: client, } } // DownloadFile handles a GET request for files in torrents func (dl *Downloader) DownloadFile(directory, torrentName, fileName string, resp http.ResponseWriter, req *http.Request, torMgr *intTor.TorrentManager, cfg config.ConfigInterface, log *logutil.Logger) { 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 || file.IsDeleted { log.Warnf("Cannot find file %s from path %s", fileName, req.URL.Path) http.Error(resp, "File not found", http.StatusNotFound) return } // log.Debugf("Opening file %s from torrent %s (%s)", fileName, torMgr.GetKey(torrent), file.Link) if file.IsBroken { http.Error(resp, "File is not available", http.StatusInternalServerError) return } unrestrict := torMgr.UnrestrictUntilOk(file.Link) if unrestrict == nil { file.IsBroken = true if cfg.EnableRepair() { log.Warnf("File %s cannot be unrestricted (link=%s) (repairing...)", fileName, file.Link) torMgr.TriggerRepair(torrent) } else { log.Warnf("Repair is disabled, skipping repair for unavailable file %s (link=%s)", fileName, file.Link) } http.Error(resp, "File is not available", http.StatusInternalServerError) return } else { if unrestrict.Filesize != file.Bytes { // this is possible if there's only 1 streamable file in the torrent // and then suddenly it's a rar file actualExt := strings.ToLower(filepath.Ext(unrestrict.Filename)) expectedExt := strings.ToLower(filepath.Ext(fileName)) if actualExt != expectedExt && unrestrict.Streamable != 1 { log.Warnf("File was changed and is not streamable: %s and %s (link=%s)", fileName, unrestrict.Filename, unrestrict.Link) } else { log.Warnf("File mismatch: %s and %s", fileName, unrestrict.Filename) } } if cfg.ShouldServeFromRclone() { if cfg.ShouldVerifyDownloadLink() { if !dl.client.CanFetchFirstByte(unrestrict.Download) { log.Warnf("File %s is not available", fileName) http.Error(resp, "File is not available", http.StatusInternalServerError) return } } redirect(resp, req, unrestrict.Download, cfg) } else { dl.streamFileToResponse(torrent, file, unrestrict, resp, req, torMgr, cfg, log) } return } } // DownloadLink handles a GET request for downloads func (dl *Downloader) DownloadLink(fileName, link string, resp http.ResponseWriter, req *http.Request, torMgr *intTor.TorrentManager, cfg config.ConfigInterface, log *logutil.Logger) { // log.Debugf("Opening file %s (%s)", fileName, link) unrestrict := torMgr.UnrestrictUntilOk(link) if unrestrict == nil { log.Warnf("File %s cannot be unrestricted (link=%s)", fileName, link) http.Error(resp, "File is not available", http.StatusInternalServerError) return } else { lFilename := strings.ToLower(fileName) unrestrictFilename := strings.ToLower(strings.TrimPrefix(unrestrict.Filename, "/")) if strings.Contains(lFilename, unrestrictFilename) { // this is possible if there's only 1 streamable file in the torrent // and then suddenly it's a rar file actualExt := filepath.Ext(unrestrictFilename) expectedExt := filepath.Ext(lFilename) if actualExt != expectedExt && unrestrict.Streamable != 1 { log.Warnf("File was changed and is not streamable: %s and %s (link=%s)", fileName, unrestrict.Filename, unrestrict.Link) } else { log.Warnf("Filename mismatch: %s and %s", fileName, unrestrict.Filename) } } if cfg.ShouldServeFromRclone() { if cfg.ShouldVerifyDownloadLink() { if !dl.client.CanFetchFirstByte(unrestrict.Download) { log.Warnf("File %s is not available", fileName) http.Error(resp, "File is not available", http.StatusInternalServerError) return } } redirect(resp, req, unrestrict.Download, cfg) } else { dl.streamFileToResponse(nil, nil, unrestrict, resp, req, torMgr, cfg, log) } return } } func (dl *Downloader) streamFileToResponse(torrent *intTor.Torrent, file *intTor.File, unrestrict *realdebrid.Download, resp http.ResponseWriter, req *http.Request, torMgr *intTor.TorrentManager, cfg config.ConfigInterface, log *logutil.Logger) { // Create a new request for the file download. dlReq, err := http.NewRequest(http.MethodGet, unrestrict.Download, 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.StatusInternalServerError) return } // copy range header if it exists // rangeLog := "" if req.Header.Get("Range") != "" { dlReq.Header.Add("Range", req.Header.Get("Range")) // rangeLog = " (range: " + req.Header.Get("Range") + ")" } // if torrent != nil { // log.Debugf("Downloading unrestricted link %s from torrent %s (%s)%s", unrestrict.Download, torMgr.GetKey(torrent), unrestrict.Link, rangeLog) // } else { // log.Debugf("Downloading unrestricted link %s (%s)%s", unrestrict.Download, unrestrict.Link, rangeLog) // } download, err := dl.client.Do(dlReq) if err != nil { if file != nil && unrestrict.Streamable == 1 { file.IsBroken = true if cfg.EnableRepair() && torrent != nil { log.Warnf("Cannot download file %s: %v (repairing...)", unrestrict.Download, err) torMgr.TriggerRepair(torrent) } else { log.Warnf("Repair is disabled, skipping repair for unavailable file %s (link=%s)", file.Path, file.Link) } } else { log.Warnf("Cannot download file %s: %v", unrestrict.Download, err) } http.Error(resp, "File is not available", http.StatusInternalServerError) return } defer download.Body.Close() if download.StatusCode/100 != 2 { if file != nil && unrestrict.Streamable == 1 { file.IsBroken = true if cfg.EnableRepair() && torrent != nil { log.Warnf("Received a %s status code for file %s (repairing...)", download.Status, file.Path) torMgr.TriggerRepair(torrent) } else { log.Warnf("Repair is disabled, skipping repair for unavailable file %s (link=%s)", file.Path, file.Link) } } else { log.Warnf("Received a %s status code for file %s", download.Status, unrestrict.Download) } http.Error(resp, "File is not available", http.StatusInternalServerError) return } for k, vv := range download.Header { for _, v := range vv { resp.Header().Add(k, v) } } // log.Debugf("Serving file %s%s", unrestrict.Download, rangeLog) buf := make([]byte, cfg.GetNetworkBufferSize()) io.CopyBuffer(resp, download.Body, buf) } func redirect(resp http.ResponseWriter, req *http.Request, url string, cfg config.ConfigInterface) { http.Redirect(resp, req, url, http.StatusFound) }