Getting File Not Found on Export of Google Drive - javascript

I'm getting a 404 file not found error when using the google drive v3 API. The file-Id I'm getting from google picker so I know the id is correct. The offending code is as following (javascript):
downloadFile: function () {
var _this = this;
gapi.client.init({
apiKey: this.developerKey,
clientId: this.clientId,
discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'],
scope: 'https://www.googleapis.com/auth/drive'
}).then(function () {
// not working with private files
gapi.client.setToken(_this.oauthToken);
gapi.client.drive.files.export({
'fileId': _this.selectedFileId,
'mimeType': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}).then(function (response) {
console.log('success!');
});
}, function (error) {
console.log(error);
});
}, function (error) {
console.log(error);
});
}
Funnily enough it doesn't happen with all files only private files. So I assume the file not found error is just a generic response back from google indicating I wasn't allowed to access the file.
Oddly enough doing a files.get works fine:
gapi.client.drive.files.get({
fileId: _this.selectedFileId,
supportsTeamDrives: true
}).then(function (response) {
console.log('worked');
}, function (error) {
console.log('failed');
});

I saw this same error when I used the https://www.googleapis.com/auth/drive.file permission: to get export to work you need to have at least the https://www.googleapis.com/auth/drive.readonly permission granted to the OAuth token you are using.

Related

after deploy, fcm alert function is not working... java.lang.IllegalArgumentException: Exactly one of token, topic or condition must be specified

I made alert service using FCM, it works fine in my local server. but after I deployed my server in ec2, trying alert function on ec2 app gives me this error :
[ient-SecureIO-1] o.a.t.websocket.pojo.PojoEndpointBase : No error handling configured for [springboot.utils.WebsocketClientEndpoint] and the following error occurred
java.lang.IllegalArgumentException: Exactly one of token, topic or condition must be specified
Reading the error message, i guess that there's no token in my server.
In notification.js, I'm trying to get token and request POST to '/register'
const firebaseModule = (function () {
async function init() {
// Your web app's Firebase configuration
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/firebase-messaging-sw.js')
.then(registration => {
var firebaseConfig = {
configuration Information
};
// Initialize Firebase
console.log("firebase Initialization");
firebase.initializeApp(firebaseConfig);
// Show Notification Dialog
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function() {
console.log("Permission granted to get token");
return messaging.getToken();
})
.then(async function(token) {
console.log("Token: ", token);
await fetch('/register', { method: 'post', body: token })
messaging.onMessage(payload => {
const title = payload.notification.title
const options = {
body : payload.notification.body
}
navigator.serviceWorker.ready.then(registration => {
registration.showNotification(title, options);
})
})
})
.catch(function(err) {
console.log("Error Occured : " +err );
})
})
})
}
}
And by debugging it by console.log(), I found out that code is stopped before "if ('serviceWorker' in navigator) {"
So I need to make it proceed. But to be honest, it's been a while since i made this function, and I don't know almost anything about Javascript. I don't even know what navigator means(I googled it, but couldn't find clear answer) I'm having trouble figuring out what is wrong and how can I fix it. Can someone help me??

Google API demo does not work locally; GAPI is null

I copied Google's demo code from this tutorial:
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get
However, when I tried to run this locally, I get the error below.
testoJS.html:14 Uncaught TypeError: Cannot read property 'signIn' of null
at authenticate
I'm not sure why the gapi variable is null even though the code imports the api module beforehand.
Here is a copy of my code; my client id, api key, and spreadsheetid are correct - I tested those values in the above website's "try this API" section. The http request works great there and returns the spreadsheet's content. However, I can't seem to run it locally.
<html>
<head></head>
<body>
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for sheets.spreadsheets.values.get
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#javascript
*/
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/spreadsheets.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("API_KEY");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/sheets/v4/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.sheets.spreadsheets.values.get({
"spreadsheetId": "SPREADSHEETID",
"range": "A1:D4"
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "CLIENT_ID"});
});
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
</body>
</html>

Shared files can't access(get list of shared file) using drive.file scope Google Drive API

The file is shared success and the shared user gets an email notification, file display in the user google drive but when we try using API to get shared files, it is not working.
var SCOPES = ["https://www.googleapis.com/auth/drive.file", "profile"];
function createPermissions(fileId, body) {
gapi.client.load("drive", "v3", function() {
gapi.client.drive.permissions
.create({
fileId: fileId,
resource: body
})
.then(function(res) {
//console.log(res);
Swal.fire("Success!", "File has been success shared!", "success");
// do something
})
.catch(function(err) {
//console.log(err);
Swal.fire({
icon: "error",
title: "Oops...",
text: "Something went wrong! Plese try agian later!!",
footer: ""
});
// do something
});
});
}
The above code is working fine, the file is successfully shared but when shared user login in-app user can't access shared files.
Anyone please suggest/help to fix the above issue?
Thanks
I would suggest you call the Drive API in this way:
// This is a good scope for testing
const SCOPES = ["https://www.googleapis.com/auth/drive"];
// This code takes into consideration that you already did all the OAuth2.0 proccess
// correctly to connect to the Drive API
module.exports.init = async function (){
// Create the Drive service
const drive = google.drive({version: 'v3', oauth2Client});
// Create permissions for an user
await createPermissions(drive, null, null);
}
// This function will create the permissions to share a file using Promises
function createPermissions(drive, fileId, body){
// These parameters are for test, past the values you want as arguments
fileId = fileId || "your-file-id";
body = body || {
"role": "writer",
"type": "user",
"emailAddress": "user#domain"
};
// Create the promise and return the value from the promise if you want to
return new Promise((resolve, reject) => {
try {
// Call the endpoint, if there are no errors you will pass the results to resolve
// to return them as the value from your promise
return drive.permissions.create({
fileId: fileId,
resource: body
},
(err, results) => {
if(err) reject(`Drive error: ${err.message}`);
resolve(results);
});
} catch (error) {
console.log(`There was a problem in the promise: ${error}`);
}
});
}
I tried it and the files are shared successfully to the user I wanted. Keep in mind to build your body as:
{
"role": "writer",
"type": "user",
"emailAddress": "user#domain"
};
Docs
Here are some links to know more about the Drive API Permissions:
Permissions.
Permissions: create.

