-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
117 lines (100 loc) · 2.31 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
package main
import (
"fmt"
"os"
"os/exec"
"strconv"
"time"
"github.com/sclevine/agouti"
)
func main() {
poll()
}
func poll() {
interval := time.Duration(getEnv("VANGUARD_INTERVAL", 10)) * time.Second
driver := agouti.ChromeDriver(
agouti.ChromeOptions(
"args", []string{
"--headless",
"--disable-gpu",
},
),
)
if err := driver.Start(); err != nil {
panic(err)
}
page, err := driver.NewPage()
if err != nil {
panic(err)
}
login(page)
for {
fmt.Println("Vanguard.....")
percentChanged, err := getPercentageChange(page)
if err != nil {
panic(err)
}
totalValue, err := getTotalValue(page)
if err != nil {
panic(err)
}
fmt.Printf("Current value: %s, Percent change: %s", totalValue, percentChanged)
page.Refresh()
time.Sleep(interval)
clearScreen()
}
driver.Stop()
}
func clearScreen() {
cmd := exec.Command("clear")
cmd.Stdout = os.Stdout
cmd.Run()
}
func login(page *agouti.Page) {
vanguardUser := os.Getenv("VANGUARD_USERNAME")
vanguardPassword := os.Getenv("VANGUARD_PASSWORD")
if err := page.Navigate("https://secure.vanguardinvestor.co.uk/Login"); err != nil {
panic(err)
}
const userInputId = "#__GUID_1006"
const passwordInputId = "#__GUID_1007"
const loginButtonClass = "button.btn-primary"
userInput := page.Find(userInputId)
passwordInput := page.Find(passwordInputId)
userInput.Fill(vanguardUser)
passwordInput.Fill(vanguardPassword)
loginBtn := page.Find(loginButtonClass)
loginBtn.Click()
}
func getPercentageChange(page *agouti.Page) (string, error) {
return getText(page, "span.value-l")
}
func getTotalValue(page *agouti.Page) (string, error) {
return getText(page, "div.value")
}
func getText(page *agouti.Page, textToFind string) (string, error) {
maxAttempts := getEnv("VANGUARD_MAX_ATTEMPTS", 20)
attempts := 0
waitTime := time.Duration(getEnv("VANGUARD_WAIT_TIME", 1)) * time.Second
for {
found, _ := page.Find(textToFind).Text()
if len(found) > 0 {
return found, nil
}
if attempts == maxAttempts {
return "", fmt.Errorf("Max attempts exceed. Cannot find %q", textToFind)
}
time.Sleep(waitTime)
attempts += 1
}
}
func getEnv(key string, fallback int) int {
if value, ok := os.LookupEnv(key); ok {
intVal, err := strconv.Atoi(value)
if err != nil {
return fallback
}
return intVal
}
return fallback
}