Sample code for 30+ languages & platforms
AutoIt

Google Drive - Build a Local Cache of Metadata

See more Google Drive Examples

This example demonstrates how to download the metadata for all files in a Google Drive account to create a local filesystem cache with the information. The cache can be used to fetch information without having to query Google Drive.

Chilkat AutoIt Downloads

AutoIt
Local $bSuccess = False

$bSuccess = True

; It requires the Chilkat API to have been previously unlocked.
; See Global Unlock Sample for sample code.

; This example uses a previously obtained access token having permission for the 
; Google Drive scope.

$oGAuth = ObjCreate("Chilkat.AuthGoogle")
$oGAuth.AccessToken = "GOOGLE_DRIVE_ACCESS_TOKEN"

$oRest = ObjCreate("Chilkat.Rest")

; Connect using TLS.
Local $bAutoReconnect = True
$bSuccess = $oRest.Connect("www.googleapis.com",443,True,$bAutoReconnect)

; Provide the authentication credentials (i.e. the access token)
$oRest.SetAuthGoogle($oGAuth)

; -------------------------------------------------------------------
; Initialize our cache object.  Indicate the location of the root cache directory, and how many cache levels are to exist.
; For small caches (level 0) all cache files are in the root directory.
; For medium caches (level 1) cache files are located in 256 sub-directories from the root.
; For large caches (level 2) cache files are located in 256x256 sub-directories two levels down from the root.
$oGdCache = ObjCreate("Chilkat.Cache")
$oGdCache.Level = 0
; Use a root directory that makes sense on your operating system..
$oGdCache.AddRoot "C:/ckCache/googleDrive"

; If we are re-building the cache, we can first delete the entire contents of the cache.
Local $iNumCacheFilesDeleted = $oGdCache.DeleteAll()

; Create a date/time object with an time 7 days from the current date/time.
$oDtExpire = ObjCreate("Chilkat.CkDateTime")
$oDtExpire.SetFromCurrentSystemTime()
$oDtExpire.AddDays(7)

; Indicate that we want ALL possible fields.
; If no fields are indicated, then only the basic fields are returned.
Local $sAllFields = "appProperties,capabilities,contentHints,createdTime,description,explicitlyTrashed,fileExtension,folderColorRgb,fullFileExtension,headRevisionId,iconLink,id,imageMediaMetadata,isAppAuthorized,kind,lastModifyingUser,md5Checksum,mimeType,modifiedByMeTime,modifiedTime,name,originalFilename,ownedByMe,owners,parents,permissions,properties,quotaBytesUsed,shared,sharedWithMeTime,sharingUser,size,spaces,starred,thumbnailLink,trashed,version,videoMediaMetadata,viewedByMe,viewedByMeTime,viewersCanCopyContent,webContentLink,webViewLink,writersCanShare"

; We're going to keep a master list of fileId's as we iterate over all the files in this Google Drive account.
; This master list will also be saved to the cache under the key "AllGoogleDriveFileIds".
$oJsonMaster = ObjCreate("Chilkat.JsonObject")

$oJsonMasterArr = ObjCreate("Chilkat.JsonArray")
$oJsonMaster.AppendArray2("fileIds",$oJsonMasterArr)

; Also keep a list of file paths.
$oJsonMasterPaths = ObjCreate("Chilkat.JsonArray")
$oJsonMaster.AppendArray2("filePaths",$oJsonMasterPaths)

; The default page size is 100, with a max of 1000.
$oRest.AddQueryParam("pageSize","200")

$oJson = ObjCreate("Chilkat.JsonObject")
Local $oJsonFileMetadata
Local $i
Local $iNumFiles

; Send the request for the 1st page.
Local $sJsonResponse = $oRest.FullRequestNoBody("GET","/drive/v3/files")

Local $iPageNumber = 1
Local $sPageToken
Local $bContinueLoop = $oRest.LastMethodSuccess And ($oRest.ResponseStatusCode = 200)

While $bContinueLoop = True

    ConsoleWrite("---- Page " & $iPageNumber & " ----" & @CRLF)
    $oJson.Load($sJsonResponse)

    $iNumFiles = $oJson.SizeOfArray("files")
    $i = 0
    While $i < $iNumFiles
        ; Add this file ID to the master list.
        $oJson.I = $i
        $oJsonMasterArr.AddStringAt(-1,$oJson.StringOf("files[i].id"))

        $i = $i + 1
    Wend

    ; Get the next page of files.
    ; If the "nextPageToken" is present in the JSON response, then use it in the "pageToken" parameter
    ; for the next request.   If no "nextPageToken" was present, then this was the last page of files.
    $sPageToken = $oJson.StringOf("nextPageToken")
    $bContinueLoop = False
