Skip to content

Commit

Permalink
feat: add retry for downloading audio chunk
Browse files Browse the repository at this point in the history
See #38
  • Loading branch information
devgianlu committed May 26, 2024
1 parent fdf6d57 commit b2ec6d5
Showing 1 changed file with 22 additions and 11 deletions.
33 changes: 22 additions & 11 deletions audio/chunked_reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package audio

import (
"fmt"
"github.com/cenkalti/backoff/v4"
log "github.com/sirupsen/logrus"
librespot "go-librespot"
"io"
Expand All @@ -10,6 +11,7 @@ import (
"regexp"
"strconv"
"sync"
"time"
)

const (
Expand Down Expand Up @@ -75,9 +77,6 @@ func NewHttpChunkedReader(log *log.Entry, audioUrl string) (_ *HttpChunkedReader
}

defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusPartialContent {
return nil, fmt.Errorf("invalid first chunk response status: %s", resp.Status)
}

// parse the Content-Range header with the complete content length
_, _, r.len, err = parseContentRange(resp)
Expand Down Expand Up @@ -108,14 +107,26 @@ func NewHttpChunkedReader(log *log.Entry, audioUrl string) (_ *HttpChunkedReader
}

func (r *HttpChunkedReader) downloadChunk(idx int) (*http.Response, error) {
return r.client.Do(&http.Request{
Method: "GET",
URL: r.url,
Header: http.Header{
"User-Agent": []string{librespot.UserAgent()},
"Range": []string{fmt.Sprintf("bytes=%d-%d", idx*DefaultChunkSize, (idx+1)*DefaultChunkSize-1)},
},
})
return backoff.RetryWithData(func() (*http.Response, error) {
resp, err := r.client.Do(&http.Request{
Method: "GET",
URL: r.url,
Header: http.Header{
"User-Agent": []string{librespot.UserAgent()},
"Range": []string{fmt.Sprintf("bytes=%d-%d", idx*DefaultChunkSize, (idx+1)*DefaultChunkSize-1)},
},
})
if err != nil {
return nil, err
}

if resp.StatusCode != http.StatusPartialContent {
_ = resp.Body.Close()
return nil, fmt.Errorf("invalid first chunk response status: %s", resp.Status)
}

return resp, nil
}, backoff.NewConstantBackOff(1*time.Second))
}

func (r *HttpChunkedReader) fetchChunk(idx int) ([]byte, error) {
Expand Down

0 comments on commit b2ec6d5

Please sign in to comment.