google drive and the google drive sdk

Post on 15-Jan-2015

2.754 Views

Category:

Technology

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

Talk di Claudio Cherubino alla DevFest 2012 @ Firenze

TRANSCRIPT

Google Drive and theGoogle Drive SDKBuilding Drive apps

Claudio CherubinoGoogle Drive Developer Relations

What is Google Drive?Yea, some marketing :)

Access Anywhere

Google Drive is everywhere you are -- on the web, in your home, at the office, and on the go.

So wherever you are, your stuff is just...there. Ready to go, ready to share.

Install it on:

PC, Mac, Android, iOS

Store your files in a safe place

Things happen. Your phone goes for a swim. Your laptop takes an infinite snooze.

No matter what happens to your devices, your files are safely stored in Google Drive.

Powerful search

Google Drive can search keywords in your files -- even the text in pictures -- to help you quickly find what you're looking for.

View anything

When a coworker shares a file with you, you may not have the supported software on your computer. With Google Drive you can open and view over 35 file types directly in the browser.

Access to a world of apps!

Google Drive works with the apps that make you more efficient.

Choose from a growing set of productivity applications, integrated right into your Drive.

Demos!Pixlr EditorHelloFaxAutoCAD WS

Google Drive SDKWhy integrate with Google Drive?

Drive SDK opportunity

Extensive Reach Effortless IntegrationPut your app in front of millions of users with billions of files

Get the best of Google Drive's sharing capabilities, storage capacity and user identity management so you can focus on your app

++

Drive SDK features

Drive● Create, Read, List, Manage files through the API● Search, sharing and revisions

Drive Web UI● Open files and docs with your app directly from Drive

Integrating with Google DriveGetting Started

Steps for integrating your app w/ Drive

Prerequisites:● Create a project in the Google APIs Console● Enable the Drive API● Create OAuth 2.0 credentials

Integration steps:● Auth with OAuth 2.0 [& OpenID Connect]● Write code for opening / saving / managing files

OAuth 2.0Introduction

Integrating with Google DriveHandling Authorization for Web apps

Java

AuthorizationUsing OAuth 2.0 - Redirecting users to the Grant screen

// Instantiating some dependenciesHttpTransport httpTransport = new NetHttpTransport();JacksonFactory jsonFactory = new JacksonFactory();

// Building the flow and the redirect URLGoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, SCOPES).build();

GoogleAuthorizationCodeRequestUrl urlBuilder = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI);

// Redirecting users to the grant screenresp.sendRedirect(urlBuilder.build());

Java

AuthorizationUsing OAuth 2.0 - Getting back & exchanging the code in your callback handler

// Reading the auth code value from the URLString authorizationCode = req.getParameter("code");

// Exchanging the auth code for tokensGoogleTokenResponse tokenResponse = flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute();

String accessToken = tokenResponse.getAccessToken();String refreshToken = tokenResponse.getRefreshToken();

Integrating with Google DriveHandling Authorization for Android

AuthorizationUsing OAuth 2.0 - Using the AccountManager

Problem!Currently not possible:

● Anonymous tokens are not allowed● App auth using API Key is Disabled for Drive for security reasons

SolutionsPermanent: Add app auth to auth authentication in Android (available w/ Google Play services!)Temporarily: Use a WebView and trigger an OAuth 2.0 flow

Check this Google IO presentation for more.

AuthorizationUsing OAuth 2.0 - Using a WebView

Steps to do WebView auth:● Redirect Users to the grant screen URL in a WebView● Use http://localhost as the redirect URI● Register a WebViewClient with an onPageStarted method to intercept page change● Detect successful/failed authorization and read the auth code from the URL of the WebView

Resources w/ code samples:● Sample code for complex login system on mobile apps● Improved Twitter OAuth for Android

Integrating with Google DriveInteracting w/ Drive files

Java

Instantiating the Drive service Object

// Building the credentials ObjectGoogleCredentials credentials = flow.createAndStoreCredential(tokenResponse, null);

// Here is the Drive serviceDrive service = new Drive.Builder(httpTransport, jsonFactory, credentials);

Java

Creating Files

// File's metadataFile body = new File();body.setTitle(title);body.setDescription(description);body.setMimeType(mimeType);

// File's contentjava.io.File fileContent = new java.io.File(filename);FileContent mediaContent = new FileContent(mimeType, fileContent);

// Executing the requestfile = service.files().insert(body, mediaContent).execute();

Java

