Showing posts with label apps. Show all posts
Showing posts with label apps. Show all posts
Thursday, March 12, 2015
New Apps Script features at Google I O—again!
This Wednesday is the start of our annual developer conference, Google I/O, and we can’t wait to share a bunch of new features that will help developers do more with Apps Script. So let’s not wait! Check out these new features launching today:

Scripts in Google Docs
Many of you have told us that you want to be able to extend Google Docs just like Google Sheets, with custom menus, dialogs, and triggers. Starting today, you can do just that (plus custom sidebars, too). To learn more about Apps Script in Docs—including a couple of secret features that we can’t tell you about yet!—please tune into the live stream with me and Jonathan Rascher on Thursday at 3:30pm PT.
Forms Service / Scripts in Google Forms
In response to another top request, you can now use the Forms Service to programmatically create and modify Google Forms, including triggers and a better way to respond to form submissions. (We’ve created a new 5-minute quickstart to get you going.) You can also extend the Google Forms editor with the same custom menus, dialogs, and sidebars as Google Docs. If you’re at I/O, learn how to build Forms with Apps Script by joining Eric Koleda and Matthew Ziegelbaum on Wednesday at 1:55pm PT.Drive Service
For those of you who use the DocsList Service to automate your Google Drive, a newer version is now available. Drive Service comes with new features like setting the owner of a file or folder or changing the sharing settings. We designed the new service from the ground up to make it easier to work with large numbers of files and also fixed a lot of bugs. If you’re at I/O, Arun Nagarajan and John McGowan will give you more insight into Drive integration on Thursday at 1:40pm PT.Faster HtmlService
At Google I/O 2012, we launched HtmlService to let you build custom user interfaces with secure client-side scripting. Starting today, you can enable an experimental version of the client-side sandbox that runs significantly faster in any browser that supports ECMAScript 5 strict mode.Improved Authorization Flow and API Console Integration
You’ve also told us that authorizing a script takes too many steps. Now, you can opt in to an experimental new authorization flow that requires fewer clicks. In addition, every script that uses the new flow automatically creates a project in the Google APIs Console. This makes it much easier to use Google APIs that aren’t built in to Apps Script. To upgrade a script to the new flow, select File > Upgrade authorization experience. If you’re at I/O, Arun Nagarajan and Christoph Schwab-Ganser will demonstrate the new flow in their session on using the YouTube Analytics API with Apps Script on Wednesday at 1:55pm PT.As you can see, we’ve been working hard to improve Apps Script for you. We hope you enjoy the new features!
![]() | Saurabh Gupta profile | twitter | blog As the product manager for Google Apps Script, Saurabh is responsible for Apps Script’s overall vision and direction. |
How to use Google Apps APIs to handle large files
Editors Note: This post is the second in a series written by Michael Cohn and Steve Ziegler from Cloud Sherpas, a software development and professional services company. We invited Cloud Sherpas to share their experiences building an application on top of Google Apps utilizing some of our APIs. Cloud Sherpas will also be participating in the Developer Sandbox at Google I/O this May where theyll be demoing their use of Google technologies and answering questions from attendees.
SherpaTools Directory Manager allows administrators to easily manage User Profiles and Shared Contacts in the Google Apps directory. SherpaTools is built on Google App Engine (GAE) utilizing the Google Web Toolkit (GWT), and makes heavy use of the Google Apps Management and Application APIs to provide new administrator and end-user features.
Last week we wrote about how SherpaTools Directory Manager uses Two Legged OAuth for authentication, and GAE Task Queue API and the Google Datastore APIs to make it easy to divide large retrievals over long intervals into smaller chunks. This week we will discuss how we used the User Profile API to retrieve the data sets and the Document List Data API to populate a Google Spreadsheet.
The features in SherpaTools use a number of additional Google Apps APIs. For example, contact data may be imported from or exported to Google Docs Spreadsheets. In the case of export, contacts are retrieved via the User Profiles or Shared Contacts API and written to memcache. Next, a new Spreadsheet is created via the Documents List Data API and the CSV byte stream is added as the media type. Below is a technical explanation of how we retrieved the User Profiles and exported them to a Google spreadsheet.
Retrieving and Storing User Profile Entries
The User Profile API makes it easy to divide retrieval of all profile entries into multiple fetch operations. The one area to tweak for this call is the size of results that can reliably be returned within 10 seconds on Google App Engine. In our testing, 100 entries per page is about the right size. Once configured, we will retrieve the feed containing the first set of entries, parse the response, and persist the results to cache. If that feed contains a link to another page containing more entries, we queue up a task to handle the next page and repeat until all pages are processed:ContactQuery query = null;//if this is the first page, there is no next link. Construct initial page urlif (nextLink == null) {String domain = getDomain(loggedInEmailAddress);String initialLink = PROFILES_FEED + domain + PROJECTION_FULL;query = new ContactQuery(new URL(initialLink));query.setMaxResults(GAE_OPTIMAL_PAGE_SIZE);} else {query = new ContactQuery(new URL(nextLink));}query.setStringCustomParameter(TWO_LEGGED_OAUTH_PARAM, loggedInEmailAddress);//fetch next profile feed containing entriesProfileFeed feed = contactsService.query(query, ProfileFeed.class);List> currentMaps = (List >)memcacheService.get(memcacheKey); for(ProfileEntry entry:feed.getEntries()){//secret sauce: convert entry into csv column header/value mapcurrentMaps.add(converter.flatten(entry));}//store updated list of converted entry maps back into memcachememcacheService.put(memcacheKey, currentMaps);if(feed.getNextLink()!=null){//start task to get next page of entriestasksService.fetchUserProfilesPageTask(spreadsheetTitle, loggedInEmailAddress, feed.getNextLink().getHref(), memcacheKey);}else{//no more pages to retrieve, start task to publish csvtasksService.exportMapsToSpreadsheet(spreadsheetTitle,loggedInEmailAddress,memcacheKey);}}
Exporting Profiles as a Google Docs Spreadsheet
One of the trickiest obstacles to work around in this effort is generating the Spreadsheet file since GAE restricts the ability to write to the File System. The Spreadsheets Data API was one possibility we considered, but we ended up feeling it was a bit of overkill, having to first create the Spreadsheet using the Docs List API and then populate the Spreadsheet one record per request. This could have generated thousands of requests to populate the entire Spreadsheet. Instead, we leveraged an open source library to write csv file data directly to a byte array, and then sent the file data as the content of the newly created Docs List entry in a single request:Once completed, this method results in a newly created, populated Google Docs Spreadsheet viewable in the logged-in users Google Docs.public void saveRowsAsSpreadsheet(String spreadsheetTitle, String loggedInEmailAddress, String memcacheKey) {//get list of csv column header/value maps from cache:List> rows = (List >)memcacheService.get(memcacheKey); //secret sauce: convert csv maps into a byte arrraybyte[] csvBytes = converter.getCsvBytes(rows);SpreadsheetEntry newDocument = new SpreadsheetEntry();MediaByteArraySource fileSource = new MediaByteArraySource(csvBytes,"text/csv");MediaContent content = new MediaContent();content.setMediaSource(fileSource);content.setMimeType(new ContentType( "text/csv"));//add MIME-Typed byte array as content to SpreadsheetEntrynewDocument.setContent(content);//set title of SpreadsheetEntrynewDocument.setTitle(new PlainTextConstruct(docTitle));URL feedUri = new URL(new StringBuilder(DOCS_URL).append(?).append(TWO_LEGGED_OAUTH_PARAM).append(=).append(userEmail).toString());docsService.insert(feedUri,newDocument);//we are done, time to delete the data stored in cachememcacheService.delete(memcacheKey);}
The one difference between these code examples and the function weve ended up with in production is that, for customers with over 1,000 Google Apps users, we have broken up Spreadsheet creation into worksheets of 1,000 rows per sheet instead of creating one Spreadsheet upon completion of retrieval of all of the User Profiles. This was to avoid running into the default maximum object size ceiling in Memcache, the maximum Google Docs List API upload data size, and the Spreadsheet maximum cell number. Tacking on this logic was not particularly complicated but ends up being quite a bit harder to follow as an example, so we left it out of this discussion.
Conclusion
This post demonstrates an approach to export a large set of Google Apps contact information into a Google Docs Spreadsheet. Many similar long-running, divisible operations can use this same approach to spread work across a string of tasks queued in the GAE Task Queue. Also, the same approach to writing Google Docs files could be used to publish a variety of types of reports from GAE. We would love to hear what you think of this approach and if you have come up with your own solution for similar issues.
Thanks to the Cloud Sherpas team for authoring this post. Check out SherpaTools at www.sherpatools.com
Wednesday, March 11, 2015
Building a Rails based app for Google Apps Marketplace
Editors note: This is a guest post by Benjamin Coe. Benjamin shares tips and best practices on using Ruby on Rails for integrating with Google Apps and launching on the Marketplace. — Arun Nagarajan
Yesware offers an app in the Google Apps Marketplace which allows our users to schedule reminders, from directly within the Gmail UI. Yesware’s app recently relaunched in the updated Google Apps Marketplace. In prep, we revamped our existing Google Apps Integration:
- Replacing OpenID with OAuth 2.0 for Single-Sign-On.
- Replacing 2-legged OAuth with OAuth 2.0 Service Accounts, for delegated account access.
- Releasing a Gmail Contextual Gadget that worked within these new authentication paradigms.
OAuth 2.0 for SSO
In the revamped Google Apps Marketplace, OAuth 2.0 replaces OpenID for facilitating Single-Sign-On. The flow is as follows:- OAuth 2.0 credentials are created in the Cloud Console, within the same project that has the Google Apps Marketplace SDK enabled.
- When accessing your application, a user is put through the standard OAuth 2.0 authentication flow using these credentials.
- If the user has the Google Apps Marketplace App installed they will be logged directly into your application, skipping the authorization step.
To implement the OAuth 2.0 authentication flow, you can use the OmniAuth Google OAuth2 Strategy gem. Assuming youre already using OmniAuth, you simply add a line to initializers/omniauth.rb that looks something like this:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["GAM_OAUTH_KEY"], ENV["GAM_OAUTH_SECRET"]
end
Yesware already had a Google OAuth 2.0 authentication strategy, so we opted to subclass the Google OAuth 2.0 OmniAuth Strategy. This allowed us to continue supporting our existing OAuth 2.0 credentials, while adding support for Google Apps Marketplace SSO. Our subclassed strategy looked like this:
# Subclass the GoogleOauth2 Omniauth strategy for
# Google Apps Marketplace V2 SSO.
module OmniAuth
module Strategies
class GoogleAppsMarketplace < OmniAuth::Strategies::GoogleOauth2
option :name, google_apps_marketplace
end
end
end
Our final initializers/omniauth.rb file was this:
Note that :access_type is set to online. This is necessary to prevent the authorization prompt from being presented to a SSO user. Omniauth defaults to an :access_type of offline.
Thats all it takes. With this OmniAuth strategy in place, when a domain administrator installs your application SSO will be available across the domain.
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["OAUTH_KEY"],
ENV["OAUTH_SECRET"],
{:scope => ENV["OAUTH_SCOPE"]}
provider :google_apps_marketplace, ENV["GAM_OAUTH_KEY"],
ENV["GAM_OAUTH_SECRET"],
{ :scope => ENV["GAM_OAUTH_SCOPE"],
:access_type => online }end
Note that :access_type is set to online. This is necessary to prevent the authorization prompt from being presented to a SSO user. Omniauth defaults to an :access_type of offline.
Thats all it takes. With this OmniAuth strategy in place, when a domain administrator installs your application SSO will be available across the domain.
OAuth 2.0 Service Accounts
To support Yeswares reminder functionality, we needed offline access to a users email account. In the past, this functionality was supported through 2-legged OAuth. In the new Google Apps Marketplace paradigm, OAuth 2.0 Service Accounts are the replacement.- In the Cloud Console, generate a private key for the OAuth 2.0 Service Account associated with your Google Apps Marketplace project.
- Download the .p12 private key generated.
- Place this key somewhere that will be accessible by your production servers, e.g., a certificates folder in your codebase.
Using the deprecated 2-Legged OAuth based approach, our authorization logic looked like this:
Rather than OpenID, we used OAuth 2.0 for associating the opensocial_viewer_id with a user. To do this, we needed to modify our OmniAuth strategy to store the opensocial_viewer_id during authentication:
Gmail.connect!(:xoauth, ben@example.com, {
token: authentication.token,
secret: authentication.secret,
consumer_key: google.key,
consumer_secret: google.secret,
read_only: true
})
Using the new Service Account Based Approach, it was as follows: key = Google::APIClient::PKCS12.load_key(With OAuth 2.0 Service Accounts, the underlying libraries we used to interact with Gmail remained the same. There were simply a few extra steps necessary to obtain an access token.
google_apps.service.p12path, # this is a constant value Google uses
# to password protect the key.
notasecret
)service_account = Google::APIClient::JWTAsserter.new(
google_apps.service.email,
https://mail.google.com/,
key
)client = Google::APIClient.new(
:application_name => APPLICATION_NAME,
:version => APPLICATION_VERSION
).tap do |client|
client.authorization = service_account.authorize(ben@example.com)end
Google.connect!(:xoauth2, ben@example.com, {
:oauth2_token => client.authorization.access_token,
})
Contextual Gadgets and SSO
Yesware provides a Gmail Contextual Gadget, for scheduling email reminders. To facilitate this, its necessary that the gadget interact with a users email account. To make this a reality, we needed to implement SSO through our contextual gadget. Google provides great reading material on this topic. However, the approach outlined concentrates on the deprecated OpenID-based SSO approach. We used a slightly modified approach.Rather than OpenID, we used OAuth 2.0 for associating the opensocial_viewer_id with a user. To do this, we needed to modify our OmniAuth strategy to store the opensocial_viewer_id during authentication:
# Subclass the GoogleOauth2 Omniauth strategy forOnce an opensocial_viewer_id was connected to a Yesware user, we could securely make API calls from our contextual gadget. To cut down on the ritual surrounding this, we wrote a Devise Google Apps OpenSocial Strategy for authenticating the OpenSocal signed requests.
# Google Apps Marketplace V2 SSO.
module OmniAuth
module Strategies
class GoogleAppsMarketplace < OmniAuth::Strategies::GoogleOauth2
option :name, google_apps_marketplace
def request_phase
# Store the opensocial_viewer_id in the session.
# this allows us to bind the Google Apps contextual
# gadget to a user account.
if request.params[opensocial_viewer_id]
session[:opensocial_viewer_id] = request.params[opensocial_viewer_id]
end
super
end
end
end
end
Now Go Forth
Once we figured out all the moving parts, we were able to use mostly off the shelf mature libraries for building our Google Apps Marketplace Integration. I hope that this retrospective look at our development process helps other Rails developers hit the ground running even faster than we did.| | Benjamin Coe profile Benjamin Coe cofounded the email productivity company Attachments.me, which was acquired by Yesware, Inc., in 2013. Before starting his own company, Ben was an engineer at FreshBooks, the world’s #1 accounting solution. Ben’s in his element when writing scalable cloud-based infrastructure, and loves reflecting on the thought-process that goes into this. A rock-climber, amateur musician, and bagel aficionado, Ben can be found roaming the streets of San Francisco. ben@yesware.com — https://github.com/bcoe— @benjamincoe |
Tuesday, March 10, 2015
Last Call for Google I O Google Apps Challenge
On March 8th, we announced the Last Call for Google I/O contest for a chance to win tickets to the event. The contest is currently underway -- with 5 challenges remaining.
The last challenge, starting on March 29th at 4:00 P.M. PDT, will be based on Google Apps and we’d encourage all eligible developers to participate. To be sure that you’re prepared for the challenge, we have indicated a prerequisite to read up on Google Apps Script.
For more information on the contest rules and timeline, please see the Google Code Blog and the Contest Site.
The last challenge, starting on March 29th at 4:00 P.M. PDT, will be based on Google Apps and we’d encourage all eligible developers to participate. To be sure that you’re prepared for the challenge, we have indicated a prerequisite to read up on Google Apps Script.
For more information on the contest rules and timeline, please see the Google Code Blog and the Contest Site.
Posted by Ryan Boyd, Google Apps Team
Want to weigh in on this topic? Discuss on Buzz
Subscribe to:
Posts (Atom)
