This repository has been archived by the owner on Oct 22, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrafficjam.go
166 lines (143 loc) · 3.57 KB
/
trafficjam.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/smtp"
"net/url"
"os"
"os/user"
)
const (
name = "trafficjam"
apiURL = "https://maps.googleapis.com/maps/api/distancematrix/json"
)
type config struct {
Origins string `json:"origins"`
Destinations string `json:"destinations"`
APIKey string `json:"api_key"`
Mode string `json:"mode"`
Avoid string `json:"avoid"`
TrafficModel string `json:"traffic_model"`
MaxDuration int `json:"max_duration"`
SMTP struct {
Host string `json:"host"`
Port int `json:"port"`
User string `json:"user"`
Pass string `json:"pass"`
} `json:"smtp"`
Recipient string `json:"recipient"`
}
type apiResponse struct {
Rows []struct {
Elements []struct {
DurationInTraffic struct {
Text string `json:"text"`
Value int `json:"value"`
} `json:"duration_in_traffic"`
Status string `json:"status"`
} `json:"elements"`
} `json:"rows"`
Status string `json:"status"`
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "usage: %s <config>\n", name)
os.Exit(1)
}
log.SetPrefix(name + ": ")
log.SetFlags(0)
conf, err := readConfig(os.Args[1])
if err != nil {
log.Fatal(err)
}
params := map[string]string{
"origins": conf.Origins,
"destinations": conf.Destinations,
"key": conf.APIKey,
"mode": conf.Mode,
"avoid": conf.Avoid,
"departure_time": "now",
"traffic_model": conf.TrafficModel,
}
apiResp, err := queryMapsAPI(params)
if err != nil {
log.Fatal(err)
}
duration := apiResp.Rows[0].Elements[0].DurationInTraffic.Value
if duration > conf.MaxDuration*60 {
if err := sendMail(conf, apiResp.Rows[0].Elements[0].DurationInTraffic.Text); err != nil {
log.Fatal(err)
}
}
}
func readConfig(filename string) (*config, error) {
var conf config
confData, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
if err := json.Unmarshal(confData, &conf); err != nil {
return nil, err
}
return &conf, nil
}
func queryMapsAPI(params map[string]string) (*apiResponse, error) {
query := url.Values{}
for key, val := range params {
if val != "" {
query.Set(key, val)
}
}
uri, err := url.Parse(apiURL)
if err != nil {
return nil, err
}
uri.RawQuery = query.Encode()
resp, err := http.Get(uri.String())
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var apiResp apiResponse
if err := json.Unmarshal(body, &apiResp); err != nil {
return nil, err
}
if apiResp.Status != "OK" {
return nil, fmt.Errorf("bad response status: %s", apiResp.Status)
}
if len(apiResp.Rows) != 1 {
return nil, fmt.Errorf("response row count is not 1")
}
if len(apiResp.Rows[0].Elements) != 1 {
return nil, fmt.Errorf("response first row element count is not 1")
}
if apiResp.Rows[0].Elements[0].Status != "OK" {
return nil, fmt.Errorf("bad response first row first element status: %s", apiResp.Rows[0].Elements[0].Status)
}
return &apiResp, nil
}
func sendMail(conf *config, body string) error {
user, err := user.Current()
if err != nil {
return err
}
hostname, err := os.Hostname()
if err != nil {
return err
}
auth := smtp.PlainAuth("", conf.SMTP.User, conf.SMTP.Pass, conf.SMTP.Host)
sender := user.Username + "@" + hostname
to := []string{conf.Recipient}
msg := []byte("To: " + conf.Recipient + "\r\n" +
"Subject: " + name + " alert\r\n" +
"\r\n" +
body + "\r\n")
return smtp.SendMail(fmt.Sprintf("%s:%d", conf.SMTP.Host, conf.SMTP.Port), auth, sender, to, msg)
}