Use a proper client for fetch byte

This commit is contained in:
Ben Sarmiento
2023-11-24 21:35:22 +01:00
parent 1e8c50a350
commit 595040ad7e
6 changed files with 97 additions and 116 deletions

View File

@@ -18,6 +18,47 @@ func (rd *RealDebrid) UnrestrictUntilOk(link string) *UnrestrictResponse {
})
}
func (rd *RealDebrid) canFetchFirstByte(url string) bool {
const maxAttempts = 3
for i := 0; i < maxAttempts; i++ {
// Create a new HTTP request
req, err := http.NewRequest("GET", url, nil)
if err != nil {
continue
}
// Set the Range header to request only the first byte
req.Header.Set("Range", "bytes=0-0")
// TODO set a proper client
resp, err := http.DefaultClient.Do(req)
if err != nil {
time.Sleep(1 * time.Second) // Add a delay before the next retry
continue
}
defer resp.Body.Close()
// If server supports partial content
if resp.StatusCode == http.StatusPartialContent {
buffer := make([]byte, 1)
_, err := resp.Body.Read(buffer)
if err == nil {
return true
}
} else if resp.StatusCode == http.StatusOK {
// If server doesn't support partial content, try reading the first byte and immediately close
buffer := make([]byte, 1)
_, err = resp.Body.Read(buffer)
if err == nil {
return true
}
}
time.Sleep(500 * time.Millisecond) // Add a delay before the next retry
}
return false
}
func retryUntilOk[T any](fn func() (T, error)) T {
// const initialDelay = 1 * time.Second
// const maxDelay = 128 * time.Second
@@ -50,44 +91,3 @@ func retryUntilOk[T any](fn func() (T, error)) T {
time.Sleep(delay)
}
}
func canFetchFirstByte(url string) bool {
const maxAttempts = 3
for i := 0; i < maxAttempts; i++ {
// Create a new HTTP request
req, err := http.NewRequest("GET", url, nil)
if err != nil {
continue
}
// Set the Range header to request only the first byte
req.Header.Set("Range", "bytes=0-0")
// Execute the request
resp, err := http.DefaultClient.Do(req)
if err != nil {
time.Sleep(1 * time.Second) // Add a delay before the next retry
continue
}
defer resp.Body.Close()
// If server supports partial content
if resp.StatusCode == http.StatusPartialContent {
buffer := make([]byte, 1)
_, err := resp.Body.Read(buffer)
if err == nil {
return true
}
} else if resp.StatusCode == http.StatusOK {
// If server doesn't support partial content, try reading the first byte and immediately close
buffer := make([]byte, 1)
_, err = resp.Body.Read(buffer)
if err == nil {
return true
}
}
time.Sleep(500 * time.Millisecond) // Add a delay before the next retry
}
return false
}