diff --git a/fileActions.go b/fileActions.go new file mode 100644 index 0000000..5612ba9 --- /dev/null +++ b/fileActions.go @@ -0,0 +1,86 @@ +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 +} diff --git a/fileActions_test.go b/fileActions_test.go new file mode 100644 index 0000000..5a065b7 --- /dev/null +++ b/fileActions_test.go @@ -0,0 +1,23 @@ +package pural + +import ( + "testing" +) + +func TestDownloadPublicBnnFile(t *testing.T) { + err := DownloadPublicBnnlists() + if err != nil { + t.Errorf("%s", err) + } + + //t.Logf("%v", f) +} + +func TestRetrievePublicBnnlistStk(t *testing.T) { + f, err := RetrievePublicBnnlistStk() + if err != nil { + t.Errorf("%s", err) + } + + t.Logf("%v", f) +}