roopakv / google-photos Goto Github PK
View Code? Open in Web Editor NEWLibrary to make hitting the Google Photos api easy
License: MIT License
Library to make hitting the Google Photos api easy
License: MIT License
Hi,
I have some really basic code, and I can't get it to work.
This actually fails silently:
const Photos = require('googlephotos')
const tokens = require('./google-photos-oauth2-token.json')
const photos = new Photos(tokens.access_token)
async function boot () {
console.log('About to make the request:')
const response = await photos.albums.list(50);
console.log('RESPONSE:', response)
}
boot()
After much head banging, I figured out that the only way to make it work is to change transport.js into:
class Transport {
constructor(authToken) {
this.authToken = authToken;
}
get(endpoint, params) {
return ky(endpoint, {
headers: this._getHeaders(),
searchParams: params,
})
}
(Note that I DELETED .json() at the end of the get call), and changed my code into:
const Photos = require('googlephotos')
const tokens = require('./google-photos-oauth2-token.json')
const photos = new Photos(tokens.access_token)
async function boot () {
console.log('About to make the request:')
const response = await photos.albums.list(50);
console.log('RESPONSE:', await response.json())
}
boot()
I eventually managed to trace the error in failing promises, with the following:
body used already for: https://photoslibrary.googleapis.com/v1/albums?pageSize=50 at Response.consumeBody
Please note that the whole program actually quit execution for some reason (!).
Please help :D
Here is the error when i want upload or create new album.
Error: input
must not begin with a slash when using prefixUrl
at new Ky (C:\Users\rig2\node_modules\ky\umd.js:256:12)
at Function.ky.(anonymous function) [as post] (C:\Users\rig2\node_modules\ky\umd.js:497:37)
at Transport.upload (C:\Users\rig2\node_modules\googlephotos\lib\transport.js:25:8)
at MediaItems.upload (C:\Users\rig2\node_modules\googlephotos\lib\media_items\index.js:18:40)
at C:\Users\rig2\Desktop\dev\copyshopy\putBlo.js:58:51
at new Promise ()
at tempUseless (C:\Users\rig2\Desktop\dev\copyshopy\putBlo.js:46:11)
at fs.readFile (C:\Users\rig2\Desktop\dev\copyshopy\putBlo.js:242:7)
at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)
'Content-Type': 'application/json'
(line 49 in transport.js) must not be set for the get request listing media items.
Additionally, the list function should check for pageSize <= 100.
I have not tested whether that fixes the function, but thought I'd leave a comment
Hi @roopakv !
Do you still plan in integrating functionality to manage token(s) and refreshToken ?
Currently what kind of workaround do you use to ensure the accesToken is not expired ?
Thanks,
Samuel
The request
package is deprecated, it is recommended to migrate away from it.
I recommend switching to got
but @root/request
is also a very easy alternative that should work as a drop-in alternative here.
// @roopakv
I am trying to upload large files some 3gb+ but I keep getting this error. I'm using version 0.3.3 from npmjs.com
RangeError [ERR_FS_FILE_TOO_LARGE]: File size (3010883500) is greater than 2 GB at tryCreateBuffer (fs.js:343:13) at Object.readFileSync (fs.js:379:14) at Object.e.readFileSync (electron/js2c/asar_bundle.js:5:8583) at Transport.upload (C:\Users\tobia\Documents\workspace\photo-uploader\node_modules\googlephotos\lib\transport.js:32:18) at MediaItems.upload (C:\Users\tobia\Documents\workspace\photo-uploader\node_modules\googlephotos\lib\media_items\index.js:18:40) at uploadFiles (C:\Users\tobia\Documents\workspace\photo-uploader\main.js:121:49) at processTicksAndRejections (internal/process/task_queues.js:97:5) at async getFilesFromDirectories (C:\Users\tobia\Documents\workspace\photo-uploader\main.js:94:9) { code: 'ERR_FS_FILE_TOO_LARGE'
My uplaod methos looks like this
const uploadFiles = async (files, albumName, prefix) => { try { // create album const prefixTitle = prefix ? `- ${prefix}` : ''; const albumRes = await photos.albums.create(`${albumName} ${prefixTitle}`); console.log(albumRes) // Upload files for (const file of files) { const res = await photos.mediaItems.upload(albumRes.id, file.name, file.fullPath); console.log(res); } console.log(`UPLOAD FROM ${albumName} SUCCESSFULLY`) } catch (error) { console.log(error) } }
Does this support bulk uploads? it uses batch upload in the api but im not sure how i would go about uploading something like a directory of images.
First, thanks for developing this... but, I do not know how to list all the items in an Album.
Can you explain how to do so?
Thanks in advance!
Yesterday you changed the api variable and remove the first "/"
I want to upload image and I can see in lib/transport upload function there is "/v1/uploads'"
When I remove the first "/", I can send the request but I get this error :
{ FetchError: invalid json response body at https://photoslibrary.googleapis.com/v1/uploads reason: Unexpected token C in JSON at position 0
at C:\Users\rig2\node_modules\ky-universal\node_modules\node-fetch\lib\index.js:272:32
at process._tickCallback (internal/process/next_tick.js:68:7)
message:
'invalid json response body at https://photoslibrary.googleapis.com/v1/uploads reason: Unexpected token C in JSON at position 0',
type: 'invalid-json' }
I am just wondering how to automatically handle expired access tokens.
I gradually understand how I can use google.auth.OAuth2() so that it will automatically request a new access token (using the refresh token) when it becomes expired but it is not clear how I should integrate this with this library ?
Should I call again new Photos(...)
but this time with the new access token ?
kr
Jan.
Trying to see list of shared albums, but all the time I'm reciving error 400 / Bad Request.
At same time, geting album list works correctly.
I setted scope of:
https://www.googleapis.com/auth/photoslibrary.readonly
https://www.googleapis.com/auth/photoslibrary.sharing
to get token I used google developer playground
const responseAlbumsShared = await photos.sharedAlbums.list(10)
for now, i'm trying only to console.log response to see if that it works
what is the problem?
Hello
If I copy the albumID in a Google Photos
url https://photos.google.com/album/ALBUM_ID
and I request a album with:
const photos = new GooglePhotos(access_token);
const response = await photos.albums.get(ALBUM_ID);
I have an error Bad Request
The only way I found is to list before my albums and get the ID from the response:
const albums = await photos.albums.list(1)
const response = await photos.albums.get(albums[0].id);
It's not ideal. Is there a way to found the album ID manually? I want to query only specific albums.
Thank you
Instead of foo.setBar(1)
should we replace them with calling the variables directly? Example: foo.bar = 1
This would allow the consumer to also query for the value instead of only being able to set it.
Hi there,
I try to get the content of an album via
const photos = new Photos(access_token);
return await photos.mediaItems.search('albumId');
I run the code in a cloud function and the function times out without result.
Function execution took 60026 ms, finished with status: 'timeout'
If I query the same 'albumId' in Google's API reference, I get a result.
https://developers.google.com/photos/library/reference/rest/v1/mediaItems/search
Any ideas what I'm doing wrong?
Hey Roopakv,
I have a question about oAuth token expiration? One time generation will work?
Hello,
I was wondering their is any typescript signature for this npm package (ex: @types/GoogleAPI) ?
Sorry in advance, im new to this...
i have a nextja app and am trying to use google-photos package together with the googleapis package (as recomeded for authorization) ... I am recieveing the following error: "ReferenceError: code is not defined" on:
const {tokens} = await oauth2Client.getToken(code);
Any help would be much appreicated.
Jon.
Sorry that's my first issue opened, so I don't know how I have to write it, I want to notify to you that on Readme, the upload multiple function is a wrong one, it should be something like that:
const response = await photos.mediaItems.uploadMultiple(albumId, files, directoryPath, requestDelay);
Thank you
It would great to add mediaItems:batchGet
method to pull multiple media items at the same time.
Docs: https://developers.google.com/photos/library/reference/rest/v1/mediaItems/batchGet
Hi,
I didn't find the method to push a media to an album with id
Is it exist ?
Please Help ?
I am uploading a relatively large file (3.47MB compared to an average 70KB image) on a slow internet connection (2.29Mbps) and the request times out after ~10 seconds.
Here is the code I'm using to upload it:
let response = await photos.mediaItems.upload(
cfg.googlePhotosAlbumID, "test", ".tempfile", "test");
And here is the error (forgive me for not catching it properly):
(node:19469) UnhandledPromiseRejectionWarning: TimeoutError: Request timed out
at Timeout.<anonymous> (/home/lux/code/js-shinobiwebhook/node_modules/ky/umd.js:181:12)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
(node:19469) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:19469) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
EDIT: I think it's also worth mentioning that uploading succeeds consistently with aforementioned smaller images, except of course when the token expires.
Is there any way to keep the connection alive, and prevent it from timing out?
Most likely my implementation is not correct:
An extract of the relevant part of my code:
const Photos = require('googlephotos');
...
node.photos = new Photos(node.config.credentials.accessToken);
...
async function get_albums_list(node){
node.warn("get_albums_list ...")
let response = await node.photos.albums.list();
node.warn("get_albums_list response :"+ response);
alert(response);
}
get_albums_list(node);
FYI node.config.credentials.accessToken
is "ya29.Il-zB8z2qrcP7qP3YVpUlt8NCsvb1ZxtsIHTlPi71HN30wFLJs7c5q..."
.
when running the above code I am getting error
(node:16) UnhandledPromiseRejectionWarning: StatusCodeError: 401 - {"error":{"code":401,"message":"Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.","status":"UNAUTHENTICATED"}}
at new StatusCodeError (/data/node_modules/request-promise-core/lib/errors.js:32:15)
at Request.plumbing.callback (/data/node_modules/request-promise-core/lib/plumbing.js:104:33)
at Request.RP$callback [as _callback] (/data/node_modules/request-promise-core/lib/plumbing.js:46:31)
at Request.self.callback (/data/node_modules/request/request.js:185:22)
at Request.emit (events.js:198:13)
at Request.<anonymous> (/data/node_modules/request/request.js:1161:10)
at Request.emit (events.js:198:13)
at IncomingMessage.<anonymous> (/data/node_modules/request/request.js:1083:12)
at Object.onceWrapper (events.js:286:20)
at IncomingMessage.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1143:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
(node:16) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
Hello,
I try to uploading a photo and pushing in a new album.
Have you got some samples?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.