-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
286 lines (252 loc) · 6.64 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
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"regexp"
"runtime"
"strings"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/gmail/v1"
)
type Configuration struct {
SteamCmdPath string `json:"steamcmd_path"`
}
func getTokenFromCache() (*oauth2.Token, error) {
tokenFile := "token.json"
token, err := ioutil.ReadFile(tokenFile)
if err != nil {
return nil, err
}
tk := &oauth2.Token{}
err = json.Unmarshal(token, tk)
if err != nil {
return nil, err
}
return tk, nil
}
func openBrowser(url string) error {
var cmd string
var args []string
switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start", ""}
case "darwin":
cmd = "open"
default:
cmd = "xdg-open"
}
if runtime.GOOS == "windows" {
args = append(args, "\""+url+"\"")
} else {
args = append(args, url)
}
return exec.Command(cmd, args...).Start()
}
func getTokenFromWeb(config *oauth2.Config) (*oauth2.Token, error) {
// Generate OAuth2 URL and open it in the default web browser
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Println("Your browser has been opened to visit:", authURL)
err := openBrowser(authURL)
if err != nil {
log.Fatalf("Failed to open web browser: %s", err)
}
// Start a local HTTP server to listen for the OAuth2 callback
listen := "localhost:80"
fmt.Printf("Listening on http://%s/\n", listen)
codeCh := make(chan string)
go func() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
if code == "" {
http.Error(w, "Missing code", http.StatusBadRequest)
return
}
codeCh <- code
})
http.ListenAndServe(listen, nil)
}()
// Wait for the authorization code
code := <-codeCh
token, err := config.Exchange(context.Background(), code)
if err != nil {
return nil, err
}
return token, nil
}
func saveTokenToCache(token *oauth2.Token) {
tokenFile := "token.json"
tokenJSON, err := json.Marshal(token)
if err != nil {
log.Fatalf("Unable to marshal token: %v", err)
}
os.WriteFile(tokenFile, tokenJSON, 0600)
}
func getClient() (*gmail.Service, error) {
b, err := os.ReadFile("credentials.json")
if err != nil {
return nil, err
}
config, err := google.ConfigFromJSON(b, gmail.GmailReadonlyScope)
if err != nil {
return nil, err
}
token, err := getTokenFromCache()
if err != nil {
token, err = getTokenFromWeb(config)
if err != nil {
return nil, err
}
saveTokenToCache(token)
}
client := config.Client(context.Background(), token)
srv, err := gmail.New(client)
if err != nil {
return nil, err
}
return srv, nil
}
func readConfig() Configuration {
configFile, err := os.Open("config.json")
if err != nil {
if os.IsNotExist(err) {
// Create a default config.json file if it doesn't exist
defaultConfig := Configuration{
SteamCmdPath: "./steamcmd/steamcmd.exe",
}
err := createDefaultConfigFile(defaultConfig)
if err != nil {
log.Fatalf("Error creating default config file: %v", err)
}
return defaultConfig
}
log.Fatalf("Error opening config file: %v", err)
}
defer configFile.Close()
decoder := json.NewDecoder(configFile)
config := Configuration{}
err = decoder.Decode(&config)
if err != nil {
log.Fatalf("Error decoding config file: %v", err)
}
return config
}
func createDefaultConfigFile(config Configuration) error {
configFile, err := os.Create("config.json")
if err != nil {
return err
}
defer configFile.Close()
encoder := json.NewEncoder(configFile)
encoder.SetIndent("", " ")
err = encoder.Encode(config)
if err != nil {
return err
}
return nil
}
func fetchSteamGuardCode(srv *gmail.Service) string {
user := "me"
query := "from:[email protected] is:unread"
messages, err := srv.Users.Messages.List(user).Q(query).Do()
if err != nil {
log.Fatal(err)
}
if len(messages.Messages) == 0 {
return ""
}
msg, err := srv.Users.Messages.Get(user, messages.Messages[0].Id).Do()
if err != nil {
log.Fatal(err)
}
for _, part := range msg.Payload.Parts {
data, err := base64.URLEncoding.DecodeString(part.Body.Data)
if err != nil {
log.Fatal(err)
}
regex := regexp.MustCompile(`Login Code\s*([A-Za-z0-9]+)`)
match := regex.FindStringSubmatch(string(data))
if len(match) > 1 {
return match[1]
}
}
return ""
}
func checkForSteamGuardInLogs(stdout, stderr *bytes.Buffer) bool {
return strings.Contains(stdout.String(), "This computer has not been authenticated for your account using Steam Guard") || strings.Contains(stderr.String(), "This computer has not been authenticated for your account using Steam Guard")
}
func main() {
config := readConfig()
srv, err := getClient()
if err != nil {
log.Fatalf("Unable to create Gmail client: %v", err)
}
args := os.Args[1:]
// Check if +quit is already present and remove it if it is as we add it later
quitIndex := -1
for i, arg := range args {
if arg == "+quit" {
quitIndex = i
break
}
}
if quitIndex != -1 {
args = append(args[:quitIndex], args[quitIndex+1:]...)
}
for {
var stderr, stdout bytes.Buffer // Buffers to capture stderr and stdout
cmd := exec.Command(config.SteamCmdPath)
cmd.Args = append(cmd.Args, args...)
cmd.Args = append(cmd.Args, "+quit") // Add +quit to the end of the arguments to make sure SteamCmd quits after running the given arguments, must always be the very last argument
fmt.Println("Running SteamCmd with given arguments: ", cmd.Args)
// Use MultiWriter to write to both stdout and the buffer
cmd.Stdout = io.MultiWriter(os.Stdout, &stdout)
cmd.Stderr = io.MultiWriter(os.Stderr, &stderr)
err := cmd.Run()
if err != nil {
if checkForSteamGuardInLogs(&stdout, &stderr) {
fmt.Println("Steam Guard code required. Fetching...")
for i := 0; i < 12; i++ {
code := fetchSteamGuardCode(srv)
if code != "" {
fmt.Printf("Fetched Steam Guard code: %s\n", code)
// Check if +set_steam_guard_code is already present
steamGuardIndex := -1
for i, arg := range args {
if arg == "+set_steam_guard_code" {
steamGuardIndex = i
}
}
// Append the Steam Guard code to the arguments or update it
if steamGuardIndex != -1 {
args[steamGuardIndex+1] = code
} else {
args = append(args, "+set_steam_guard_code", code)
}
break
} else {
fmt.Println("No Steam Guard code found. Waiting 10 seconds...")
}
time.Sleep(10 * time.Second)
}
} else {
fmt.Println("Error running SteamCmd:", err)
return
}
} else {
fmt.Println("Successfully run SteamCmd with given arguments.")
return
}
}
}