The Google Drive SDK opens up a great number of possibilities of integration with third-party applications and services. One such integration is via the new Web Intents API.
Web Intents lets web developers integrate their web apps with third-party services and avoid implementing the same feature with similar services over and over again. With Web Intents, a service can register itself to handle specific functionality, such as saving a file or sharing data. Client applications can then discover and interact with the service to use that specific functionality.
In this post, we’ll look at code for two example apps: a service that exposes a “save” web intent, and a client that consumes it to save files to Google Drive.
To demonstrate web intents, we wrote a proof of concept app called Cloudfilepicker.com. This is a service that lets users or applications save and retrieve data from Drive via the Web Intents API. With Cloudfilepicker, any application that fires a “save” intent can save to Google Drive without directly implementing the API.
To build a service application like cloudfilepicker.com that interacts with Drive and Web Intents, create a Chrome app whose manifest exposes a http://webintents.org/save intent action. For example:
http://webintents.org/save
{ "name": "Google Drive Web Intent", "version": "1", "app": { "launch": { "local_path": "index.html" } }, "intents": { "http://webintents.org/save": [ { "type" : ["image/png", "image/jpg", "image/jpeg"], "href": "save.html", "title": "Save to Drive" } ] } }
The intent declaration in the app manifest describes the functionality that your application offers, the data it can work with, and what to launch when the user chooses your application.
In order to use the Drive API, the page has to get an OAuth token for the user. The complete JavaScript implementation of the OAuth flow is available in the project repository.
Once the app receives a valid OAuth token, we can load the Drive client library and perform the file upload request using multipart upload. A Web Intent with action http://webintents.org/save can provide the file data in two ways: as a base64-encoded string or a blob, and our app should support both. With the former, we have to pass the string to the request, while with the latter we have to read the blob content and base64 encode it before we can pass it to insertBase64Data:
insertBase64Data
const boundary = '-------314159265358979323846'; const delimiter = "\r\n--" + boundary + "\r\n"; const close_delim = "\r\n--" + boundary + "--"; function makeApiCall(authResult) { gapi.client.load('drive', 'v2', function() { if(window.webkitIntent) { var data = window.webkitIntent.data; if(data.constructor.name == "Blob") { insertFileData(data, authResult, processResponse); } else if(typeof(data) == "string") { var meta = { 'title': "Test Image " + (new Date()).toJSON(), 'mimeType': window.webkitIntent.type }; insertBase64Data(data.replace(/data:image\/([^;]*);base64,/,""), window.webkitIntent.type, meta, authResult); } } }); } function insertBase64Data(data, contentType, metadata, authRequest, callback) { var multipartRequestBody = delimiter + 'Content-Type: application/json\r\n\r\n' + JSON.stringify(metadata) + delimiter + 'Content-Type: ' + contentType + '\r\n' + 'Content-Transfer-Encoding: base64\r\n' + '\r\n' + data + close_delim; var request = gapi.client.request({ 'path': '/upload/drive/v2/files', 'method': 'POST', 'params': {'uploadType': 'multipart'}, 'headers': { 'Content-Type': 'multipart/mixed; boundary="' + boundary + '"' }, 'body': multipartRequestBody}); if (!callback) { callback = function(file) { console.log(file.id); }; } request.execute(callback); } function insertFileData(fileData, authRequest, callback) { var reader = new FileReader(); reader.readAsBinaryString(fileData); reader.onload = function(e) { var contentType = fileData.type || 'application/octet-stream'; var metadata = { 'title': fileData.fileName, 'mimeType': contentType }; var base64Data = btoa(reader.result); insertBase64Data(base64Data, contentType, metadata, authRequest, callback); } }
Now, any web app that wants to save data to Google Drive could use this service instead of implementing the same functionality by invoking webkitStartActivity with a save intent.
webkitStartActivity
An example client app is http://www.imagemator.com. This app lets users manipulate and save images, but has no direct Drive API integration. When the user invokes the “save” intent in imagemator.com, if they have the “Save to Drive” app installed they will see Drive as an option in the list of apps that can fulfill that action:
If the user selects “Save to Drive”, the browser will send a request to the page listed as the href property of the intent declaration -- save.html in the sample manifest above. The following code shows how to trigger the save request:
href
var fileData = canvas.toDataURL(); var intent = new WebkitIntent({'action': 'http://webintents.org/save', 'type':'image/png', 'data': fileData}); var onSuccess = function(data) { // handle any data that might be sent back }; window.navigator.webkitStartActivity(intent, onSuccess);
To learn more about the Web Intents check webintents.org, and visit https://developers.google.com/drive to learn about the Google Drive SDK. The complete sample described in this post is also available on https://github.com/PaulKinlan/WebIntents/tree/master/server/demos/cloudfilepicker.
Are you an expert in the Drive API or Google Apps APIs? Are you an expert in Google Apps Script? If you are, then you must have been busy coding away for the Google Apps Developer Challenge since its launch earlier last month.
Now it’s time to wow the judges, as the Google Apps Developer Challenge is now open for submissions! If you would like to submit your application, please submit on the website using one of the three following categories:
If you are not ready, don’t worry -- as you still have time. The submission deadline is 24 August 2012 at 23:59:59 PT. Remember to use the many resources available to you in order to get ready. Ask questions on the Google+ Office Hours and Google Developers Live. Read up on Apps Script and the Drive and Apps APIs on Google Developers. Review the latest updates since Google I/O as well as the pre-submission checklist. Post questions and comments using the hashtag #gappschallenge on Google+. Review, and most importantly, finalize your application!
Best of luck!
Editor’s Note: This blog post is authored by Naveen Venkat, from Zoho. We've welcomed many of Zoho's apps in the Google Apps Marketplace and are happy to see them join the Drive developer community as well. -- Steven Bazyl
Zoho is a suite of online applications targeted at small and medium sized businesses. We offer over 25 services ranging from the basic productivity suite all the way up to business applications like CRM, project management, invoicing, custom app building platform and much more. We’ve just rolled out Zoho Office integration with Google Drive.
Zoho's applications can be broadly classified into 3 categories: Productivity, Business and Collaboration apps. Productivity apps are the basic needs of an office environment and include the likes of a word processor, spreadsheet, presentation tool, calendar etc. Business apps include CRM, projects, custom application building platform, invoicing and bookkeeping services. Collaboration tools facilitate real time collaboration across geographical locations. Email, chat, discussions, docs wiki etc are what round out this category of services.
We have many Google and Google Apps customers using Zoho applications through Google Apps Marketplace, Google Chrome Webstore or directly using "Sign in using Google" on our login page. Tightly integrating Zoho's applications with Google's services is very crucial for us. During the launch of Google Drive, Google announced the availability of a SDK and the related Google Drive APIs that would facilitate third party apps to integrate with the service. We used this opportunity and initially started integrating Zoho Show (presentation tool) with Google Drive. At that time, we felt that the APIs are very extensive and pretty straight forward. This inspired us to integrate our entire Zoho Office Suite with Google Drive. In just a couple of weeks, we were able to integrate Zoho Writer (word processor), Zoho Sheet (spreadsheet tool), and Zoho Show (presentation tool) with Google Drive.
Some of the goals that we had in our mind when we started our integration were, to be able to :
Above all, we also focussed on enabling SSO to login into Zoho with Google accounts without having to provide any extra information.
The first step in integrating an app with Google Drive is to register the app in the Google APIs console. Because we have three different apps, we created three different projects - Writer, Sheet and Show so that they would be listed separately in the contextual menu of Google Drive. In the console, we also have to enable Drive APIs and SDK to get access to Drive APIs for the App ID. The console then prompts you to create OAuth 2.0 client ID for authenticating the user with the app. Once this is done, we had to provide Google some basic information about our app such as brand icons, default and secondary mime types, authorization scopes etc.
The next step is to create a Google Chrome Web listing which allows users to install your app in Google Drive. Since we already have Zoho apps listed in the Chrome Web Store it was easy for us to make a few changes in our existing listing. We’ve added the following code in the manifest files to enable Drive for our apps.
"container" : "GOOGLE_DRIVE", "api_console_project_id" : "<APP_ID>",
APP_ID is the application’s ID which can be found in the Google APIs console.
APP_ID
This makes the Chrome Web Store listing Drive enabled, so now users simply have to install our Chrome Web Store apps and the Drive features will be enabled:
Google Drive apps are required to use OAuth 2.0 for authorization and are strongly encouraged to use OpenID Connect for authentication. Our Zoho Office Suite already supported OpenID authentication, so it was easy for us to implement it for the Z Writer, Sheet and Show apps for Google Drive.
To enable authentication for Drive users on our Zoho app we’ve added the following scopes to our Drive apps’ configuration page in the Google APIs Console:
https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile
This will make sure access to the authentication information of the user is granted alongside access to the Drive API allowing us to access Google’s OpenID Connect endpoints.
Our previous outings with GData APIs introduced us to OAuth2.0. OAuth 2.0 takes care of the authorization flow for a new user and smoothly transitioning the user to the Zoho application environment.
Users can create a new document from Google Drive’s UI or edit their existing Google Drive documents with Zoho’s editors. And when the user hits save, the modified document will be saved in Google Drive as a new document, thereby leaving the original Document untouched. This new document comes with extensions recognized by Zoho's apps. For example, a text document, Test.doc, from Google drive, when edited in Zoho Writer and saved, will be saved as Test.zdoc in Google Drive.
Users can invite their Google contacts to collaborate on their Google Drive documents and edit them using Zoho editors.
One of the main challenges that we faced during the integration was when multiple users need to collaborate on the same document in Zoho's editors.
In the recently launched Drive version v2 Google supports Permissions Feed to manage resource sharing. Based on the document permissions, we’ll allow the user to access the document for collaboration. Thus the Google users with whom the document has been shared can collaborate with each other in Zoho’s editor, without having to sign-in with Zoho explicitly. Zoho apps support inline collaboration which facilitates the shared users to collaborate seamlessly.
Thanks to Google team for their continued support right through the integration.
Editor’s Note: This blog post is authored by Peldi Guilizzoni, from Balsamiq. As a user of Balsamiq myself, it was great to see them join as one of the first Drive apps! -- Steven Bazyl
Hi there! My name is Peldi and I am the founder of Balsamiq, a small group of passionate individuals who believe work should be fun and that life's too short for bad software.
We make Balsamiq Mockups, a rapid wireframing tool that reproduces the experience of sketching interfaces on a whiteboard, but using your computer, so they’re easier to share, modify, and get honest feedback on. Mockups look like sketches, so stakeholders won’t get distracted by little details, and can focus on what’s important instead.
We sell Mockups as a Desktop application, a web application and as a plugin to a few different platforms. An iPad version is also in the works.
We believe that tools should adapt to the way people like to work, not the other way around. That's why when Google Drive came out, we jumped at the chance to integrate Mockups with it. This is the story of how the integration happened.
First of all, a little disclaimer. Although my job these days is to be CEO and all that, I come from a programming background. I started coding at 12, worked at Macromedia/Adobe for 6 years as a programmer. I'd say I'm a pretty good programmer…just a bit rusty, ok? I realize that the decision to write the code for Mockups for Google Drive myself instead of asking one of Balsamiq's better programmers to do it might have been a bit foolish, but we really wanted to be a launch partner and the programmers were already busy with lots of other stuff, plus I didn't want to pass up on the chance to work on something cool after dinner for a while. ;) OK so now you know the background, let's get started.
Once I got access to the Google Drive API documentation and looked around a bit, I started by following the detailed "sample application" tutorial.
The sample was written in python, used OAuth, the Google API Console, and ran on Google App Engine, all technologies I hadn't been exposed to before.
Following along brought me back to my childhood days of copying programs line by line from PC Magazine, not really understanding what I was doing but loving it nonetheless. :)
The trickiest part was figuring out how OAuth worked: it's a bit of a mess, but after you play with it a little and read a few docs, it starts making sense, stick with it, it's the future! ;) Plus the downloadable sample app had hidden all that stuff in a neat little library, so you don't have to worry about it so much.
Setting up the sample application took around 2-3 hours, easy peasy. Once that was done, I just had to convert it to become Balsamiq Mockups for Google Drive. Because I had done this before for other platforms, this was finally something I was comfortable with doing. The bulk of our code is encapsulated into our Flash-based Mockups editor, so all I had to do was to write a few functions to show the editor to the user and set it up using our internal APIs. Then I had to repurpose the "open with" and "edit" APIs from the sample app to work with the Mockups editor. All and all, this took maybe a day of work. Yay!
Once the proof of concept was up, I started turning the code into a real app. I cleaned up the code, added some comments, created a code repository for it in our bazaar server, set up a staging environment (a parallel Google App Engine application and unpublished Chrome Web Store listing) and integrated the build and deployment into our Jenkins server.
One tricky bit worth mentioning about integrating with Jenkins: the Google App Engine deployment script appcfg.py asks for a password interactively, which is a problem if you want to deploy automatically. The solution was to use the echo pwd | appcfg.py trick found here.
After some more testing and refinements, shipping day came, Balsamiq Mockups for Google Drive was live.
It was a very exciting day. Getting mentioned in the official Google blog was quite awesome. The only stressful moment came because for some reason my Google App Engine account was not set up for payments (I could have sworn I had done it in advance), so our app went over our bandwidth quota an hour after launch, resulting in people receiving a white blank screen instead of the app. Two people even gave us bad reviews because of it. Boo! :(
In the days that followed, things went pretty well. People started trying it out, and only a few bug reports came. One very useful Google App Engine feature is the "errors per second" chart in the dashboard, which gives you an insight on how your app is doing.
I noticed that we had a few errors, but couldn't figure out why. With the help of the docs and our main Developer Relations contact at Google, we narrowed them down to a couple of OAuth issues: one was that the library I was using didn't save the refresh_token properly, and another that had to do with sessions timing out when people use the editor for over an hour and then go to save their work.
Fixing these bugs took way longer than what I wanted, mostly due to the fact that I'm a total OAuth and Python n00b.
After a few particularly frustrating bug hunting sessions, I decided to rewrite the backend to Java. The benefits of this approach are that a) we get static type checking and b) I can get help from some of our programmers since Java is a language we're all already familiar with here.
Since by now the Java section of the Google Drive SDK website had been beefed up, the rewrite only took a day, and it felt awesome. Sorry python, I guess I'm too old for you.
The hardest part of the java rewrite was the Jenkins integration, since the echo pwd trick doesn't work with the java version of appcfg. To get around that, I had to write an Expect script, based on this Fábio Uechi blog post. By the way, I would recommend reading the Expect README, it has an awesome 1995 retro feel to it.
Overall, integrating Balsamiq Mockups with Google Drive was a breeze. Google is a technology company employing some of the brightest people in our industry, and it shows. The APIs are clean and extremely well tested. The people at Google are very responsive whenever I have an issue and have been instrumental in making us successful.
While the application is still pretty young - we are working on adding support for Drive images, linking, symbols… - we are very happy with the results we're getting already. The Drive application netted around $2,500 in its first full month of operation, and sales are growing fast.
Alright, back to coding for me, yay! :)
Peldi
Today at Google I/O, we announced many enhancements to Google Apps Script to help you build richer applications and share your apps with users. Apps Script began as a tool for helping users get more done with their Google spreadsheets. Over time, Apps Script has grown to handle much more. It's a platform to extend Google spreadsheets and Sites, and a convenient way to create web applications.
We launched script.google.com as a destination for Apps Script developers. You can now create scripts from script.google.com or from Google Drive. Plus, your projects are now stored in Google Drive, and you can share them just like a Google document or spreadsheet.
HtmlService can help you create beautiful interfaces using Apps Script. HtmlService allows you to create web apps using HTML, client-side JavaScript, and CSS. You can also use jQuery to build web apps. HtmlService uses Google Caja to ensure that the HTML content served by your web apps is safer for you and your users.
We also launched a better way to store your application's data, ScriptDb . Every script now has an embedded JSON database. You no longer have to rely on a spreadsheet to store the data. Using ScriptDb, you can store a larger volume of data and search easily. We designed ScriptDb to be easy to use. It doesn't need connection strings or special passwords, and you can directly store and search your JavaScript objects without the need to convert them to a different format. You can learn more about ScriptDb on the Google Apps Script Developers page.
There are also now more options for deploying your web app. Your apps can now, with authorization, run as the user behind the keyboard, not just the script owner. This brings a new level of versatility to web apps built with Apps Script.
Finally, we wanted to make it easy to distribute your apps. You can now publish your apps in the Chrome Web Store . Register and package your app directly from the Publish menu in Google Apps Script. Then customize your listing from the Chrome Web Store and publish your app to the world.
We added a lot of new functionality to Apps Script, so in addition to our developer reference documentation , we've also created a new user guide . If you need further help you can reach out to us on Stack Overflow . You can also make feature requests and report issues on the Apps Script page on Google Code.
Building with Google Apps Script has become a lot easier and more powerful. We can't wait to see what you build. Happy scripting!
Editor’s Note: Kevin Winter is a guest author from the AdWords API Developer Relations team. He implemented these features in his 20% time. - Jan Kleinert
Google Spreadsheets provides powerful charting functionality to let you analyze your data many different ways. We recently added the ability to programmatically create, modify and delete Spreadsheet charts using Google Apps Script.
Charts that a user creates in a Google Spreadsheet are called Embedded Charts. Apps Script can be used to manage these types of Spreadsheet Charts. Each EmbeddedChart belongs to a Sheet. Embedded charts are named this way because they are embedded onto a Sheet within the spreadsheet. Embedded charts align to the upper left hand corner of the specified column and row in the spreadsheet.
EmbeddedChart
Sheet
Let’s say I want to track my gas mileage using Google Spreadsheets. First, I create a Spreadsheet, and set up columns and formulas. Next, I add a form interface to make it easy to add new entries and a chart to visualize my mileage. Now I can start recording data - but each time I add enough entries to go past the ranges the chart uses, I need to manually increase them. How about we use some Apps Script magic to solve this?
The script below iterates through all charts on this sheet and determines if any of the ranges need to be expanded (i.e. if there are more rows with data to display). It then updates the title, builds the new EmbeddedChart object and saves it to the sheet. It could also add a menu interface or a trigger to execute this periodically or when the spreadsheet is edited.
function expandCharts() { var sheet = SpreadsheetApp.getActiveSheet() // Get a list of all charts on this Sheet. var charts = sheet.getCharts(); for (var i in charts) { var chart = charts[i]; var ranges = chart.getRanges(); // Returns an EmbeddedChartBuilder with this chart’s settings. var builder = chart.modify(); for (var j in ranges) { var range = ranges[j]; // rangeShouldExpand_ is defined later. if (rangeShouldExpand_(range)) { // Removes the old range and substitutes the new one. builder.removeRange(range); var newRange = expandRange_(range); builder.addRange(newRange); } } // Update title. builder.setOption('title', 'Last updated ' + new Date().toString()); // Must be called to save changes. sheet.updateChart(builder.build()); } } function rangeShouldExpand_(range) { var s = range.getSheet(); var numColumns = range.getNumColumns() var values = s.getSheetValues(range.getLastRow(), range.getColumn(), 2, numColumns); for (var i = 0; i < numColumns; i++) { // If the next row has the same pattern of values, // it’s probably the same type of data and should be expanded. if (!values[0][i] && !values[1][i] || !!values[0][i] && !!values[1][i]) { continue; } else { return false; } } return true; } function expandRange_(range) { var s = range.getSheet() var startRow = range.getRow(); var startCol = range.getColumn(); var numRows = range.getNumRows(); var numCols = range.getNumColumns(); while (rangeShouldExpand_(range)) { numRows++; range = s.getRange(startRow, startCol, numRows, numCols); } return range; }
What if you wanted to create a new chart from scratch? You can do that too!
var sheet = SpreadsheetApp.getActiveSheet(); var chart = sheet.newChart() .setPosition(5, 6, 5, 5) .setChartType(Charts.ChartType.AREA) .addRange(sheet.getActiveRange()) .build(); sheet.insertChart(chart);
In the above code example, we’ve gotten a reference to an EmbeddedChartBuilder, set its position within the sheet, change the chartType, add the currently selected range and insert the new chart.
EmbeddedChartBuilder
The EmbeddedChartBuilder allows you to modify the chart in a couple ways:
addRange
removeRange
setOption
setChartType
setPosition
Embedded charts use more options than regular Apps Script charts, so options are handled slightly differently. Developers can pass a dotted field path to change options. For example, to change the animation duration, you can do this:
builder.setOption("animation.duration", 1000);
Now that we’ve created a bunch of charts, your spreadsheet is probably pretty cluttered. Want to clear it and start afresh with charts? Just remove them all:
var sheet = SpreadsheetApp.getActiveSheet(); var charts = sheet.getCharts(); for (var i in charts) { sheet.removeChart(charts[i]); }
Just like standalone charts, you can use embedded charts elsewhere. You can add them to a UIApp or a sites page as well as sending them as an email attachment:
// Attach all charts from the current sheet to an email. var charts = SpreadsheetApp.getActiveSheet().getCharts(); MailApp.sendEmail( "recipient@example.com", "Income Charts", // Subject "Here's the latest income charts", // Content {attachments: charts });
We hope you found this blog post useful. Enjoy editing embedded charts using Google Apps Script!
At the end of last year we launched the UserManager Apps Script service, allowing Google Apps domain administrators to write scripts to programmatically create, delete and edit their user accounts.
We are now extending the family of Domain services with two new additions: NicknameManager and GroupsManager.
The NicknameManager service allows domain administrators to define alternate email addresses (i.e. “nicknames”) with a single line of code, as in the following example:
var nickname = NicknameManager.createNickname("user", "nick");
With the GroupsManager service, Google Apps domain administrators can create and delete groups, and manage their members and owners. The following example shows how to list all members of a group given its unique groupId:
groupId
function listMembers(groupId) { var members = GroupsManager.getGroup(groupId).getAllMembers(); for (var i in members) { var member = members[i]; Logger.log(i + ": " + member); } }
With the same service, one line of code is enough to add a member to a group:
GroupsManager.getGroup(groupId).addMember(memberId);
If you want to know more about the new NicknameManager and GroupsManager services, please check our documentation, and don’t hesitate to get in touch with us if you have questions or suggestions.