Google App Script: ContentService web app usage - google-apps-script

I am stuck for 3 days now trying to get 2 google gadgets to reliably communicate on a google site to exchange anonymous user session information based on UiInstance.getId() value. Since gadget-to-gadget pubsub feature is deprecated, I am trying to use the ContentService in the server gadget to service a doPost request from originating from the client gadget - the idea being, I will store the session information in a server gadget and pull the data into gadgets on other pages in the site - not sure if this is possible.
BUT, I am stuck even trying to tinker with the various examples on the ContentService posted on StackOverflow. I am stuck at a very basic step and unable to proceed beyond the super simple server code below. I am not able to figure out what would the URL of the server gadget I need to use from my client gadget. I seem to be getting confusing results.
Server code:
function doGet(e) {
var output = ContentService.createTextOutput();
output.setContent("Hi from ContentServer!");
return output;
}
Steps I followed:
1) Published the server as a web app and set it up so anyone/anonymous can access it.
2) The publish window popup says the gadget is available at
https://script.google.com/macros/s/AKfycbyIa07kBC-gqG0nJq3Up5GzUntbTaYcM1KmaYF7vQvFIWN_qxA/exec
3) If I use a browser to open the link, I get "Unknown macro doGet".
4) If I click on the link given by "Test web app for your latest code." from the publish window popup, it seems to take me to
https://script.googleusercontent.com/echo?user_content_key=WwuWW_Hhp2wlHpHWsX-qAwu7jtKrwlt1fkkesojKEWeJXKm5AoUOhuRHxu4RIHLrWovOBUsHhOB3No0RYr05RE4tWtliFlXKm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnG5I1NuldcVdfVF6dOROkmljXtr0dWIARhfeRbamxWJIIJeMc5tWnrGPpehwqDtynQ&lib=MfYY3NqJ0IdcpreIfwd3uwgmzn1S_adTp
The above link from step 4 works from a browser BUT its very flaky from my client gadget! It seems to work the very first time I version and publish it but returns raw HTML if I update the version even once.
I believe I am missing some trivial step OR there is a serious version control or deployment bug with web-app gadgets.
I have checked out the following threads on stackoverflow that were pretty useful.
How to use ContentService and doPost to create a REST API
KamilG seems to have overcome the issue here Another doGet() issue with Google Apps Script - "Unknown macro doGet" error
But its very wobbly for me and I am unable to pin down any reliable procedure the get the ContentService working from my server gadget.
Any help and explanation will be much appreciated.
Here is my client gadget code.
function doGet(e) {
// var url = "https://script.google.com/macros/s/AKfycbyIa07kBC-gqG0nJq3Up5GzUntbTaYcM1KmaYF7vQvFIWN_qxA/exec";
//var url = "https://script.googleusercontent.com/echo?user_content_key=9tzQxTSPm8ADsHKl4bCg6ru-49C19kYZCW8IRuWiWi-Xe_lTlQZS4xq8v5aPqjR6Ybj7-xjjJXyQPhOH0T3KFtJUtXc7U-Dkm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnJlCLn2pnKC0O1TYz53ccgjxtVC9ccM8kFegFJ0AJSK_YP_ylqfjfm1EU_BUbZUu-88PMDJ6xpj8&lib=MTLHdJRs3UPYj3bYgbhBNnNGZ7UmftE34";
var url = "https://script.googleusercontent.com/echo?user_content_key=LvlwGkBktQ732xyD1HJbh5OhMsuhkidt_rOovw-olm-wJQF4LlErMDSxsfDaAb4UBYqOeTI3-8soIBj-KaOCDi0WlUav4Nl_m5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnG5I1NuldcVdfVF6dOROkmljXtr0dWIARhfeRbamxWJIIJeMc5tWnrGPpehwqDtynQ&lib=MfYY3NqJ0IdcpreIfwd3uwgmzn1S_adTp";
// WELL ONE OF THE URLS WORKS FROM ABOVE!!! BUT ONLY TILL I UPDATE THE SERVER WEB APP VERSION :(
var app = UiApp.createApplication().setTitle("ClientService Client test");
app.setStyleAttribute("background", "azure");
var fetchMethod = 'get';
var response = UrlFetchApp.fetch(url, {method: fetchMethod});
//var lbl = app.createHTML("<b>Response :</b>" + response.getContentText());
var lbl = app.createTextArea().setText(response.getContentText());
var lbl1 = app.createHTML("<b>Response code :</b> "
+ response.getResponseCode());
app.add(lbl);
app.add(lbl1);
return app;
}
Help needed please.

