gphotos

package module
v2.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 4, 2021 License: MIT Imports: 10 Imported by: 1

README

Google Photos API client for Go

Go Reference Go Report Card codebeat badge codecov GitHub release GitHub

This package provides a client for using the Google Photos API in go. Uses the original photoslibrary package, that was provided by Google and now it's maintained here.

The package offers access to these Google Photos services:

  • CachedAlbumsService is a service to manage albums.
  • MediaItemsService is a service to manage media items (Photos and Videos).
  • Uploader is a service to upload items.

This project will maintain compatibility with the last two Go major versions published.

Installation

$ go get github.com/gphotosuploader/google-photos-api-client-go/v2

Features

The package could be consumed using three different services in isolation or a gphotos.Client. It implements Google Photos error handling best practices. It uses an exponential backoff policy with a maximum of 5 retries.

CachedAlbumsService
Uploader
  • Offers two uploaders implementing the /v1/uploads endpoint.
    • BasicUploader is a simple HTTP uploader.
    • ResumableUploader is an uploader implementing resumable uploads. It could be used for large files, like videos. See documentation.

Authentication

The gphotos library does not directly handle authentication. Instead, when creating a new client, pass an http.Client that can handle authentication for you. The easiest and recommended way to do this is using the golang.org/x/oauth2 library, but you can always use any other library that provides an http.Client.

Access to the API requires OAuth client credentials from a Google developers project. This project must have the Library API enabled as described here.

import (
    "golang.org/x/oauth2"

    gphotos "github.com/gphotosuploader/google-photos-api-client-go/v2"
)

func main() {
    ctx := context.Background()
    oc := oauth2Config := oauth2.Config{
        ClientID:     "... your application Client ID ...",
        ClientSecret: "... your application Client Secret ...",
        // ...
    }
    tc := oc.Client(ctx, "... your user Oauth Token ...")
    client := gphotos.NewClient(tc)
}

Note that when using an authenticated Client, all calls made by the client will include the specified OAuth token. Therefore, authenticated clients should almost never be shared between different users. See the oAuth2 docs for complete instructions on using that library.

Limitations

Only images and videos can be uploaded. If you attempt to upload non videos or images or formats that Google Photos doesn't understand, Google Photos will give an error when creating media item.

Photo storage and quality

All media items uploaded to Google Photos using the API are stored in full resolution at original quality. They count toward the user’s storage. The API does not offer a way to upload in "high quality" mode.

Duplicates

If you upload the same image (with the same binary data) twice then Google Photos will deduplicate it. However it will retain the filename from the first upload which may be confusing. In practise this shouldn't cause too many problems.

Albums

Note that you can only add media items that have been uploaded by this application to albums that this application has created, see here why.

Rate Limiting

Google Photos imposes a rate limit on all API clients. The quota limit for requests to the Library API is 10,000 requests per project per day. The quota limit for requests to access media bytes (by loading a photo or video from a base URL) is 75,000 requests per project per day.

Used by

  • gphotos-uploader-cli: A command line to sync your pictures and videos with Google Photos. Supporting linux/macOs.

Documentation

Overview

Package gphotos provides a client for calling the Google Photos API.

Usage:

import gphotos "github.com/gphotosuploader/google-photos-api-client-go/v2"

Construct a new Google Photos client, it needs an authenticated HTTP Client see Authentication section below.

client, err := gphotos.NewClient(httpClient)
...

Use WithUploader(), WithAlbumsService(), WithMediaItemsService() to customize it. By default:

  • Uses an Album repository with an in-memory cache.
  • Uses a basic HTTP uploader, you can find a resumable one using uploader.NewResumableUploader().

It can get Album from the library, returning ErrAlbumNotFound in case it does not exist:

title := "my-album"
album, err := client.Albums.GetByTitle(ctx, title)
if errors.Is(err, ErrAlbumNotFound) {
   // album does not exist
}
...

It can upload a new item to your library:

media, err := client.UploadFileToLibrary(ctx, "/my-folder/my-picture.jpg")
if err != nil {
   // handle error
}
...

Or upload and adding it to an Album:

media, err := client.UploadFileToAlbum(ctx, album.ID, "/my-folder/my-picture.jpg")
if err != nil {
   // handle error
}
...

Authentication

The gphotos library does not directly handle authentication. Instead, when creating a new client, pass an http.Client that can handle authentication for you. The easiest and recommended way to do this is using the golang.org/x/oauth2 library, but you can always use any other library that provides an http.Client. Access to the API requires OAuth client credentials from a Google developers project. This project must have the Library API enabled as described in https://developers.google.com/photos/library/guides/get-started.

	import (
		"golang.org/x/oauth2"

		gphotos "github.com/gphotosuploader/google-photos-api-client-go/v2"
 )
	func main() {
		ctx := context.Background()
		oc := oauth2Config := oauth2.Config{
			ClientID:     "... your application Client ID ...",
			ClientSecret: "... your application Client Secret ...",
         // ...
		}
		tc := oc.Client(ctx, "... your user Oauth Token ...")
		client, err := gphotos.NewClient(tc)
     ...
	}

