-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
233 lines (197 loc) · 5.49 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
package main
import (
"context"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
"time"
"github.com/ghodss/yaml"
"golang.org/x/oauth2/google"
"google.golang.org/api/gmail/v1"
"google.golang.org/api/option"
)
// TODO: Error handling
// TODO: Writing logs to a file
// TODO: Add readme file
// How to run it
// How to build it
// Hot to operate it
type Info struct {
Email string `yaml:"email"`
Path string `yaml:"path"`
}
type Config struct {
Name string `yaml:"name"`
NotifierEmail string `yaml:"notifierEmail"`
Checks []Info `yaml:"checks"`
}
func (k Config) getPath(from string) string {
for _, kk := range k.Checks {
if kk.Email == from {
return kk.Path
}
}
return ""
}
func main() {
f, err := os.OpenFile("cad-creation-automation.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
wrt := io.MultiWriter(os.Stdout, f)
log.SetOutput(wrt)
configData, err := os.ReadFile("config.yaml")
if err != nil {
log.Println("Failed to read config file")
return
}
var c Config
err = yaml.Unmarshal(configData, &c)
if err != nil {
log.Printf("err: %v\n", err)
return
}
log.Println("Starting the process", time.Now().Local().String(), c.Name)
ctx := context.Background()
b, err := ioutil.ReadFile("credentials.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
return
}
// If modifying these scopes, delete your previously saved token.json.
config, err := google.ConfigFromJSON(b, gmail.GmailModifyScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
return
}
checkMailClient := getClient(config, "checkMailClientToken")
srv, err := gmail.NewService(ctx, option.WithHTTPClient(checkMailClient))
if err != nil {
log.Fatalf("Unable to retrieve Gmail client: %v", err)
return
}
llist, err := srv.Users.Labels.List("me").Do()
if err != nil {
log.Println("failed to list label", err)
return
}
cadCreationLabelID := ""
for _, label := range llist.Labels {
if label.Name == "cad-creation-automation" {
cadCreationLabelID = label.Id
}
}
if cadCreationLabelID == "" {
res, err := srv.Users.Labels.Create("me", &gmail.Label{Name: "cad-creation-automation"}).Do()
if err != nil {
log.Println("failed to create label", err)
return
}
cadCreationLabelID = res.Id
}
fromClause := ""
for _, cc := range c.Checks {
fromClause += cc.Email + " OR "
}
fromClause = strings.TrimSuffix(fromClause, " OR ")
tick := time.NewTicker(30 * time.Second)
defer tick.Stop()
profile, err := srv.Users.GetProfile("me").Do()
if err != nil {
log.Println("cannot get profile", err)
return
}
log.Println("email address is ", profile.EmailAddress)
query := fmt.Sprintf("from:(%s),label:(inbox,-cad-creation-automation),newer_than:2d", fromClause)
log.Println("query", query)
for range tick.C {
// process 2 days message
req := srv.Users.Messages.List("me").Q(query)
// if pageToken != "" {
// req.PageToken(pageToken)
// }
req.MaxResults(50)
r, err := req.Do()
if err != nil {
log.Printf("Unable to retrieve messages: %v\n", err)
continue
}
log.Println()
log.Printf("Processing %v messages...\n", len(r.Messages))
for _, m := range r.Messages {
msg, err := srv.Users.Messages.Get("me", m.Id).Do()
if err != nil {
log.Printf("Unable to retrieve message %v: %v\n", m.Id, err)
log.Println("One attachement is being skipped")
continue
}
from := ""
date := ""
subject := ""
for _, h := range msg.Payload.Headers {
if h.Name == "Date" {
date = h.Value
}
if h.Name == "Subject" {
subject = h.Value
}
if h.Name == "From" {
from = strings.Split(strings.TrimSuffix(h.Value, ">"), "<")[1]
}
}
log.Printf("Processing email from <%s> having subject <%s> on date <%s>\n", from, subject, date)
for _, part := range msg.Payload.Parts {
if part.MimeType == "application/octet-stream" {
attachmentID := part.Body.AttachmentId
res, err := srv.Users.Messages.Attachments.Get("me", msg.Id, attachmentID).Do()
if err != nil {
log.Println("failed to download attachement", err)
continue
}
data, err := base64.URLEncoding.DecodeString(res.Data)
if err != nil {
log.Println("error decoding body data", err)
continue
}
tm := time.Unix(msg.InternalDate/1000, 0)
year, month, day := tm.Date()
stringdate := fmt.Sprintf("%v-%v-%v", day, month, year)
fullPath := c.getPath(from) + "/" + stringdate
_, err = os.Stat(fullPath)
if os.IsNotExist(err) {
err = os.MkdirAll(fullPath, 0755)
if err != nil {
log.Println("cannot create directory", err)
continue
}
}
fileName := fmt.Sprintf("%s/%s", fullPath, part.Filename)
// // If the file doesn't exist, create it, or append to the file
f, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Println("failed to open file", err)
continue
}
_, err = f.Write([]byte(data))
if err != nil {
log.Println("failed to write data into file", err)
continue
}
f.Close()
}
}
_, err = srv.Users.Messages.Modify("me", msg.Id, &gmail.ModifyMessageRequest{AddLabelIds: []string{cadCreationLabelID}}).Do()
if err != nil {
log.Println("failed to modify message", err)
continue
}
}
log.Println("Checking USB")
detectusb(c.Name, profile.EmailAddress, c.NotifierEmail, srv)
}
}