-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
210 lines (176 loc) · 5.47 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
package weatherupdate
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"strings"
"time"
"golang.org/x/net/context"
"google.golang.org/appengine"
"google.golang.org/appengine/log"
"google.golang.org/appengine/urlfetch"
)
const (
weddingYear = 2017
weddingMonth = time.September
weddingDay = 23
weddingHour = 15
twilioNumber = "+17035551234"
passphrase = "wedding weather"
weatherHistoryKey = "history1"
)
var (
weatherAPI = "http://api.openweathermap.org/data/2.5/forecast?zip=22304&units=imperial&APPID=" + os.Getenv("WEATHER_API_KEY")
twilioSendSMSAPI = "https://api.twilio.com/2010-04-01/Accounts/" + os.Getenv("TWILIO_ACCOUNT_SID") + "/Messages"
)
func init() {
http.HandleFunc("/checkTask", checkTaskHandler)
http.HandleFunc("/checkNow", checkNowHandler)
http.HandleFunc("/checkPhone", checkPhoneHandler)
}
type weatherResponse struct {
List []struct {
Dt int64 `json:"dt"`
Main struct {
Temp float32 `json:"temp"`
Humidity int `json:"humidity"`
} `json:"main"`
Weather []struct {
ID int `json:"id"`
Main string `json:"main"`
Description string `json:"description"`
Icon string `json:"icon"`
} `json:"weather"`
} `json:"list"`
}
func checkTaskHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
results, err := fetchWeather(ctx, weatherAPI)
if err != nil {
http.Error(w, "could not fetch weather data", http.StatusInternalServerError)
log.Errorf(ctx, "could not fetch weather data: %v", err)
return
}
var history = new(weatherHistory)
history.load(ctx)
if history.changed(*results) {
msgBody := messageBody(*results)
history.update(ctx, *results)
receiverNumbers := []string{"+18455551234", "+12405551234"}
for _, n := range receiverNumbers {
log.Infof(ctx, "sending to: %s", n)
if err := sendMessage(ctx, msgBody, n); err != nil {
http.Error(w, "could not send sms", http.StatusInternalServerError)
log.Errorf(ctx, "could not send sms: %v", err)
}
}
}
}
const smsAllowContent = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Message>
<Body>%s</Body>
</Message>
</Response>`
const smsDenyContent = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Message>
<Media>%s</Media>
</Message>
</Response>`
func checkNowHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
w.Header().Set("Content-Type", "text/xml")
body := r.PostFormValue("Body")
if !strings.EqualFold(body, passphrase) {
media := "http://www.icge.co.uk/languagesciencesblog/wp-content/uploads/2014/04/you_shall_not_pass1.jpg"
fmt.Fprintf(w, smsDenyContent, media)
return
}
results, err := fetchWeather(ctx, weatherAPI)
if err != nil {
http.Error(w, "could not fetch weather data", http.StatusInternalServerError)
log.Errorf(ctx, "could not fetch weather data: %v", err)
return
}
reply := messageBody(*results)
fmt.Fprintf(w, smsAllowContent, reply)
}
const phoneMessage = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say voice="woman">%s</Say>
</Response>`
func checkPhoneHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
w.Header().Set("Content-Type", "text/xml")
results, err := fetchWeather(ctx, weatherAPI)
if err != nil {
http.Error(w, "could not fetch weather data", http.StatusInternalServerError)
log.Errorf(ctx, "could not fetch weather data: %v", err)
return
}
reply := phoneBody(*results)
fmt.Fprintf(w, phoneMessage, reply)
}
func fetchWeather(ctx context.Context, url string) (*weatherResponse, error) {
resp, err := urlfetch.Client(ctx).Get(url)
if err != nil {
return nil, fmt.Errorf("could not get weather api data: %v", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf(resp.Status)
}
var results = new(weatherResponse)
defer resp.Body.Close()
if err = json.NewDecoder(resp.Body).Decode(&results); err != nil {
return nil, fmt.Errorf("count not decode weather response: %v", err)
}
return results, nil
}
func sendMessage(ctx context.Context, body string, toNumber string) error {
vals := url.Values{}
vals.Set("To", toNumber)
vals.Set("From", twilioNumber)
vals.Set("Body", body)
mb := strings.NewReader(vals.Encode())
req, err := http.NewRequest("POST", twilioSendSMSAPI, mb)
if err != nil {
return fmt.Errorf("could not create sms request: %v", err)
}
req.SetBasicAuth(os.Getenv("TWILIO_ACCOUNT_SID"), os.Getenv("TWILIO_AUTH_TOKEN"))
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
_, err = urlfetch.Client(ctx).Do(req)
if err != nil {
return fmt.Errorf("could not send sms request: %v", err)
}
return nil
}
func messageBody(results weatherResponse) string {
msg := "Wedding Weather Report\n"
for _, r := range results.List {
t := time.Unix(r.Dt, 0)
if isWeddingDay(t) {
msg += fmt.Sprintf("Temp: %d degrees\nHumidity: %d%%\n%s: %s",
int(r.Main.Temp), r.Main.Humidity, r.Weather[0].Main, r.Weather[0].Description)
}
}
return msg
}
func phoneBody(results weatherResponse) string {
msg := "Wedding Weather Report. September 23rd at 3pm. "
for _, r := range results.List {
t := time.Unix(r.Dt, 0)
if isWeddingDay(t) {
msg += fmt.Sprintf("Temperature: %d degrees. Humidity: %d%%. Conditions: %s.",
int(r.Main.Temp), r.Main.Humidity, r.Weather[0].Description)
}
}
return msg
}
func isWeddingDay(d time.Time) bool {
return d.Year() == weddingYear && d.Month() == weddingMonth &&
d.Day() == weddingDay && d.Hour() == weddingHour
}