• Manu Yadav 25
  • NEWBIE
  • 0 Points
  • Member since 2017
  • Salesforce developer
  • Salesforce.com


  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 2
    Replies
Hi,

Apex Controller
===============================
public class GoogleDriveController
{
    private static String key = '1030522894057-aoqqrckioqgqpljnh277n5cr8hqfhd0s.apps.googleusercontent.com';
    private Static String secert = 'plgBENpw7SMXGCvCpwDWEmdf';
    private Static string redirect_uri = 'https://manuyadav-dev-ed.lightning.force.com/lightning/o/Account/list';
    //private Static string redirect_uri = 'https://manuyadav-dev-ed.lightning.force.com/0016F00002RFSohQAH';
    private String accessToken;
    
    @AuraEnabled
    public static String createAuthURL() {
        String key = EncodingUtil.urlEncode(key,'UTF-8');
        String uri = EncodingUtil.urlEncode(redirect_uri,'UTF-8');
        String authuri = '';
        system.debug('++++++Authstart+++++++'+authuri);
        authuri = 'https://accounts.google.com/o/oauth2/auth?'+
            'client_id='+key+
            '&response_type=code'+
            '&scope=https://www.googleapis.com/auth/drive'+
            '&redirect_uri='+uri+
            '&state=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' +
            +
            '&access_type=offline';
        system.debug('++++++AuthUri+++++++'+authuri);
        return authuri;
    }
    
    @AuraEnabled
    public static String getaccessToken(String code)
    { 
        // String authurl=createAuthURL();
        //Getting access token from google
        HttpRequest req = new HttpRequest();
        System.debug('++AsscessToken++'+req);
        req.setMethod('POST');
        req.setEndpoint('https://accounts.google.com/o/oauth2/token');
        req.setHeader('content-type', 'application/x-www-form-urlencoded');
        String messageBody ='code='+code+'client_id='+key+'&client_secret='+secert+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code';
        req.setHeader('Content-length', String.valueOf(messageBody.length()));
        req.setBody(messageBody);
        req.setTimeout(60*1000);
        
        Http h = new Http();
        String resp;
        system.debug('++token string resp++'+resp);
        HttpResponse res = h.send(req);
        system.debug('++tokenresp++'+res);
        resp = res.getBody();
        system.debug('++tokenrespgetbody++'+resp);
        Map<String,object> responseMap =(Map<String,object>)JSON.deserializeUntyped(res.getBody()) ;  
        String token =  String.valueOf(responseMap.get('access_token'));
        system.debug('++token++'+Token);
        return token;
        
    }
    
    @AuraEnabled
    public static String uploadFile(String attachmentId, String accessToken) {
        List<ContentVersion> cvFile = [SELECT VersionData,FileType,ContentDocumentId FROM ContentVersion WHERE ContentDocumentId =: attachmentId];
        Blob myBlob = cvFile[0].VersionData;
        String url = 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media';
        string authorizationHeader = 'Bearer ' + accessToken; 
        Integer contentSize = myBlob.size();
        HttpRequest req = new HttpRequest();
        system.debug('++++++++Filereq+++++++'+req);
        req.setheader('Authorization',authorizationHeader);
        req.setheader('Content-Length',String.valueOf(contentSize));
        req.setheader('Content-Type','image/'+cvFile[0].FileType);
        req.setMethod('POST'); 
        req.setEndpoint(url); 
        req.setBodyAsBlob(myBlob); 
        Http h = new Http(); 
        system.debug('++++++++FileHTTP+++++++'+h);
        Httpresponse resp = h.send(req);
        system.debug('++++++++File+++++++'+resp);
        //After file was successfully upload we delete the file
        delete new ContentDocument(Id = cvFile[0].ContentDocumentId);
        return String.valueOf(resp.getStatuscode());
    }
}

Component
=============================
<aura:component controller="GoogleDriveController" implements="lightning:isUrlAddressable,force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
      <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="accessToken" type="String" />
    <aura:attribute name="myRecordId" type="String" default="0016F000024M3iGQAS" description="This is the record where we will temproary store the file"/>
    
    <lightning:card title="Google Drive Demo">
        <lightning:button variant="brand" label="Google Drive Auth" title="Google Drive Auth" onclick="{! c.doAuth }" />
        <hr/>
        <p class="slds-p-horizontal_small">
            <!--file upload part -->
            <lightning:fileUpload label="upload file to Drive" name="fileUploader"
                multiple="false" accept=".jpg, .png" recordId="{!v.myRecordId}" onuploadfinished="{!c.handleFilesChange}" />
          </p>
    </lightning:card>
</aura:component>

