-
Notifications
You must be signed in to change notification settings - Fork 4
/
calendar.go
65 lines (56 loc) · 1.57 KB
/
calendar.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
package main
import (
"log"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt"
"google.golang.org/api/calendar/v3"
)
type EventsChecker struct {
calendarService *calendar.Service
}
type EmptyEventError struct {
}
func (e EmptyEventError) Error() string {
return "No event for this date"
}
//check if there is any event for date
func (e EventsChecker) getEventForDate(calendarId string, dateTime time.Time) (*calendar.Event, error) {
beginOfDay := time.Date(dateTime.Year(), dateTime.Month(), dateTime.Day(), 3, 0, 0, 0, dateTime.Location())
endOfDay := time.Date(dateTime.Year(), dateTime.Month(), dateTime.Day(), 23, 59, 0, 0, dateTime.Location())
formattedStart := beginOfDay.Format(time.RFC3339)
formattedEnd := endOfDay.Format(time.RFC3339)
cal, err := e.calendarService.Events.List(calendarId).
TimeMin(formattedStart).
TimeMax(formattedEnd).
MaxResults(1).
ShowDeleted(false).
SingleEvents(true).
Do()
if err != nil {
log.Println("Calendar id:" + calendarId)
log.Fatalf("Unable to get calendar: %v", err)
}
if len(cal.Items) > 0 {
return cal.Items[0], nil
} else {
return nil, EmptyEventError{}
}
}
func initCalendarService(email string, key []byte) (*calendar.Service, error) {
conf := &jwt.Config{
Email: email,
PrivateKey: key,
Scopes: []string{
"https://www.googleapis.com/auth/calendar",
},
TokenURL: google.JWTTokenURL,
}
client := conf.Client(oauth2.NoContext)
svc, err := calendar.New(client)
if err != nil {
log.Fatalf("Unable to create calendar service: %v", err)
}
return svc, err
}