Fetching Files

// Getting file's metadataFile file = service.files().get(fileId).execute();

// Downloading the file's contentif (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) { HttpResponse resp = service.getRequestFactory().buildGetRequest( new GenericUrl(file.getDownloadUrl())).execute(); InputStream content = resp.getContent();}

Integrating with Google DriveAdding the Drive Web-UI Integration

UI Integration - "Create"

UI Integration - "Open with"

Distribution - Chrome Web Store

Steps for adding Drive UI integration

Prerequisites:● Create a Chrome Web Store listing (Painful !)● Install the application from the CWS● Enable and configure the Drive SDK in the Google APIs Console

Integration steps:● Support OAuth 2.0 server-side flow● Read action and file ID from URL parameter

JSON

Passing context on open & createWhat happens when somebody launches your app from Drive?

{ "action" : "create", "parentId" : "0ADK06pfg"

}

{ "action" : "open", "ids" : ["0Bz0bd"]

}

URL

https://www.yourapp.com/drive?code=<authorization code>&state=<JSON>

Create actions

Open actions

JSON

Passing context on open & createWhat happens when somebody launches your app from Drive?

{ "action" : "open", "exportIds" : ["0Bz0bd"]

}

URL

https://www.yourapp.com/drive?code=<authorization code>&state=<JSON>

Open native Google Docs actions

Integrating with Google DriveAdding the Drive Android App Integration

Receiving intents from the Drive app

● Export an Activity that supports an intent with the following info:● action: drive.intent.action.DRIVE_OPEN● path: content://com.google.android.drive/open/resourceId● type: MIME type of the file

● Declare your API Project ID in the Activity's metadata

● List supported MIME types in the intent-filter element

● The intent will not include the body of the document nor the user account

● Retrieve the file from the Drive API using the resourceId provided by the intent in the path

Receiving intents from the Drive app

Check this Google IO presentation for more.

XML

Receiving intents from the Drive app

<manifest …>

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

<application …>

<activity android:name="DriveActivity" android:label="@string/cloud_paint" android:icon="@drawable/app_icon"

android:exported="true">

<meta-data android:name="com.google.android.apps.drive.APP_ID" android:value="id=1234567890" />

<intent-filter>

<action android:name="com.google.android.apps.drive.DRIVE_OPEN" />

<data android:mimeType="text/plain" />

<data android:mimeType="text/html" />

</intent-filter>

</activity>

</application>

</manifest>

Java

Receiving intents from the Drive app

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

final Intent intent = getIntent();

final String action = intent.getAction();

if ("drive.intent.action.DRIVE_OPEN".equals(action)) {

String fileId = intent.getStringExtra("resourceId");

// Prompt the user to choose the account to use and process the file using the Drive API.

} else {

// Other action.

}

}

Integrating with Google DriveThe Google Picker

UI Integration - Embedded file picker

JS

Embedding the picker

google.setOnLoadCallback(createPicker);google.load('picker', '1');

var view = new google.picker.View(google.picker.ViewId.DOCS);view.setMimeTypes("image/png,image/jpeg,image/jpg");

function createPicker() { picker = new google.picker.PickerBuilder() .enableFeature(google.picker.Feature.MULTISELECT_ENABLED) .setAppId(YOUR_APP_ID) .addView(view) .setCallback(pickerCallback) .build(); picker.setVisible(true);}

JS

Handling picker selections

// A simple callback implementation.function pickerCallback(data) { if (data.action == google.picker.Action.PICKED) { var fileId = data.docs[0].id; alert('The user selected: ' + fileId); }}

Security and other features

The Drive SDK has 2 security models.

● The first one gives you full access to the user's Drive○ Read and/or write all files○ Manage all files○ List all files○ ...

A brief (but important) note on security

Drive's second security model is a per-file security model

● More restrictive file level access● Simple rules - an app can open any file that:

○ The user opened with the app through the Drive UI○ The user opened with the app through the Picker API○ The app created itself

A brief (but important) note on security

● Resumable upload & download● Indexable text● Search!● Conversions to native Google Documents● Export of native Google Documents in many formats● OCR● Revisions● List installed apps● Copy files, Trash files, Touch files● Folders● User Permissions● Shortcuts

○ Auto-generated MIME type○ Contentless○ Indexable & syncable!

Other Features / tips & tricks

<Thank You!>http://developers.google.com/drive

ccherubino@google.comhttp://plus.claudiocherubino.it#ccherubino

top related