country-geo-locations/internal/downloader/downloader.go

88 lines
1.7 KiB
Go
Raw Permalink Normal View History

2023-12-19 13:56:03 +01:00
package downloader
import (
"errors"
"io"
2024-11-26 13:35:54 +01:00
"net/http"
2023-12-19 13:56:03 +01:00
"os"
"strings"
req "github.com/levigross/grequests"
2024-01-25 12:52:09 +01:00
"github.com/schollz/progressbar/v3"
2023-12-19 13:56:03 +01:00
)
2024-11-26 13:35:54 +01:00
var (
ErrAccessDenied = errors.New("restricted access (credentials required)")
ErrInvalidURL = errors.New("invalid url")
ErrUnknownAuthority = errors.New("certificate from unknown authority")
)
2024-03-02 10:55:27 +01:00
type Context struct {
Filename string
Link string
2023-12-19 13:56:03 +01:00
}
2024-03-02 10:55:27 +01:00
func NewContext(filename, link string) *Context {
return &Context{
Filename: filename,
Link: link,
}
}
func (c *Context) Download() error {
resp, err := req.Head(c.Link, nil)
2023-12-19 13:56:03 +01:00
if err != nil {
if strings.Contains(err.Error(), "no such host") {
2024-11-26 13:35:54 +01:00
return ErrInvalidURL
2023-12-19 13:56:03 +01:00
}
2024-03-02 10:55:27 +01:00
if strings.Contains(err.Error(), "certificate signed by unknown authority") {
2024-11-26 13:35:54 +01:00
return ErrUnknownAuthority
2024-03-02 10:55:27 +01:00
}
return err
2023-12-19 13:56:03 +01:00
}
2024-01-25 12:52:09 +01:00
defer resp.Close()
2024-11-26 13:35:54 +01:00
if resp.StatusCode == http.StatusNotFound {
return ErrInvalidURL
2024-03-02 10:55:27 +01:00
}
2024-11-26 13:35:54 +01:00
if resp.StatusCode == http.StatusUnauthorized {
return ErrAccessDenied
2024-03-02 10:55:27 +01:00
}
2024-11-26 13:35:54 +01:00
if resp.StatusCode != http.StatusOK {
return errors.New(resp.RawResponse.Status)
2023-12-19 13:56:03 +01:00
}
2024-01-25 12:52:09 +01:00
resp.Close()
2023-12-19 13:56:03 +01:00
2024-03-02 10:55:27 +01:00
resp, err = req.Get(c.Link, nil)
2023-12-19 13:56:03 +01:00
if err != nil {
2024-03-02 10:55:27 +01:00
return err
2023-12-19 13:56:03 +01:00
}
var filesize int64
2024-01-25 12:52:09 +01:00
if resp.RawResponse.ContentLength > -1 {
2023-12-19 13:56:03 +01:00
filesize = resp.RawResponse.ContentLength
}
2024-03-02 10:55:27 +01:00
destFile, err := os.OpenFile(c.Filename, os.O_CREATE|os.O_WRONLY, 0644)
2024-01-25 12:52:09 +01:00
if err != nil {
2024-03-02 10:55:27 +01:00
return err
2024-01-25 12:52:09 +01:00
}
defer destFile.Close()
2023-12-19 13:56:03 +01:00
2024-01-25 12:52:09 +01:00
bar := progressbar.DefaultBytes(
filesize,
"downloading",
)
2023-12-19 13:56:03 +01:00
2024-01-25 12:52:09 +01:00
_, err = io.Copy(io.MultiWriter(destFile, bar), resp.RawResponse.Body)
if err != nil {
2024-03-02 10:55:27 +01:00
return err
2024-01-25 12:52:09 +01:00
}
2023-12-19 13:56:03 +01:00
2024-03-02 10:55:27 +01:00
return nil
2023-12-19 13:56:03 +01:00
}
2024-03-02 10:55:27 +01:00
func (c *Context) FileExists() bool {
_, err := os.Stat(c.Filename)
2023-12-19 13:56:03 +01:00
return !errors.Is(err, os.ErrNotExist)
}