-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
338 lines (288 loc) · 7.81 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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package main
import (
"clerk_trades/clerk"
"clerk_trades/email"
"clerk_trades/gemini"
"clerk_trades/utils"
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
func usage(code int) {
fmt.Printf(`CLERK TRADES - U.S. Government Official Financial Report Tracker
Usage: %s [<ticker_duration> | <list>] [OPTIONS]
Arguments:
ticker_duration Duration for the application ticker to check for new
reports on Clerk website. Minimum 3h (e.g. 24h, 72h).
Only accepts 'h' for hours before the integer.
If not specified, it will not check for new reports.
list Specify the number of reports to list their trades.
(type=int). This argument must be betweengreater than
0 but less that 6.
If used, the program will exit after printing.
Note: Only one of these two arguments may be provided at a time.
OPTIONS:
-n, --name <name> List reports of a specific individual.
-e, --email Enable email notifications for trade results via Mailgun.
Configure settings in 'gunmail.config' to activate.
--log Save logs to file.
-v, --verbose Enable verbose output for detailed logging and information.
-h, --help Display this help menu.
`, os.Args[0])
os.Exit(code)
}
var (
verbose bool
mail bool
name string
)
func main() {
var update time.Duration
var listReports int
for i := 1; i < len(os.Args); i++ {
arg := os.Args[i]
switch {
case arg == "-h" || arg == "--help" || arg == "help":
usage(0)
case arg == "-v" || arg == "--verbose" || arg == "verbose":
verbose = true
case arg == "--log":
logName := time.Now().Format("01021504") + ".log"
logFile, err := os.Create(logName)
if err != nil {
log.Fatalf("could not create logfile %q: %v", logFile.Name(), err)
}
log.SetOutput(io.MultiWriter(os.Stderr, logFile))
log.Printf("successfully created logfile %q.\n", logFile.Name())
case arg == "-e" || arg == "--email" || arg == "email":
log.Printf("loading Mailgun settings..")
err := email.LoadMailGun()
if err != nil {
log.Fatalln(err)
}
mail = true
log.Printf("results will be sent to %v\n", email.Mailgun.EmailTo)
case strings.HasPrefix(arg, "-n") || strings.HasPrefix(arg, "--name"):
if strings.Contains(arg, "=") {
name = strings.SplitN(arg, "=", 2)[1]
} else if i+1 < len(os.Args) && !strings.HasPrefix(os.Args[i+1], "-") {
name = os.Args[i+1]
i++
} else {
log.Fatalln("error: -n flag requires a name.")
}
default:
if n, err := strconv.Atoi(arg); err == nil && n > 0 && n < 6 {
listReports = n
} else if duration, err := parseCustomDuration(arg); err == nil {
if duration < 3*time.Hour {
log.Fatalln("error: minimum duration must be 3h.")
}
update = duration
} else {
if name != "" {
continue
}
log.Fatalln("error: invalid argument:", arg)
}
}
}
if name != "" {
update = time.Duration(24 * time.Hour)
listReports = 0
if err := copyFile(clerk.FILE_LINKS, clerk.FILE_BACKUP); err != nil {
log.Println("error copying file:", err)
}
if err := os.Remove(clerk.FILE_LINKS); err != nil {
log.Println("error removing file:", err)
}
go HandleInterrupt()
}
if update == 0 && (listReports > 5 || listReports <= 0) || update != 0 && listReports != 0 {
usage(1)
}
if verbose {
log.Println("verbose is active.")
gemini.SetVerbose(true)
clerk.SetVerbose(true)
}
if update != 0 {
log.Printf("ticker scheduled to check for new reports every %s.\n", fmt.Sprintf("%.0fh", update.Hours()))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ticker := time.NewTicker(update)
defer ticker.Stop()
go func() {
for {
select {
case <-ctx.Done():
if verbose {
log.Println("ticker stopped.")
}
return
case <-ticker.C:
if err := checkReports(update, listReports, name); err != nil {
log.Println("error:", err)
}
}
}
}()
}
if err := checkReports(update, listReports, name); err != nil {
log.Println("error:", err)
}
if update == 0 {
if verbose {
log.Println("ticker is disabled. program exit.")
}
return
}
select {}
}
func checkReports(update time.Duration, listReports int, name string) error {
var err error
var files []string
var links []string
var loop bool
links, _ = utils.ReadJSON[[]string](clerk.FILE_LINKS)
if verbose {
log.Printf("loaded %d reports.\n", len(links))
}
if update != 0 {
if name != "" {
log.Printf("checking for new reports of %s.\n", name)
} else {
log.Println("checking for new reports.")
}
files, err, loop = clerk.SiteCheck(links, name)
if err != nil {
return err
}
} else {
if len(links) == 0 {
log.Fatalln("no report links stored. run program with updater first, to links from clerk site.")
}
files = links
if listReports > 0 {
if len(files)-1 >= listReports {
files = files[len(files)-listReports:] // Keep only the last listReports files
}
}
}
if len(files) > 0 {
log.Printf("allocating space for %d reports in memory.\n", len(files))
}
var fileContent [][]byte
var wg sync.WaitGroup
var mu sync.Mutex
for _, file := range files {
wg.Add(1)
go func(file string) {
defer wg.Done()
content, err := fetchFileContent(file)
if err != nil {
log.Printf("failed to fetch content for report %s: %v\n", file, err)
return
}
mu.Lock()
fileContent = append(fileContent, content)
mu.Unlock()
}(file)
}
wg.Wait()
if len(fileContent) == 0 {
log.Println("nothing new to process.")
return err
}
// Process reports
trades, err := gemini.ProsessReports(fileContent, files)
if err != nil {
return err
}
if mail {
emailBody, err := email.GenerateEmailBody(trades)
if err != nil {
return err
}
if email.Mailgun.Paid {
if err := email.SendHTMLToMailingList(emailBody); err != nil {
return err
}
} else {
if err := email.SendHTMLTo(emailBody); err != nil {
return err
}
}
if verbose {
log.Println("trade reports have been e-mailed.")
}
}
if loop {
defer func() {
go checkReports(update, listReports, name)
}()
}
return nil
}
func fetchFileContent(link string) ([]byte, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", link, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.5938.62 Safari/537.36")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch file: %s", resp.Status)
}
return io.ReadAll(resp.Body)
}
func parseCustomDuration(input string) (time.Duration, error) {
if strings.HasSuffix(input, "h") {
hours := strings.TrimSuffix(input, "h")
if n, err := strconv.Atoi(hours); err == nil {
return time.Duration(n) * time.Hour, nil
}
}
return 0, fmt.Errorf("invalid duration format; only hours (h) are accepted")
}
func HandleInterrupt() {
closeChan := make(chan os.Signal, 1)
signal.Notify(closeChan, os.Interrupt, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
s := <-closeChan
log.Printf("\n%+v recived. shutting down.\n", s)
if err := copyFile(clerk.FILE_BACKUP, clerk.FILE_LINKS); err != nil {
log.Println("error copying file:", err)
}
if err := os.Remove(clerk.FILE_BACKUP); err != nil {
log.Println("error removing file:", err)
}
os.Exit(0)
}
func copyFile(src, dst string) error {
sourceFile, err := os.Open(src)
if err != nil {
return err
}
defer sourceFile.Close()
destFile, err := os.Create(dst)
if err != nil {
return err
}
defer destFile.Close()
_, err = io.Copy(destFile, sourceFile)
return err
}