-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
96 lines (75 loc) · 2.11 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
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"golang.org/x/oauth2"
)
var (
configfilepath = flag.String("c", "./config.yaml", "pge config file path")
)
func main() {
flag.Parse()
config, err := readConfig(*configfilepath)
if err != nil {
log.Fatal(err)
}
service:
srv, err := NewGmailService(config.CredentialFile, config.TokenFile, config.Query)
if err == ErrCredentialFileExists {
setupCredential()
} else if err == ErrTokenFileExists {
setUpToken(srv.config, srv.tokenFile)
goto service
} else if err != nil {
log.Fatal(err)
}
run(srv, config)
}
func readConfig(configfilepath string) (config *GstpConfig, err error) {
cdata, err := ReadFile(configfilepath)
if err != nil {
return config, err
}
config, err = UnMarshallConfig(cdata)
if err != nil {
return config, err
}
return config, nil
}
func setupCredential() {
fmt.Println("error:")
fmt.Println("\tcredential.json file not found")
fmt.Println("\tGo to the Google Developers API Console: https://console.developers.google.com/apis/credentials")
fmt.Println("\tand download credential json file in this directory.")
os.Exit(1)
}
func setUpToken(config *oauth2.Config, tokenPath string) {
var code string
fmt.Println()
fmt.Println("1. Sign in to your browser with the gmail account you want to track")
fmt.Println()
fmt.Println("2. Open the following link and authorise gmail account:")
fmt.Println(config.AuthCodeURL("pge", oauth2.AccessTypeOffline))
fmt.Println()
fmt.Println("3. Enter the authorisation code:")
if _, err := fmt.Scan(&code); err != nil {
log.Printf("Failed to read authorisation code: %v\n", err)
}
fmt.Println()
token, err := config.Exchange(context.Background(), code)
if err != nil {
log.Printf("Failed to exchange authorisation code for token: %v\n", err)
}
tokenFile, err := os.OpenFile(tokenPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Printf("Failed to open token file for writing: %v\n", err)
}
defer tokenFile.Close()
if err := json.NewEncoder(tokenFile).Encode(token); err != nil {
log.Printf("Failed to write token: %v\n", err)
}
}