-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
304 lines (239 loc) · 6.44 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Package main is the main package
package main
import (
"crypto/sha1"
"encoding/binary"
"encoding/hex"
"errors"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"runtime"
"sync"
"github.com/fekle/simplewebwatcher/config"
"time"
"io"
"github.com/codegangsta/cli"
"github.com/everdev/mack"
"github.com/skratchdot/open-golang/open"
)
func main() {
if err := app(); err != nil {
log.Fatal(err)
}
}
func app() error {
// set max procs to cpu count though only needed for go versions < 1.5
runtime.GOMAXPROCS(runtime.NumCPU())
// determine home directory
var userHome string
if runtime.GOOS == "windows" {
userHome = os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if userHome == "" {
userHome = os.Getenv("USERPROFILE")
}
} else {
userHome = os.Getenv("HOME")
}
// create paths
homePath := filepath.Join(userHome, ".simplewebwatcher")
configPath := filepath.Join(homePath, "config")
logPath := filepath.Join(homePath, "log")
// create application home directory, if not exists
if err := os.MkdirAll(homePath, 0700); err != nil {
return err
}
// chdir to the application home path
if err := os.Chdir(homePath); err != nil {
return err
}
{
logFile, err := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0700)
if err != nil {
log.Fatal("error opening file:", err)
}
defer logFile.Close()
log.SetOutput(io.MultiWriter(logFile, os.Stdout))
}
// check if Working Directory is valid
{
cwd, err := os.Getwd()
if err != nil {
return err
}
if cwd != homePath {
if err := errors.New("wrong pwd"); err != nil {
return err
}
}
}
// check if config exists
{
if _, err := os.Stat(configPath); os.IsNotExist(err) {
// no config found - crete new default config and exit
log.Println("config not found, creating new default config at", configPath)
configFile, err := os.Create(configPath)
if err != nil {
return err
}
defer configFile.Close()
if err := config.WriteConfig(config.NewDefaultConfig(), configFile); err != nil {
return err
}
log.Println("default config created - please edit")
return nil
}
}
// variable for config
var safeConfig *config.ThreadSafeConfigWrapper
// read config
{
log.Println("reading config from", configPath)
configFile, err := os.Open(configPath)
if err != nil {
return err
}
defer configFile.Close()
configBytes, err := ioutil.ReadAll(configFile)
if err != nil {
return err
}
tmpConfig, err := config.ReadConfig(string(configBytes))
if err != nil {
return err
}
// create and initialize new threadsafeconfig
safeConfig = new(config.ThreadSafeConfigWrapper)
safeConfig.Set(*tmpConfig)
}
app := cli.NewApp()
app.Name = "simplewebwatcher"
app.Usage = "adsf"
app.Version = "0.0.1"
// flags TODO: Allow user to specify config location - what about the application directory?
//app.Flags = []cli.Flag{
// cli.StringFlag{
// Name: "config, c",
// Value: "",
// },
//}
// commands TODO: add daemon mode?
app.Commands = []cli.Command{
{
// mode to use for cronjobs
Name: "cron",
Usage: "query all pages once, then quit",
Action: func(c *cli.Context) {
if err := func() error {
// create sync waitgroup
waitGroup := new(sync.WaitGroup)
// iterate through configured sites and spawn a gouroutine for each one
for i := range safeConfig.Get().Site {
waitGroup.Add(1)
go doCheck(safeConfig, i, waitGroup, homePath)
}
// wait for all checks to finish
waitGroup.Wait()
// write new configuration
{
configFile, err := os.OpenFile(configPath, os.O_RDWR, 0700)
defer configFile.Close()
if err != nil {
return err
}
newConf := safeConfig.Get()
log.Println("updating config file")
if err := config.WriteConfig(&newConf, configFile); err != nil {
return err
}
}
return nil
}(); err != nil {
log.Fatalln("ERROR:", err)
}
},
},
}
return app.Run(os.Args)
}
func doCheck(safeConfig *config.ThreadSafeConfigWrapper, pos int, wg *sync.WaitGroup, dir string) {
defer wg.Done()
// copy site config
siteConfig := safeConfig.Get().Site[pos]
// create new http client
webClient := &http.Client{}
// configure request
req, err := http.NewRequest("GET", siteConfig.URL, nil)
if err != nil {
log.Println(err)
return
}
// if set, configure http basic auth
if siteConfig.Password != "" && len(siteConfig.Password) > 0 && siteConfig.Username != "" && len(siteConfig.Username) > 0 {
req.SetBasicAuth(siteConfig.Username, siteConfig.Password)
}
// execute request
resp, err := webClient.Do(req)
if err != nil {
log.Println(err)
moptions := mack.AlertOptions{
Title: siteConfig.Description,
Message: "simplewebwatcher had a problem checking " + siteConfig.URL + ":\n" + err.Error(),
Style: "informational",
Buttons: "Open",
DefaultButton: "Open",
Duration: 0,
}
if _, err = mack.AlertBox(moptions); err != nil {
log.Println(err)
return
}
return
}
defer resp.Body.Close()
// read body and determine size
body, err := ioutil.ReadAll(resp.Body)
size := binary.Size(body)
// determine sha1 hash
var hash string
{
hasher := sha1.New()
_, err := hasher.Write(body)
if err != nil {
log.Println(err)
return
}
hash = hex.EncodeToString(hasher.Sum(nil))
}
// compare size and hash to stored data
if size != siteConfig.LastBytes || hash != siteConfig.LastHash {
// announce match
log.Println(siteConfig.Description, " | ", siteConfig.LastBytes, "->", size, " | ", siteConfig.LastHash, "->", hash, " | ", "change detected")
// set options for alert, and execute it - OSX ONLY
moptions := mack.AlertOptions{
Title: siteConfig.Description,
Message: "simplewebwatcher noticed a change on " + siteConfig.URL,
Style: "informational",
Buttons: "Open",
DefaultButton: "Open",
Duration: 0,
}
if _, err = mack.AlertBox(moptions); err != nil {
log.Println(err)
return
}
// open site in browser
open.Run(siteConfig.URL)
// update current site config
siteConfig.LastBytes = size
siteConfig.LastHash = hash
siteConfig.LastCheck = time.Now()
// write new site config to safe config
safeConfig.SetSite(pos, siteConfig)
} else {
// announce mismatch
log.Println(siteConfig.Description, " | ", siteConfig.LastBytes, "->", size, " | ", siteConfig.LastHash, "->", hash, " | ", "no change detected")
}
}