Local $bHasMorePages = $oJson.LastMethodSuccess
    If ($bHasMorePages = True) Then
        $oRest.ClearAllQueryParams()
        $oRest.AddQueryParam("pageSize","200")
        $oRest.AddQueryParam("pageToken",$sPageToken)
        $sJsonResponse = $oRest.FullRequestNoBody("GET","/drive/v3/files")
        $bContinueLoop = $oRest.LastMethodSuccess And ($oRest.ResponseStatusCode = 200)
        $iPageNumber = $iPageNumber + 1
    EndIf

Wend

; Check to see if the above loop exited with errors...
If ($oRest.LastMethodSuccess = False) Then
    ConsoleWrite($oRest.LastErrorText & @CRLF)
    Exit
EndIf

; Check to see if the above loop exited with errors...
; A successful response will have a status code equal to 200.
If ($oRest.ResponseStatusCode <> 200) Then
    ConsoleWrite("response status code = " & $oRest.ResponseStatusCode & @CRLF)
    ConsoleWrite("response status text = " & $oRest.ResponseStatusText & @CRLF)
    ConsoleWrite("response header: " & $oRest.ResponseHeader & @CRLF)
    ConsoleWrite("response JSON: " & $sJsonResponse & @CRLF)
    Exit
EndIf

; Iterate over the file IDs and download the metadata for each, saving each to the cache...
; Also, keep in-memory hash entries of the name and parent[0] so we can quickly 
; build the path-->fileId cache entries. (Given that the Google Drive REST API uses
; fileIds, this gives us an easy way to lookup a fileId based on a filePath.)
$oHashTable = ObjCreate("Chilkat.Hashtable")
; Set the capacity of the hash table to something reasonable for the number of files
; to be hashed.
$oHashTable.ClearWithNewCapacity(521)

$oSbPathForFileId = ObjCreate("Chilkat.StringBuilder")

; Used for storing the file name and parents[0] in the hashTable.
$oSaFileInfo = ObjCreate("Chilkat.StringArray")
$oSaFileInfo.Unique = False

Local $sFileId
$iNumFiles = $oJsonMaster.SizeOfArray("fileIds")
$i = 0
While $i < $iNumFiles
    $oJsonMaster.I = $i
    $sFileId = $oJsonMaster.StringOf("fileIds[i]")
    $oSbPathForFileId.SetString("/drive/v3/files/")
    $oSbPathForFileId.Append($sFileId)

    $oRest.ClearAllQueryParams()
    $oRest.AddQueryParam("fields",$sAllFields)
    $sJsonResponse = $oRest.FullRequestNoBody("GET",$oSbPathForFileId.GetAsString())
    If (($oRest.LastMethodSuccess <> True) Or ($oRest.ResponseStatusCode <> 200)) Then
        ; Force an exit of this loop..
        $iNumFiles = 0
    EndIf

    ; Save this file's metadata to the local cache.
    ; The lookup key is the fileId.
    $oGdCache.SaveTextDt($sFileId,$oDtExpire,"",$sJsonResponse)

    ; Get this file's name and parent[0], and put this information
    ; in our in-memory hashtable to be used below..
    $oJson.Load($sJsonResponse)

    $oSaFileInfo.Clear 
    $oSaFileInfo.Append($oJson.StringOf("name"))
    $oSaFileInfo.Append($oJson.StringOf("parents[0]"))
    $oHashTable.AddStr($sFileId,$oSaFileInfo.Serialize())

    ConsoleWrite($oJson.StringOf("name") & ", " & $oJson.StringOf("parents[0]") & @CRLF)

    $i = $i + 1
Wend

; Check to see if the above loop exited with errors...
If ($oRest.LastMethodSuccess = False) Then
    ConsoleWrite($oRest.LastErrorText & @CRLF)
    Exit
EndIf

