google realtime api / drive api -> get user role for realtime doc - javascript

I have a realtime app and get the collaborators with doc.getCollaborators() and this gives me an array [] doc is from the type gapi.drive.realtime.Document:
According to the API Reference there is no field like isOwner that shows me if the current collaborator is the owner of the realtime document "doc"
My Question how can I find out which role the collaborators of a doc has.
In the API documentation I find: "The Realtime API supports owner, reader and writer roles"
If I try to use gapi.client.drive.permissions.list suggested from the google drive api reference:
function retrievePermissions(fileId, callback) {
var request = gapi.client.drive.permissions.list({
'fileId': fileId
});
request.execute(function (resp) {
callback(resp.items);
});
}
retrievePermissions(self.realtimeDocId, function (resp) {
resp;
});
Then I get the following error message:
Error in Realtime load callback: TypeError: Cannot read property
'permissions' of undefined TypeError: Cannot read property
'permissions' of undefined

To use the drive API you must load it separately from the Realtime API.
window.gapi.client.load('drive', 'v3', function ()
{
// Run your code here.
});
After getting the permissions list, you can use the permissions ID for each user returned from your RealtimeDoc::getCollaborators call.

You may want to check how you've place your codes, based on the documentation, you can integrate Realtime API to the Drive platform.
Realtime documents are attached to files stored in Google Drive. Accordingly, your application should use the Drive REST API to interact with Drive files. For example, to create a new file, use the files.insert method from the Drive REST API. To retrieve a file that already exists, use the files.get method.
For more information on interacting with files in Google Drive, see Google Drive Integration.
As for code implementation you can check CodeMirror Collaboration with Google Drive Realtime Api.
Drive API:
/**
* Creates a new Realtime file.
* #param title {string} title of the newly created file.
* #param callback {Function} the callback to call after creation.
*/
rtclient.createRealtimeFile = function(title, callback) {
gapi.client.load('drive', 'v2', function() {
gapi.client.drive.files.insert({
'resource': {
mimeType: rtclient.REALTIME_MIMETYPE,
title: title
}
}).execute(callback);
});
}
For Realtime API:
// We have a file ID in the query parameters, so we will use it to load a file.
if (fileId) {
gapi.drive.realtime.load(fileId, this.onFileLoaded, this.initializeModel, handleErrors);
return;
}
Hope this info helps.

Related

Getting Google Cloud Platform custom metadata " firebaseStorageDownloadToken" programmatically

I am using Firebase Cloud Storage.
I know how to get the URL of a downloaded file (tags.txt) using Firebase SDK function running on a client javascript :
storage.ref('tags.txt').getDownloadURL().then((url) => {
console.log(url);
});
I want to get the downloadURL from Node.JS . I do know this function does not exists for Node.JS
However, In Google Cloud Platform you can get the following key/value pair :
firebaseStorageDownloadTokens : 0ea9a60a-7719-4c6b-9cb5-7fcf69d7c633, the value being the token you want. From this token I can easily build the downloadURL I need.
The path to get there is:
Cloud Storage / "Bucket name" / Bucket details / tags.txt / EDIT METADATA / Custom metadata.
I try this code to access this metadata :
async function getBucketMetadata() {
const bucketName = "gs://tags.appspot.com";
try {
// Get Bucket Metadata
let metadata = await admin.storage().bucket(bucketName).file('tags.txt').getMetadata();
console.log(metadata)
}
catch (err) {
console.log(err.message)
}
}
I got keys/values (not a real project though) info such as:
bucket:'tags.appspot.com'
contentType:'text/plain'
crc32c:'Y1Sdxw=='
etag:'CI1EETD18Co9vECEAE='
generation:'162694124484794756'
id:'tags-admin.appspot.com/tags.txt/162694431484794756'
kind:'storage#object'
md5Hash:'P1YSFER4xSf5p0/KWrdQWx1z1Lyg=='
mediaLink:'https://storage.googleapis.com/download/storage/v1/b/tags-admin.appspot.com/o/tags.txt?generation=162694443184794756&alt=media'
metageneration:'1'
name:'tags.txt'
selfLink:'https://www.googleapis.com/storage/v1/b/tags-admin.appspot.com/o/tags.txt'
size:'5211247'
storageClass:'STANDARD'
timeCreated:'2021-07-22T09:01:24.862Z'
timeStorageClassUpdated:'2021-07-22T09:01:24.862Z'
updated:'2021-07-22T09:01:24.862Z'
But nothing regarding the key/value pair I want : firebaseStorageDownloadTokens : 0ea9a60a-7719-4c6b-9cb5-7fcf69d7c633
If the key/value can be seen on Google Cloud Platform , I do believe the key/value is also accessible via some code.
Your help is appreciated.
I mixed up two projects. I re-tried it, and its work pretty nicely. Using this method I can retrieve the file token and build the file URL around it on the back-end. The front-end function getDownloadURL() is not longer required.
Thanks for your help anyway.
The code become:
async function getBucketMetadata() {
const bucketName = "gs://tags.appspot.com";
try {
// Get Bucket Metadata
let metadata = await admin.storage().bucket(bucketName).file('tags.txt').getMetadata();
console.log(metadata[0].metadata.firebaseStorageDownloadTokens)
}
catch (err) {
console.log(err.message)
}
}

