PowerBuilder
PowerBuilder
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 PowerBuilder Downloads
integer li_rc
integer li_Success
oleobject loo_GAuth
oleobject loo_Rest
integer li_BAutoReconnect
oleobject loo_GdCache
integer li_NumCacheFilesDeleted
oleobject loo_DtExpire
string ls_AllFields
oleobject loo_JsonMaster
oleobject loo_JsonMasterArr
oleobject loo_JsonMasterPaths
oleobject loo_Json
oleobject loo_JsonFileMetadata
integer i
integer li_NumFiles
string ls_JsonResponse
integer li_PageNumber
string ls_PageToken
integer li_BContinueLoop
integer li_BHasMorePages
oleobject loo_HashTable
oleobject loo_SbPathForFileId
oleobject loo_SaFileInfo
string ls_FileId
oleobject loo_SbPath
integer li_BFinished
string ls_StrJsonMaster
li_Success = 0
li_Success = 1
// 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.
loo_GAuth = create oleobject
li_rc = loo_GAuth.ConnectToNewObject("Chilkat.AuthGoogle")
if li_rc < 0 then
destroy loo_GAuth
MessageBox("Error","Connecting to COM object failed")
return
end if
loo_GAuth.AccessToken = "GOOGLE_DRIVE_ACCESS_TOKEN"
loo_Rest = create oleobject
li_rc = loo_Rest.ConnectToNewObject("Chilkat.Rest")
// Connect using TLS.
li_BAutoReconnect = 1
li_Success = loo_Rest.Connect("www.googleapis.com",443,1,li_BAutoReconnect)
// Provide the authentication credentials (i.e. the access token)
loo_Rest.SetAuthGoogle(loo_GAuth)
// -------------------------------------------------------------------
// 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.
loo_GdCache = create oleobject
li_rc = loo_GdCache.ConnectToNewObject("Chilkat.Cache")
loo_GdCache.Level = 0
// Use a root directory that makes sense on your operating system..
loo_GdCache.AddRoot("C:/ckCache/googleDrive")
// If we are re-building the cache, we can first delete the entire contents of the cache.
li_NumCacheFilesDeleted = loo_GdCache.DeleteAll()
// Create a date/time object with an time 7 days from the current date/time.
loo_DtExpire = create oleobject
li_rc = loo_DtExpire.ConnectToNewObject("Chilkat.CkDateTime")
loo_DtExpire.SetFromCurrentSystemTime()
loo_DtExpire.AddDays(7)
// Indicate that we want ALL possible fields.
// If no fields are indicated, then only the basic fields are returned.
ls_AllFields = "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".
loo_JsonMaster = create oleobject
li_rc = loo_JsonMaster.ConnectToNewObject("Chilkat.JsonObject")
loo_JsonMasterArr = create oleobject
li_rc = loo_JsonMasterArr.ConnectToNewObject("Chilkat.JsonArray")
loo_JsonMaster.AppendArray2("fileIds",loo_JsonMasterArr)
// Also keep a list of file paths.
loo_JsonMasterPaths = create oleobject
li_rc = loo_JsonMasterPaths.ConnectToNewObject("Chilkat.JsonArray")
loo_JsonMaster.AppendArray2("filePaths",loo_JsonMasterPaths)
// The default page size is 100, with a max of 1000.
loo_Rest.AddQueryParam("pageSize","200")
loo_Json = create oleobject
li_rc = loo_Json.ConnectToNewObject("Chilkat.JsonObject")
// Send the request for the 1st page.
ls_JsonResponse = loo_Rest.FullRequestNoBody("GET","/drive/v3/files")
li_PageNumber = 1
li_BContinueLoop = loo_Rest.LastMethodSuccess AND (loo_Rest.ResponseStatusCode = 200)
do while li_BContinueLoop = 1
Write-Debug "---- Page " + string(li_PageNumber) + " ----"
loo_Json.Load(ls_JsonResponse)
li_NumFiles = loo_Json.SizeOfArray("files")
i = 0
do while i < li_NumFiles
// Add this file ID to the master list.
loo_Json.I = i
loo_JsonMasterArr.AddStringAt(-1,loo_Json.StringOf("files[i].id"))
i = i + 1
loop
// 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.
ls_PageToken = loo_Json.StringOf("nextPageToken")
li_BContinueLoop = 0
li_BHasMorePages = loo_Json.LastMethodSuccess
if li_BHasMorePages = 1 then
loo_Rest.ClearAllQueryParams()
loo_Rest.AddQueryParam("pageSize","200")
loo_Rest.AddQueryParam("pageToken",ls_PageToken)
ls_JsonResponse = loo_Rest.FullRequestNoBody("GET","/drive/v3/files")
li_BContinueLoop = loo_Rest.LastMethodSuccess AND (loo_Rest.ResponseStatusCode = 200)
li_PageNumber = li_PageNumber + 1
end if
loop
// Check to see if the above loop exited with errors...
if loo_Rest.LastMethodSuccess = 0 then
Write-Debug loo_Rest.LastErrorText
destroy loo_GAuth
destroy loo_Rest
destroy loo_GdCache
destroy loo_DtExpire
destroy loo_JsonMaster
destroy loo_JsonMasterArr
destroy loo_JsonMasterPaths
destroy loo_Json
return
end if
// Check to see if the above loop exited with errors...
// A successful response will have a status code equal to 200.
if loo_Rest.ResponseStatusCode <> 200 then
Write-Debug "response status code = " + string(loo_Rest.ResponseStatusCode)
Write-Debug "response status text = " + loo_Rest.ResponseStatusText
Write-Debug "response header: " + loo_Rest.ResponseHeader
Write-Debug "response JSON: " + ls_JsonResponse
destroy loo_GAuth
destroy loo_Rest
destroy loo_GdCache
destroy loo_DtExpire
destroy loo_JsonMaster
destroy loo_JsonMasterArr
destroy loo_JsonMasterPaths
destroy loo_Json
return
end if
// 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.)
loo_HashTable = create oleobject
li_rc = loo_HashTable.ConnectToNewObject("Chilkat.Hashtable")
// Set the capacity of the hash table to something reasonable for the number of files
// to be hashed.
loo_HashTable.ClearWithNewCapacity(521)
loo_SbPathForFileId = create oleobject
li_rc = loo_SbPathForFileId.ConnectToNewObject("Chilkat.StringBuilder")
// Used for storing the file name and parents[0] in the hashTable.
loo_SaFileInfo = create oleobject
li_rc = loo_SaFileInfo.ConnectToNewObject("Chilkat.StringArray")
loo_SaFileInfo.Unique = 0
li_NumFiles = loo_JsonMaster.SizeOfArray("fileIds")
i = 0
do while i < li_NumFiles
loo_JsonMaster.I = i
ls_FileId = loo_JsonMaster.StringOf("fileIds[i]")
loo_SbPathForFileId.SetString("/drive/v3/files/")
loo_SbPathForFileId.Append(ls_FileId)
loo_Rest.ClearAllQueryParams()
loo_Rest.AddQueryParam("fields",ls_AllFields)
ls_JsonResponse = loo_Rest.FullRequestNoBody("GET",loo_SbPathForFileId.GetAsString())
if (loo_Rest.LastMethodSuccess <> 1) OR (loo_Rest.ResponseStatusCode <> 200) then
// Force an exit of this loop..
li_NumFiles = 0
end if
// Save this file's metadata to the local cache.
// The lookup key is the fileId.
loo_GdCache.SaveTextDt(ls_FileId,loo_DtExpire,"",ls_JsonResponse)
// Get this file's name and parent[0], and put this information
// in our in-memory hashtable to be used below..
loo_Json.Load(ls_JsonResponse)
loo_SaFileInfo.Clear()
loo_SaFileInfo.Append(loo_Json.StringOf("name"))
loo_SaFileInfo.Append(loo_Json.StringOf("parents[0]"))
loo_HashTable.AddStr(ls_FileId,loo_SaFileInfo.Serialize())
Write-Debug loo_Json.StringOf("name") + ", " + loo_Json.StringOf("parents[0]")
i = i + 1
loop
// Check to see if the above loop exited with errors...
if loo_Rest.LastMethodSuccess = 0 then
Write-Debug loo_Rest.LastErrorText
destroy loo_GAuth
destroy loo_Rest
destroy loo_GdCache
destroy loo_DtExpire
destroy loo_JsonMaster
destroy loo_JsonMasterArr
destroy loo_JsonMasterPaths
destroy loo_Json
destroy loo_HashTable
destroy loo_SbPathForFileId
destroy loo_SaFileInfo
return
end if
// Check to see if the above loop exited with errors...
// A successful response will have a status code equal to 200.
if loo_Rest.ResponseStatusCode <> 200 then
Write-Debug "response status code = " + string(loo_Rest.ResponseStatusCode)
Write-Debug "response status text = " + loo_Rest.ResponseStatusText
Write-Debug "response header: " + loo_Rest.ResponseHeader
Write-Debug "response JSON: " + ls_JsonResponse
destroy loo_GAuth
destroy loo_Rest
destroy loo_GdCache
destroy loo_DtExpire
destroy loo_JsonMaster
destroy loo_JsonMasterArr
destroy loo_JsonMasterPaths
destroy loo_Json
destroy loo_HashTable
destroy loo_SbPathForFileId
destroy loo_SaFileInfo
return
end if
// 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"
//
Write-Debug "---- building paths ----"
loo_SbPath = create oleobject
li_rc = loo_SbPath.ConnectToNewObject("Chilkat.StringBuilder")
li_NumFiles = loo_JsonMaster.SizeOfArray("fileIds")
i = 0
do while i < li_NumFiles
loo_JsonMaster.I = i
loo_SbPath.Clear()
ls_FileId = loo_JsonMaster.StringOf("fileIds[i]")
li_BFinished = 0
do while (li_BFinished = 0)
loo_SaFileInfo.Clear()
loo_SaFileInfo.AppendSerialized(loo_HashTable.LookupStr(ls_FileId))
// Append this file or directory name.
loo_SbPath.Prepend(loo_SaFileInfo.GetString(0))
// Get the parent fileId
ls_FileId = loo_SaFileInfo.GetString(1)
// If this fileId is not in the hashtable, then it's the fileId for "My Drive", and we are finished.
if loo_HashTable.Contains(ls_FileId) = 0 then
li_BFinished = 1
else
loo_SbPath.Prepend("/")
end if
loop
Write-Debug string(i) + ": " + loo_SbPath.GetAsString()
// Store the filePath --> fileId mapping in our local cache.
ls_FileId = loo_JsonMaster.StringOf("fileIds[i]")
loo_GdCache.SaveTextDt(loo_SbPath.GetAsString(),loo_DtExpire,"",ls_FileId)
loo_JsonMasterPaths.AddStringAt(-1,loo_SbPath.GetAsString())
i = i + 1
loop
// Save the master list of file IDs and file paths to the local cache.
loo_JsonMaster.EmitCompact = 0
ls_StrJsonMaster = loo_JsonMaster.Emit()
loo_GdCache.SaveTextNoExpire("AllGoogleDriveFileIds","",ls_StrJsonMaster)
Write-Debug "JSON Master Record:"
Write-Debug ls_StrJsonMaster
// 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",
// ]
// }
Write-Debug "Entire cache rebuilt..."
destroy loo_GAuth
destroy loo_Rest
destroy loo_GdCache
destroy loo_DtExpire
destroy loo_JsonMaster
destroy loo_JsonMasterArr
destroy loo_JsonMasterPaths
destroy loo_Json
destroy loo_HashTable
destroy loo_SbPathForFileId
destroy loo_SaFileInfo
destroy loo_SbPath