diff calsync/gcalclient/gcalclient.go @ 49:2991c1166852

start calsync in go. Calendar list seems to sync
author drewp@bigasterisk.com
date Mon, 19 Aug 2024 13:25:03 -0700
parents
children a9b720445bcf
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/calsync/gcalclient/gcalclient.go	Mon Aug 19 13:25:03 2024 -0700
@@ -0,0 +1,81 @@
+package gcalclient
+
+import (
+	"context"
+	"log"
+	"net/url"
+	"time"
+
+	"google.golang.org/api/calendar/v3"
+)
+
+type GCalClient struct {
+	ctx context.Context
+	srv *calendar.Service
+}
+
+// Same as calendar.Event, but includes the source calendar url
+type CalendarEvent struct {
+	*calendar.Event
+	CalendarUrl string
+}
+
+func MakeCalUrl(calId string) string {
+	return "http://bigasterisk.com/calendar/" + url.QueryEscape(calId)
+}
+
+func New(ctx context.Context) (*GCalClient, error) {
+	// If modifying these scopes, delete your previously saved token.json.
+	err, srv := newService(ctx)
+	if err != nil {
+		log.Fatalf("Unable to retrieve Calendar client: %v", err)
+	}
+	return &GCalClient{ctx, srv}, nil
+}
+
+func (gc *GCalClient) Close() {
+	// todo: disconnect watches if possible
+}
+
+func (gc *GCalClient) AllCalendars() ([]*calendar.CalendarListEntry, error) {
+	// todo: pagination
+	list, err := gc.srv.CalendarList.List().MaxResults(100).Do()
+	if err != nil {
+		return nil, err
+	}
+	list.Items = list.Items[:4]
+	return list.Items, nil
+}
+
+// FindEvents considers all calendars
+func (gc *GCalClient) FindEvents(s time.Time) ([]*CalendarEvent, error) {
+	cals, err := gc.AllCalendars()
+	if err != nil {
+		return nil, err
+	}
+
+	ret := make([]*CalendarEvent, 0)
+	for _, cal := range cals {
+		calUrl := MakeCalUrl(cal.Id)
+		log.Println("  getting events from ", calUrl)
+		list, err := gc.srv.
+			Events.List(cal.Id).
+			ShowDeleted(false).
+			SingleEvents(true).
+			TimeMin(s.Format(time.RFC3339)).
+			MaxResults(2).
+			OrderBy("startTime").
+			Do()
+		if err != nil {
+			return nil, err
+		}
+		for _, event := range list.Items {
+			ev := &CalendarEvent{
+				Event:       event,
+				CalendarUrl: calUrl,
+			}
+			ret = append(ret, ev)
+		}
+	}
+	return ret, nil
+}