Google Drive API failing. Files:get response CORS error

I have a web application that relies on saving files to Google Drive and later retrieving them from the server. I am using the Google API Javascript Client and using similar code to the Google Drive API example to retrieve the file. I use a request to the Google API get service to retrieve the file metadata and then I use that file's downloadUrl contained in the metadata to request that file through an XmlHttpRequest, retrieving the access token from the Google API.
getContents = function(fileId,callbackFunction) {
var request = gapi.client.drive.files.get({ fileId : fileId});
request.execute(function(metadata) {
if(metadata.downloadUrl) {
var connection = new haxe.Http(metadata.downloadUrl);
var accessToken = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse(true).access_token;
connection.setHeader("Authorization","Bearer " + accessToken);
connection.async = true;
connection.onData = function(data) {
callbackFunction(metadata,haxe.io.Bytes.ofString(data));
};
connection.onError = function(error) {
callbackFunction(metadata,null);
};
connection.request(false);
}
});
}
As recently as of yesterday, the Google API has stopped working when retrieving files. I can get the file metadata just fine, but when requesting the downloadUrl, it is blocked by the CORS policy because the Google API response does not contain the 'Access-Control-Allow-Origin' header. I have made no changes to the relevant code for a long time, so I am at a loss as to why this suddenly stopped working. Does anyone have any insight as to the source of this problem?

authenticating a service account to call a Google API with JavaScript client library