This functioning as intended for the most part, but I think there might be some alternatives.
Regarding your point #3 - That URL above works. There must have been something wrong with the version you tested (perhaps you didn't declare doGet correctly?).
The link from #4 is a one time use redirect that happens when you Content Service. See the redirect section here all the way at the bottom. This link is short lived and you might be fast enough to catch it in a browser but a another separate calling client (the "gadget") might not be so lucky. So you should never call the googlecontentservice.com link directly.
Regarding the overall issue of flakiness of ContentService, I have not seen this. If I properly use the /exec link and then properly increment the version after every appropriate change things work as expected for me.
I built a simple web app accessing your Content Service and things seem to work fine for me consistently. See below. The code looks identical to yours but I am using the first url.
https://script.google.com/macros/s/AKfycbw6nlfv5ME6F3Z2WBdW24YAgfQm_E5gYV0xrMDvDwZLrX7PdMU/exec
As an alternative - is there a reason you are doing a server side UrlFetch from one script to another? If you can fetch the data server side, can you just perform the logic of the content script w/in the UI script?

Related

How do get the url "https://script.google.com/macros/d/{SCRIPT ID}/usercallback" responding / up and running

I'm a beginner in Google Apps Script.
I'm basically trying to use the OAuth service in a Google Apps Script to be able to connect a Google spreadsheet to Yahoo fantasy API.
I'm using the package you can found here:
https://github.com/googleworkspace/apps-script-oauth2
In the "read me" part you can see that oauth libraries will by default use the callback url https://script.google.com/macros/**d**/{SCRIPT ID}/usercallback
So I try to use this package in my script, but when I publish my script it creates the following url:
https://script.google.com/macros/**s**/{SCRIPT ID}/
Notice it's an "s" instead of the "d" in the url.
I can access properly to https://script.google.com/macros/**s**/{SCRIPT ID}/exec and so on but the url containing the "d", which is expected to be use by OAuth service, return an error.
When trying to access the url in a browser I got:
an error if I call ../usercallback
the message: "Sorry, the file you've asked doesn't exist", if I call the ../exec
.. is https://script.google.com/macros/**d**/{SCRIPT ID} in that case.
I've been looking on internet for having this url working but no success (it that so obvious that no one else had the issue except me?).
I tried several thing, i've created a project and linked my script to that project, i played a bit with the configuration in the project in regards to what i found on internet, like credential for API, but still can't have the url with a "/d/" responding.
I'm not sure of the meaning of the "s" (script?) or the "d" in the url.
I'm not sure if it has something to do with the way I publish my script or if I need to have specific function in my script or maybe some configuration of the script, maybe I need to persevere with the project thing...
I think that you should re-read the Readme.md file from the Google OAuth Sample GitHub repo. Also I think that d and s parts of Google Apps SCript URLs are irrelevant for using the "OAuth Service".
The .../exec URL is generated when making a new deployment. This URL doesn't contain the script Id... please bear in mind that a single Google Apps Script project might be deployed multiple times and have all or some deployments being live at the same time. Each web app deployment will have it's own URL... none of them have the script id. By the other hand, you might not need to make a deployment in order to be able to use "the OAuth service", this is needed only if the script will be receiving GET/POST HTTP requests.
You should not to access the ../usercallback in the browser, as you will be doing a GET request without proving the required data. This URL should be added when getting the credentials to be used with the "OAuth Service" from the OAuth provider, in this case Yahoo, as the redirect URI.
The referred repo includes multiple samples about how to use the "OAuth Service", one of the is Yahoo.gs
Resources
https://developers.google.com/apps-script/guides/web
https://developers.google.com/apps-script/concepts/deployments

