Prevent stale torrents

This commit is contained in:
Ben Adrian Sarmiento
2024-06-28 21:10:31 +02:00
parent 7cd8c9e5c9
commit c781a5fc7c
5 changed files with 9 additions and 121 deletions

View File

@@ -2,11 +2,9 @@ package universal
import (
"context"
"fmt"
"io"
"net/http"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"time"
@@ -20,10 +18,9 @@ import (
)
type Downloader struct {
rd *realdebrid.RealDebrid
workerPool *ants.Pool
RequestedBytes atomic.Uint64
TotalBytes atomic.Uint64
rd *realdebrid.RealDebrid
workerPool *ants.Pool
TotalBytes atomic.Uint64
}
func NewDownloader(rd *realdebrid.RealDebrid, workerPool *ants.Pool) *Downloader {
@@ -51,7 +48,6 @@ func (dl *Downloader) StartResetBandwidthCountersJob() {
ticker := time.NewTicker(24 * time.Hour)
for {
dl.rd.TokenManager.ResetAllTokens()
dl.RequestedBytes.Store(0)
dl.TotalBytes.Store(0)
<-ticker.C
}
@@ -234,14 +230,9 @@ func (dl *Downloader) streamFileToResponse(
return
}
// Update the download statistics
reqBytes, _ := parseRangeHeader(req.Header.Get("Range"))
if reqBytes == 0 && unrestrict != nil {
reqBytes = uint64(unrestrict.Filesize)
}
dl.RequestedBytes.Add(reqBytes)
dl.TotalBytes.Add(uint64(n))
if cfg.ShouldLogRequests() {
log.Debugf("Served %d MB of the requested %d MB of file %s (range=%s)", bToMb(uint64(n)), bToMb(reqBytes), unrestrict.Filename, req.Header.Get("Range"))
log.Debugf("Served %d MB of file %s (range=%s)", bToMb(uint64(n)), unrestrict.Filename, req.Header.Get("Range"))
}
})
}
@@ -250,50 +241,6 @@ func redirect(resp http.ResponseWriter, req *http.Request, url string) {
http.Redirect(resp, req, url, http.StatusFound)
}
func parseRangeHeader(rangeHeader string) (uint64, error) {
if rangeHeader == "" { // Empty header means no range request
return 0, nil
}
if !strings.HasPrefix(rangeHeader, "bytes=") {
return 0, fmt.Errorf("invalid range header format")
}
parts := strings.SplitN(rangeHeader[6:], "-", 2) // [6:] removes "bytes="
if len(parts) != 2 {
return 0, fmt.Errorf("invalid range specification")
}
var start, end uint64
var err error
// Case 1: "bytes=100-" (from byte 100 to the end)
if parts[0] != "" {
start, err = strconv.ParseUint(parts[0], 10, 64)
if err != nil {
return 0, fmt.Errorf("invalid start value: %w", err)
}
}
// Case 2: "bytes=-200" (last 200 bytes)
if parts[1] != "" {
end, err = strconv.ParseUint(parts[1], 10, 64)
if err != nil {
return 0, fmt.Errorf("invalid end value: %w", err)
}
}
// Handle "bytes=500-100" (invalid range)
if start > end {
return 0, fmt.Errorf("invalid range: start cannot be greater than end")
}
// Calculate bytes to read
bytesToRead := end - start + 1 // +1 because ranges are inclusive
return bytesToRead, nil
}
type byteCounter struct {
totalBytes *int64
}