Files
zurg/internal/universal/get.go
Ben Sarmiento fcbbff9ea2 read file fix
2023-11-12 00:37:35 +01:00

224 lines
7.2 KiB
Go

package universal
import (
"fmt"
"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"
intTor "github.com/debridmediamanager.com/zurg/internal/torrent"
zurghttp "github.com/debridmediamanager.com/zurg/pkg/http"
"github.com/debridmediamanager.com/zurg/pkg/logutil"
"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 *intTor.TorrentManager, c config.ConfigInterface, cache *expirable.LRU[string, string]) {
log := logutil.NewLogger().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)
} else {
intHttp.HandleDirectoryListing(w, r, t, c)
}
return
}
baseDirectory := segments[len(segments)-3]
accessKey := segments[len(segments)-2]
filename := segments[len(segments)-1]
torrent, _ := t.TorrentMap.Get(accessKey)
if torrent == nil {
log.Warnf("Cannot find torrent %s in the directory %s", accessKey, baseDirectory)
http.Error(w, "File not found", http.StatusNotFound)
return
}
file, _ := torrent.SelectedFiles.Get(filename)
if file == nil {
log.Warnf("Cannot find file from path %s", requestPath)
http.Error(w, "File not found", http.StatusNotFound)
return
}
if data, exists := cache.Get(requestPath); exists {
streamFileToResponse(torrent, data, w, r, t, c, log)
return
}
if file.Link == "" {
// This is a dead file, serve an alternate file
log.Warnf("File %s is not yet available, zurg is repairing the torrent", filename)
streamErrorVideo("https://www.youtube.com/watch?v=bGTqwt6vdcY", w, r, t, c, log)
return
}
link := file.Link
resp := t.UnrestrictUntilOk(link)
if resp == nil {
go t.Repair(torrent.AccessKey)
log.Warnf("File %s is no longer available, torrent is marked for repair", file.Path)
streamErrorVideo("https://www.youtube.com/watch?v=gea_FJrtFVA", w, r, t, c, log)
return
} else if resp.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(resp.Filename)
expectedExt := filepath.Ext(filename)
if actualExt != expectedExt && resp.Streamable != 1 {
log.Warnf("File was changed and is not streamable: %s and %s", filename, resp.Filename)
streamErrorVideo("https://www.youtube.com/watch?v=t9VgOriBHwE", w, r, t, c, log)
return
} else {
log.Warnf("Filename mismatch: %s and %s", filename, resp.Filename)
}
}
cache.Add(requestPath, resp.Download)
streamFileToResponse(torrent, resp.Download, w, r, t, c, log)
}
func streamFileToResponse(torrent *intTor.Torrent, url string, w http.ResponseWriter, r *http.Request, t *intTor.TorrentManager, c config.ConfigInterface, log *zap.SugaredLogger) {
// Create a new request for the file download.
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, t, c, log)
return
}
// copy range header if it exists
if r.Header.Get("Range") != "" {
req.Header.Add("Range", r.Header.Get("Range"))
}
// Create a custom HTTP client
client := zurghttp.NewHTTPClient(c.GetToken(), 10, c)
resp, err := client.Do(req)
if err != nil {
log.Warnf("Cannot download file %v ; torrent is marked for repair", err)
if torrent != nil {
go t.Repair(torrent.AccessKey)
}
streamErrorVideo("https://www.youtube.com/watch?v=FSSd8cponAA", w, r, t, c, log)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
log.Warnf("Received a %s status code ; torrent is marked for repair", resp.Status)
if torrent != nil {
go t.Repair(torrent.AccessKey)
}
streamErrorVideo("https://www.youtube.com/watch?v=BcseUxviVqE", w, r, t, 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, t *intTor.TorrentManager, c config.ConfigInterface, log *zap.SugaredLogger) {
resp := t.UnrestrictUntilOk(link)
if resp == nil {
http.Error(w, "REAL-DEBRID IS DOWN", http.StatusInternalServerError)
return
}
streamFileToResponse(nil, resp.Download, w, r, t, c, log)
}
func createErrorFile(path, link string) *intTor.File {
ret := intTor.File{
Link: link,
}
ret.Path = path
return &ret
}
func GetFileReader(torrent *intTor.Torrent, file *intTor.File, offset int64, size int, t *intTor.TorrentManager, c config.ConfigInterface, log *zap.SugaredLogger) io.ReadCloser {
unres := t.UnrestrictUntilOk(file.Link)
if unres == nil {
if strings.Contains(file.Link, "www.youtube.com") {
log.Errorf("Even the error page is broken! Sorry!")
return nil
}
log.Warnf("File %s is no longer available, torrent is marked for repair", file.Path)
if torrent != nil {
go t.Repair(torrent.AccessKey)
}
errFile := createErrorFile("unavailable.mp4", "https://www.youtube.com/watch?v=gea_FJrtFVA")
return GetFileReader(nil, errFile, 0, 0, t, c, log)
}
req, err := http.NewRequest(http.MethodGet, unres.Download, nil)
if err != nil {
if strings.Contains(file.Link, "www.youtube.com") {
log.Errorf("Even the error page is broken! Sorry!")
return nil
}
log.Errorf("Error creating new request: %v", err)
errFile := createErrorFile("new_request.mp4", "https://www.youtube.com/watch?v=H3NSrObyAxM")
return GetFileReader(nil, errFile, 0, 0, t, c, log)
}
if size == 0 {
size = int(file.Bytes)
}
req.Header.Add("Range", fmt.Sprintf("bytes=%v-%v", offset, size-1))
client := zurghttp.NewHTTPClient(c.GetToken(), 10, c)
resp, err := client.Do(req)
if err != nil {
if strings.Contains(file.Link, "www.youtube.com") {
log.Errorf("Even the error page is broken! Sorry!")
return nil
}
log.Warnf("Cannot download file %v ; torrent is marked for repair", err)
if torrent != nil {
go t.Repair(torrent.AccessKey)
}
errFile := createErrorFile("cannot_download.mp4", "https://www.youtube.com/watch?v=FSSd8cponAA")
return GetFileReader(nil, errFile, 0, 0, t, c, log)
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
if strings.Contains(file.Link, "www.youtube.com") {
log.Errorf("Even the error page is broken! Sorry!")
return nil
}
log.Warnf("Received a %s status code ; torrent is marked for repair", resp.Status)
if torrent != nil {
go t.Repair(torrent.AccessKey)
}
errFile := createErrorFile("not_ok_status.mp4", "https://www.youtube.com/watch?v=BcseUxviVqE")
return GetFileReader(nil, errFile, 0, 0, t, c, log)
}
return resp.Body
}