Google Photosから画像URLの取得の仕方について調べたので備忘します。
Google PhotosのAPIはないため、Picasa Web Albums Data APIを用います。
Google APIsのセットアップ
Google OAuth2.0認証のクライアント登録、RefreshTokenの取得は以下を参考に実施。
- Node.jsでGoogle SpreadSheetsを操作してみよう。
- スマホで撮った写真を Line Message API を利用して Google Cloud Functions から Google Photos へアップする
- GooglePhotoにある写真を取得し、Slackに送信するBotを作った話
esteban-uo/picasa 3rdパーティを利用しました
公式のクライアント ライブラリの中にnode.jsは提供されていないので、以下「picasa」ライブラリを用いました。
https://github.com/esteban-uo/picasa
Picasa Web Albums Data API 公式Doc:
https://developers.google.com/picasa-web/docs/3.0/reference
サンプルコード
index.js
'use strict';
const Picasa = require('picasa');
const config = {
clientId: 'yourClientId',
redirectURI: 'redirectURI',
clientSecret: 'yourClientSecret'
};
const refreshToken = 'yourRefreshToken';
const picasa = new Picasa();
let accessToken;
// アクセストークンを取得します。
picasa.renewAccessToken(config, refreshToken)
.then(token => {
accessToken = token;
// アルバム一覧を取得します。
return picasa.getAlbums(accessToken, null);
})
.then(albums => {
// アルバム内の写真一覧を取得します。
return Promise.all(albums.map(album => {
return picasa.getPhotos(accessToken, {albumId: album.id});
}));
})
.then(albumResults => {
for (const photos of albumResults) {
for (const photo of photos) {
console.log(`Content-Type: ${photo.content.type}, URL: ${photo.content.src}`)
}
}
})
.catch(error => {
console.log(error);
});
AlbumとPhotoのオブジェクトについては以下のような構造でした。
(適当にマスクしました。)
album オブジェクト
album.json
{
"thumbnail": [{
"url": "https://lh3.googleusercontent.com/.../.../.../.../xxx",
"height": 160,
"width": 160
}],
"id": "6495466432978937825",
"name": "6495466432978937825",
"num_photos": 270,
"published": "2017-12-03T23:27:09.000Z",
"title": "アルバムタイトル",
"summary": "",
"location": "",
"nickname": "Kenji K",
"rights": "protected",
"access": "protected"
}
photo オブジェクト
photo.json
{
"id": "xxx",
"album_id": "xxx",
"access": "protected",
"width": "6000",
"height": "4000",
"size": "1725207",
"checksum": "",
"timestamp": "1511213016000",
"image_version": 25335,
"commenting_enabled": "true",
"comment_count": 0,
"content": {
"type": "image/jpeg",
"src": "https://lh3.googleusercontent.com/.../.../.../.../DSC_0856.JPG"
},
"title": "DSC_0856.JPG",
"summary": ""
}