If your application needs a way to let users easily choose a file from their Drive, this is for you.
Users can browse and select files from their Drive file list using the Google Picker API. The Google Picker API provides a user interface containing a list of all the user's files in Google Drive.
Since the user interface is generated by the Picker API, there is very little effort in adding the Picker to an existing site. This article will show how to use the picker for your application, and discuss some of the configuration options.
First create a view on the data describing the type of Picker that we will be using. In this case, we’ll use google.picker.ViewId.DOCS. For more types of Picker, see the documentation.
google.picker.ViewId.DOCS
var view = new google.picker.View(google.picker.ViewId.DOCS);
You can set the MIME types to filter the list of files. This allows you to specify your application’s specific file types to display to the user.
view.setMimeTypes("text/plain,text/html");
Use a PickerBuilder to set the required configuration parameters for your Picker.
PickerBuilder
var picker = new google.picker.PickerBuilder() .enableFeature(google.picker.Feature.NAV_HIDDEN) .setAppId("your app id") .addView(view) .setTitle("Select a Text File") .setCallback(pickerCallback).build();
Once configured, the picker can be popped up to the user as often as you like, using
picker.setVisible(true)
When a user selects a file with the Picker, the callback set in setCallback is called with the data from the dialog. Pass this callback as the action to perform when a user selects a file in the Picker.
setCallback
function pickerCallback(data) { if (data.action == google.picker.Action.PICKED) { var fileId = data.docs[0].id; alert('The user selected: ' + fileId); } }
Check the data’s action, in this case google.picker.action.PICKED, and if it is appropriate, access the file ID as the the first element of the docs attribute.
google.picker.action.PICKED
Here are some additional tips on customizing your Picker.
var picker = new google.picker.PickerBuilder() .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
var picker = new google.picker.PickerBuilder() .enableFeature(google.picker.Feature.NAV_HIDDEN)
For a complete example, including how to load the Picker library, please visit our the Drive SDK documentation. Also, see the Picker API documentation for more information.
Have you tried using the Google Drive API? If so, you’re aware that it allows you to programmatically manage a user’s Google Drive and build applications to manipulate files stored in the user’s account. However, the API might still be capable of doing a few things you didn’t know about. Here is a list of five specific use cases and how each of them can be addressed with the API.
When a file in Google Drive is shared publicly, it can be downloaded without authentication at the URL provided by the API in the webContentLink field of the Files resource. To retrieve that value, send a GET request to retrieve the file metadata and look for the webContentLink element in the JSON response, as in the following example:
webContentLink
{ "kind": "drive#file", "id": "0B8E...", "etag": "WtRjAP...", "selfLink": "https://www.googleapis.com/drive/v2/files/0B8E...", "webContentLink": "https://docs.google.com/a/google.com/uc?id=0B8E...", ... }
When setting permissions for a file with the Drive API, you can choose one of owner, writer and reader as the value for the role parameter. The Drive UI also lists another role, commenter, which is not allowed for that parameter.
owner
writer
reader
role
commenter
In order to grant comment-only access to a user with the Drive API, you have to set the role parameter to reader and include the value commenter in the list of additionalRoles, as in the following example:
additionalRoles
{ "kind": "drive#permission", ... "role": "reader", "additionalRoles": [ "commenter" ], ... }
It is possible to restrict the list of files (and folders) returned by the Drive API by specifying some search criteria in the q query parameter. Each file has a parents collection listing all folders containing it, and the root folder in Google Drive can be conveniently addressed with the alias ‘root’. All you need to do to retrieve all files in that folder is add a search query for element with ‘root’ in their parents collection, as in the following example:
‘root’
GET https://www.googleapis.com/drive/v2/files?q='root' in parents
Remember to URL-encode the search query for transmission unless you are using one of the available client libraries.
Your application might need to know if users have enough available quota to save a file, in order to handle the case when they don’t. Quota information is available in the About feed of the Drive API:
{ "kind": "drive#about", ... "quotaBytesTotal": "59055800320", "quotaBytesUsed": "14547272", "quotaBytesUsedInTrash": "511494", ... }
The feed includes three values related to quota management: quotaBytesTotal, quotaBytesUsed and quotaBytesUsedInTrash. The first value indicates the total amount of bytes available to the user (new accounts currently get 5GB for free) while the second one tells how many of those bytes are in use. In case you need to get more free space, you can use the last value to know how many bytes are used by files that have been trashed. An application might use this value to recommend emptying the trash bin before suggesting to get additional storage.
quotaBytesTotal
quotaBytesUsed
quotaBytesUsedInTrash
Google Drive allows users to store any kind of file and to install applications to open file types that are not directly supported by the native Google applications. In case you need to know what applications are installed and what file types each of them can open, you can retrieve the Apps feed and look for the primaryMimeTypes and secondaryMimeTypes elements for supported MIME types or primaryFileExtensions and secondaryFileExtensions for file extensions:
primaryMimeTypes
secondaryMimeTypes
primaryFileExtensions
secondaryFileExtensions
{ "kind": "drive#app", "name": "Pixlr Editor", ... "primaryMimeTypes": [ "image/psd", "image/pxd", "application/vnd.google-apps.drive-sdk.419782477519" ], "secondaryMimeTypes": [ "image/png", "image/jpeg", "image/gif", "image/bmp" ], "primaryFileExtensions": [ "pxd", "psd" ], "secondaryFileExtensions": [ "jpg", "png", "jpeg", "bmp", "gif" ], … }
Note: to access the Apps feed you have to request access to the https://www.googleapis.com/auth/drive.apps.readonly OAuth scope.
https://www.googleapis.com/auth/drive.apps.readonly
Charts are a great way to visualize information. They let you arrange data in meaningful ways, allow you to tell a story, and can really catch the reader's eye. But when dealing with large datasets, visualizing all the data at once can be somewhere between a tough to impossible mission. You usually need to filter the data and concentrate on a specific part that is of interest, and then when you want to see a different part of the data you'll need to filter it again and refresh the view. That's why we're happy to announce the introduction of dashboards in Apps Script, which allow you to compose multiple charts and filters into a single experience!
What is a dashboard? A dashboard is a visual structure that lets you organize and manage multiple charts that share the same underlying data. The three building blocks of a dashboard are the data source, charts, and controls. Controls are user interface widgets (category pickers, range sliders, or autocompleting text boxes) that someone can interact with in order to drive the data managed by a dashboard to the charts that are part of it.
Dashboards in Apps Script Because of its interactive nature, a dashboard is built in a Google Apps Script UI application. A UI application can be embedded in a Spreadsheet or a Site or served as HTML using the "Deploy as web app" option. They are perfect for creating interactive reports, where users can gain extra insight through exploring the data.
Creating a simple dashboard UI Application Have a look at the following example dashboard where a category picker and a range slider are used to drive the data visualized by a pie chart and a table chart.
Note that a dashboard is an interactive entity. Playing with its controls will change the charts in real time. You can see exactly how this dashboard was created, and learn more about how to build dashboards in general, by reading through our new Building a Charts Dashboard tutorial.
Going further Dashboards can of course be much more complex than the above example. Here is a video demonstrating a more complex dashboard embedded in a Spreadsheet:
To conclude, dashboards are powerful gadgets that allow you to handle and get valuable insights on complex datasets. Now made easy to build in Apps Script, try it on your data.
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