Js Component
=====================
({
    
    doInit : function(component, event, helper) {
        
       //if(component.get("v.pageReference") != undefined && component.get("v.pageReference") != 'undefined') 
       if(component.get("v.pageReference") != undefined && component.get("v.pageReference") != 'undefined'){
        var code = component.get("v.pageReference").state.c__code;
           console.log('test');
        console.log('code',code);
        if(code != undefined)
            var action  = component.get("c.getaccessToken");
            console.log('actioncheckinggg',action);
            action.setParams({
                "code" : code
                           });
            action.setCallback(this, function(response){
            var status = response.getState();
                console.log('checkinggg',status);
            if(status === "SUCCESS"){
                var accessToken = response.getReturnValue();
                console.log('tokennn',accessToken)
                component.set("v.accessToken", accessToken);
                
            }
        });
        
        $A.enqueueAction(action);
        }
      },
    
    doAuth : function(component, event, helper) {
        
        var action  = component.get("c.createAuthURL");
        action.setCallback(this, function(response){
            var status = response.getState();
            console.log('checkinggg auth****',status);
            if(status === "SUCCESS"){
                console.log('response',response.getReturnValue());
                var authUrl = response.getReturnValue();
                window.location.href = response.getReturnValue();
                
                
                //if you want to use standard method use below code. But it will open in new tab.
                /* var urlEvent = $A.get("e.force:navigateToURL");
                urlEvent.setParams({
                  "url": authUrl
                });
                urlEvent.fire();*/
                
            }
        });
        
        $A.enqueueAction(action);
    },
    
    handleFilesChange : function(component, event, helper) {
        var uploadedFiles = event.getParam("files");
        var attachmentId = uploadedFiles[0].documentId;
        var code = component.get("v.accessToken");
        
        var action  = component.get("c.uploadFile");
        action.setParams({
            "attachmentId": attachmentId,
            "accessToken" : code
        });
        action.setCallback(this, function(response){
            var status = response.getState();
            
            if(status === "SUCCESS"){
                var responseCode = response.getReturnValue();
                console.log('checkinggg+++upload',responseCode);
                if(responseCode == '200')
                    alert('File Uploaded successfully');
                else
                    alert('There was some error');
            }
        });
        
        $A.enqueueAction(action);
    }
})

In the above code, I could not get token access from the external application then I tried to start debugging even doinit method is not calling from the component. 
Hi,

Apex Controller
===============================
public class GoogleDriveController
{
    private static String key = '1030522894057-aoqqrckioqgqpljnh277n5cr8hqfhd0s.apps.googleusercontent.com';
    private Static String secert = 'plgBENpw7SMXGCvCpwDWEmdf';
    private Static string redirect_uri = 'https://manuyadav-dev-ed.lightning.force.com/lightning/o/Account/list';
    //private Static string redirect_uri = 'https://manuyadav-dev-ed.lightning.force.com/0016F00002RFSohQAH';
    private String accessToken;
    
    @AuraEnabled
    public static String createAuthURL() {
        String key = EncodingUtil.urlEncode(key,'UTF-8');
        String uri = EncodingUtil.urlEncode(redirect_uri,'UTF-8');
        String authuri = '';
        system.debug('++++++Authstart+++++++'+authuri);
        authuri = 'https://accounts.google.com/o/oauth2/auth?'+
            'client_id='+key+
            '&response_type=code'+
            '&scope=https://www.googleapis.com/auth/drive'+
            '&redirect_uri='+uri+
            '&state=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' +
            +
            '&access_type=offline';
        system.debug('++++++AuthUri+++++++'+authuri);
        return authuri;
    }
    
    @AuraEnabled
    public static String getaccessToken(String code)
    { 
        // String authurl=createAuthURL();
        //Getting access token from google
        HttpRequest req = new HttpRequest();
        System.debug('++AsscessToken++'+req);
        req.setMethod('POST');
        req.setEndpoint('https://accounts.google.com/o/oauth2/token');
        req.setHeader('content-type', 'application/x-www-form-urlencoded');
        String messageBody ='code='+code+'client_id='+key+'&client_secret='+secert+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code';
        req.setHeader('Content-length', String.valueOf(messageBody.length()));
        req.setBody(messageBody);
        req.setTimeout(60*1000);
        
        Http h = new Http();
        String resp;
        system.debug('++token string resp++'+resp);
        HttpResponse res = h.send(req);
        system.debug('++tokenresp++'+res);
        resp = res.getBody();
        system.debug('++tokenrespgetbody++'+resp);
        Map<String,object> responseMap =(Map<String,object>)JSON.deserializeUntyped(res.getBody()) ;  
        String token =  String.valueOf(responseMap.get('access_token'));
        system.debug('++token++'+Token);
        return token;
        
    }
    
    @AuraEnabled
    public static String uploadFile(String attachmentId, String accessToken) {
        List<ContentVersion> cvFile = [SELECT VersionData,FileType,ContentDocumentId FROM ContentVersion WHERE ContentDocumentId =: attachmentId];
        Blob myBlob = cvFile[0].VersionData;
        String url = 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media';
        string authorizationHeader = 'Bearer ' + accessToken; 
        Integer contentSize = myBlob.size();
        HttpRequest req = new HttpRequest();
        system.debug('++++++++Filereq+++++++'+req);
        req.setheader('Authorization',authorizationHeader);
        req.setheader('Content-Length',String.valueOf(contentSize));
        req.setheader('Content-Type','image/'+cvFile[0].FileType);
        req.setMethod('POST'); 
        req.setEndpoint(url); 
        req.setBodyAsBlob(myBlob); 
        Http h = new Http(); 
        system.debug('++++++++FileHTTP+++++++'+h);
        Httpresponse resp = h.send(req);
        system.debug('++++++++File+++++++'+resp);
        //After file was successfully upload we delete the file
        delete new ContentDocument(Id = cvFile[0].ContentDocumentId);
        return String.valueOf(resp.getStatuscode());
    }
}

Component
=============================
<aura:component controller="GoogleDriveController" implements="lightning:isUrlAddressable,force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
      <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="accessToken" type="String" />
    <aura:attribute name="myRecordId" type="String" default="0016F000024M3iGQAS" description="This is the record where we will temproary store the file"/>
    
    <lightning:card title="Google Drive Demo">
        <lightning:button variant="brand" label="Google Drive Auth" title="Google Drive Auth" onclick="{! c.doAuth }" />
        <hr/>
        <p class="slds-p-horizontal_small">
            <!--file upload part -->
            <lightning:fileUpload label="upload file to Drive" name="fileUploader"
                multiple="false" accept=".jpg, .png" recordId="{!v.myRecordId}" onuploadfinished="{!c.handleFilesChange}" />
          </p>
    </lightning:card>
</aura:component>

Js Component
=====================
({
    
    doInit : function(component, event, helper) {
        
       //if(component.get("v.pageReference") != undefined && component.get("v.pageReference") != 'undefined') 
       if(component.get("v.pageReference") != undefined && component.get("v.pageReference") != 'undefined'){
        var code = component.get("v.pageReference").state.c__code;
           console.log('test');
        console.log('code',code);
        if(code != undefined)
            var action  = component.get("c.getaccessToken");
            console.log('actioncheckinggg',action);
            action.setParams({
                "code" : code
                           });
            action.setCallback(this, function(response){
            var status = response.getState();
                console.log('checkinggg',status);
            if(status === "SUCCESS"){
                var accessToken = response.getReturnValue();
                console.log('tokennn',accessToken)
                component.set("v.accessToken", accessToken);
                
            }
        });
        
        $A.enqueueAction(action);
        }
      },
    
    doAuth : function(component, event, helper) {
        
        var action  = component.get("c.createAuthURL");
        action.setCallback(this, function(response){
            var status = response.getState();
            console.log('checkinggg auth****',status);
            if(status === "SUCCESS"){
                console.log('response',response.getReturnValue());
                var authUrl = response.getReturnValue();
                window.location.href = response.getReturnValue();
                
                
                //if you want to use standard method use below code. But it will open in new tab.
                /* var urlEvent = $A.get("e.force:navigateToURL");
                urlEvent.setParams({
                  "url": authUrl
                });
                urlEvent.fire();*/
                
            }
        });
        
        $A.enqueueAction(action);
    },
    
    handleFilesChange : function(component, event, helper) {
        var uploadedFiles = event.getParam("files");
        var attachmentId = uploadedFiles[0].documentId;
        var code = component.get("v.accessToken");
        
        var action  = component.get("c.uploadFile");
        action.setParams({
            "attachmentId": attachmentId,
            "accessToken" : code
        });
        action.setCallback(this, function(response){
            var status = response.getState();
            
            if(status === "SUCCESS"){
                var responseCode = response.getReturnValue();
                console.log('checkinggg+++upload',responseCode);
                if(responseCode == '200')
                    alert('File Uploaded successfully');
                else
                    alert('There was some error');
            }
        });
        
        $A.enqueueAction(action);
    }
})

In the above code, I could not get token access from the external application then I tried to start debugging even doinit method is not calling from the component. 
I am able to create a file in Google drive with the below code:

Http http = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files?uploadType=media');
req.setHeader('content-type', 'text/plain');
req.setHeader('Authorization','Bearer '+accessToken);
String messageBody = 'Hi, This message is from Salesforce';
req.setBody(messageBody); 
req.setTimeout(60*1000);
HttpResponse resp = http.send(req);

But now i want to create a file inside a folder in Google drive. I am using end point as:

req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files/0B602YDdndVQ6b3RnR2NYQXo5TXM/children?uploadType=media');
where 0B602YDdndVQ6b3RnR2NYQXo5TXM is the folder id.

Can someone please tell me what other changes i have to do in the above code in order to create the file inside a folder?