-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
229 lines (195 loc) · 7.18 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/joho/godotenv"
"github.com/robfig/cron/v3"
"github.com/sendgrid/sendgrid-go"
"github.com/sendgrid/sendgrid-go/helpers/mail"
)
// QueryResult struct represents the JSON structure of the API response
type QueryResult struct {
QueryResult struct {
Data struct {
Rows []interface{} `json:"rows"`
} `json:"data"`
} `json:"query_result"`
}
// DataProcessor is a type that represents a function to process the data from the API response
type DataProcessor func([]interface{}) (interface{}, error)
// init function to load environment variables from a .env file
func init() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
}
func main() {
nowFlag := flag.Bool("now", false, "Run the task immediately, ignoring the schedule")
flag.Parse()
// Load the configurations from environment variables
redashBaseURL := getEnv("REDASH_BASE_URL", "")
redashAPIKey := getEnv("REDASH_API_KEY", "")
redashQueryID := getEnv("REDASH_QUERY_ID", "")
googleChatWebhookURL := getEnv("GOOGLE_CHAT_WEBHOOK_URL", "")
sendGridAPIKey := getEnv("SENDGRID_API_KEY", "")
senderEmail := getEnv("SENDER_EMAIL", "")
emailSubject := getEnv("EMAIL_SUBJECT", "Member Counts Notification")
recipientEmails := getEnv("RECIPIENT_EMAILS", "")
hour := getEnv("SCHEDULE_HOUR", "8") // Default to 8
minute := getEnv("SCHEDULE_MINUTE", "30") // Default to 30
timezoneStr := getEnv("TIMEZONE", "America/Toronto") // Default to America/Toronto
var processor DataProcessor = countMembersProcessor
// If the --now flag is provided, run the task immediately and exit
if *nowFlag {
runScheduledTask(redashBaseURL, redashAPIKey, redashQueryID, googleChatWebhookURL, sendGridAPIKey, senderEmail, emailSubject, recipientEmails, processor)
return
}
// Load the location from the timezone string
location, err := time.LoadLocation(timezoneStr)
if err != nil {
log.Fatal("Invalid timezone: ", err)
}
// Create a new cron scheduler with the loaded location
c := cron.New(cron.WithSeconds(), cron.WithLocation(location))
// Constructing the schedule using the retrieved hour and minute
schedule := fmt.Sprintf("0 %s %s * * *", minute, hour)
// Scheduling the task to run at the specified time
_, err = c.AddFunc(schedule, func() {
runScheduledTask(redashBaseURL, redashAPIKey, redashQueryID, googleChatWebhookURL, sendGridAPIKey, senderEmail, emailSubject, recipientEmails, processor)
})
if err != nil {
log.Fatal("Could not schedule task: ", err)
}
c.Start()
// Use a WaitGroup to keep the application running indefinitely
var wg sync.WaitGroup
wg.Add(1)
wg.Wait()
}
// runScheduledTask is a function to run the scheduled task for fetching and processing the data
func runScheduledTask(redashBaseURL, redashAPIKey, redashQueryID, googleChatWebhookURL, sendGridAPIKey, senderEmail, emailSubject, recipientEmails string, processor DataProcessor) {
// Construct the URLs for refreshing and fetching results
refreshURL := fmt.Sprintf("%s/api/queries/%s/refresh", redashBaseURL, redashQueryID)
resultsURL := fmt.Sprintf("%s/api/queries/%s/results.json?api_key=%s", redashBaseURL, redashQueryID, redashAPIKey)
// Create a custom HTTP client
client := &http.Client{}
// Refresh the query with Authorization header
req, err := http.NewRequest("POST", refreshURL, nil)
if err != nil {
log.Println("Error creating refresh request: ", err)
return
}
req.Header.Add("Authorization", "Key "+redashAPIKey)
_, err = client.Do(req)
if err != nil {
log.Println("Error refreshing query: ", err)
return
}
// Sleep or poll until the results are ready
time.Sleep(10 * time.Second) // Adjust as needed
// Fetch the results using API key in the URL
resp, err := http.Get(resultsURL)
if err != nil {
log.Println("Error getting results: ", err)
return
}
defer resp.Body.Close()
// Decode the results into the QueryResult struct
var result QueryResult
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
log.Println("Error decoding results: ", err)
return
}
// Process the data using the provided processor function
processedData, err := processor(result.QueryResult.Data.Rows)
if err != nil {
log.Printf("Error processing data: %v", err)
return
}
// Convert the processed data to an integer
count, ok := processedData.(int)
if !ok {
log.Printf("Error: Processed data is not an integer")
return
}
// Send the processed data to Google Chat
err = sendMessageToGoogleChat(googleChatWebhookURL, count)
if err != nil {
log.Printf("Error sending message to Google Chat: %v", err)
}
// Send the processed data via email
err = sendEmail(sendGridAPIKey, senderEmail, emailSubject, fmt.Sprintf("Total member count for %s: *%d*", time.Now().Format("January 2, 2006"), count), recipientEmails)
if err != nil {
log.Printf("Error sending email: %v", err)
}
}
// countMembersProcessor is a function to process the data and return the number of rows as the processed data
func countMembersProcessor(rows []interface{}) (interface{}, error) {
return len(rows), nil
}
// sendMessageToGoogleChat is a function to send the count message to Google Chat Webhook
func sendMessageToGoogleChat(webhookURL string, count int) error {
// Format the current date to "Month Day, Year" format
currentDate := time.Now().Format("January 2, 2006")
// Construct the message to be sent
message := map[string]interface{}{
"text": fmt.Sprintf("Total member count for %s: *%d*", currentDate, count),
}
// Marshal the message to JSON
messageBytes, err := json.Marshal(message)
if err != nil {
return err
}
// Send the message to the provided webhook URL
resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(messageBytes))
if err != nil {
return err
}
defer resp.Body.Close()
// Check the response status
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to send message to Google Chat, status: %d, response: %s", resp.StatusCode, string(body))
}
return nil
}
// sendEmail is a function to send the count message via email using SendGrid
func sendEmail(sendGridAPIKey, senderEmail, subject, body, recipientEmails string) error {
from := mail.NewEmail("Member Counts App", senderEmail)
toEmails := parseEmails(recipientEmails)
for _, toEmail := range toEmails {
to := mail.NewEmail("", toEmail)
message := mail.NewSingleEmail(from, subject, to, body, body)
client := sendgrid.NewSendClient(sendGridAPIKey)
response, err := client.Send(message)
if err != nil {
return err
}
if response.StatusCode != http.StatusAccepted {
return fmt.Errorf("failed to send email, status: %d, response: %s", response.StatusCode, response.Body)
}
}
return nil
}
// parseEmails is a helper function to parse the comma-separated list of recipient emails
func parseEmails(emailsStr string) []string {
return strings.Split(emailsStr, ",")
}
// getEnv is a function to fetch the value of the environment variable identified by key,
// returns fallback if the environment variable is not set.
func getEnv(key, fallback string) string {
if value, exists := os.LookupEnv(key); exists {
return value
}
return fallback
}