angular.module('EssayApp.directives').directive "gdriveUploader", ['$timeout', '$window', 'FileKeeper', ($timeout, $window, FileKeeper) -> restrict: 'A' scope: true require: "ngModel" link: (scope, element, attrs, ngModel) -> $timeout (-> scope.root = element scope.root = element.closest(attrs.uploaderRoot) if attrs.uploaderRoot? # filesContainer = $(attrs.filesContainer) if attrs.filesContainer scope.developerKey = attrs.devKey scope.clientId = attrs.clientId scope.guid = attrs.guid api_scope = [ 'https://www.googleapis.com/auth/drive.readonly' ] scope.oauthToken = undefined scope.endpoint = attrs.url scope.keeper = FileKeeper.build(scope, element, attrs, ngModel) $window.onGApiLoad = -> scope.gApiLoaded = true gapi.load 'auth', 'callback': onGAuthApiLoad gapi.load 'picker', 'callback': onGPickerApiLoad return $window.onGAuthApiLoad = -> scope.gAuthApiLoaded = true return $window.onGPickerApiLoad = -> scope.pickerApiLoaded = true scope.createPicker() return scope.openUploader = -> # console.log 'openUploader' return unless scope.gApiLoaded? && scope.gAuthApiLoaded? && scope.pickerApiLoaded? if !scope.oauthToken $window.gapi.auth.authorize { 'client_id': scope.clientId 'scope': api_scope 'immediate': false }, scope.handleAuthResult else scope.createPicker() return scope.handleAuthResult = (authResult) -> if authResult && !authResult.error scope.oauthToken = authResult.access_token scope.createPicker() return scope.createPicker = -> if scope.pickerApiLoaded && scope.oauthToken (new (google.picker.PickerBuilder)) .setLocale('#{I18n.locale}') .setOAuthToken(scope.oauthToken) .setDeveloperKey(scope.developerKey) .setCallback(scope.pickerCallback) .addView(google.picker.ViewId.DOCUMENTS) .addView(google.picker.ViewId.PRESENTATIONS) .addView(google.picker.ViewId.SPREADSHEETS) .addView(google.picker.ViewId.PDFS) .addView(google.picker.ViewId.FOLDERS) .enableFeature(google.picker.Feature.NAV_HIDDEN) .enableFeature(google.picker.Feature.MULTISELECT_ENABLED) # .enableFeature(google.picker.Feature.MINE_ONLY) .build().setVisible(true) return scope.pickerCallback = (data) -> if data[google.picker.Response.ACTION] == google.picker.Action.PICKED input = undefined uploader = undefined guid = undefined input = $('form input[type="file"]').eq(0) $.each data[google.picker.Response.DOCUMENTS], (_i, file) -> scope.keeper._add_pending(file) $.post(scope.endpoint, $.param( 'source': 'google_drive' 'file_id': file[google.picker.Document.ID] 'token': scope.oauthToken 'guid': scope.guid )).then ((data)-> scope.keeper.addUploadedFile(data.files[0], file) ), (err)-> scope.keeper._remove_pending(file) return $.getScript('https://apis.google.com/js/api.js?onload=onGApiLoad') return ), 0, false ]