Note that when using an authenticated Client, all calls made by the client will include the specified OAuth token. Therefore, authenticated clients should almost never be shared between different users. See the oauth2 docs for complete instructions on using that library.

Limitations

Google Photos API imposes some limitations, please read them all at: https://github.com/gphotosuploader/google-photos-api-client-go/

Index

Constants

View Source
const (
	// View the photos, videos and albums in your Google Photos
	DrivePhotosReadonlyScope = "https://www.googleapis.com/auth/drive.photos.readonly"

	// View and manage your Google Photos library
	PhotoslibraryScope = "https://www.googleapis.com/auth/photoslibrary"

	// Add to your Google Photos library
	PhotoslibraryAppendonlyScope = "https://www.googleapis.com/auth/photoslibrary.appendonly"

	// View your Google Photos library
	PhotoslibraryReadonlyScope = "https://www.googleapis.com/auth/photoslibrary.readonly"

	// Manage photos added by this app
	PhotoslibraryReadonlyAppcreateddataScope = "https://www.googleapis.com/auth/photoslibrary.readonly.appcreateddata"

	// Manage and add to shared albums on your behalf
	PhotoslibrarySharingScope = "https://www.googleapis.com/auth/photoslibrary.sharing"
)

OAuth2 scopes used by this API.

Variables

This section is empty.

Functions

func WithAlbumsService

func WithAlbumsService(s AlbumsService) *option

WithAlbumsService configures the Albums Service.

func WithMediaItemsService

func WithMediaItemsService(s MediaItemsService) *option

WithMediaItemsService configures the Media Items Service.

func WithUploader

func WithUploader(s MediaUploader) *option

WithUploader configures the Media Uploader.

Types

type AlbumsService added in v2.1.0

type AlbumsService interface {
	AddMediaItems(ctx context.Context, albumId string, mediaItemIds []string) error
	RemoveMediaItems(ctx context.Context, albumId string, mediaItemIds []string) error
	Create(ctx context.Context, title string) (*albums.Album, error)
	GetById(ctx context.Context, id string) (*albums.Album, error)
	GetByTitle(ctx context.Context, title string) (*albums.Album, error)
	List(ctx context.Context) ([]albums.Album, error)
}

AlbumsService represents a Google Photos client for albums management.

type Client

type Client struct {
	Albums     AlbumsService
	MediaItems MediaItemsService
	Uploader   MediaUploader
}

Client is a Google Photos client with enhanced capabilities.

func NewClient

func NewClient(authenticatedClient *http.Client, options ...Option) (*Client, error)

NewClient constructs a new gphotos.Client from the provided HTTP client and the given options. The client is an HTTP client used for calling Google Photos. It needs the proper authentication in place.

By default it will use a in memory cache for Albums repository and implements retries with Exponential backoff.

Use WithUploader(), WithAlbumsService(), WithMediaItemsService() to customize it.

There is a resumable uploader implemented on uploader.NewResumableUploader().

func (Client) UploadFileToAlbum

func (c Client) UploadFileToAlbum(ctx context.Context, albumId string, filePath string) (media_items.MediaItem, error)

UploadFileToAlbum uploads the specified file to the album in Google Photos.

func (Client) UploadFileToLibrary

func (c Client) UploadFileToLibrary(ctx context.Context, filePath string) (media_items.MediaItem, error)

UploadFileToLibrary uploads the specified file to Google Photos.

type MediaItemsService added in v2.1.0

type MediaItemsService interface {
	Create(ctx context.Context, mediaItem media_items.SimpleMediaItem) (media_items.MediaItem, error)
	CreateMany(ctx context.Context, mediaItems []media_items.SimpleMediaItem) ([]media_items.MediaItem, error)
	CreateToAlbum(ctx context.Context, albumId string, mediaItem media_items.SimpleMediaItem) (media_items.MediaItem, error)
	CreateManyToAlbum(ctx context.Context, albumId string, mediaItems []media_items.SimpleMediaItem) ([]media_items.MediaItem, error)
	Get(ctx context.Context, mediaItemId string) (*media_items.MediaItem, error)
	ListByAlbum(ctx context.Context, albumId string) ([]media_items.MediaItem, error)
}

MediaItemsService represents a Google Photos client for media management.

type MediaUploader added in v2.1.0

type MediaUploader interface {
	UploadFile(ctx context.Context, filePath string) (uploadToken string, err error)
}

MediaUploader represents a Google Photos client fo media upload.

type Option

type Option interface {
	Name() string
	Value() interface{}
}

Option represents a configurable parameter.

Directories

Path Synopsis
internal
log

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL