Browse Source

Split file

Gabriel Capella 3 weeks ago
parent
commit
d19579d4b5
2 changed files with 120 additions and 85 deletions
  1. 114 0
      mailchimp/mailchimp.go
  2. 6 85
      main.go

+ 114 - 0
mailchimp/mailchimp.go

@@ -0,0 +1,114 @@
+package mailchimp
+
+import (
+	"crypto/md5"
+	"encoding/hex"
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"strings"
+
+	"github.com/sirupsen/logrus"
+	"github.com/spf13/viper"
+)
+
+type MailchimpAPI struct {
+	APIKey     string
+	Server     string
+	AudienceID string
+}
+
+type Member struct {
+	EmailAddress string `json:"email_address"`
+	Status       string `json:"status_if_new,omitempty"`
+}
+
+func NewMailchimpAPI() *MailchimpAPI {
+	return &MailchimpAPI{
+		APIKey:     viper.GetString("mailchimp.api_key"),
+		Server:     viper.GetString("mailchimp.server"),
+		AudienceID: viper.GetString("mailchimp.audience_id"),
+	}
+}
+
+func (api *MailchimpAPI) emailHash(email string) string {
+	hash := md5.Sum([]byte(strings.ToLower(email)))
+	return hex.EncodeToString(hash[:])
+}
+
+func (api *MailchimpAPI) EmailExists(email string) (bool, error) {
+	hash := api.emailHash(email)
+	url := fmt.Sprintf("https://%s.api.mailchimp.com/3.0/lists/%s/members/%s",
+		api.Server,
+		api.AudienceID,
+		hash)
+
+	req, _ := http.NewRequest("GET", url, nil)
+	req.SetBasicAuth("anystring", api.APIKey)
+	resp, err := http.DefaultClient.Do(req)
+	if err != nil {
+		return false, err
+	}
+	defer resp.Body.Close()
+
+	return resp.StatusCode == http.StatusOK, nil
+}
+
+func (api *MailchimpAPI) AddEmail(email string) error {
+	url := fmt.Sprintf("https://%s.api.mailchimp.com/3.0/lists/%s/members",
+		api.Server,
+		api.AudienceID)
+
+	member := Member{
+		EmailAddress: email,
+		Status:       "subscribed",
+	}
+	body, _ := json.Marshal(member)
+
+	req, _ := http.NewRequest("POST", url, strings.NewReader(string(body)))
+	req.SetBasicAuth("anystring", api.APIKey)
+	req.Header.Add("Content-Type", "application/json")
+
+	resp, err := http.DefaultClient.Do(req)
+	if err != nil {
+		return err
+	}
+	defer resp.Body.Close()
+
+	if resp.StatusCode >= 400 {
+		return fmt.Errorf("failed to add email: %s", email)
+	}
+	return nil
+}
+
+func (api *MailchimpAPI) TagEmail(email, tag string) error {
+	hash := api.emailHash(email)
+	url := fmt.Sprintf("https://%s.api.mailchimp.com/3.0/lists/%s/members/%s/tags",
+		api.Server,
+		api.AudienceID,
+		hash)
+
+	body := map[string]interface{}{
+		"tags": []map[string]string{
+			{"name": tag, "status": "active"},
+		},
+	}
+	jsonBody, _ := json.Marshal(body)
+
+	req, _ := http.NewRequest("POST", url, strings.NewReader(string(jsonBody)))
+	req.SetBasicAuth("anystring", api.APIKey)
+	req.Header.Add("Content-Type", "application/json")
+
+	resp, err := http.DefaultClient.Do(req)
+	if err != nil {
+		return err
+	}
+	defer resp.Body.Close()
+
+	if resp.StatusCode >= 400 {
+		logrus.Errorf("Tagging failed: status %d", resp.StatusCode)
+		return fmt.Errorf("failed to tag email: %s", email)
+	}
+	return nil
+}
+

+ 6 - 85
main.go

