/
google.go
500 lines (440 loc) · 15.7 KB
/
google.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package calendar
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/user"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/skratchdot/open-golang/open"
// "github.com/skratchdot/open-golang/open"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
calendar "google.golang.org/api/calendar/v3"
)
const googleCalendarDateTimeFormat = time.RFC3339
// https://www.google.com/url?q=https://teams.microsoft.com/l/meetup-join/19%253ameeting_MTU0YzY5MTgtNDZjNy00MjM4LTg5MzYtYTgxZDk0MzJjYzAx%2540thread.v2/0?context%3D%257b%2522Tid%2522%253a%2522e0793d39-0939-496d-b129-198edd916feb%2522%252c%2522Oid%2522%253a%25225a399f46-82c6-4606-84bf-a154d4b60548%2522%257d&sa=D&source=calendar&ust=1600608611212000&usg=AOvVaw2TYDQ2tagscOoJNxkpzKRw
// https://zoom.us/j/8415370125?pwd=V0FCaURjRU5GVW5pd0lKak0yTUd5Zz09
var zoomURLRegexp = regexp.MustCompile(`https://.*?zoom\.us/(?:j/(\d+)|my/(\S+))`)
var teamsURLRegexp = regexp.MustCompile(`https://.*?teams.microsoft.com/.*`)
var webexURLRegexp = regexp.MustCompile(`https://.*?webex.com/.*j.php?.*>`)
var zoomURLRegexpPwd = regexp.MustCompile(`https://.*?zoom\.us/j/.*pwd=(\S+)`)
var discordURLRegexp = regexp.MustCompile(`https://discord.com/channels.*`)
// var zoomDescriptionRegexpPwd = regexp.MustCompile(`Password: (.*)</span>`)
// var zoomDescriptionRegexpJustPwd = regexp.MustCompile(`Password: (.*)`)
// GoogleCal - Structure to hold stuff
type GoogleCal struct {
Provider string
Client *http.Client
AuthURL string
}
// GetAuthURL - Return the AuthURL
func (p *GoogleCal) GetAuthURL() string {
return p.AuthURL
}
// GetToken - Get Oauth 2.0 Token
func (p *GoogleCal) GetToken() (*oauth2.Token, error) {
usr, err := user.Current()
if err != nil {
fmt.Println("No current user")
os.Exit(1)
}
directory := filepath.Join(usr.HomeDir, ".config", "google", "no-more-lateness.json")
config, err := readGoogleClientConfigFromFile(directory)
if err != nil && err.Error() != "oauth2/google: no credentials found" {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Your browser is about to open. When it does, please authorize the application when prompted and paste the token it gives you below.")
time.Sleep(5 * time.Second)
open.Run(p.AuthURL)
fmt.Print("Authorization token: ")
var authCode string
if _, err := fmt.Scan(&authCode); err != nil {
return &oauth2.Token{}, errors.WithStack(err)
}
tok, err := config.Exchange(context.TODO(), authCode)
if err != nil {
return &oauth2.Token{}, err
// log.Fatalf("Unable to retrieve token from web: %v", err)
}
return tok, nil
}
// GetClient - Apply DNS updates to Google DNS Hosted Zone
func (p *GoogleCal) GetClient() (bool, error) {
usr, err := user.Current()
if err != nil {
fmt.Println("No current user")
os.Exit(1)
}
directory := filepath.Join(usr.HomeDir, ".config", "google", "no-more-lateness.json")
config, err := readGoogleClientConfigFromFile(directory)
if err != nil && err.Error() != "oauth2/google: no credentials found" {
fmt.Println(err)
os.Exit(1)
}
client := getClient(config)
p.AuthURL = config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
p.Client = client
return true, nil
}
// GetEvents - Return the next num events
func (p *GoogleCal) GetEvents(num int64, attendee string) ([]MeetingEvent, error) {
eventList := []MeetingEvent{}
// ********* Use the client to do things... ****************
srv, err := calendar.New(p.Client)
if err != nil {
log.Fatalf("Unable to retrieve Calendar client: %v", err)
}
t := time.Now().Add(time.Hour * -1).Format(time.RFC3339)
events, err := srv.Events.List("primary").ShowDeleted(false).
SingleEvents(true).TimeMin(t).MaxResults(num).OrderBy("startTime").Do()
if err != nil {
log.Fatalf("Unable to retrieve next ten of the user's events: %v", err)
}
// fmt.Println("Upcoming events:")
if len(events.Items) == 0 {
fmt.Println("No upcoming events found.")
} else {
for _, item := range events.Items {
// fmt.Printf("%s\n", item.Summary)
date := item.Start.DateTime
if date == "" {
date = item.Start.Date
}
url, ok := MeetingURLFromEvent(item)
if !ok {
// do we care?
} else {
soon := IsMeetingSoon(item)
mtgResponse := ""
// _ = open.Run(url.String())
// fmt.Printf("%v,(%v),<%s>\n", item.Summary, date, url)
for _, att := range item.Attendees {
if att.Email == attendee {
mtgResponse = att.ResponseStatus
if att.ResponseStatus == "declined" {
soon = false
}
}
}
startTime, err := MeetingStartTime(item)
if err != nil {
// no action needed
} else {
eventList = append(eventList, MeetingEvent{
Description: item.Summary,
Start: startTime,
MeetingProvider: "No Need",
MeetingLink: *url,
IsMeetingSoon: soon,
MeetingResponse: mtgResponse,
})
}
}
}
}
return eventList, nil
}
// IsMeetingSoon returns true if the meeting is less than 5 minutes from now.
func IsMeetingSoon(event *calendar.Event) bool {
startTime, err := MeetingStartTime(event)
if err != nil {
return false
}
minutesUntilStart := time.Until(startTime).Minutes()
return -8 < minutesUntilStart && minutesUntilStart < 3
}
// MeetingStartTime returns the calendar event's start time.
func MeetingStartTime(event *calendar.Event) (time.Time, error) {
if event == nil || event.Start == nil || event.Start.DateTime == "" {
return time.Time{}, errors.New("event does not have a start datetime")
}
return time.Parse(googleCalendarDateTimeFormat, event.Start.DateTime)
}
// MeetingURLFromEvent returns a URL if the event is a Zoom meeting.
func MeetingURLFromEvent(event *calendar.Event) (*url.URL, bool) {
// var zoomPassword string
// fmt.Println(fmt.Sprintf("EL: %s", event.Location))
input := event.Location + " " + event.Description
if videoEntryPointURL, ok := conferenceVideoEntryPointURL(event); ok {
input = videoEntryPointURL + " " + input
}
stringURL := ""
haveMatch := false
// ZOOM Matches
matches := zoomURLRegexp.FindAllStringSubmatch(input, -1)
if len(matches) == 0 || len(matches[0]) == 0 {
// fmt.Println("No matches...")
//return nil, false
} else {
// fmt.Println(event.Description)
// haspass := zoomURLRegexpPwd.FindAllStringSubmatch(event.Description, -1)
haspass := zoomURLRegexpPwd.FindAllStringSubmatch(input, -1)
// TODO: (REMOVE) this no longer works, because Zoom now encrypts the password for URI inclusion
// there is no way to calulate this from the base password.
// if len(haspass) == 0 {
// // descPass := zoomDescriptionRegexpPwd.FindAllStringSubmatch(event.Description, -1)
// descPass := zoomDescriptionRegexpPwd.FindAllStringSubmatch(input, -1)
// if len(descPass) >= 1 {
// if len(descPass[0]) >= 2 {
// zoomPassword = strings.Split(descPass[0][1], "<")[0]
// }
// } else {
// justPass := zoomDescriptionRegexpJustPwd.FindAllStringSubmatch(event.Description, -1)
// // fmt.Println(fmt.Sprintf("%#v", justPass))
// if len(justPass) >= 1 {
// if len(justPass[0]) >= 2 {
// zoomPassword = justPass[0][1]
// }
// }
// }
// }
// passcode := ""
//fmt.Println("~~~~~~~~~~~~~~~~~~~")
//fmt.Println(fmt.Sprintf("%#v", event.ConferenceData))
// if event.ConferenceData != nil {
// //fmt.Println(event.ConferenceData.ConferenceId)
// //fmt.Println(event.ConferenceData.Notes)
// if strings.Contains(event.ConferenceData.Notes, "Passcode") {
// passcode = strings.TrimSpace(strings.Split(event.ConferenceData.Notes, ":")[1])
// // fmt.Println(pc)
// }
// }
//fmt.Println(event.ConferenceData)
//fmt.Println("~~~~~~~~~~~~~~~~~~~")
// By default, match the whole URL.
stringURL = matches[0][0]
// fmt.Println("~~~~~~~~~~~~~~~~~~~")
// fmt.Println(fmt.Sprintf("matches: %d", len(matches[0])))
// fmt.Println(fmt.Sprintf("matches: %s", matches[0]))
// fmt.Println(fmt.Sprintf("matches: %s", matches[0][0]))
// fmt.Println(fmt.Sprintf("matches: %s", matches[0][1]))
// fmt.Println(fmt.Sprintf("matches: %s", matches[0][2]))
if len(matches[0]) >= 2 {
if _, err := strconv.Atoi(matches[0][1]); err == nil {
if len(haspass) >= 1 {
if len(haspass[0]) >= 2 {
// stringURL = "zoommtg://zoom.us/join?confno=" + matches[0][1] + "&pwd=" + haspass[0][1]
passWd := haspass[0][1]
if strings.Contains(passWd, "<") {
passWd = strings.SplitN(passWd, "<", 2)[0]
}
stringURL = "https://zoom.us/j/" + matches[0][1] + "?pwd=" + passWd
} else {
// stringURL = "zoommtg://zoom.us/join?confno=" + matches[0][1]
stringURL = "https://zoom.us/j/" + matches[0][1]
}
} else {
// if zoomPassword == "" {
// if passcode == "" {
// stringURL = "zoommtg://zoom.us/join?confno=" + matches[0][1]
stringURL = "https://zoom.us/j/" + matches[0][1]
// } else {
// // stringURL = "zoommtg://zoom.us/join?confno=" + matches[0][1] + "&pwd=" + passcode
// stringURL = "https://zoom.us/j/" + matches[0][1] + "?pwd=" + passcode
// }
// } else {
// // stringURL = "zoommtg://zoom.us/join?confno=" + matches[0][1] + "&pwd=" + zoomPassword
// stringURL = "https://zoom.us/j/" + matches[0][1] + "?pwd=" + zoomPassword
// }
}
haveMatch = true
// stringURL = strings.Replace(stringURL, "<", "", 1)
// stringURL = strings.Replace(stringURL, ">", "", 1)
} else {
fmt.Println("Error AtoI")
}
}
}
if !haveMatch {
// MS TEAMS Matches
// fmt.Println("trying ms")
matches = teamsURLRegexp.FindAllStringSubmatch(event.Description, -1)
if len(matches) == 0 || len(matches[0]) == 0 {
//fmt.Println("No matches...")
//return nil, false
} else {
// haspass := zoomURLRegexpPwd.FindAllStringSubmatch(event.Description, -1)
// By default, match the whole URL.
stringURL = matches[0][0]
stringURL = strings.TrimSuffix(stringURL, ">")
haveMatch = true
// If we have a meeting ID in the URL, then use zoommtg:// instead of the HTTPS URL.
// if len(matches[0]) >= 2 {
// if _, err := strconv.Atoi(matches[0][1]); err == nil {
// //if len(haspass) >= 1 {
// // if len(haspass[0]) >= 2 {
// // stringURL = "zoommtg://zoom.us/join?confno=" + matches[0][1] + "&pwd=" + haspass[0][1]
// // } else {
// // stringURL = "zoommtg://zoom.us/join?confno=" + matches[0][1]
// // }
// //} else {
// stringURL = "teams://teams.microsoft.com/join?confno=" + matches[0][1]
// //}
// haveMatch = true
// }
// }
}
}
if !haveMatch {
// Cisco WebEx Matches
//fmt.Println("trying webex")
matches = webexURLRegexp.FindAllStringSubmatch(event.Description, -1)
if len(matches) == 0 || len(matches[0]) == 0 {
// fmt.Println("No matches...")
// return nil, false
} else {
// haspass := zoomURLRegexpPwd.FindAllStringSubmatch(event.Description, -1)
// By default, match the whole URL.
stringURL = matches[0][0]
stringURL = strings.TrimSuffix(stringURL, ">")
haveMatch = true
// If we have a meeting ID in the URL, then use zoommtg:// instead of the HTTPS URL.
// if len(matches[0]) >= 2 {
// if _, err := strconv.Atoi(matches[0][1]); err == nil {
// //if len(haspass) >= 1 {
// // if len(haspass[0]) >= 2 {
// // stringURL = "zoommtg://zoom.us/join?confno=" + matches[0][1] + "&pwd=" + haspass[0][1]
// // } else {
// // stringURL = "zoommtg://zoom.us/join?confno=" + matches[0][1]
// // }
// //} else {
// stringURL = "teams://teams.microsoft.com/join?confno=" + matches[0][1]
// //}
// haveMatch = true
// }
// }
}
}
if !haveMatch {
// Discord Matches
// fmt.Println("trying discord")
input := event.Location + " " + event.Description
matches = discordURLRegexp.FindAllStringSubmatch(input, -1)
if len(matches) == 0 || len(matches[0]) == 0 {
// fmt.Println("No matches...")
return nil, false
} else {
// haspass := zoomURLRegexpPwd.FindAllStringSubmatch(event.Description, -1)
// By default, match the whole URL.
stringURL = matches[0][0]
stringURL = strings.Replace(stringURL, "https", "discord", 1)
haveMatch = true
// If we have a meeting ID in the URL, then use zoommtg:// instead of the HTTPS URL.
// if len(matches[0]) >= 2 {
// if _, err := strconv.Atoi(matches[0][1]); err == nil {
// //if len(haspass) >= 1 {
// // if len(haspass[0]) >= 2 {
// // stringURL = "zoommtg://zoom.us/join?confno=" + matches[0][1] + "&pwd=" + haspass[0][1]
// // } else {
// // stringURL = "zoommtg://zoom.us/join?confno=" + matches[0][1]
// // }
// //} else {
// stringURL = "teams://teams.microsoft.com/join?confno=" + matches[0][1]
// //}
// haveMatch = true
// }
// }
}
}
//fmt.Println(stringURL)
parsedURL, err := url.Parse(stringURL)
if err != nil {
return nil, false
}
return parsedURL, haveMatch
}
// conferenceVideoEntryPointURL returns the URL for the video entrypoint if one exists.
func conferenceVideoEntryPointURL(event *calendar.Event) (string, bool) {
if event.ConferenceData == nil {
return "", false
}
for _, entryPoint := range event.ConferenceData.EntryPoints {
// fmt.Println(fmt.Sprintf("ep-%s, %s", entryPoint.EntryPointType, entryPoint.Uri))
if entryPoint.EntryPointType == "video" && strings.Contains(entryPoint.Uri, "zoom") {
return entryPoint.Uri, true
}
if entryPoint.EntryPointType == "video" && strings.Contains(entryPoint.Uri, "teams") {
return entryPoint.Uri, true
}
}
return "", false
}
// readGoogleClientConfigFromFile reads the content of a file and parses it as an *oauth2.Config
func readGoogleClientConfigFromFile(filepath string) (*oauth2.Config, error) {
b, err := ioutil.ReadFile(filepath)
if err != nil {
return nil, errors.WithStack(err)
}
//fmt.Println(fmt.Sprintf("%#v", string(b[:])))
// If modifying these scopes, delete your previously saved client_secret.json.
conf, err := google.ConfigFromJSON(b, calendar.CalendarReadonlyScope)
if err != nil {
return nil, errors.WithStack(err)
}
return conf, nil
}
// Retrieve a token, saves the token, then returns the generated client.
func getClient(config *oauth2.Config) *http.Client {
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
usr, err := user.Current()
if err != nil {
fmt.Println("No current user")
os.Exit(1)
}
tokFile := filepath.Join(usr.HomeDir, ".config", "google", "no-more-lateness_token.json")
tok, err := tokenFromFile(tokFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(tokFile, tok)
}
return config.Client(context.Background(), tok)
}
// Request a token from the web, then returns the retrieved token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf("Go to the following link in your browser then type the "+
"authorization code: \n%v\n", authURL)
var authCode string
if _, err := fmt.Scan(&authCode); err != nil {
log.Fatalf("Unable to read authorization code: %v", err)
}
tok, err := config.Exchange(context.TODO(), authCode)
if err != nil {
log.Fatalf("Unable to retrieve token from web: %v", err)
}
return tok
}
// Retrieves a token from a local file.
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
tok := &oauth2.Token{}
err = json.NewDecoder(f).Decode(tok)
return tok, err
}
// Saves a token to a file path.
func saveToken(path string, token *oauth2.Token) {
fmt.Printf("Saving credential file to: %s\n", path)
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
}