Skip to content

Commit

Permalink
Add email template for body message
Browse files Browse the repository at this point in the history
  • Loading branch information
eljuanchosf committed Dec 16, 2015
1 parent eab6210 commit 3438acb
Show file tree
Hide file tree
Showing 8 changed files with 120 additions and 2,255 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,6 @@ _testmain.go
*.test
*.prof

*.db

config.yml
8 changes: 4 additions & 4 deletions caching/caching.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"time"

"github.com/boltdb/bolt"
"github.com/eljuanchosf/gocafier/logging"
log "github.com/eljuanchosf/gocafier/logging"
"github.com/kr/pretty"
"github.com/mitchellh/go-homedir"
)
Expand Down Expand Up @@ -66,7 +66,7 @@ func createDatabase(cacheFilename string) error {
cacheFilename += "/.gocafier.db"
}

logging.LogStd(fmt.Sprintf("Setting cache file to %s ", cacheFilename), true)
log.LogStd(fmt.Sprintf("Setting cache file to %s ", cacheFilename), true)

config := &bolt.Options{Timeout: 1 * time.Second}
appdb, err = bolt.Open(cacheFilename, 0600, config)
Expand Down Expand Up @@ -125,8 +125,8 @@ func ListPackages() {
appdb.View(func(tx *bolt.Tx) error {
c := tx.Bucket([]byte(bucketName)).Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
logging.LogStd(fmt.Sprintf("key=%s", k), true)
logging.LogStd(fmt.Sprintf("value=%s\n", pretty.Formatter(v)), true)
log.LogStd(fmt.Sprintf("key=%s", k), true)
log.LogStd(fmt.Sprintf("value=%s\n", pretty.Formatter(v)), true)
}
return nil
})
Expand Down
Binary file removed caching/my.db
Binary file not shown.
14 changes: 14 additions & 0 deletions email-template.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<h2>Envío {{.PackageNumber}}</h2>
Hay un update del envío de referencia.
<h4>Origen del envío</h4>
<p>
{{.From}}
</p>
<h4>Ultimo(s) movimiento(s)</h4>
<p>
<ul>
{{ range $movement := .Movements }}
<li>{{ $movement.Date }}: <strong>{{ $movement.Description }}</strong></li>
{{ end }}
</ul>
</p>
80 changes: 33 additions & 47 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,12 @@ package main
import (
"fmt"

"gopkg.in/gomail.v2"

"github.com/eljuanchosf/gocafier/Godeps/_workspace/src/gopkg.in/alecthomas/kingpin.v2"
"github.com/eljuanchosf/gocafier/caching"
"github.com/eljuanchosf/gocafier/logging"
log "github.com/eljuanchosf/gocafier/logging"
"github.com/eljuanchosf/gocafier/notifications"
"github.com/eljuanchosf/gocafier/ocaclient"
"github.com/eljuanchosf/gocafier/settings"
"github.com/kr/pretty"
)