; Check to see if the above loop exited with errors...
; A successful response will have a status code equal to 200.
If ($oRest.ResponseStatusCode <> 200) Then
    ConsoleWrite("response status code = " & $oRest.ResponseStatusCode & @CRLF)
    ConsoleWrite("response status text = " & $oRest.ResponseStatusText & @CRLF)
    ConsoleWrite("response header: " & $oRest.ResponseHeader & @CRLF)
    ConsoleWrite("response JSON: " & $sJsonResponse & @CRLF)
    Exit
EndIf

; Now that all the fileId's are in the cache, let's build the directory path
; for each fileID.  

; (Technically, a fileId can have multiple parents, which means it can be in multiple directories
; at once.  This is only going to build directory paths following the 0'th parent ID in the parents list.)

; The directory path for files in "My Drive" will be just the filename.
; For files in sub-directories, the path will be relative, such as "subdir1/subdir2/something.pdf"
; 

ConsoleWrite("---- building paths ----" & @CRLF)

$oSbPath = ObjCreate("Chilkat.StringBuilder")
$iNumFiles = $oJsonMaster.SizeOfArray("fileIds")
$i = 0
While $i < $iNumFiles
    $oJsonMaster.I = $i

    $oSbPath.Clear 

    $sFileId = $oJsonMaster.StringOf("fileIds[i]")
Local $bFinished = False
    While ($bFinished = False)
        $oSaFileInfo.Clear 
        $oSaFileInfo.AppendSerialized($oHashTable.LookupStr($sFileId))
        ; Append this file or directory name.
        $oSbPath.Prepend($oSaFileInfo.GetString(0))
        ; Get the parent fileId
        $sFileId = $oSaFileInfo.GetString(1)
        ; If this fileId is not in the hashtable, then it's the fileId for "My Drive", and we are finished.
        If ($oHashTable.Contains($sFileId) = False) Then
            $bFinished = True
        Else
            $oSbPath.Prepend("/")
        EndIf

    Wend

    ConsoleWrite($i & ": " & $oSbPath.GetAsString() & @CRLF)

    ; Store the filePath --> fileId mapping in our local cache.
    $sFileId = $oJsonMaster.StringOf("fileIds[i]")
    $oGdCache.SaveTextDt($oSbPath.GetAsString(),$oDtExpire,"",$sFileId)

    $oJsonMasterPaths.AddStringAt(-1,$oSbPath.GetAsString())

    $i = $i + 1
Wend

; Save the master list of file IDs and file paths to the local cache.
$oJsonMaster.EmitCompact = False
Local $strJsonMaster = $oJsonMaster.Emit()
$oGdCache.SaveTextNoExpire("AllGoogleDriveFileIds","",$strJsonMaster)
ConsoleWrite("JSON Master Record:" & @CRLF)
ConsoleWrite($strJsonMaster & @CRLF)

; The JSON Master Cache Record looks something like this:
; An application can load the JSON master record and iterate over all the files
; in Google Drive by file ID, or by path.  
; {
;   "fileIds": [
;     "0B53Q6OSTWYolQlExSlBQT1phZXM",
;     "0B53Q6OSTWYolVHRPVkxtYWFtZkk",
;     "0B53Q6OSTWYolRGZEV3ZGUTZfNFk",
;     "0B53Q6OSTWYolS2FXSjliMXQxSU0",
;     "0B53Q6OSTWYolZUhxckMzb0dRMzg",
;     "0B53Q6OSTWYolbUF6WS1Gei1oalk",
;     "0B53Q6OSTWYola296ODZUSm5GYU0",
;     "0B53Q6OSTWYolbTE3c3J5RHBUcHM",
;     "0B53Q6OSTWYolTmhybWJSUGd5Q2c",
;     "0B53Q6OSTWYolY2tPU1BnYW02T2c",
;     "0B53Q6OSTWYolTTBBR2NvUE81Zzg",
;   ],
;   "filePaths": [
;     "testFolder/abc/123/pigs.json",
;     "testFolder/starfish20.jpg",
;     "testFolder/penguins2.jpg",
;     "testFolder/starfish.jpg",
;     "testFolder/abc/123/starfish.jpg",
;     "testFolder/abc/123/penguins.jpg",
;     "testFolder/abc/123",
;     "testFolder/abc",
;     "testFolder/testHello.txt",
;     "testFolder",
;     "helloWorld.txt",
;   ]
; }

ConsoleWrite("Entire cache rebuilt..." & @CRLF)