/
g0.go
175 lines (147 loc) · 4.35 KB
/
g0.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
// Copyright (C) 2019 rameshvk. All rights reserved.
// Use of this source code is governed by a MIT-style license
// that can be found in the LICENSE file.
// Package g0 implements a simple gmail library for zero-inbox people.
package g0
import (
"encoding/base64"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/gmail/v1"
"google.golang.org/api/option"
"github.com/pkg/browser"
"github.com/tvastar/g0/digest"
)
// Digests returns the digests of all unread inbox messages
func Digests(configFile, tokenFile, localPort string) ([]string, error) {
srv, err := getService(configFile, tokenFile, localPort)
if err != nil {
return nil, err
}
user := "me"
r, err := srv.Users.Messages.List(user).Q("in:inbox is:unread").Do()
if err != nil {
return nil, err
}
results := []string{}
opt := digest.Options{
LineLimit: 10,
ColLimit: 80,
OmitLinks: true,
}
for _, m := range r.Messages {
mm, err := srv.Users.Messages.Get(user, m.Id).Format("RAW").Do()
if err != nil {
return nil, err
}
decoded, err := base64.URLEncoding.DecodeString(mm.Raw)
if err != nil {
return nil, err
}
digested, err := digest.Message(string(decoded), opt)
if err != nil {
return nil, err
}
results = append(results, digested)
}
return results, nil
}
// MarkRead marks all unread inbox messages as read
func MarkRead(configFile, tokenFile, localPort string) error {
srv, err := getService(configFile, tokenFile, localPort)
if err != nil {
return err
}
user := "me"
r, err := srv.Users.Messages.List(user).Q("in:inbox is:unread").Do()
if err != nil {
return err
}
req := &gmail.BatchModifyMessagesRequest{RemoveLabelIds: []string{"UNREAD"}}
for _, m := range r.Messages {
req.Ids = append(req.Ids, m.Id)
}
if len(req.Ids) > 0 {
return srv.Users.Messages.BatchModify(user, req).Do()
}
return nil
}
func getService(configFile, tokenFile, localPort string) (*gmail.Service, error) {
toksrc, err := getClientToken(configFile, tokenFile, localPort)
if err != nil {
return nil, err
}
opt1 := option.WithScopes(gmail.GmailReadonlyScope, gmail.GmailModifyScope)
opt2 := option.WithTokenSource(toksrc)
return gmail.NewService(context.Background(), opt1, opt2)
}
func getClientToken(configFile, tokenFile, localPort string) (oauth2.TokenSource, error) {
var config *oauth2.Config
bytes, err := ioutil.ReadFile(configFile) // nolint
if err == nil {
config, err = google.ConfigFromJSON(bytes, gmail.GmailReadonlyScope, gmail.GmailModifyScope)
}
if err != nil {
return nil, err
}
ctx := context.Background()
tok := &oauth2.Token{}
if bytes, err = ioutil.ReadFile(tokenFile); err == nil { // nolint
err = json.NewDecoder(strings.NewReader(string(bytes))).Decode(tok)
} else {
config.RedirectURL = "http://localhost" + localPort
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
tok, err = config.Exchange(ctx, getAuthCode(authURL, localPort))
if err == nil {
saveTokenFile(tokenFile, tok)
}
}
return config.TokenSource(ctx, tok), err
}
func saveTokenFile(path string, token *oauth2.Token) {
log.Printf("Saving credential file to: %s\n", path)
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
must(err)
if err == nil {
must(json.NewEncoder(f).Encode(token))
must(f.Close())
}
}
type statusCodeHandler chan string
func (s statusCodeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
if code != "" {
s <- code
}
}
func getAuthCode(url, localPort string) string {
ch := make(chan string, 1)
srv := &http.Server{Addr: localPort, Handler: statusCodeHandler(ch)}
go func() {
// returns ErrServerClosed on graceful close
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
// NOTE: there is a chance that next line won't have time to run,
// as main() doesn't wait for this goroutine to stop. don't use
// code with race conditions like these for production. see post
// comments below on more discussion on how to handle this.
log.Fatalf("ListenAndServe(): %s", err)
}
}()
defer func() { must(srv.Shutdown(context.Background())) }()
if err := browser.OpenURL(url); err != nil {
log.Fatalf("Unable to open browser: %v", err)
}
return <-ch
}
func must(err error) {
if err != nil {
log.Println(err)
}
}