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

82 lines
1.5 KiB
Go
Raw Normal View History

2023-12-19 13:56:03 +01:00
package downloader
import (
"errors"
"fmt"
"io"
"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-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-03-02 10:55:27 +01:00
return fmt.Errorf("invalid url")
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") {
return fmt.Errorf("certificate from unknown authority")
}
return err
2023-12-19 13:56:03 +01:00
}
2024-01-25 12:52:09 +01:00
defer resp.Close()
if resp.StatusCode == 404 {
2024-03-02 10:55:27 +01:00
return fmt.Errorf("invalid url")
}
if resp.StatusCode == 401 {
return fmt.Errorf("restricted access (credentials required)")
}
if resp.StatusCode != 200 {
return fmt.Errorf(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)
}