goo
github.com/bowbaq/googlephoto
go get github.com/bowbaq/googlephoto
goo

github.com/bowbaq/googlephoto

An API client for Google Photo written in Go

go get github.com/bowbaq/googlephoto
Readme

Google Photo API client

GoDoc

Example

package main

import (
  "encoding/json"
  "fmt"
  "io/ioutil"
  "log"
  "net/http"

  "github.com/Bowbaq/googlephoto"
  "golang.org/x/oauth2"
  "golang.org/x/oauth2/google"
)

func main() {
  client := googlephoto.NewClient(oauth2Client())

  photos := make(map[string]*googlephoto.Photo)

  albums, err := client.ListAlbums()
  check(err)

  for _, album := range albums {
    albumPhotos, err := client.ListPhotos(album)
    check(err)

    for _, photo := range albumPhotos {
      photos[photo.ID] = photo
    }
  }

  fmt.Printf("Found %s unique photos\n", len(photos))
}

func oauth2Client() *http.Client {
  conf := &oauth2.Config{
    // Get Oauth2 credentials from https://console.developers.google.com
    ClientID:     "<client id>",
    ClientSecret: "<client secret>",
    RedirectURL:  "http://localhost/",
    Scopes: []string{
      "https://picasaweb.google.com/data/",
    },
    Endpoint: google.Endpoint,
  }

  var token oauth2.Token
  tokenData, err := ioutil.ReadFile("./token.json")
  if err == nil {
    err = json.Unmarshal(tokenData, &token)

    if err != nil {
      log.Println(err)
      token = refreshToken(conf)
    }
  } else {
    log.Println(err)
    token = refreshToken(conf)
  }

  return conf.Client(oauth2.NoContext, &token)
}

func refreshToken(conf *oauth2.Config) oauth2.Token {
  url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline)
  fmt.Printf("Visit the URL for the auth dialog: %v\n", url)

  var authCode string
  fmt.Println("Your browser should have redirected to: http://localhost/?state=state&code=<code>")
  fmt.Print("Paste the code: ")
  fmt.Scanln(&authCode)

  token, err := conf.Exchange(oauth2.NoContext, authCode)
  check(err)

  data, err := json.Marshal(token)
  check(err)

  ioutil.WriteFile("./token.json", data, 0400)

  return *token
}

func check(err error) {
  if err != nil {
    log.Fatal(err)
  }
}

GitHub Stars

12

LAST COMMIT

7yrs ago

MAINTAINERS

0

CONTRIBUTORS

1

OPEN ISSUES

0

OPEN PRs

0
VersionTagPublished
v0.0.0-20151108213551-f96b4bcdad66
2yrs ago
No alternatives found
No tutorials found
Add a tutorial