In Google Apps Script, avoid second 'Review Permissions' prompt, possibly by using approval_prompt

I have searched StackOverflow, etc. for a solution to this problem, and several answers 'point me in a direction' (mentioning approval_prompt = auto not approval_prompt = force), but none are applicable (as far as I can tell) to my situation.
I have a Web Application hosted at www.mjpanel.com that expects to use a Google Apps Script that I 'own', but the Javascript at www.mjpanel.com calls the Google Apps Script (deployed as a Web App with doGet()) as a Web Service. It expects the web service call to return various JSON objects.
If the user has not yet authorized my application, the call to the Google Apps Script Web App / Web Service will not return a JSON object, causing www.mjpanel.com Javascript code to fail saying "Invalid Request" (because it isn't a JSON object as my code expects).
To prevent this from happening, www.mjpanel.com uses gapi.auth2.init to get the permissions/scopes it needs. I'm developing everything now, so if/whenever the Google Apps Script evolve to use something (like sending GMail emails as the user) that is new, I have been figuring out the scope to request, adding it to the list of scopes in the gapi.auth2.init call, and everything is fine. The next time a user uses the app., they get initially prompted for the newly added scope, then everything proceeds fine.
However, now sometimes one of my test users has a Web Service call fail because Google Apps Script is returning another request for permissions for a 'new permission' of 'Have Offline Access'.
There's nothing about my script that would warrant the user needing to grant this permission.
When I research, a lot of stuff (mostly about requesting OAuth2 stuff in a 'structure' different than the way my app. is set up) says it has to do with submitting a 'approval_prompt=force' in my request URL.
However, the way I have my app set up, all the URLs I would use (aside from my 'custom stuff' in the query string) are dictated by Google Apps Script. And I can't find any place where any URL I use has an approval_prompt in it.
I can't figure out where I would need to configure that approval_prompt to be auto (as is recommended in the 'successful answers' I find).
Of if the idea of approval_prompt is 'on the wrong track', any information in general to help me solve this problem would be greatly appreciated.
Thanks in advance for any help you can give me.
Unfortunately the Google Apps Script native OAuth flow includes approval_prompt=force. This causes the following conditions:
If cookie exists in browser and has permission for this application the consent screen will not be displayed.
If cookie exists in browser but does not have permission for this application: consent screen will be displayed
If cookie does not exist in browser and the application has permissions: application will request 'Have offline access'.
The easiest way around this is to manage your own OAuth flow and use the Execution API. The following link will take you to the javascript quick start.
https://developers.google.com/apps-script/guides/rest/quickstart/target-script

Onedrive API vs LiveSDK

I am developing for WP8.1 and probably will port on other platforms.
I want to integrate a OneDrive functionality, however, I can't understand what is the difference between LiveSDK (from NuGet packages) and OneDrive API.
It seems that Microsoft does not communicate at all regarding that, I really don't understand why. As far as I understood, the LiveSDK is the old one and will be replaced by OneDrive API, but the LiveSDK seems so much simpler to use that I can't understand their logic... On top of that both have been updated recently (in April for the LiveSDK).
So my question is
As long as my app has not been published yet, should I move to
OneDrive API, or keep on the LiveSDK?
Does anyone has already
tried both?
What are the limitations and benefits of both?
Based on a future-proof sight, I will go for the OneDrive API, but my main concern is:
Is is possible to login as easily on OneDrive API than with the Live SDK? (Working temporary solution below)
For now, I have been able to login with the LiveSDK using a single button and three lines of code, no user input required at all, where the AuthenticateAndContinue method used by the OneDrive API opens a Webcontrol and requires to enter manually the login and password.
At the end I have used the LiveSDK Authentication and use the access token provided with the OneDrive API. It is not a clean approach from my point of view, but I couldn't manage to get the AuthenticateAndContinue method to work (I get a 404 error answer after the login).
If anybody has a better solution, I am opened to suggestions :)
[Solution extracted from question to get out of "unanswered" stack]
In summary, my current method is the following:
Authenticate using LiveSDK API
Use the session cookie and the OneDrive API from there
The simplified code is the following:
The method below allows to log in silently, only the first time requires a manual validation from the user allowing the program to use its Live account.
It does not require any password from the user
var authClient = new LiveAuthClient();
var authResult = await authClient.LoginAsync(new string[] {
"wl.signin", "onedrive.readwrite", "onedrive.appfolder"});
if (authResult.Session == null)
throw new InvalidOperationException("You need to sign in and give consent to the app.");
var Connection = new ODConnection("https://api.onedrive.com/v1.0",
new MicrosoftAccountAuthenticationInfo() { TokenType = "Bearer",
AccessToken = odArgs.Session.AccessToken });
It is not as clean as I would like (using 2 different SDK), but it works :)