firebase.messaging.getToken() not working as expected on Google Chrome

I'm trying to ensure that I'll be able to get an fcm device token from firebase whenever I request one via messaging.getToken(). Though I'm having an issue retrieving the token constantly on Google Chrome, it works intermittently.
When I test getting an FCM device token on page refresh on Firefox, it works every single time without fail and I receive a token in my callback function.
On the other hand with Google Chrome, its a completely different story, I only manage to receive a token intermittently. My code stops running at the point where I print in the console "Notification permission granted". No error messages from the catch block.
Upon further investigation, I found that the function messaging.getToken() does not return a token i.e. it was undefined, again, this only happens when I use Google Chrome.
I also tried doing this in a Brave browser, the behavior is similar to that of Google Chrome, except with Google Chrome, when I paste the following code into the console:
if(token){
console.log("value of token is:", token)
}
else
{
console.log("value of token is:", token);
}
});
it actually prints the token, whereas Brave doesn't.
Then of course IE and Safari don't support Firebase messaging
Code
firebase-init.js:
var firebaseConfig = {
apiKey: "api-key-here",
authDomain: "domain-here",
databaseURL: "data-base-url-here",
projectId: "project-id",
storageBucket: "storage-bucket",
messagingSenderId: "sender-id-here",
appId: "app-id-here"
};
console.log(firebase);
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
// Request for permission
Notification.requestPermission()
.then((permission) => {
console.log('Notification permission granted.');
console.log(permission);
//code stops running here on google chrome
messaging.getToken()
.then((currentToken) => {
if (currentToken) {
console.log('Token: ' + currentToken);
sendTokenToServer(currentToken);
var data = { newToken: currentToken };
var url = "/Account/UpdateFirebaseToken";
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
dataType: "text",
processData: false,
contentType: "application/json; charset=utf-8",
success: function (data, status, jqXHR) {
console.log("successfully retrieved token:", data, status, jqXHR);
},
error: function (jqXHR, status, err) {
console.log(err);
},
complete: function (jqXHR, status) {
console.log("request complete");
}
});
} else {
//doesn't reach here
console.log('No Instance ID token available. Request permission to generate one.');
setTokenSentToServer(false);
}
})
.catch(function (err) {
//doesn't reach here either
console.log('An error occurred while retrieving token. ', err);
setTokenSentToServer(false);
});
})
.catch(function (err) {
console.log('Unable to get permission to notify.', err);
});
//});
firebase-messaging-sw.js:
importScripts('https://www.gstatic.com/firebasejs/6.2.3/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/6.2.3/firebase-messaging.js');
var config = {
apiKey: "api-key-here",
authDomain: "auth-domain-here",
messagingSenderId: "sender-id",
};
firebase.initializeApp(config);
var messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
var dataFromServer = JSON.parse(payload.data.notification);
var notificationTitle = dataFromServer.title;
var notificationOptions = {
body: dataFromServer.body,
icon: dataFromServer.icon,
data: {
url: dataFromServer.url
}
};
return self.registration.showNotification(notificationTitle, notificationOptions);
});
self.addEventListener("notificationclick", function (event) {
var urlToRedirect = event.notification.data.url;
event.notification.close();
event.waitUntil(self.clients.openWindow(urlToRedirect));
});
Removing the following script tag:
<script src="https://cdn.jsdelivr.net/npm/promise-polyfill"></script>
from my _Layout.cshtml resolved the issue.
I'm not sure how that script is interfering with the promises, but I'd really appreciate it if someone could explain it to me.
It seems to be related with IndexedDB (that's where it hangs when debugging
the firebase code).
I had the exact same issue you did although I was injecting promise-polyfill through a webpack build. Your post allowed me to fix something that was making me mad for several weeks.
I resolved my particular issue by only applying the polyfill if window.Promise was not present so that my code (and the firebase SDK) would use the native Promise.

Is there a way to execute spreadsheets.values.update without OAuth authentication?

I'm making a discord bot that will be open to the public to use, and it will work by updating a google spreadsheet with values given in a command. Unfortunately, from what I see in the API documentation's "Try this API" feature, I can only use Google OAuth v2. Using an API key as a form of authentication gives me the error: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project. How can I make it so that a user doesn't need to sign in for this to work?
This is the code:
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/spreadsheets"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/sheets/v4/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.sheets.spreadsheets.values.update({
"spreadsheetId": "1AFCiplLlZRdO5Phb4DUh8M8sKKnUimJftVDGH9UAA3M",
"range": "Ratings!H2",
"valueInputOption": "RAW",
"resource": {
"values": [
[
7.5
]
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: YOUR_CLIENT_ID});
});
Thank you if you can help me, this has been stumping me for a while now.
spreadsheet: https://docs.google.com/spreadsheets/d/1AFCiplLlZRdO5Phb4DUh8M8sKKnUimJftVDGH9UAA3M/edit#gid=569426832

Categories

Resources