diff --git a/app-src/scripts/main/global-services/google-api-s.js b/app-src/scripts/main/global-services/google-api-s.js index 0b6e1f51a8..d4cd6a2fe5 100644 --- a/app-src/scripts/main/global-services/google-api-s.js +++ b/app-src/scripts/main/global-services/google-api-s.js @@ -16,13 +16,42 @@ constructor(GOOGLE, $q) { this.$q = $q; this.GOOGLE = GOOGLE; - console.log('GOOGLE CONSTRUCTOR'); - gapi.load('client:auth2', this.initClient.bind(this)); } - initClient() { - console.log(this); + initAllIfNotDone() { + const defer = this.$q.defer(); + this.loadLib(() => { + gapi.load('client:auth2', () => { + return this.initClient(defer) + }); + }); + + return defer.promise; + } + + loadJs(url, cb) { + const that = this; + const script = document.createElement('script'); + script.setAttribute('src', url); + script.setAttribute('type', 'text/javascript'); + + this.isScriptLoaded = false; + const loadFunction = () => { + if (that.isScriptLoaded) return; + that.isScriptLoaded = true; + cb && cb(); + }; + script.onload = loadFunction.bind(that); + script.onreadystatechange = loadFunction.bind(that); + document.getElementsByTagName("head")[0].appendChild(script); + } + + loadLib(cb) { + this.loadJs('//apis.google.com/js/api.js', cb); + } + + initClient(defer) { // Array of API discovery doc URLs for APIs used by the quickstart const DISCOVERY_DOCS = ['https://sheets.googleapis.com/$discovery/rest?version=v4']; // Authorization scopes required by the API; multiple scopes can be @@ -30,17 +59,17 @@ const SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly' + ' https://www.googleapis.com/auth/drive'; - gapi.client.init({ + return gapi.client.init({ //apiKey: this.GOOGLE.API_KEY, clientId: this.GOOGLE.CLIENT_ID, discoveryDocs: DISCOVERY_DOCS, scope: SCOPES }).then(() => { console.log('INIT DONE'); + defer.resolve(); // Listen for sign-in state changes. gapi.auth2.getAuthInstance().isSignedIn.listen(this.updateSigninStatus.bind(this)); - // Handle the initial sign-in state. this.updateSigninStatus.bind(this); }); @@ -56,10 +85,8 @@ } login() { - return gapi.auth2.getAuthInstance().signIn() - .then(() => { - console.log('CB'); - }); + return this.initAllIfNotDone() + .then(() => gapi.auth2.getAuthInstance().signIn()); } logout() { @@ -75,7 +102,6 @@ getSpreadsheetHeadings() { console.log('getSpreadsheetHeadings'); - console.log(this); const defer = this.$q.defer();