How to connect to the Facebook Graph API from Google Apps Script?

I'm trying to connect to the Facebook Graph API via a Google Apps Script but I'm getting an error
I've tried:
function myFunction (name) {
FB.init({
appId : '{your-app-id}',
status : true,
xfbml : true,
version : 'v2.0'
});
var jsonData = UrlFetchApp.fetch("graph.facebook.com/"; + name);
}
I've also tried:
function myFuntion(name) {
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id',
xfbml : true,
version : 'v2.0'
});
};
var jsonData = UrlFetchApp.fetch("graph.facebook.com/"; + name);
}
but neither have worked, I always get a:
"ReferenceError: "FB" is not defined." and a "ReferenceError: "window" is not
defined"
and
"(#4) Application request limit reached","type":"OAuthException","code":4}}
despite putting in my facebook app ID into the variable. I know that "window" is part of an external javascript library so that's why I'm unable to use it in a Google Apps Script, but even after looking at other posts I'm still confused on why I get a "FB" is not defined error.
Any ideas on how to solve this?
There are error codes at the bottom of this page:
Facebook Graph API - Error codes
The "OAuthException" has to do with the Login Status. If you get that error, then you aren't logged in, and to get what you want, you need to be logged in.
You can get an App Access Token using a Server to Server request. There are four types of
Access Tokens:
User - to read, modify or write a specific person's Facebook data on their behalf.
App - modify and read the app settings, and publish Open Graph actions.
Page - read, write or modify the data belonging to a Facebook Page.
Client - the client token is used rarely. Very limited Access to Facebook.
Forms of Access Tokens
User access tokens come in two forms: short-lived tokens and long-lived tokens
short-lived - lifetime of about an hour or two - generated via web login
long-lived - lifetime of about 60 days
You probably don't have an App Access Token. You have an App ID, but that's different than an App Token.
You only get your App Token once. You need to run some code to get it.
Note, that you also must know your App Secret in order to run this code. If you don't know, or have your App Secret, then you need to get that.
See if you can run this code:
//A Facebook App Token never changes unless you go to the Facebook Developers Console,
//and you
//change the App Secret. So, do NOT keep requesting a new App Token. Just get it once,
//then
//hard code it into a backend secret function.
// The App Token can be used to modify your App, but you can just do that 'Manually'
function getOneTimeFB_AppToken() {
Logger.log("getOneTimeFB_AppToken ran");
//keep this info secret
//Generate an App Access Token
var myApp_ID = 'Your App ID';
var myAppSecret = 'Your App Secret';
var optnAppTkn = {"method" : "get"};
var getAppTknURL = "https://graph.facebook.com/oauth/access_token?client_id=" + myApp_ID + "&client_secret=" + myAppSecret + "&grant_type=client_credentials"
var getAppTkn = UrlFetchApp.fetch(getAppTknURL, optnAppTkn);
Logger.log("Object returned from GET: " + getAppTkn)
var myAppTkn = getAppTkn.getContentText();
Logger.log("myAppTkn: " + myAppTkn);
};
Run that code, then in the script editor, choose the VIEW menu, and the LOGS menu item. Read what is in the LOGS. Don't keep running this code over and over again. Just run it once if it's successful.
If that code works, then you just successfully communicated with Facebook.
You need to understand what the Tokens can do, and what your options are. If you are not going to get a token from a user through client side authorization, then you need to understand the App Token.
App Tokens allow you to interact with Facebook on behalf of an app rather than a user. This can be used to read YOUR app insights and modify the parameters of YOUR app.
You never want to use an App Token in client side (browser) code. That would be a major security problem.
However, if a user has granted your application publishing permissions, then you can use the App Token to publish content to Facebook on behalf of that person. So, app access token can be used in place of a user access token to make API calls IF your app has been granted publishing permissions.
But how do you get publishing permissions? Well, there is no way to get the initial short term access token through the server. That just makes sense if you think about it in terms of security. You can't get the initial, short term access token any other way than through a client login. So, if you want to do something that isn't within the bounds of the App Access Token, you can't do it without having the user login through client side.
You can achieve a client side login, without using the JavaScript SDK. So, in the case of an Apps Script Stand Alone HTML web app, you can still use Facebook login without needing to link to the Facebook JavaScript SDK. If you need to do that, let me know.
In that code, FB is an object. The object needs to be assigned "key/value" pairs. Every "key/value" pair is an element (property) in the object. The error is directly related to how objects work. That FB object gets assigned values from a link (inside HTML) to the Facebook API. If you are trying to use an HTML link to the Facebook API from server side (.gs) code, it won't work. There are lots of things that could be going wrong. In order to know exactly what is going wrong, we need to know whether that code is in a gs file, or an HTML file inside a <script> tag.
There are a couple of ways to connect to Facebook:
From HTML (Client Side)
From the server with HTTP Requests
It looks like the code you are using is from an example of how to use the Facebook JavaScript SDK that is meant to run from inside HTML. The problem with that, is that Apps Script sanitizes HTML sent to the browser. So, if you try to link to the Facebook JavaScript SDK through the HTML, you may not get access. I know that, in the past, I have not been able to use a link to the Facebook API in HTML with the NATIVE sandboxed mode. I haven't tried the new IFRAME sandbox mode.

