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-01-25 12:52:09 +01:00
|
|
|
func handleError(err error) {
|
|
|
|
fmt.Println(err.Error())
|
2023-12-19 13:56:03 +01:00
|
|
|
os.Exit(0)
|
|
|
|
}
|
|
|
|
|
|
|
|
func DownloadFile(path, url string) {
|
2024-01-25 12:52:09 +01:00
|
|
|
resp, err := req.Head(url, nil)
|
2023-12-19 13:56:03 +01:00
|
|
|
if err != nil {
|
|
|
|
if strings.Contains(err.Error(), "no such host") {
|
|
|
|
handleError(errors.New("invalid url"))
|
|
|
|
} else if strings.Contains(err.Error(), "certificate signed by unknown authority") {
|
2024-01-25 12:52:09 +01:00
|
|
|
handleError(errors.New("certificate from unknown authority"))
|
2023-12-19 13:56:03 +01:00
|
|
|
}
|
|
|
|
handleError(err)
|
|
|
|
}
|
2024-01-25 12:52:09 +01:00
|
|
|
defer resp.Close()
|
|
|
|
if resp.StatusCode == 404 {
|
2023-12-19 13:56:03 +01:00
|
|
|
handleError(errors.New("invalid url"))
|
2024-01-25 12:52:09 +01:00
|
|
|
} else if resp.StatusCode == 401 {
|
|
|
|
handleError(errors.New("restricted access (credentials required)"))
|
|
|
|
} else if resp.StatusCode != 200 {
|
|
|
|
handleError(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-01-25 12:52:09 +01:00
|
|
|
resp, err = req.Get(url, nil)
|
2023-12-19 13:56:03 +01:00
|
|
|
if err != nil {
|
|
|
|
handleError(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
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-01-25 12:52:09 +01:00
|
|
|
destFile, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644)
|
|
|
|
if err != nil {
|
|
|
|
handleError(err)
|
|
|
|
}
|
|
|
|
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 {
|
|
|
|
handleError(err)
|
|
|
|
}
|
2023-12-19 13:56:03 +01:00
|
|
|
|
2024-01-25 12:52:09 +01:00
|
|
|
fmt.Println("Saved file to", path)
|
2023-12-19 13:56:03 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func FileExists(path string) bool {
|
|
|
|
_, err := os.Stat(path)
|
|
|
|
return !errors.Is(err, os.ErrNotExist)
|
|
|
|
}
|