I want to make JSON-RPC calls from localhost (WAMP environment) to the Google FusionTables API (and a couple of other APIs) using the Google Client Library for JavaScript
Steps I have taken:
setup a project on the Google Developer Console
enabled the FusionTables API
created a service account and downloaded the JSON file.
successfully loaded the JS client library with the auth package: gapi.load('client:auth2', initAuth);
constructed the init method parameter the following 3 ways:
the downloaded JSON verbatim
the downloaded JSON modified to include the scope
just the client ID and scope
tried (and failed) to initialize the GoogleAuth instance: gapi.auth2.init(params)
function failed(reason) {
console.log(reason);
}
gapi.load('client:auth2', initAuth);
function initAuth() {
var APIkey = 'MY API KEY';
gapi.client.setApiKey(APIkey); //I understand this to be unnecessary with authorized requests, included just for good measure
var GDTSAKey = 'MY SERVICE ACCOUNT KEY';
var scopes = 'https://www.googleapis.com/auth/fusiontables';
gapi.auth2.init({
client_id: "101397488004556049686",
scope: 'https://www.googleapis.com/auth/fusiontables'
}).then(signin, failed("couldn't initiate"));
//passing the downlaoded JSON object verbatim as parameter to init didn't work either
} //initAuth()
function signin() {
gapi.auth2.getAuthInstance().signIn().then(makeAPIcall), failed("couldn't sign-in");
}
function makeAPIcall(){
gapi.client.load('fusiontables', 'v2', function(){
var tableId = '1PSI_...';
var table = gapi.client.fusiontables.table.get(tableId);
document.querySelector("#result").innerHTML = table;
});
}
based on JS client library >> Samples
the gapi.auth2.init method invokes the second callback (which I understand to be an error handler): failed("couldn't initiate"), but then, curiously, I also get `couldn't sign in' which could only have originated from within the provided success handler. What's going on? How do I get this to work?
Note: I am only willing to try the CORS/xhr, if there is no way to do it with JS client lib.
What's going on?
You are trying to use a service account with the Google JavaScript client library which does not support service accounts.
How do I get this to work?
Switch to Oauth2 authentication or if you must use a service account switch to a server sided language like PHP or python for example. Which support service account authentication.

Google Drive API Error Daily Limit for Unauthenticated Use Exceeded

Im getting error on using Google API.
having right to connect with Google Drive and add new sheet and insert data into it.
It was working till yesterday but when i run the application today.
Im getting error :
Error appears after users given token and tried to access the DRIVE API to get all the files
domain: "usageLimits"
extendedHelp: "https://code.google.com/apis/console"
message: "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
reason: "dailyLimitExceededUnreg"
I have not changed any settings.
Following API are enables for my application access token. Do i have to add / enable more API to make it work.
I was using NodeJS to download a file, but was forgetting to pass the auth.
Initially I was using:
function downloadFiles() {
const service = google.drive('v3');
const dest = fs.createWriteStream('/tmp/foo.csv');
const fileId = '12345_ID_GOES_HERE';
service.files.export({
fileId: fileId,
mimeType: 'text/csv'
});
}
afterwards, I added an auth argument to the function, and passed it to the export method as well:
function downloadFiles(auth) {
const service = google.drive('v3');
const dest = fs.createWriteStream('/tmp/foo.csv');
const fileId = '12345_ID_GOES_HERE';
service.files.export({
auth: auth,
fileId: fileId,
mimeType: 'text/csv'
})
}
I am getting auth by creating an instance of google-auth-library
The problem was while getting access token. I was not providing correct scopes.
When i changed the scope to
https://spreadsheets.google.com/feeds https://docs.google.com/feeds
https://www.googleapis.com/auth/drive.file
it worked fine

Youtube Data API and Google Cloud Endpoints

I'm having issues getting Google cloud endpoints working in tandem with the YouTube data API v3 in my javascript client. I think my issue is around the gapi.client.setApiKey() method setting the key for both my endpoints API and the YouTube api. When I do set the key YouTube works but my endpoints do not and I see the following error using my endpoints API:
{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured. The API () is not enabled for your project. Please use the Google
Developers Console to update your configuration.",
"extendedHelp": "https://console.developers.google.com"
}
Without the key my endpoints work but youtube search does not and I get this message using the search feature:
{
"domain": "usageLimits",
"reason": "dailyLimitExceededUnreg",
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"extendedHelp": "https://code.google.com/apis/console"
}
The code that loads the API is summarised below but essentially I have followed the endpoints python/javascript tutorial and the youtube data API tutorials!
init = function(apiRoot) {
var apisToLoad;
var callback = function(){
if(--apisToLoad == 0){
enableButtons();
}
}
apisToLoad = 2; // must match number of calls to gapi.client.load()
gapi.client.load('myAPIName', 'v1', callback, apiRoot);
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
};
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
//sets the api key
gapi.client.setApiKey('APIKeyForYouTubeFromDevConsole');
}
To verify only the youtube API requests with the API key remove the api.client.setApiKey method call.
In calls to the YouTube data API add a key parameter to the API request:
var request = gapi.client.youtube.search.list({
part: 'snippet',
type: 'video',
maxResults: 12,
q: searchValue,
key: 'YourAPIKeyGoesHere'
});
This means only these API calls are authorised and not the endpoints calls.
I'm not extremely familiar with the Youtube Data API. But I recognize the code you used for your Endpoints as the code that we provide. You can definitely use this code for the Endpoints API. For the Youtube Data one, I suggest looking here.
Looks like the code you need would be something like this :
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.services.youtube.YouTube;
public class myClass {
/**
* Define a global instance of a Youtube object, which will be used
* to make YouTube Data API requests.
*/
private static YouTube youtube;
public static void main(String[] args) {
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
try {
// Authorize the request.
Credential credential = Auth.authorize(scopes, "invideoprogramming");
// This object is used to make YouTube Data API requests.
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
.setApplicationName([YOUR APP])
.build();
}
From there you should be able to use the youtube object to make your calls, and the gapi to send stuff to your endpoint.

Categories

Resources