gphotos

package module
v3.0.5 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2024 License: MIT Imports: 13 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 archived here.

The package offers access to these Google Photos services:

  • Albums is a service to manage albums.
  • MediaItems 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 three major published published versions of Go.

Installation

google-photos-api-client-go is compatible with modern Go releases in module mode. You can install it using:

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

Usage

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

Construct a new Google Photos client, then use the various services on the client to access different parts of the Google Photos API.

For example:

// httpClient has been previously authenticated using oAuth authenticated
client := gphotos.NewClient(httpClient)

// list all albums for the authenticated user
albums, err := client.Albums.List(context.Background())

The services of a client divide the API into logical chunks and correspond to the structure of the Google Photos API documentation at https://developers.google.com/photos/library/reference/rest.

NOTE: Using the context package, one can easily pass cancelation signals and deadlines to various services of the client for handling a request. In case there is no context available, then context.Background() can be used as a starting point.

Authentication

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

Access to the API requires OAuth 2.0 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/v3"
)

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)
    
    // list all albums for the authenticated user
    albums, err := client.Albums.List(ctx)
}

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.

Features

Retries following best practices
Albums service
Media Items service
  • Offers an independent albums.Service implementing the Google Photos MediaItems API.
  • The client accepts a customized media items service using client.MediaItems.
Uploader
  • Offers two uploaders implementing the Google Photos Uploads API.
    • uploader.SimpleUploader is a simple HTTP uploader.
    • uploader.ResumableUploader is an uploader implementing resumable uploads. It could be used for large files, like videos. See documentation.
  • The client accepts a customized media items service using client.Uploader.

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 twice, with the same binary content, then Google Photos will deduplicate it. However, it will retain the filename from the first upload which may be confusing. In practice, 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

Documentation

Overview

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

Usage:

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

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

// httpClient has been previously authenticated using oAuth authenticated client := gphotos.NewClient(httpClient)

// list all albums for the authenticated user albums, err := client.Albums.List(context.Background())

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

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

It can upload a new item to your library:

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

Or upload and adding it to an Album:

media, err := client.UploadToAlbum(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/v3"
	 )
		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)

         // list all albums for the authenticated user
         albums, err := client.Albums.List(ctx)
		}

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 (
	// PhotoslibraryScope allows viewing and managing your Google Photos library
	// Not recommended. Only request access to the scopes you need with [incremental authorization].
	//
	// [incremental authorization]: https://developers.google.com/photos/library/guides/authorization#what-scopes
	PhotoslibraryScope = "https://www.googleapis.com/auth/photoslibrary"

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

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

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

OAuth2 scopes used by this API.

View Source
const (
	Version = "v3.0.0"
)

Variables

This section is empty.

Functions

func GooglePhotosServiceRetryPolicy

func GooglePhotosServiceRetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error)

GooglePhotosServiceRetryPolicy provides a retry policy implementing Google Photos best practices.

See: https://developers.google.com/photos/library/guides/best-practices#error-handling

Types

type AlbumsService

type AlbumsService interface {
	AddMediaItems(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)
	PaginatedList(ctx context.Context, options *albums.PaginatedListOptions) (albums []albums.Album, nextPageToken string, err error)
}

AlbumsService represents a Google Photos client for albums management.

type Client

type Client struct {
	// Uploader implementation used when uploading files to Google Photos.
	Uploader MediaUploader

	// Services used for talking to different parts of the Google Photos API.
	Albums     AlbumsService
	MediaItems MediaItemsService
}

A Client manages communication with the Google Photos API.

func NewClient

func NewClient(httpClient *http.Client) (*Client, error)

NewClient returns a new Google Photos API client. API methods require authentication, provide an net/http.Client that will perform the authentication for you (such as that provided by the golang.org/x/oauth2 library).

func NewClientWithBaseURL

func NewClientWithBaseURL(httpClient *http.Client, baseURL string) (*Client, error)

NewClientWithBaseURL returns a new Google Photos API client with a custom baseURL. See NewClient for more details.

func (*Client) Upload

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

Upload uploads the specified file and creates the media item in Google Photos.

func (*Client) UploadToAlbum

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

UploadToAlbum uploads the specified file and creates the media item in the specified album in Google Photos.

type ErrDailyQuotaExceeded

type ErrDailyQuotaExceeded struct{}

ErrDailyQuotaExceeded is returned when the Google Photos API 'All request' per day quota is exceeded.

See: https://developers.google.com/photos/library/guides/api-limits-quotas#general-quota-limits

func (*ErrDailyQuotaExceeded) Error

func (e *ErrDailyQuotaExceeded) Error() string

type MediaItemsService

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)
	PaginatedList(ctx context.Context, options *media_items.PaginatedListOptions) (mediaItems []media_items.MediaItem, nextPageToken string, err error)
}

MediaItemsService represents a Google Photos client for media management.

type MediaUploader

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

MediaUploader represents a Google Photos client fo media upload.

Directories

Path Synopsis
internal
log

Jump to

Keyboard shortcuts

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