@@ -1,13 +1,10 @@
 package main
 
 import (
-	"crypto/md5"
 	"database/sql"
-	"encoding/hex"
-	"encoding/json"
 	"fmt"
-	"net/http"
 	"strings"
+	"sync-mailchimp/mailchimp"
 	"time"
 
 	"github.com/sirupsen/logrus"
@@ -55,84 +52,6 @@ func getEmailsFromMySQL() ([]string, error) {
 	return emails, nil
 }
 
-func emailHash(email string) string {
-	hash := md5.Sum([]byte(strings.ToLower(email)))
-	return hex.EncodeToString(hash[:])
-}
-
-func emailExists(email string) (bool, error) {
-	hashStr := emailHash(email)
-	url := fmt.Sprintf("https://%s.api.mailchimp.com/3.0/lists/%s/members/%s",
-		viper.GetString("mailchimp.server"),
-		viper.GetString("mailchimp.audience_id"),
-		hashStr)
-
-	req, _ := http.NewRequest("GET", url, nil)
-	req.SetBasicAuth("anystring", viper.GetString("mailchimp.api_key"))
-	resp, err := http.DefaultClient.Do(req)
-	if err != nil {
-		return false, err
-	}
-	defer resp.Body.Close()
-	return resp.StatusCode == http.StatusOK, nil
-}
-
-func addEmail(email string) error {
-	url := fmt.Sprintf("https://%s.api.mailchimp.com/3.0/lists/%s/members",
-		viper.GetString("mailchimp.server"),
-		viper.GetString("mailchimp.audience_id"))
-	member := Member{
-		EmailAddress: email,
-		Status:       "subscribed",
-	}
-	body, _ := json.Marshal(member)
-
-	req, _ := http.NewRequest("POST", url, strings.NewReader(string(body)))
-	req.SetBasicAuth("anystring", viper.GetString("mailchimp.api_key"))
-	req.Header.Add("Content-Type", "application/json")
-
-	resp, err := http.DefaultClient.Do(req)
-	if err != nil {
-		return err
-	}
-	defer resp.Body.Close()
-
-	if resp.StatusCode >= 400 {
-		return fmt.Errorf("failed to add email: %s", email)
-	}
-	return nil
-}
-
-func tagEmail(email, tag string) error {
-	hashStr := emailHash(email)
-	url := fmt.Sprintf("https://%s.api.mailchimp.com/3.0/lists/%s/members/%s/tags",
-		viper.GetString("mailchimp.server"),
-		viper.GetString("mailchimp.audience_id"),
-		hashStr)
-
-	body := map[string]interface{}{
-		"tags": []map[string]string{
-			{"name": tag, "status": "active"},
-		},
-	}
-	jsonBody, _ := json.Marshal(body)
-
-	req, _ := http.NewRequest("POST", url, strings.NewReader(string(jsonBody)))
-	req.SetBasicAuth("anystring", viper.GetString("mailchimp.api_key"))
-	req.Header.Add("Content-Type", "application/json")
-
-	resp, err := http.DefaultClient.Do(req)
-	if err != nil {
-		return err
-	}
-	defer resp.Body.Close()
-
-	if resp.StatusCode >= 400 {
-		return fmt.Errorf("failed to tag email: %s", email)
-	}
-	return nil
-}
-
 var rootCmd = &cobra.Command{
 	Use:   "sync-mailchimp",
 	Short: "Sync MySQL emails with Mailchimp",
@@ -142,9 +61,11 @@ var rootCmd = &cobra.Command{
 			logrus.Fatalf("MySQL error: %v", err)
 		}
 
+		api := mailchimp.NewMailchimpAPI()
+
 		var toAdd []string
 		for _, email := range emails {
-			exists, err := emailExists(email)
+			exists, err := api.EmailExists(email)
 			if err != nil {
 				logrus.Warnf("Check failed for %s: %v", email, err)
 				continue
@@ -160,7 +81,7 @@ var rootCmd = &cobra.Command{
 			fmt.Scanln(&input)
 			if strings.ToLower(input) == "y" {
 				for _, email := range toAdd {
-					if err := addEmail(email); err != nil {
+					if err := api.AddEmail(email); err != nil {
 						logrus.Errorf("Failed to add %s: %v", email, err)
 					} else {
 						logrus.Infof("Added %s", email)
@@ -171,7 +92,7 @@ var rootCmd = &cobra.Command{
 
 		tag := time.Now().Format("January 2006")
 		for _, email := range emails {
-			if err := tagEmail(email, tag); err != nil {
+			if err := api.TagEmail(email, tag); err != nil {
 				logrus.Warnf("Failed to tag %s: %v", email, err)
 			} else {
 				logrus.Infof("Tagged %s with %s", email, tag)