Use Google Calendar as a task manager

August 15, 2016

A geek solution is not always compliant with... a non-geek girlfriend.
Repeatitive tasks, duration, notifications, multi-users... Google Calendar fits perfectly with this kind of usages.

What i want is to control some tasks (power on electrical stuff, make a backup, control heater, shutters...).

Why not using a simple cron ?
Of course, for a backup no more is needed.

Heater on a cron ? Not optimal ! Depends on :

I need a tool where I can edit easily a task. Easily means without a SSH connection, just with one finger.

Here an example of a daily task on a dairy.

With 2 clicks it's possible to cancel one of these, including for non-geek people.

i.e : this is my heater calendar. With "repeat" function when creating a new event, it took me about 10 minutes to add all rules for a week.

From my desk, mobile or tablet it is very easy to edit any rules if, for example, I planned some holidays.

From my android phone

Just add the synchronization for the new diary.

Here it is what it looks like on my phone (sorry for french language...)

Put a new event or task, it will synchronize automatically :)

Even you can share a calendar with your roomates.

Google Calendar API

Go to https://developers.google.com/apis-explorer/#p/
and subscribe to the calendar API.
It's free for 10 000 calls per day.

It means :

For now it is enough for my needs but if I need more than 7 tasks, another solution will come :)

You can also follow instructions from https://developers.google.com/google-apps/calendar/overview

Take a look at : https://developers.google.com/google-apps/calendar/v3/reference/

A simple REST API, usable by CURL or anything else. In my case, I wanted something a little "touchy" so I started from golang example :

https://developers.google.com/google-apps/calendar/quickstart/go

Why ?

First of all, I created a new calendar dedicated to one of my plugs :

In your calendar properties, retrieve the calendar id :

golang example

This is the base example :

package main

import (  
  "encoding/json"
  "fmt"
  "io/ioutil"
  "log"
  "net/http"
  "net/url"
  "os"
  "os/user"
  "path/filepath"
  "time"

  "golang.org/x/net/context"
  "golang.org/x/oauth2"
  "golang.org/x/oauth2/google"
  "google.golang.org/api/calendar/v3"
)

// getClient uses a Context and Config to retrieve a Token
// then generate a Client. It returns the generated Client.
func getClient(ctx context.Context, config *oauth2.Config) *http.Client {  
  cacheFile, err := tokenCacheFile()
  if err != nil {
    log.Fatalf("Unable to get path to cached credential file. %v", err)
  }
  tok, err := tokenFromFile(cacheFile)
  if err != nil {
    tok = getTokenFromWeb(config)
    saveToken(cacheFile, tok)
  }
  return config.Client(ctx, tok)
}

// getTokenFromWeb uses Config to request a Token.
// It 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 code string
  if _, err := fmt.Scan(&code); err != nil {
    log.Fatalf("Unable to read authorization code %v", err)
  }

  tok, err := config.Exchange(oauth2.NoContext, code)
  if err != nil {
    log.Fatalf("Unable to retrieve token from web %v", err)
  }
  return tok
}

// tokenCacheFile generates credential file path/filename.
// It returns the generated credential path/filename.
func tokenCacheFile() (string, error) {  
  usr, err := user.Current()
  if err != nil {
    return "", err
  }
  tokenCacheDir := filepath.Join(usr.HomeDir, ".credentials")
  os.MkdirAll(tokenCacheDir, 0700)
  return filepath.Join(tokenCacheDir,
    url.QueryEscape("calendar-go-quickstart.json")), err
}

// tokenFromFile retrieves a Token from a given file path.
// It returns the retrieved Token and any read error encountered.
func tokenFromFile(file string) (*oauth2.Token, error) {  
  f, err := os.Open(file)
  if err != nil {
    return nil, err
  }
  t := &oauth2.Token{}
  err = json.NewDecoder(f).Decode(t)
  defer f.Close()
  return t, err
}

// saveToken uses a file path to create a file and store the
// token in it.
func saveToken(file string, token *oauth2.Token) {  
  fmt.Printf("Saving credential file to: %s\n", file)
  f, err := os.Create(file)
  if err != nil {
    log.Fatalf("Unable to cache oauth token: %v", err)
  }
  defer f.Close()
  json.NewEncoder(f).Encode(token)
}

func main() {  
  ctx := context.Background()

  b, err := ioutil.ReadFile("client_secret.json")
  if err != nil {
    log.Fatalf("Unable to read client secret file: %v", err)
  }

  // If modifying these scopes, delete your previously saved credentials
  // at ~/.credentials/calendar-go-quickstart.json
  config, err := google.ConfigFromJSON(b, calendar.CalendarReadonlyScope)
  if err != nil {
    log.Fatalf("Unable to parse client secret file to config: %v", err)
  }
  client := getClient(ctx, config)

  srv, err := calendar.New(client)
  if err != nil {
    log.Fatalf("Unable to retrieve calendar Client %v", err)
  }

  t := time.Now().Format(time.RFC3339)
  events, err := srv.Events.List("primary").ShowDeleted(false).
    SingleEvents(true).TimeMin(t).MaxResults(10).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 {
    for _, i := range events.Items {
      var when string
      // If the DateTime is an empty string the Event is an all-day Event.
      // So only Date is available.
      if i.Start.DateTime != "" {
        when = i.Sta```rt.DateTime
      } else {
        when = i.Start.Date
      }
      fmt.Printf("%s (%s)\n", i.Summary, when)
    }
  } else {
    fmt.Printf("No upcoming events found.\n")
  }

}

srv.Events.List("primary") : replace "primary" with your specific calendar ID.

Now, you have a list of events from your calendar.

[email protected]:/home/mathieu/dev# go run quickstart.go  
Upcoming events:  
 (2016-07-11T12:30:00+02:00)
[email protected]:/home/mathieu/dev#  

2 modifications :
- all day event must be parsed and returned - only current events must be returned.

You can see modifications in final code.

Configuration file

It's a simple map between calendar ids and json output names :

{
        "calendars": [ {
                "CalendarId": "[email protected]",
                "OutputName": "heater"
        }, {
                "CalendarId": "[email protected]",
                "OutputName": "video"
        }]
}

Output

I built a simple structure :

{
    "plug1": "",
    "plug2": "",
    "heater": "17"
}

This output is very easy to use in a bash script with JQ.
Here an example I written, it launches motion :

#!/bin/bash

LOCKFILE="/var/.videolock"

output=$(jq .video $1)

# video is on
if [ "$output" = "\"\"" ]  
then  
        echo "video is on"
        #check if lock file exists
        if [ -f "$LOCKFILE" ]
        then
                # nothing to do
                echo "already running"
        else
                #put lock file
                touch $LOCKFILE
                # start video
                motion -c /etc/motion/motion.conf
        fi
fi

# video is off
if [ "$output" = "null" ]  
then  
        if [ -f "$LOCKFILE" ]
        then
                rm $LOCKFILE
                killall motion
        fi
fi  

Final code

No argument is needed. I put configurations files names directly into my code. Uggly ? Yes for production, not for a POC. :-)

https://github.com/mathieupassenaud/google-calendar-retreiver