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

Added maillog overview apis. Fixed some bugs.

Jack4a9f13826d3f
diff --git a/core/api/mail_boxes/v1/mailboxes.go b/core/api/mail_boxes/v1/mailboxes.go
index 3150cf2d..0460ce1b 100644
--- a/core/api/mail_boxes/v1/mailboxes.go
+++ b/core/api/mail_boxes/v1/mailboxes.go
@@ -25,11 +25,11 @@ type AddMailboxReq struct {
g.Meta `path:"/mailbox/create" tags:"MailBox" method:"post" summary:"Create mailbox" in:"body"`
Authorization string `json:"authorization" dc:"Authorization" in:"header"`
Domain string `json:"domain" v:"required|domain" dc:"Domain"`
- Username string `json:"username" v:"required|min-length:1" dc:"Username"`
- Password string `json:"password" v:"required|min-length:1" dc:"Password"`
- Status int `json:"status" v:"required" dc:"Status" d:"1"`
+ FullName string `json:"full_name" v:"required|passport" dc:"username"`
+ Password string `json:"password" v:"required|password" dc:"Password"`
+ Active int `json:"active" v:"required" dc:"Status" d:"1"`
IsAdmin int `json:"isAdmin" v:"required" dc:"IsAdmin" d:"0"`
- Quota int `json:"quota" v:"required" dc:"Quota" d:"5242880"`
+ Quota int `json:"quota" v:"required|min:1" dc:"Quota" d:"5242880"`
}
type AddMailboxRes struct {
@@ -39,13 +39,12 @@ type AddMailboxRes struct {
type UpdateMailboxReq struct {
g.Meta `path:"/mailbox/update" tags:"MailBox" method:"post" summary:"Update mailbox" in:"body"`
Authorization string `json:"authorization" dc:"Authorization" in:"header"`
- Email string `json:"email" v:"required|email" dc:"Email"`
- Domain string `json:"domain" v:"required" dc:"Domain"`
- Username string `json:"username" v:"required" dc:"Username"`
- Password string `json:"password" v:"required" dc:"Password"`
+ Domain string `json:"domain" v:"required|domain" dc:"Domain"`
+ FullName string `json:"full_name" v:"required|passport" dc:"username"`
+ Password string `json:"password" v:"password" dc:"Password"`
Active int `json:"active" v:"required" dc:"Status" d:"1"`
IsAdmin int `json:"isAdmin" v:"required" dc:"IsAdmin" d:"0"`
- Quota int `json:"quota" v:"required" dc:"Quota" d:"5242880"`
+ Quota int `json:"quota" v:"required|min:1" dc:"Quota" d:"5242880"`
}
type UpdateMailboxRes struct {
@@ -67,8 +66,8 @@ type GetMailboxReq struct {
Authorization string `json:"authorization" dc:"Authorization" in:"header"`
Keyword string `json:"keyword" dc:"Keyword"`
Domain string `json:"domain" v:"required|domain" dc:"Domain"`
- Page int `json:"page" dc:"Page" d:"1"`
- PageSize int `json:"page_size" dc:"Page size" d:"20"`
+ Page int `json:"page" v:"min:1" dc:"Page" d:"1"`
+ PageSize int `json:"page_size" v:"min:1" dc:"Page size" d:"20"`
}
type GetMailboxRes struct {
diff --git a/core/api/overview/v1/overview.go b/core/api/overview/v1/overview.go
index a382b7d2..5c811ef3 100644
--- a/core/api/overview/v1/overview.go
+++ b/core/api/overview/v1/overview.go
@@ -7,10 +7,10 @@ import (
type OverviewReq struct {
g.Meta `path:"/overview" tags:"Overview" method:"get" summary:"Get overview information" in:"query"`
- Authorization string `json:"authorization" dc:"Authorization" in:"header"`
- Domains []string `v:"required" dc:"Domains" dc:"Domains"`
- StartTime int `v:"required" dc:"StartTime" dc:"StartTime"`
- EndTime int `v:"required" dc:"EndTime" dc:"EndTime"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ Domain string `v:"required|domain" dc:"Domains" dc:"Domain"`
+ StartTime int `v:"required" dc:"StartTime" dc:"StartTime"`
+ EndTime int `v:"required" dc:"EndTime" dc:"EndTime"`
}
type OverviewRes struct {
diff --git a/core/go.mod b/core/go.mod
index ff2f6535..530ac2f4 100644
--- a/core/go.mod
+++ b/core/go.mod
@@ -5,6 +5,7 @@ go 1.22.0
toolchain go1.23.2
require (
+ github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5
github.com/docker/docker v28.0.2+incompatible
github.com/g0rbe/go-chattr v1.0.1
github.com/go-acme/lego/v4 v4.22.2
diff --git a/core/go.sum b/core/go.sum
index 57f2ceea..41121da0 100644
--- a/core/go.sum
+++ b/core/go.sum
@@ -28,6 +28,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0=
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
+github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5 h1:IEjq88XO4PuBDcvmjQJcQGg+w+UaafSy8G5Kcb5tBhI=
+github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5/go.mod h1:exZ0C/1emQJAw5tHOaUDyY1ycttqBAPcxuzf7QbY6ec=
github.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo=
github.com/Microsoft/go-winio v0.4.14 h1:+hMXMk01us9KgxGb7ftKQt2Xpf5hH/yky+TDA+qxleU=
github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA=
diff --git a/core/internal/controller/domains/domains_v1_apply_cert.go b/core/internal/controller/domains/domains_v1_apply_cert.go
index ff23a1b8..186d8c90 100644
--- a/core/internal/controller/domains/domains_v1_apply_cert.go
+++ b/core/internal/controller/domains/domains_v1_apply_cert.go
@@ -19,7 +19,7 @@ func (c *ControllerV1) ApplyCert(ctx context.Context, req *v1.ApplyCertReq) (res
}
// Apply for the certificate
- err = domains.ApplyLetsEncryptCertWithHttp(ctx, req.Domain, acc.Email)
+ err = domains.ApplyLetsEncryptCertWithHttp(ctx, req.Domain, acc)
if err != nil {
res.SetError(err)
diff --git a/core/internal/controller/mail_boxes/mail_boxes_v1_add_mailbox.go b/core/internal/controller/mail_boxes/mail_boxes_v1_add_mailbox.go
index 876d1075..8b248ae4 100644
--- a/core/internal/controller/mail_boxes/mail_boxes_v1_add_mailbox.go
+++ b/core/internal/controller/mail_boxes/mail_boxes_v1_add_mailbox.go
@@ -11,13 +11,14 @@ func (c *ControllerV1) AddMailbox(ctx context.Context, req *v1.AddMailboxReq) (r
res = &v1.AddMailboxRes{}
mailbox := &v1.Mailbox{
- Username: req.Username + "@" + req.Domain,
+ Username: req.FullName + "@" + req.Domain,
Password: req.Password,
- FullName: req.Username,
+ FullName: req.FullName,
IsAdmin: req.IsAdmin,
Quota: int64(req.Quota),
- LocalPart: req.Username,
+ LocalPart: req.FullName,
Domain: req.Domain,
+ Active: req.Active,
}
if err = mail_boxes.Add(ctx, mailbox); err != nil {
diff --git a/core/internal/controller/mail_boxes/mail_boxes_v1_get_mailbox.go b/core/internal/controller/mail_boxes/mail_boxes_v1_get_mailbox.go
index c3d808ea..ca8f505d 100644
--- a/core/internal/controller/mail_boxes/mail_boxes_v1_get_mailbox.go
+++ b/core/internal/controller/mail_boxes/mail_boxes_v1_get_mailbox.go
@@ -40,5 +40,7 @@ func (c *ControllerV1) GetMailbox(ctx context.Context, req *v1.GetMailboxReq) (r
res.Data.Total = total
res.Data.List = mailboxList
+ res.SetSuccess("Success")
+
return
}
diff --git a/core/internal/controller/mail_boxes/mail_boxes_v1_update_mailbox.go b/core/internal/controller/mail_boxes/mail_boxes_v1_update_mailbox.go
index 59a77015..609e8a1c 100644
--- a/core/internal/controller/mail_boxes/mail_boxes_v1_update_mailbox.go
+++ b/core/internal/controller/mail_boxes/mail_boxes_v1_update_mailbox.go
@@ -1,35 +1,22 @@
package mail_boxes
import (
- "context"
- "strings"
-
- "github.com/gogf/gf/v2/errors/gerror"
-
"billionmail-core/api/mail_boxes/v1"
"billionmail-core/internal/service/mail_boxes"
+ "context"
)
func (c *ControllerV1) UpdateMailbox(ctx context.Context, req *v1.UpdateMailboxReq) (res *v1.UpdateMailboxRes, err error) {
res = &v1.UpdateMailboxRes{}
- if req.Email == "" {
- return nil, gerror.New("Email address cannot be empty")
- }
-
- parts := strings.Split(req.Email, "@")
- if len(parts) != 2 {
- return nil, gerror.New("Invalid email format")
- }
-
mailbox := &v1.Mailbox{
- Username: req.Email,
+ Username: req.FullName + "@" + req.Domain,
Password: req.Password, // If empty, password won't be updated
- FullName: req.Username,
+ FullName: req.FullName,
IsAdmin: req.IsAdmin,
Quota: int64(req.Quota),
- LocalPart: parts[0],
- Domain: parts[1],
+ LocalPart: req.FullName,
+ Domain: req.Domain,
Active: req.Active,
}
diff --git a/core/internal/model/rbac.go b/core/internal/model/rbac.go
index 3a75acb6..f28b28e5 100644
--- a/core/internal/model/rbac.go
+++ b/core/internal/model/rbac.go
@@ -6,7 +6,7 @@ import (
// Account defines the account model
type Account struct {
- Id int64 `json:"id"` // ID
+ Id int64 `json:"account_id"` // ID
Username string `json:"username"` // Username
Email string `json:"email"` // Email
Password string `json:"-"` // Password (hidden in JSON output)
@@ -18,7 +18,7 @@ type Account struct {
// Role defines the role model
type Role struct {
- Id int64 `json:"id"` // ID
+ Id int64 `json:"role_id"` // ID
Name string `json:"name"` // Role name
Description string `json:"description"` // Description
Status int `json:"status"` // Status 0:disabled 1:enabled
diff --git a/core/internal/service/domains/ssl.go b/core/internal/service/domains/ssl.go
index 6439df77..cd465ba4 100644
--- a/core/internal/service/domains/ssl.go
+++ b/core/internal/service/domains/ssl.go
@@ -1,20 +1,65 @@
package domains
import (
+ "billionmail-core/internal/model"
+ "billionmail-core/internal/service/acme"
+ "billionmail-core/internal/service/public"
"context"
- "github.com/gogf/gf/v2/errors/gerror"
+ "encoding/json"
+ "github.com/gogf/gf/v2/frame/g"
)
// ApplyLetsEncryptCertWithHttp applies for a Let's Encrypt certificate for the given domain.
-func ApplyLetsEncryptCertWithHttp(ctx context.Context, domain string, email string) error {
- return gerror.New("Not implemented")
-
- //crt, key, err := acme.ApplySSLWithExistingServer(ctx, []string{domain}, email, "http", "", nil, public.AbsPath("../ssl"))
- //
- //if err != nil {
- // return err
- //}
- //
- //// Save the certificate and key to the database
- //g.DB().Model("letsencrypts").Insert()
+func ApplyLetsEncryptCertWithHttp(ctx context.Context, domain string, accountInfo *model.Account) error {
+ certificate, privateKey, err := acme.ApplySSLWithExistingServer(ctx, []string{domain}, accountInfo.Email, "http", "", nil, public.AbsPath("../ssl"))
+
+ if err != nil {
+ return err
+ }
+
+ dnsNames := "[]"
+ notAfter := "0000-00-00"
+ notBefore := "0000-00-00"
+ endTime := 0
+ status := -1
+ subject := ""
+
+ if certificate != "" {
+ certInfo := acme.GetCertInfo(certificate)
+ notAfter = certInfo.NotAfter
+ notBefore = certInfo.NotBefore
+ subject = certInfo.Subject
+ endTime = certInfo.Endtime
+ dnsNamesBytes, err := json.Marshal([]string{domain})
+ if err == nil {
+ dnsNames = string(dnsNamesBytes)
+ }
+ status = 1
+ }
+
+ // 获取申请进度日志
+ progress := acme.GetAcmeLogBody(ctx)
+ pdata := g.Map{
+ "certificate": certificate,
+ "private_key": privateKey,
+ "error_info": "",
+ "progress": progress,
+ "status": status,
+ "not_after": notAfter,
+ "not_before": notBefore,
+ "dns": dnsNames,
+ "endtime": endTime,
+ "subject": subject,
+ }
+
+ // Save the certificate and key to the database
+ _, err = g.DB().Model("letsencrypts").Insert(pdata)
+
+ if err != nil {
+ return err
+ }
+
+ // TODO: Apply the certificate to the service, postfix, dovecot, etc.
+
+ return nil
}
diff --git a/core/internal/service/mail_boxes/mail_boxes.go b/core/internal/service/mail_boxes/mail_boxes.go
index 62f58851..1acc588f 100644
--- a/core/internal/service/mail_boxes/mail_boxes.go
+++ b/core/internal/service/mail_boxes/mail_boxes.go
@@ -3,16 +3,26 @@ package mail_boxes
import (
v1 "billionmail-core/api/mail_boxes/v1"
"context"
- "crypto/md5"
+ "encoding/base64"
+ "encoding/hex"
"fmt"
"time"
+ "github.com/GehirnInc/crypt/md5_crypt"
"github.com/gogf/gf/v2/frame/g"
)
-func Add(ctx context.Context, mailbox *v1.Mailbox) error {
- // 加密密码
- mailbox.PasswordEncode = fmt.Sprintf("%x", md5.Sum([]byte(mailbox.Password)))
+func Add(ctx context.Context, mailbox *v1.Mailbox) (err error) {
+ // Encode password
+ mailbox.PasswordEncode = PasswdEncode(ctx, mailbox.Password)
+
+ // Crypt password
+ mailbox.Password, err = PasswdMD5Crypt(ctx, mailbox.Password)
+
+ if err != nil {
+ err = fmt.Errorf("Generate password md5-crypt failed: %w", err)
+ return
+ }
now := time.Now().Unix()
mailbox.CreateTime = now
@@ -20,17 +30,24 @@ func Add(ctx context.Context, mailbox *v1.Mailbox) error {
mailbox.Active = 1
mailbox.Maildir = fmt.Sprintf("%s@%s/", mailbox.LocalPart, mailbox.Domain)
- _, err := g.DB().Model("mailbox").Ctx(ctx).Insert(mailbox)
+ _, err = g.DB().Model("mailbox").Ctx(ctx).Insert(mailbox)
return err
}
-func Update(ctx context.Context, mailbox *v1.Mailbox) error {
+func Update(ctx context.Context, mailbox *v1.Mailbox) (err error) {
mailbox.UpdateTime = time.Now().Unix()
if mailbox.Password != "" {
- mailbox.PasswordEncode = fmt.Sprintf("%x", md5.Sum([]byte(mailbox.Password)))
+ mailbox.Password, err = PasswdMD5Crypt(ctx, mailbox.Password)
+
+ if err != nil {
+ err = fmt.Errorf("Generate password md5-crypt failed: %w", err)
+ return
+ }
+
+ mailbox.PasswordEncode = PasswdEncode(ctx, mailbox.Password)
}
- _, err := g.DB().Model("mailbox").
+ _, err = g.DB().Model("mailbox").
Ctx(ctx).
Where("username", mailbox.Username).
Update(mailbox)
@@ -62,3 +79,34 @@ func Get(ctx context.Context, domain, keyword string, page, pageSize int) ([]v1.
return mailboxes, count, err
}
+
+func PasswdEncode(ctx context.Context, password string) string {
+ return hex.EncodeToString([]byte(base64.StdEncoding.EncodeToString([]byte(password))))
+}
+
+func PasswdDecode(ctx context.Context, password string) (string, error) {
+ decoded, err := hex.DecodeString(password)
+ if err != nil {
+ return "", err
+ }
+ decodedStr, err := base64.StdEncoding.DecodeString(string(decoded))
+ if err != nil {
+ return "", err
+ }
+ return string(decodedStr), nil
+}
+
+func PasswdMD5Crypt(ctx context.Context, password string) (string, error) {
+ // use md5_crypt package to generate MD5-CRYPT hash
+ crypter := md5_crypt.New()
+
+ // Generate generates a hash using the given password and salt.
+ // The salt is optional and can be empty.
+ // If the salt is empty, a random salt will be generated.
+ result, err := crypter.Generate([]byte(password), []byte(""))
+ if err != nil {
+ return "", err
+ }
+
+ return result, nil
+}
diff --git a/core/internal/service/maillog_stat/overview.go b/core/internal/service/maillog_stat/overview.go
new file mode 100644
index 00000000..7490652a
--- /dev/null
+++ b/core/internal/service/maillog_stat/overview.go
@@ -0,0 +1,508 @@
+package maillog_stat
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "fmt"
+ "github.com/gogf/gf/v2/database/gdb"
+ "github.com/gogf/gf/v2/frame/g"
+ "sort"
+ "strconv"
+ "time"
+)
+
+// Overview maillog data overview structure
+type Overview struct{}
+
+// NewOverview new overview instance
+func NewOverview() *Overview {
+ return &Overview{}
+}
+
+// filterAndPrepareTimeSection filter and provide time section
+func (o *Overview) filterAndPrepareTimeSection(startTime, endTime int64) (int64, int64) {
+ if startTime > 0 && endTime < 0 {
+ endTime = time.Now().Unix()
+ }
+
+ if startTime > endTime {
+ panic(public.Lang("end_time must greater than start_time"))
+ }
+
+ return startTime, endTime
+}
+
+// buildBaseQuery build basic query
+func (o *Overview) buildBaseQuery(campaignID int64, domain string, startTime, endTime int64) *gdb.Model {
+ query := g.DB().Model("mailstat_send_mails ms")
+ query.LeftJoin("mailstat_senders s", "sm.postfix_message_id=s.postfix_message_id")
+ query.Where("s.postfix_message_id is not null")
+
+ if domain != "" {
+ query.Where("s.sender LIKE ?", "%@"+domain)
+ }
+
+ if startTime > 0 {
+ query.Where("sm.log_time_millis > ?", startTime*1000-1)
+ }
+
+ if endTime > 0 {
+ query.Where("sm.log_time_millis < ?", endTime*1000+1)
+ }
+
+ return query
+}
+
+// Overview overview the maillog
+func (o *Overview) Overview(campaignID int64, domain string, startTime, endTime int64) map[string]interface{} {
+ startTime, endTime = o.filterAndPrepareTimeSection(startTime, endTime)
+
+ return map[string]interface{}{
+ "dashboard": o.overviewDashboard(campaignID, domain, startTime, endTime),
+ "mail_providers": o.overviewProviders(campaignID, domain, startTime, endTime),
+ "send_mail_chart": o.chartSendMail(campaignID, domain, startTime, endTime),
+ "bounce_rate_chart": o.chartBounceRate(campaignID, domain, startTime, endTime),
+ "open_rate_chart": o.chartOpenRate(campaignID, domain, startTime, endTime),
+ "click_rate_chart": o.chartClickRate(campaignID, domain, startTime, endTime),
+ }
+}
+
+// overviewDashboard dashboard data
+func (o *Overview) overviewDashboard(campaignID int64, domain string, startTime, endTime int64) map[string]interface{} {
+ query := o.buildBaseQuery(campaignID, domain, startTime, endTime)
+
+ query.LeftJoin("mailstat_opened o", "sm.postfix_message_id=o.postfix_message_id")
+ query.LeftJoin("mailstat_clicked c", "sm.postfix_message_id=c.postfix_message_id")
+
+ query.Fields("count(*) as sends")
+ query.Fields("ifnull(sum(case when status='sent' and dsn like '2.%' then 1 else 0 end), 0) as delivered")
+ query.Fields("count(distinct o.postfix_message_id) as opened")
+ query.Fields("count(distinct c.postfix_message_id) as clicked")
+ query.Fields("ifnull(sum(case when status='bounced' then 1 else 0 end), 0) as bounced")
+
+ var result gdb.Record
+ err := query.Scan(&result)
+ if err != nil {
+ g.Log().Error(context.Background(), err)
+ return nil
+ }
+
+ aggregate := map[string]interface{}{
+ "sends": 0,
+ "delivered": 0,
+ "opened": 0,
+ "clicked": 0,
+ "bounced": 0,
+ }
+
+ for k, v := range result {
+ if _, ok := aggregate[k]; !ok {
+ continue
+ }
+ aggregate[k] = v.Int()
+ }
+
+ if aggregate["sends"].(int) > 0 {
+ aggregate["delivery_rate"] = float64(aggregate["delivered"].(int)) / float64(aggregate["sends"].(int)) * 100
+ } else {
+ aggregate["delivery_rate"] = 0
+ }
+
+ if aggregate["sends"].(int) > 0 {
+ aggregate["bounce_rate"] = float64(aggregate["bounced"].(int)) / float64(aggregate["sends"].(int)) * 100
+ aggregate["open_rate"] = float64(aggregate["opened"].(int)) / float64(aggregate["sends"].(int)) * 100
+ aggregate["click_rate"] = float64(aggregate["clicked"].(int)) / float64(aggregate["sends"].(int)) * 100
+ } else {
+ aggregate["bounce_rate"] = 0
+ aggregate["open_rate"] = 0
+ aggregate["click_rate"] = 0
+ }
+
+ return aggregate
+}
+
+// overviewProviders statistic mail provider
+func (o *Overview) overviewProviders(campaignID int64, domain string, startTime, endTime int64) []map[string]interface{} {
+ startTime, endTime = o.filterAndPrepareTimeSection(startTime, endTime)
+
+ query := o.buildBaseQuery(campaignID, domain, startTime, endTime)
+
+ query = query.LeftJoin("mailstat_opened o", "sm.postfix_message_id=o.postfix_message_id")
+ query = query.LeftJoin("mailstat_clicked c", "sm.postfix_message_id=c.postfix_message_id")
+
+ query = query.Fields("sm.mail_provider")
+ query = query.Fields("count(*) as sends")
+ query = query.Fields("ifnull(sum(case when status='sent' and dsn like '2.%' then 1 else 0 end), 0) as delivered")
+ query = query.Fields("count(distinct o.postfix_message_id) as opened")
+ query = query.Fields("count(distinct c.postfix_message_id) as clicked")
+ query = query.Fields("ifnull(sum(case when status='bounced' then 1 else 0 end), 0) as bounced")
+
+ query = query.Group("sm.mail_provider")
+
+ var results []gdb.Record
+ err := query.Scan(&results)
+ if err != nil {
+ g.Log().Error(context.Background(), err)
+ return nil
+ }
+
+ aggregate := map[string]interface{}{
+ "sends": 0,
+ "delivered": 0,
+ "opened": 0,
+ "clicked": 0,
+ "bounced": 0,
+ }
+
+ m := make(map[string]map[string]interface{})
+
+ for _, result := range results {
+ provider := result["mail_provider"].String()
+ if _, ok := m[provider]; !ok {
+ m[provider] = make(map[string]interface{})
+ for k, v := range aggregate {
+ m[provider][k] = v
+ }
+ }
+
+ for k, v := range result {
+ if _, ok := aggregate[k]; !ok {
+ continue
+ }
+ m[provider][k] = v.Int()
+ }
+ }
+
+ var lst []map[string]interface{}
+ for k, item := range m {
+ item["mail_provider"] = k
+ if item["sends"].(int) > 0 {
+ item["delivery_rate"] = float64(item["delivered"].(int)) / float64(item["sends"].(int)) * 100
+ item["bounce_rate"] = float64(item["bounced"].(int)) / float64(item["sends"].(int)) * 100
+ item["open_rate"] = float64(item["opened"].(int)) / float64(item["sends"].(int)) * 100
+ item["click_rate"] = float64(item["clicked"].(int)) / float64(item["sends"].(int)) * 100
+ } else {
+ item["delivery_rate"] = 0
+ item["bounce_rate"] = 0
+ item["open_rate"] = 0
+ item["click_rate"] = 0
+ }
+ lst = append(lst, item)
+ }
+
+ // descending by sends
+ sort.Slice(lst, func(i, j int) bool {
+ return lst[i]["sends"].(int) > lst[j]["sends"].(int)
+ })
+
+ return lst
+}
+
+func (o *Overview) fillChartData(data []map[string]interface{}, fillItem map[string]interface{}, fillType, fillKey string, startTime, endTime int64) []map[string]interface{} {
+ switch fillType {
+ case "daily":
+ return o.fillChartDataDaily(data, fillItem, fillKey, startTime, endTime)
+ case "hourly":
+ return o.fillChartDataHourly(data, fillItem, fillKey)
+ case "monthly":
+ return o.fillChartDataMonthly(data, fillItem, fillKey, startTime, endTime)
+ default:
+ return data
+ }
+}
+
+func (o *Overview) fillChartDataHourly(data []map[string]interface{}, fillItem map[string]interface{}, fillKey string) []map[string]interface{} {
+ for _, item := range data {
+ if x, ok := item["x"].(string); ok {
+ if val, err := strconv.Atoi(x); err == nil {
+ item[fillKey] = val
+ }
+ }
+ }
+
+ if len(data) == 24 {
+ return data
+ }
+
+ m := make(map[int]map[string]interface{})
+ for _, item := range data {
+ if val, ok := item[fillKey].(int); ok {
+ m[val] = item
+ }
+ }
+
+ var lst []map[string]interface{}
+ for i := 0; i < 24; i++ {
+ if item, ok := m[i]; ok {
+ lst = append(lst, item)
+ continue
+ }
+
+ item := make(map[string]interface{})
+ for k, v := range fillItem {
+ item[k] = v
+ }
+ item[fillKey] = i
+ lst = append(lst, item)
+ }
+
+ return lst
+}
+
+func (o *Overview) fillChartDataDaily(data []map[string]interface{}, fillItem map[string]interface{}, fillKey string, startTime, endTime int64) []map[string]interface{} {
+ if startTime < 0 || endTime < 0 {
+ return data
+ }
+
+ if startTime > endTime {
+ return data
+ }
+
+ m := make(map[string]map[string]interface{})
+ for _, item := range data {
+ if x, ok := item["x"].(string); ok {
+ m[x] = item
+ }
+ }
+
+ var lst []map[string]interface{}
+ for i := startTime; i <= endTime; i += 86400 {
+ dayDateObj := time.Unix(i, 0)
+ dayDate := dayDateObj.Format("2006-01-02")
+ dayTime := time.Date(dayDateObj.Year(), dayDateObj.Month(), dayDateObj.Day(), 0, 0, 0, 0, time.Local).Unix()
+
+ if item, ok := m[dayDate]; ok {
+ item[fillKey] = dayTime
+ lst = append(lst, item)
+ continue
+ }
+
+ item := make(map[string]interface{})
+ for k, v := range fillItem {
+ item[k] = v
+ }
+ item[fillKey] = dayTime
+ lst = append(lst, item)
+ }
+
+ return lst
+}
+
+func (o *Overview) fillChartDataMonthly(data []map[string]interface{}, fillItem map[string]interface{}, fillKey string, startTime, endTime int64) []map[string]interface{} {
+ if startTime < 0 || endTime < 0 {
+ return data
+ }
+
+ if startTime > endTime {
+ return data
+ }
+
+ m := make(map[string]map[string]interface{})
+ for _, item := range data {
+ if x, ok := item["x"].(string); ok {
+ m[x] = item
+ }
+ }
+
+ var lst []map[string]interface{}
+ for i := startTime; i <= endTime; i += 86400 {
+ dayDateObj := time.Unix(i, 0)
+ dayDate := dayDateObj.Format("2006-01-02")
+ dayTime := time.Date(dayDateObj.Year(), dayDateObj.Month(), dayDateObj.Day(), 0, 0, 0, 0, time.Local).Unix()
+
+ if item, ok := m[dayDate]; ok {
+ item[fillKey] = dayTime
+ lst = append(lst, item)
+ continue
+ }
+
+ item := make(map[string]interface{})
+ for k, v := range fillItem {
+ item[k] = v
+ }
+ item[fillKey] = dayTime
+ lst = append(lst, item)
+ }
+
+ return lst
+}
+
+// sendMailDashboard dashboard data for send mail
+func (o *Overview) sendMailDashboard(campaignID int64, domain string, startTime, endTime int64) map[string]interface{} {
+ startTime, endTime = o.filterAndPrepareTimeSection(startTime, endTime)
+
+ query := o.buildBaseQuery(campaignID, domain, startTime, endTime)
+
+ query = query.Fields("count(*) as sends")
+ query = query.Fields("ifnull(sum(case when status='sent' and dsn like '2.%' then 1 else 0 end), 0) as delivered")
+ query = query.Fields("count(*) - ifnull(sum(case when status='sent' and dsn like '2.%' then 1 else 0 end), 0) as failed")
+
+ var result gdb.Record
+ err := query.Scan(&result)
+ if err != nil {
+ g.Log().Error(context.Background(), err)
+ return nil
+ }
+
+ aggregate := map[string]interface{}{
+ "sends": 0,
+ "delivered": 0,
+ "failed": 0,
+ }
+
+ for k, v := range result {
+ aggregate[k] = v.Int()
+ }
+
+ if aggregate["sends"].(int) > 0 {
+ aggregate["delivery_rate"] = float64(aggregate["delivered"].(int)) / float64(aggregate["sends"].(int)) * 100
+ aggregate["failure_rate"] = float64(aggregate["failed"].(int)) / float64(aggregate["sends"].(int)) * 100
+ } else {
+ aggregate["delivery_rate"] = 0
+ aggregate["failure_rate"] = 0
+ }
+
+ return aggregate
+}
+
+func (o *Overview) prepareChartData(startTime, endTime int64) (string, string) {
+ columnType := "daily"
+ datetimeFormat := "2006-01-02"
+ secs := endTime - startTime
+
+ if secs < 86400 {
+ columnType = "hourly"
+ datetimeFormat = "15"
+ }
+
+ xAxisField := fmt.Sprintf("strftime('%s', datetime(sm.log_time_millis/1000, 'unixepoch', 'localtime')) as x", datetimeFormat)
+
+ return columnType, xAxisField
+}
+
+func (o *Overview) chartSendMail(campaignID int64, domain string, startTime, endTime int64) map[string]interface{} {
+ startTime, endTime = o.filterAndPrepareTimeSection(startTime, endTime)
+
+ query := o.buildBaseQuery(campaignID, domain, startTime, endTime)
+
+ columnType, xAxisField := o.prepareChartData(startTime, endTime)
+
+ query = query.Fields(xAxisField)
+ query = query.Fields("count(*) as sends")
+ query = query.Fields("ifnull(sum(case when status='sent' and dsn like '2.%' then 1 else 0 end), 0) as delivered")
+ query = query.Fields("count(*) - ifnull(sum(case when status='sent' and dsn like '2.%' then 1 else 0 end), 0) as failed")
+
+ query = query.Group("x")
+ query = query.Order("x")
+
+ var results []map[string]interface{}
+ err := query.Scan(&results)
+ if err != nil {
+ g.Log().Error(context.Background(), err)
+ return nil
+ }
+
+ fillItem := map[string]interface{}{
+ "sends": 0,
+ "delivered": 0,
+ "failed": 0,
+ }
+
+ return map[string]interface{}{
+ "column_type": columnType,
+ "dashboard": o.sendMailDashboard(campaignID, domain, startTime, endTime),
+ "data": o.fillChartData(results, fillItem, columnType, "x", startTime, endTime),
+ }
+}
+
+func (o *Overview) chartBounceRate(campaignID int64, domain string, startTime, endTime int64) map[string]interface{} {
+ startTime, endTime = o.filterAndPrepareTimeSection(startTime, endTime)
+
+ query := o.buildBaseQuery(campaignID, domain, startTime, endTime)
+
+ columnType, xAxisField := o.prepareChartData(startTime, endTime)
+
+ query = query.Fields(xAxisField)
+ query = query.Fields(gdb.Raw("case when count(*) > 0 then round(1.0 * ifnull(sum(case when status='bounced' then 1 else 0 end), 0) / count(*) * 100.0, 2) else 0.0 end as bounce_rate"))
+
+ query = query.Group("x")
+ query = query.Order("x")
+
+ var results []map[string]interface{}
+ err := query.Scan(&results)
+ if err != nil {
+ g.Log().Error(context.Background(), err)
+ return nil
+ }
+
+ fillItem := map[string]interface{}{
+ "bounce_rate": 0.0,
+ }
+
+ return map[string]interface{}{
+ "column_type": columnType,
+ "data": o.fillChartData(results, fillItem, columnType, "x", startTime, endTime),
+ }
+}
+
+func (o *Overview) chartOpenRate(campaignID int64, domain string, startTime, endTime int64) map[string]interface{} {
+ startTime, endTime = o.filterAndPrepareTimeSection(startTime, endTime)
+
+ query := o.buildBaseQuery(campaignID, domain, startTime, endTime)
+
+ columnType, xAxisField := o.prepareChartData(startTime, endTime)
+
+ query = query.LeftJoin("mailstat_opened o", "sm.postfix_message_id=o.postfix_message_id")
+
+ query = query.Fields(xAxisField)
+ query = query.Fields("case when ifnull(sum(case when status='sent' and dsn like '2.%' then 1 else 0 end), 0) > 0 then round(1.0 * count(distinct o.postfix_message_id) / ifnull(sum(case when status='sent' and dsn like '2.%' then 1 else 0 end), 0) * 100, 2) else 0.0 end as open_rate")
+
+ query = query.Group("x")
+
+ var results []map[string]interface{}
+ err := query.Scan(&results)
+ if err != nil {
+ g.Log().Error(context.Background(), err)
+ return nil
+ }
+
+ fillItem := map[string]interface{}{
+ "open_rate": 0.0,
+ }
+
+ return map[string]interface{}{
+ "column_type": columnType,
+ "data": o.fillChartData(results, fillItem, columnType, "x", startTime, endTime),
+ }
+}
+
+func (o *Overview) chartClickRate(campaignID int64, domain string, startTime, endTime int64) map[string]interface{} {
+ startTime, endTime = o.filterAndPrepareTimeSection(startTime, endTime)
+
+ query := o.buildBaseQuery(campaignID, domain, startTime, endTime)
+
+ columnType, xAxisField := o.prepareChartData(startTime, endTime)
+
+ query = query.LeftJoin("mailstat_clicked c", "sm.postfix_message_id=c.postfix_message_id")
+
+ query = query.Fields(xAxisField)
+ query = query.Fields("case when ifnull(sum(case when status='sent' and dsn like '2.%' then 1 else 0 end), 0) > 0 then round(1.0 * count(distinct c.postfix_message_id) / ifnull(sum(case when status='sent' and dsn like '2.%' then 1 else 0 end), 0) * 100, 2) else 0.0 end as click_rate")
+
+ query = query.Group("x")
+
+ var results []map[string]interface{}
+ err := query.Scan(&results)
+ if err != nil {
+ g.Log().Error(context.Background(), err)
+ return nil
+ }
+
+ fillItem := map[string]interface{}{
+ "click_rate": 0.0,
+ }
+
+ return map[string]interface{}{
+ "column_type": columnType,
+ "data": o.fillChartData(results, fillItem, columnType, "x", startTime, endTime),
+ }
+}