goPural/fileActions.go

87 lines
1.8 KiB
Go

package pural
import (
"archive/zip"
"bytes"
"io"
"io/ioutil"
"net/http"
"os"
"time"
bnn "gitea.statsd.de/dom/goBnn"
)
func downloadFile(filepath string, resp *http.Response) error {
// Create the file
file, err := os.Create(filepath)
if err != nil {
return err
}
defer file.Close()
// Write the body to file
_, err = io.Copy(file, resp.Body)
if err != nil {
return err
}
return nil
}
// DownloadBnnlists - Download both price lists. The lists are public so we do not necessarily login before downloading.
func DownloadPublicBnnlists() error {
client := &http.Client{}
// https://www.pural.de/handler-bereich
// Download PLStk .BNN
r, err := client.Get("https://www.pural.de/wp-content/uploads/2021/02/PL-Stk-Mae-2021.bnn_.zip")
if err != nil {
return err
}
downloadFile(("PL-Stk-" + time.Now().Format("20060102150405") + ".BNN.zip"), r)
// Download PL-Krt .BNN
r, err = client.Get("https://www.pural.de/wp-content/uploads/2021/02/PL-Krt-Mae-2021.bnn_.zip")
if err != nil {
return err
}
downloadFile(("PL-Krt" + time.Now().Format("20060102150405") + ".BNN.zip"), r)
return nil
}
// RetrievePublicBnnlistStk - Downloads list PL and converts bnn list into an array
func RetrievePublicBnnlistStk() (bnn.Bnn, error) {
// Download bnn
resp, err := http.Get("https://www.pural.de/wp-content/uploads/2021/02/PL-Stk-Mae-2021.bnn_.zip")
if err != nil {
return bnn.Bnn{}, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return bnn.Bnn{}, err
}
zipReader, err := zip.NewReader(bytes.NewReader(body), int64(len(body)))
if err != nil {
return bnn.Bnn{}, err
}
fileReader, err := zipReader.File[0].Open()
if err != nil {
return bnn.Bnn{}, err
}
defer fileReader.Close()
b, err := bnn.ReadBnn(fileReader)
if err != nil {
return bnn.Bnn{}, err
}
return b, nil
}