Android Code Snippet GoogleDrive via API V3

Attachments

  • GoogleDrive.bas
    13.9 KB · Views: 1,304

Star-Dust

Expert
Licensed User
Longtime User
Thanks, maybe I ask too much, but it would be helpful to have an example or instructions on how to embed it.:D:D:D
 

mw71

Active Member
Licensed User
Longtime User
Hi,

For a small project for demonstration, I have unfortunately no time at the moment. I hope I can do it later.

A good start is the oAuth2 tutorial from Erel.

In addition, you need the source of the OkHTTPUtils and must insert these two modules into the project (instead of the Libary).
https://www.b4x.com/android/forum/threads/54723

To the HttpJob Class add the follow Code:
B4X:
'Sends a PATCH request with the given string as the post data
Public Sub PatchBytes(Link As String, Data() As Byte)
    req.InitializePatch2(Link, Data)
    CallSubDelayed2(HttpUtils2Service, "SubmitJob", Me)
End Sub

Then the class appended in Post 1 must be imported.

(Dim GDrive As GoogleDrive)
1. Initialize: GDrive.Initialize(Me, "Drive", clientId, clientSecret)
2. Connect: GDrive.ConnectToDrive (Connect, Test the Connection, Refresh the Token, if necessary)
-> Call Connected or ConnectFaild (Faild in the Main, can be made better)
3. You can Search for Folders, Files, Upload and Download Files.....
- Files are identified by ID, not by name!
- to search for files in subfolders, the ID of the Parrent folder must be specified
- Folder are special Files
4. The event which is raise when the job is completed can be viewed in the code, e.g. CallSub2 (evModule, evName & "_FileFound", fileEntry.Get ("id"))

greetings
 

@13

New Member
Licensed User
Thanks so much!
May I ask you how you've implemented oauth2.TestConnect?

B4X:
Sub ConnectToDrive
Log("GoogleDrive ConnectToDrive")
  
    'Write log files
    If DoWriteLog Then CreateLogFile
  
    Log("GoogleDrive, Access Token request")
    oauth2.GetAccessToken
    Wait For OAuth2_AccessTokenAvailable (Success As Boolean, Token As TokenInformation)
  
    If Success = True Then
        myAccessToken=Token.AccessToken
        myRefreshToken=Token.RefreshToken
          
        Log("GoolgeDrive, Run Test Connect")
        oauth2.TestConnect '  <---------------------------------------    <---------------------------------------
        Wait For oauth2_TestFinish(Erfolg As Boolean, Token As TokenInformation)
  
        If Erfolg=True Then
            Log("GoogleDrive, Run Test Connect")
            myAccessToken=Token.AccessToken
            myRefreshToken=Token.RefreshToken
            SendConnected
            Return
        Else
            Log("Google Drive, Test Connect Error")
        End If
    Else
        WriteLog("Google Drive, No Access Token")
    End If

..........
 

DonManfred

Expert
Licensed User
Longtime User

mw71

Active Member
Licensed User
Longtime User
sri, TestConnect i added

B4X:
Sub TestConnect
    Log("oAuth TestConnect")
   
    ti.Valid=False
   
    Dim h_tc As HttpJob
    h_tc.Initialize("", Me)
    h_tc.Download2("https://www.googleapis.com/drive/v3/files", _
         Array As String("access_token", ti.AccessToken, _
                         "corpora", "user", _
                         "q","mimeType!='application/vnd.google-apps.folder' and trashed=false"))
    Wait For (h_tc) JobDone(h_tc As HttpJob)
   
    If h_tc.Success Then
        Log(h_tc.GetString)
        ti.Valid=True
    Else
        Log("OAuth, Getting access token from refresh token in TestConnect")
        Dim j_rt As HttpJob
        j_rt.Initialize("", Me)
        j_rt.PostString("https://www.googleapis.com/oauth2/v4/token", _
        $"refresh_token=${ti.RefreshToken}&client_id=${mClientId}&grant_type=refresh_token&redirect_uri=${packageName & ":/oath"}"$)

        Wait For (j_rt) JobDone(j_rt As HttpJob)

        If j_rt.Success Then
            Log("OAuth TestConnect, Refresh access token Success")
           
            Dim jp As JSONParser
            jp.Initialize(j_rt.GetString)
            Dim m As Map = jp.NextObject
            ti.AccessExpiry = DateTime.Now + m.Get("expires_in")
            ti.AccessToken = m.Get("access_token")
            If m.ContainsKey("refresh_token") Then ti.RefreshToken = m.Get("refresh_token")
            ti.Valid = True
            SaveToken
        Else
            Log("OAuth TestConnect, Refresh Token Error")
        End If
        j_rt.Release       
    End If
   
    h_tc.Release
    CallSubDelayed3(mTarget, mEventName & "_TestFinish", ti.Valid, ti)
End Sub
 

Star-Dust

Expert
Licensed User
Longtime User
Thank's
 

Duque

Active Member
Licensed User
Longtime User
Great job guys, it was very easy to implement a backup system by following these steps.
but...

How can I SEE mail with this same token?
 

Duque

Active Member
Licensed User
Longtime User
I got it that way, I even got the profile picture
B4X:
'Retorna el correo
Sub Mail As ResumableSub
   Dim mp As Map

    Dim j As HttpJob
    j.Initialize("", Me)
    j.Download2("https://www.googleapis.com/drive/v3/about?fields=user&access_token="&myAccessToken,Array As String())                     
    Wait For (j) JobDone(j As HttpJob)
   
    If j.Success Then
        mp = mpData(j.GetString)
        CallSub2(evModule, evName & "_getMail",mp)
    Else
       
        oauth2.ResetToken
        ToastMessageShow("Online data not available.", True)
    End If
    j.Release
   
   
    Return mp
End Sub

Sub mpData(data As String) As Map

    Dim l1 As String = data
    l1= l1.SubString(1)
    Dim q As String ="""user"": {"
    l1=l1.Replace(q,"")
    l1= l1.Replace("}","")
   
    Dim l2 As String
    l2="[{"&l1&"}]"
    l2= l2.Replace(CRLF,"")
    l2= l2.Replace(" ","")
   


    Dim parce As JSONParser
    parce.Initialize(l2)
   
       
    Dim list1 As List = parce.NextArray
    For Each map1 As Map In list1
'    Log("1 = "&map1.Get("displayName"))
'    Log("2 = "&map1.Get("photoLink"))
'    Log("3 = "&map1.Get("me"))
'    Log("4 = "&map1.Get("permissionId"))
'    Log("5 = "&map1.Get("emailAddress"))
    Next


Return map1
End Sub
 
Top