var (
Expand All @@ -29,63 +27,51 @@ const (
)

func main() {
logging.LogStd(fmt.Sprintf("Starting gocafier %s ", version), true)
logging.SetupLogging(*debug)
log.LogStd(fmt.Sprintf("Starting gocafier %s ", version), true)
log.SetupLogging(*debug)

kingpin.Version(version)
kingpin.Parse()
config = settings.LoadConfig("config.yml")
settings.LoadConfig(*configPath)
caching.CreateBucket(*cachePath)

packageType := "paquetes"
packageNumber := "3867500000015544038"
logging.LogPackage(packageNumber, "Verifying...")
pastData, err := caching.GetPackage(packageNumber)
if err != nil {
panic(err)
}

//pastData.Data[0].Log[0] = caching.DetailLog{}
currentData, err := ocaclient.RequestData(packageType, packageNumber)
if err != nil {
panic(err)
}

currentData.Data[0].Type = packageType
for _, packageNumber := range settings.Values.Packages {
log.LogPackage(packageNumber, "Verifying...")
pastData, err := caching.GetPackage(packageNumber)
if err != nil {
panic(err)
}

if pastData == nil {
logging.LogPackage(packageNumber, "Package does not exists in cache, saving initial data.")
//currentData.Save()
logging.LogPackage(packageNumber, "Sending notification...")
err = SendNotification(currentData)
packageType := "paquetes"
//pastData.Data[0].Log[0] = caching.DetailLog{}
currentData, err := ocaclient.RequestData(packageType, packageNumber)
if err != nil {
panic(err)
}
} else {
diff, diffFound := pastData.DiffWith(currentData)
if diffFound {
logging.LogPackage(packageNumber, "Change detected. Sending notification.")
fmt.Printf("%# v", pretty.Formatter(diff))
//currentData.Save()

currentData.Data[0].Type = packageType

if pastData == nil {
log.LogPackage(packageNumber, "Package does not exist in cache, saving initial data.")
changeDetected(packageNumber, currentData, nil)
} else {
logging.LogPackage(packageNumber, "No change.")
diff, diffFound := pastData.DiffWith(currentData)
if diffFound {
changeDetected(packageNumber, currentData, diff)
} else {
log.LogPackage(packageNumber, "No change.")
}
}
}
caching.Close()
}

func SendNotification(currentData caching.OcaPackageDetail) error {
packageCode := currentData.Data[0].Code
m := gomail.NewMessage()
m.SetHeader("From", config.Email.From)
m.SetHeader("To", config.Email.To)
m.SetHeader("Subject", fmt.Sprintf(config.Email.Subject, packageCode))
m.SetBody("text/html", fmt.Sprintf(config.Email.Body, packageCode))

d := gomail.NewPlainDialer(config.SMTP.Server, config.SMTP.Port, *smtpUser, *smtpPassword)
if err := d.DialAndSend(m); err != nil {
return err
func changeDetected(packageNumber string, currentData caching.OcaPackageDetail, diff []caching.DetailLog) {
var err error
log.LogPackage(packageNumber, "Change detected.")
err = notifications.Send(currentData, diff, *smtpUser, *smtpPassword)
if err != nil {
panic(err)
}
logging.LogPackage(packageCode, "Notification sent")
return nil
//currentData.Save()
}
62 changes: 62 additions & 0 deletions notifications/notifications.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package notifications

import (
"bytes"
"fmt"
"strings"
"text/template"

"github.com/eljuanchosf/gocafier/caching"
log "github.com/eljuanchosf/gocafier/logging"
"github.com/eljuanchosf/gocafier/settings"
"gopkg.in/gomail.v2"
)

func loadBodyTemplate(packageNumber string, packageDetail caching.OcaPackageDetail, diff []caching.DetailLog) string {
var fullBody bytes.Buffer

type emailData struct {
PackageNumber string
From string
Movements []caching.DetailLog
}

originDetails := packageDetail.Data[0].Detail[0]

var packageData emailData
packageData.PackageNumber = packageNumber
packageData.From = fmt.Sprintf("%s %s, %s, %s",
strings.TrimSpace(originDetails.DomicilioRetiro),
strings.TrimSpace(originDetails.NumeroRetiro),
strings.TrimSpace(originDetails.LocalidadRetiro),
strings.TrimSpace(originDetails.PciaRetiro))

packageData.Movements = diff
t, _ := template.ParseFiles("email-template.html")
t.Execute(&fullBody, packageData)
return fullBody.String()
}

//Send sends the email notification
func Send(currentData caching.OcaPackageDetail, diff []caching.DetailLog, smtpUser string, smtpPassword string) error {
packageNumber := currentData.Data[0].Code

if diff == nil {
diff = currentData.Data[0].Log
}

log.LogPackage(packageNumber, "Sending notification...")
m := gomail.NewMessage()
m.SetHeader("From", settings.Values.Email.From)
m.SetHeader("To", settings.Values.Email.To)
m.SetHeader("Subject", fmt.Sprintf(settings.Values.Email.Subject, packageNumber))
m.SetBody("text/html", loadBodyTemplate(packageNumber, currentData, diff))

d := gomail.NewPlainDialer(settings.Values.SMTP.Server, settings.Values.SMTP.Port, smtpUser, smtpPassword)
if err := d.DialAndSend(m); err != nil {
return err
}

log.LogPackage(packageNumber, "Notification sent")
return nil
}
11 changes: 5 additions & 6 deletions settings/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"gopkg.in/yaml.v2"
)

var Values Config

//Config represents the config structure for the package
type Config struct {
Email struct {
Expand All @@ -26,11 +28,9 @@ type Config struct {
}

//LoadConfig reads the specified config file
func LoadConfig(filename string) Config {
var config Config

func LoadConfig(filename string) {
if filename == "." {
filename = "../config.yml"
filename = "config.yml"
}

logging.LogStd(fmt.Sprintf("Loading config from %s", filename), true)
Expand All @@ -39,9 +39,8 @@ func LoadConfig(filename string) Config {
if err != nil {
panic(err)
}
err = yaml.Unmarshal(source, &config)
err = yaml.Unmarshal(source, &Values)
if err != nil {
panic(err)
}
return config
}
Loading

0 comments on commit 3438acb

Please sign in to comment.