diff --git a/apier/tp.go b/apier/tp.go index d3d62599e..5e08a1ef3 100644 --- a/apier/tp.go +++ b/apier/tp.go @@ -23,6 +23,12 @@ package apier import ( "errors" "fmt" + "io/ioutil" + "log" + "os" + "path/filepath" + + "github.com/cgrates/cgrates/engine" "github.com/cgrates/cgrates/utils" ) @@ -40,3 +46,48 @@ func (self *ApierV1) GetTPIds(attrs AttrGetTPIds, reply *[]string) error { } return nil } + +type AttrImportTPZipFile struct { + TPid string + File []byte +} + +func (self *ApierV1) ImportTPZipFile(attrs AttrImportTPZipFile, reply *string) error { + tmpDir, err := ioutil.TempDir("/tmp", "cgr_") + if err != nil { + *reply = "ERROR: creating temp directory!" + return err + } + zipFile := filepath.Join(tmpDir, "/file.zip") + if err = ioutil.WriteFile(zipFile, attrs.File, os.ModePerm); err != nil { + *reply = "ERROR: writing zip file!" + return err + } + if err = utils.Unzip(zipFile, tmpDir); err != nil { + *reply = "ERROR: unziping file!" + return err + } + if err = filepath.Walk(tmpDir, func(path string, info os.FileInfo, err error) error { + if !info.IsDir() { + return nil + } + csvFiles, err := filepath.Glob(filepath.Join(path, "*csv")) + if csvFiles != nil { + if attrs.TPid == "" { + *reply = "ERROR: missing TPid!" + return err + } + csvImporter := engine.TPCSVImporter{attrs.TPid, self.StorDb, path, ',', false, ""} + if errImport := csvImporter.Run(); errImport != nil { + log.Fatal(errImport) + } + } + return err + }); err != nil { + *reply = "ERROR: finding csv files!" + return err + } + os.RemoveAll(tmpDir) + *reply = "OK" + return nil +} diff --git a/utils/coreutils.go b/utils/coreutils.go index 4b089cd32..65a90e673 100644 --- a/utils/coreutils.go +++ b/utils/coreutils.go @@ -19,6 +19,7 @@ along with this program. If not, see package utils import ( + "archive/zip" "bytes" "crypto/rand" "crypto/sha1" @@ -27,9 +28,12 @@ import ( "encoding/json" "errors" "fmt" + "io" "io/ioutil" "math" "net/http" + "os" + "path/filepath" "regexp" "strconv" "strings" @@ -281,3 +285,38 @@ func HttpJsonPost(url string, skipTlsVerify bool, content interface{}) ([]byte, } return respBody, nil } + +func Unzip(src, dest string) error { + r, err := zip.OpenReader(src) + if err != nil { + return err + } + defer r.Close() + + for _, f := range r.File { + rc, err := f.Open() + if err != nil { + return err + } + defer rc.Close() + + path := filepath.Join(dest, f.Name) + if f.FileInfo().IsDir() { + os.MkdirAll(path, f.Mode()) + } else { + f, err := os.OpenFile( + path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) + if err != nil { + return err + } + defer f.Close() + + _, err = io.Copy(f, rc) + if err != nil { + return err + } + } + } + + return nil +}