Skip to content

BillionMail gives you open-source MailServer, NewsLetter, Email Marketing — fully self-hosted, dev-friendly, and free from monthly fees. Join the discord: https://discord.gg/asfXzBUhZr

Refactor contact export logic to streamline file generation and improve error handling

lotke5ef1c6ff30c
diff --git a/core/api/contact/v1/contact.go b/core/api/contact/v1/contact.go
index 7c465e62..ea703eb5 100644
--- a/core/api/contact/v1/contact.go
+++ b/core/api/contact/v1/contact.go
@@ -120,9 +120,6 @@ type ExportContactsReq struct {
type ExportContactsRes struct {
api_v1.StandardRes
- Data struct {
- FileUrl string `json:"file_url" dc:"Download URL"`
- } `json:"data"`
}
type DeleteGroupReq struct {
diff --git a/core/internal/controller/contact/contact_v1_export_contacts.go b/core/internal/controller/contact/contact_v1_export_contacts.go
index fca63e53..5cd16693 100644
--- a/core/internal/controller/contact/contact_v1_export_contacts.go
+++ b/core/internal/controller/contact/contact_v1_export_contacts.go
@@ -15,11 +15,7 @@ import (
"fmt"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
- "github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gtime"
- "io"
- "os"
- "path/filepath"
"strings"
"time"
)
@@ -33,12 +29,11 @@ func (c *ControllerV1) ExportContacts(ctx context.Context, req *v1.ExportContact
req.IncludeInactive = true
}
- // Create temporary directory
- tempDir := filepath.Join(gfile.MainPkgPath(), "temp", "exports")
- if err = gfile.Mkdir(tempDir); err != nil {
- //fmt.Printf("Failed to create directory: %v, path: %s\n", err, tempDir)
+ // Get request object
+ r := g.RequestFromCtx(ctx)
+ if r == nil {
res.Code = 500
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create temp directory")))
+ res.SetError(gerror.New(public.LangCtx(ctx, "Unable to obtain the request context")))
return
}
@@ -74,35 +69,41 @@ func (c *ControllerV1) ExportContacts(ctx context.Context, req *v1.ExportContact
}
}
- // Generate filename
+ // Export file based on format
+ var content string
+ var fileName string
timestamp := gtime.Now().Format("YmdHis")
- fileName := fmt.Sprintf("contacts_export_%s.%s", timestamp, req.Format)
- filePath := filepath.Join(tempDir, fileName)
- fmt.Println("File path: ", filePath)
- // Export file based on format
- var fileContent []byte
- fileContent, err = exportContactFile1(allContacts, req.Format)
- if err != nil {
- fmt.Println("Export file error: ", err)
+ switch req.Format {
+ case "csv":
+ content, err = exportContactsToCSV(allContacts)
+ fileName = fmt.Sprintf("contacts_export_%s.csv", timestamp)
+ case "txt":
+ content, err = exportContactsToTXT(allContacts)
+ fileName = fmt.Sprintf("contacts_export_%s.txt", timestamp)
+ case "excel":
res.Code = 500
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to export contacts")))
+ res.SetError(gerror.New(public.LangCtx(ctx, "Excel format not implemented")))
+ return
+ default:
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "Unsupported format")))
return
}
- // Write file
- if err = gfile.PutBytes(filePath, fileContent); err != nil {
- fmt.Println("Write file error: ", err)
+ if err != nil {
res.Code = 500
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to save file")))
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to export contacts")))
return
}
- res.Data.FileUrl = filePath
+ // Set response headers for file download
+ r.Response.Header().Set("Content-Type", "application/octet-stream")
+ r.Response.Header().Set("Content-Disposition", "attachment; filename="+fileName)
+ r.Response.Write([]byte(content))
- } else { // Separate export
+ } else { // Separate export - ZIP file
var files []ExportFile
- totalContacts := 0
// Create file for each group
for _, groupId := range req.GroupIds {
@@ -128,54 +129,56 @@ func (c *ControllerV1) ExportContacts(ctx context.Context, req *v1.ExportContact
continue
}
- // Generate filename
- fileName := fmt.Sprintf("%s.%s", group.Name, req.Format)
- filePath := filepath.Join(tempDir, fileName)
-
- // Export file
- fileContent, err := exportContactFile1(filteredContacts, req.Format)
- if err != nil {
- continue
+ // Export file content
+ var content string
+ switch req.Format {
+ case "csv":
+ content, err = exportContactsToCSV(filteredContacts)
+ case "txt":
+ content, err = exportContactsToTXT(filteredContacts)
+ case "excel":
+ res.Code = 500
+ res.SetError(gerror.New(public.LangCtx(ctx, "Excel format not implemented")))
+ return nil, nil
+ default:
+ res.Code = 400
+ res.SetError(gerror.New(public.LangCtx(ctx, "Unsupported format")))
+ return nil, nil
}
- // Write file
- if err = gfile.PutBytes(filePath, fileContent); err != nil {
+ if err != nil {
continue
}
+ fileName := fmt.Sprintf("%s.%s", group.Name, req.Format)
files = append(files, ExportFile{
- Path: filePath,
Name: fileName,
+ Content: content,
Contacts: len(filteredContacts),
})
- totalContacts += len(filteredContacts)
}
if len(files) == 0 {
- // fmt.Println("No contacts found")
res.Code = 400
res.SetError(gerror.New(public.LangCtx(ctx, "No contacts to export")))
- return
+ return nil, nil
}
- // Create ZIP file
+ // Create ZIP file in memory
timestamp := gtime.Now().Format("YmdHis")
zipFileName := fmt.Sprintf("contacts_export_%s.zip", timestamp)
- zipPath := filepath.Join(tempDir, zipFileName)
- if err = createZipFile(files, zipPath); err != nil {
- fmt.Println("Create ZIP file error: ", err)
+ zipContent, err := createZipFileInMemory(files)
+ if err != nil {
res.Code = 500
res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create zip file")))
- return
+ return nil, nil
}
- // Clean up temporary files
- for _, file := range files {
- os.Remove(file.Path)
- }
-
- res.Data.FileUrl = zipPath
+ // Set response headers for ZIP file download
+ r.Response.Header().Set("Content-Type", "application/octet-stream")
+ r.Response.Header().Set("Content-Disposition", "attachment; filename="+zipFileName)
+ r.Response.Write(zipContent)
}
var groups []*entity.ContactGroup
@@ -192,142 +195,119 @@ func (c *ControllerV1) ExportContacts(ctx context.Context, req *v1.ExportContact
})
res.SetSuccess(public.LangCtx(ctx, "Contacts exported successfully"))
- return
+ return res, nil
}
// ExportFile Export file information
type ExportFile struct {
- Path string // File path
Name string // File name
+ Content string // File content
Contacts int // Contact count
}
-// createZipFile Create ZIP file
-func createZipFile(files []ExportFile, zipPath string) error {
- // Create zip file
- zipFile, err := os.Create(zipPath)
- if err != nil {
- return fmt.Errorf("failed to create zip file: %v", err)
- }
- defer zipFile.Close()
+// createZipFileInMemory creates a ZIP file in memory
+func createZipFileInMemory(files []ExportFile) ([]byte, error) {
+ var buf bytes.Buffer
+ zipWriter := zip.NewWriter(&buf)
- // Create zip writer
- zipWriter := zip.NewWriter(zipFile)
- defer zipWriter.Close()
-
- // Iterate through source files
for _, file := range files {
- // Open source file
- srcFile, err := os.Open(file.Path)
- if err != nil {
- return fmt.Errorf("failed to open source file %s: %v", file.Path, err)
- }
- defer srcFile.Close()
-
// Create zip entry
zipEntry, err := zipWriter.Create(file.Name)
if err != nil {
- return fmt.Errorf("failed to create zip entry for %s: %v", file.Name, err)
+ return nil, fmt.Errorf("failed to create zip entry for %s: %v", file.Name, err)
}
- // Copy file content to zip
- if _, err := io.Copy(zipEntry, srcFile); err != nil {
- return fmt.Errorf("failed to copy file content to zip for %s: %v", file.Name, err)
+ // Write file content to zip
+ _, err = zipEntry.Write([]byte(file.Content))
+ if err != nil {
+ return nil, fmt.Errorf("failed to write content to zip for %s: %v", file.Name, err)
}
}
- return nil
-}
-
-// exportContactFile1
-func exportContactFile1(contacts []*entity.Contact, format string) ([]byte, error) {
- var content []byte
- switch format {
- case "csv":
- // Create CSV writer
- var csvData [][]string
-
- // Add CSV headers
- headers := []string{
- "email", // Email address
- "attributes", // Attributes
- "active", // Active status
- "create_time", // Create time
- }
- csvData = append(csvData, headers)
+ err := zipWriter.Close()
+ if err != nil {
+ return nil, fmt.Errorf("failed to close zip writer: %v", err)
+ }
- // Add data rows
- for _, c := range contacts {
- if c.Attribs == nil {
- c.Attribs = make(map[string]string)
- }
- // Convert attributes to JSON string
- attribsJSON, err := json.Marshal(c.Attribs)
- if err != nil {
- attribsJSON = []byte("{}")
- }
+ return buf.Bytes(), nil
+}
- // Format time
- createdAt := ""
- if c.CreateTime != 0 {
- // Convert timestamp to time string
- t := time.Unix(int64(c.CreateTime), 0)
- createdAt = t.Format("2006-01-02 15:04:05")
- }
+// exportContactsToCSV exports contacts to CSV format
+func exportContactsToCSV(contacts []*entity.Contact) (string, error) {
+ var buf bytes.Buffer
+ writer := csv.NewWriter(&buf)
+
+ // Write CSV headers
+ headers := []string{
+ "email", // Email address
+ "attributes", // Attributes
+ "active", // Active status
+ "create_time", // Create time
+ }
+ if err := writer.Write(headers); err != nil {
+ return "", err
+ }
- row := []string{
- c.Email,
- string(attribsJSON),
- fmt.Sprintf("%d", c.Active),
- createdAt,
- }
- csvData = append(csvData, row)
+ // Write data rows
+ for _, c := range contacts {
+ if c.Attribs == nil {
+ c.Attribs = make(map[string]string)
}
-
- // Write CSV data
- buf := &bytes.Buffer{}
- writer := csv.NewWriter(buf)
- err := writer.WriteAll(csvData)
+ // Convert attributes to JSON string
+ attribsJSON, err := json.Marshal(c.Attribs)
if err != nil {
- return nil, err
+ attribsJSON = []byte("{}")
}
- content = buf.Bytes()
- case "txt":
- var lines []string
- for _, c := range contacts {
- // Convert attributes to JSON string
- attribsJSON, err := json.Marshal(c.Attribs)
- if err != nil {
- attribsJSON = []byte("{}")
- }
-
- // Format create time
- createdAt := ""
- if c.CreateTime != 0 {
- // Convert timestamp to time string
- t := time.Unix(int64(c.CreateTime), 0)
- createdAt = t.Format("2006-01-02 15:04:05")
- }
+ // Format time
+ createdAt := ""
+ if c.CreateTime != 0 {
+ // Convert timestamp to time string
+ t := time.Unix(int64(c.CreateTime), 0)
+ createdAt = t.Format("2006-01-02 15:04:05")
+ }
- // Format: email,attributes,active,created_at
- line := fmt.Sprintf("%s,%s,%d,%s",
- c.Email,
- string(attribsJSON),
- c.Active,
- createdAt,
- )
- lines = append(lines, line)
+ row := []string{
+ c.Email,
+ string(attribsJSON),
+ fmt.Sprintf("%d", c.Active),
+ createdAt,
+ }
+ if err := writer.Write(row); err != nil {
+ return "", err
}
- content = []byte(strings.Join(lines, "\n"))
+ }
- case "excel":
+ writer.Flush()
+ return buf.String(), nil
+}
+
+// exportContactsToTXT exports contacts to TXT format
+func exportContactsToTXT(contacts []*entity.Contact) (string, error) {
+ var lines []string
+ for _, c := range contacts {
+ // Convert attributes to JSON string
+ attribsJSON, err := json.Marshal(c.Attribs)
+ if err != nil {
+ attribsJSON = []byte("{}")
+ }
- return nil, fmt.Errorf("excel format not implemented")
+ // Format create time
+ createdAt := ""
+ if c.CreateTime != 0 {
+ // Convert timestamp to time string
+ t := time.Unix(int64(c.CreateTime), 0)
+ createdAt = t.Format("2006-01-02 15:04:05")
+ }
- default:
- return nil, fmt.Errorf("unsupported format: %s", format)
+ // Format: email,attributes,active,created_at
+ line := fmt.Sprintf("%s,%s,%d,%s",
+ c.Email,
+ string(attribsJSON),
+ c.Active,
+ createdAt,
+ )
+ lines = append(lines, line)
}
-
- return content, nil
+ return strings.Join(lines, "\n"), nil
}
diff --git a/core/internal/controller/tags/tags_v1_batch_tag_contacts.go b/core/internal/controller/tags/tags_v1_batch_tag_contacts.go
index a1e07786..257477f1 100644
--- a/core/internal/controller/tags/tags_v1_batch_tag_contacts.go
+++ b/core/internal/controller/tags/tags_v1_batch_tag_contacts.go
@@ -114,14 +114,11 @@ func (c *ControllerV1) BatchTagContacts(ctx context.Context, req *v1.BatchTagCon
})
successMsg := public.LangCtx(ctx, "Batch tag operation completed")
- if req.MarkInclude == 1 {
- successMsg = public.LangCtx(ctx, "Successfully added {} tags to contacts with {} tag assignments", len(req.TagIds), totalProcessedCount)
- } else {
- successMsg = public.LangCtx(ctx, "Successfully removed {} tags from contacts with {} tag removals", len(req.TagIds), totalProcessedCount)
- }
+ //successMsg := public.LangCtx(ctx, "Successfully added {} tags to contacts with {} tag assignments", len(req.TagIds), totalProcessedCount)
if totalSkippedCount > 0 {
successMsg += public.LangCtx(ctx, " ( {} skipped, {} errors)", totalSkippedCount, totalErrorCount)
+ successMsg += public.LangCtx(ctx, " ( {} skipped, {} errors)", totalSkippedCount, totalErrorCount)
}
res.SetSuccess(successMsg)