-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_playlist_thumbnail.go
executable file
·67 lines (64 loc) · 1.2 KB
/
get_playlist_thumbnail.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package api
import (
"context"
"fmt"
"io"
"net/http"
"time"
"github.com/pkg/errors"
"github.com/thavlik/t4vd/base/pkg/base"
)
func GetPlaylistThumbnail(
ctx context.Context,
opts base.ServiceOptions,
playlistID string,
w io.Writer,
) error {
url := fmt.Sprintf("%s/playlist/thumbnail?list=%s",
opts.Endpoint,
playlistID,
)
if w == nil {
// we only want to cache the video
url += "&nodownload=1"
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req = req.WithContext(ctx)
if opts.HasBasicAuth() {
req.SetBasicAuth(
opts.BasicAuth.Username,
opts.BasicAuth.Password,
)
}
var timeout time.Duration
if opts.HasTimeout() {
timeout = opts.Timeout
} else {
timeout = defaultTimeout
}
resp, err := (&http.Client{
Timeout: timeout,
}).Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return ErrNotCached
} else if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("status code %v: %s",
resp.StatusCode,
string(body),
)
}
if w != nil {
if _, err := io.Copy(w, resp.Body); err != nil {
return errors.Wrap(err, "copy")
}
}
return nil
}