diff --git a/internal/universal/get.go b/internal/universal/get.go index 55d3e3d..0947cf6 100644 --- a/internal/universal/get.go +++ b/internal/universal/get.go @@ -1,6 +1,7 @@ package universal import ( + "fmt" "io" "net/http" "path" @@ -140,6 +141,43 @@ func streamFileToResponse(torrent *torrent.Torrent, url string, w http.ResponseW io.CopyBuffer(w, resp.Body, buf) } +func StreamFile(torrent *torrent.Torrent, url string, offset int64, size int, t *torrent.TorrentManager, c config.ConfigInterface, log *zap.SugaredLogger) io.ReadCloser { + // 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 nil + } + + // pass range header from offset and size + req.Header.Add("Range", "bytes="+fmt.Sprintf("%d-%d", offset, size-1)) + + // 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 nil + } + + 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 nil + } + + return resp.Body +} + func streamErrorVideo(link string, w http.ResponseWriter, r *http.Request, t *torrent.TorrentManager, c config.ConfigInterface, log *zap.SugaredLogger) { resp := t.UnrestrictUntilOk(link) if resp == nil {