moved download func over to client

This commit is contained in:
Dan Anglin 2024-06-20 11:03:05 +01:00
parent cf3b08e726
commit 96cf748874
Signed by: dananglin
GPG key ID: 0C1D44CFBEE68638
3 changed files with 37 additions and 36 deletions

View file

@ -11,6 +11,7 @@ import (
"io"
"net/http"
"net/url"
"os"
"time"
"codeflow.dananglin.me.uk/apollo/enbas/internal"
@ -60,7 +61,40 @@ func (g *Client) AuthCodeURL() string {
)
}
func (g *Client) DownloadFile(url, path string) error {
func (g *Client) DownloadMedia(url, path string) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("unable to create the HTTP request: %w", err)
}
request.Header.Set("User-Agent", g.UserAgent)
response, err := g.HTTPClient.Do(request)
if err != nil {
return fmt.Errorf("received an error after attempting the download: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return fmt.Errorf(
"did not receive an OK response from the GoToSocial server: got %d",
response.StatusCode,
)
}
file, err := os.Create(path)
if err != nil {
return fmt.Errorf("unable to create %s: %w", path, err)
}
defer file.Close()
if _, err = io.Copy(file, response.Body); err != nil {
return fmt.Errorf("unable to save the download to %s: %w", path, err)
}
return nil
}
@ -70,7 +104,7 @@ func (g *Client) sendRequest(method string, url string, requestBody io.Reader, o
request, err := http.NewRequestWithContext(ctx, method, url, requestBody)
if err != nil {
return fmt.Errorf("unable to create the HTTP request, %w", err)
return fmt.Errorf("unable to create the HTTP request: %w", err)
}
request.Header.Set("Content-Type", "application/json; charset=utf-8")

View file

@ -499,7 +499,7 @@ func (s *ShowExecutor) showMediaFromStatus(gtsClient *client.Client) error {
}
if !fileExists {
if err := utilities.DownloadFile(mediaURL, mediaFilePath); err != nil {
if err := gtsClient.DownloadMedia(mediaURL, mediaFilePath); err != nil {
return fmt.Errorf("unable to download the media attachment: %w", err)
}
}

View file

@ -7,10 +7,7 @@ package utilities
import (
"errors"
"fmt"
"io"
"net/http"
"os"
"time"
)
func ReadFile(path string) (string, error) {
@ -33,33 +30,3 @@ func FileExists(path string) (bool, error) {
return true, nil
}
// TODO: move to client package
func DownloadFile(url, path string) error {
client := http.Client{
CheckRedirect: func(r *http.Request, _ []*http.Request) error {
r.URL.Opaque = r.URL.Path
return nil
},
Timeout: time.Second * 30,
}
resp, err := client.Get(url)
if err != nil {
return fmt.Errorf("unable to download the file: %w", err)
}
defer resp.Body.Close()
file, err := os.Create(path)
if err != nil {
return fmt.Errorf("unable to create %s: %w", path, err)
}
defer file.Close()
if _, err = io.Copy(file, resp.Body); err != nil {
return fmt.Errorf("unable to save the download to %s: %w", path, err)
}
return nil
}