package main
import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"strings"
"github.com/yeka/zip"
)
type (
IZipWriter interface {
WriteFile(fileName, password, content string) error
RemoveFile(fileName string) error
}
zipWriter struct{}
)
func NewZip() IZipWriter {
return &zipWriter{}
}
func (h *zipWriter) WriteFile(fileName, password, content string) error {
dir := path.Join(os.Getenv("STORAGE_DIR"))
filedir := fmt.Sprintf("%s/%s", dir, fileName)
if !path.IsAbs(dir) {
return errors.New("Path must be absolute value")
}
if err := os.WriteFile(filedir+".txt", []byte{}, 644); err != nil {
return err
}
file, err := os.Create(filedir + ".zip")
if err != nil {
return err
}
zipw := zip.NewWriter(file)
zw, err := zipw.Encrypt(fileName+".txt", password, zip.AES256Encryption)
if err != nil {
return err
}
if _, err = io.Copy(zw, bytes.NewReader([]byte(content))); err != nil {
return err
}
defer func() {
zipw.Close()
zipw.Flush()
}()
return nil
}
func (h *zipWriter) RemoveFile(fileName string) error {
dir := path.Join(os.Getenv("STORAGE_DIR"))
files, err := os.ReadDir(dir)
if err != nil {
return err
}
if len(files) > 0 {
for _, file := range files {
fn := file.Name()
if _, err := fs.Stat(os.DirFS(dir), fn); err != nil {
return err
}
if strings.Contains(fn, fileName) {
if err := os.Remove(fmt.Sprintf("%s/%s", dir, fn)); err != nil {
return err
}
} else {
return errors.New("File name is not exists")
}
}
}
return nil
}