1/* Copyright 2015 The Chromium OS Authors. All rights reserved. 2 * Use of this source code is governed by a BSD-style license that can be 3 * found in the LICENSE file. 4 */ 5 6/* Client id obtained from API console credential page should be set before 7 * running this script. */ 8if (!CLIENT_ID) { 9 console.error.log('CLIENT_ID is not set'); 10} 11 12/* Initialize a Google Drive picker after Google client API is loaded. */ 13function onGoogleClientApiLoad() { 14 var picker = new Picker({ 15 clientId: CLIENT_ID, 16 button: document.getElementById('google_drive_pick_file') 17 }); 18} 19 20/* Initializes a Google Drive picker and loads drive API and picker API.*/ 21var Picker = function(options) { 22 this.clientId = options.clientId; 23 this.button = options.button; 24 this.button.addEventListener('click', this.open.bind(this)); 25 26 gapi.client.load('drive', 'v2'); 27 gapi.load('picker', {callback: this.onPickerApiLoaded.bind(this) }); 28} 29 30/* Enable the button after picker API is loaded. */ 31Picker.prototype.onPickerApiLoaded = function() { 32 this.button.disabled = false; 33}; 34 35/* Let user authenticate and show file picker. */ 36Picker.prototype.open = function(){ 37 if (gapi.auth.getToken()) { 38 this.showFilePicker(); 39 } else { 40 this.authenticate(this.showFilePicker.bind(this)); 41 } 42}; 43 44/* Run authenticate using auth API. */ 45Picker.prototype.authenticate = function(callback) { 46 gapi.auth.authorize( 47 { 48 client_id: this.clientId + '.apps.googleusercontent.com', 49 scope: 'https://www.googleapis.com/auth/drive.readonly', 50 immediate: false 51 }, 52 callback); 53}; 54 55/* Create a picker using picker API. */ 56Picker.prototype.showFilePicker = function() { 57 var accessToken = gapi.auth.getToken().access_token; 58 this.picker = new google.picker.PickerBuilder(). 59 addView(google.picker.ViewId.DOCS). 60 setAppId(this.clientId). 61 setOAuthToken(accessToken). 62 setCallback(this.onFilePicked.bind(this)). 63 build(). 64 setVisible(true); 65}; 66 67/* Request the file using drive API once a file is picked. */ 68Picker.prototype.onFilePicked = function(data) { 69 if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) { 70 var file = data[google.picker.Response.DOCUMENTS][0]; 71 var id = file[google.picker.Document.ID]; 72 var request = gapi.client.drive.files.get({fileId: id}); 73 request.execute(this.onFileGet.bind(this)); 74 } 75}; 76 77/* Retrieve the file URL and access token and set it as audio source. */ 78Picker.prototype.onFileGet = function(file) { 79 var accessToken = gapi.auth.getToken().access_token; 80 var authedUrl = file.downloadUrl + "&access_token=" 81 + encodeURIComponent(accessToken); 82 audio_source_set(authedUrl); 83}; 84