add csv zip file import apier method

This commit is contained in:
Radu Ioan Fericean
2014-08-30 17:06:13 +03:00
parent 97d2277642
commit 153ca2c2fd
2 changed files with 90 additions and 0 deletions

View File

@@ -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
}

View File

@@ -19,6 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>
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
}