Google Drive API says some files do not exist when in fact they do

So, I've gotten to the point in my app where I can retrieve a list of spreadsheet documents from a user's Google Drive account by using the Google Spreadsheet API. I populate the file list in a ui control that users can click on to then retrieve the list of its worksheets. It's working as expected in some cases, but in others it is not. In my request, I use the url that comes back from the file list, and even so, the API responds with:
Sorry, the file you have requested does not exist.
Make sure that you have the correct URL and that the owner of the file hasn't deleted it.
Well, surely the file wasn't deleted. I got it back in the response to my request for the files list. I also can get to the file via a normal web browser. Also, the URL is correct because that's the one the API responded with. My code does not manipulate the url that comes back in that initial files response. In fact, here is the URL that is used to grab the worksheets:
https://spreadsheets.google.com/feeds/worksheets/{long key here}/private/full
So, my question is why does my request for some worksheets come back with a response with the actual list of worksheets, but on others (which I have access to, and I know exists) I get the faulty response.
Thanks,
Arie
My app is using OAuth 2.0 and I ran into the same error with new Google Sheets. What fixed that was making a change in scope param sent during OAuth's authorize call and then reauthorising (reinitiating OAuth flow and obtaining new tokens).
Until now scope in my app was just:
https://spreadsheets.google.com/feeds
Updated scope and solution to the issue in my case:
https://spreadsheets.google.com/feeds https://docs.google.com/feeds
I'm running into this in my own stuff. At least for what I'm running into, it seems to be an issue with New Sheets. I'm sorry to not have more of a solution (I'm still trying to find out what to fix on my end) but this may help you narrow down the issue.