Chilkat Examples

ChilkatHOME.NET Core C#Android™AutoItCC#C++Chilkat2-PythonCkPythonClassic ASPDataFlexDelphi ActiveXDelphi DLLGoJavaLianjaMono C#Node.jsObjective-CPHP ActiveXPHP ExtensionPerlPowerBuilderPowerShellPureBasicRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++VB.NETVBScriptVisual Basic 6.0Visual FoxProXojo Plugin

Visual FoxPro Examples

Web API Categories

ASN.1
AWS KMS
AWS Misc
Amazon EC2
Amazon Glacier
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Async
Azure Cloud Storage
Azure Key Vault
Azure Service Bus
Azure Table Service
Base64
Bounced Email
Box
CAdES
CSR
CSV
Certificates
Code Signing
Compression
DKIM / DomainKey
DNS
DSA
Diffie-Hellman
Digital Signatures
Dropbox
Dynamics CRM
EBICS
ECC
Ed25519
Email Object
Encryption
FTP
FileAccess
Firebase
GMail REST API
GMail SMTP/IMAP/POP
Geolocation
Google APIs
Google Calendar
Google Cloud SQL
Google Cloud Storage
Google Drive
Google Photos
Google Sheets
Google Tasks
Gzip
HTML-to-XML/Text
HTTP

HTTP Misc
IMAP
JSON
JSON Web Encryption (JWE)
JSON Web Signatures (JWS)
JSON Web Token (JWT)
Java KeyStore (JKS)
MHT / HTML Email
MIME
MS Storage Providers
Microsoft Graph
Misc
NTLM
OAuth1
OAuth2
OIDC
Office365
OneDrive
OpenSSL
Outlook
Outlook Calendar
Outlook Contact
PDF Signatures
PEM
PFX/P12
PKCS11
POP3
PRNG
REST
REST Misc
RSA
SCP
SCard
SFTP
SMTP
SSH
SSH Key
SSH Tunnel
ScMinidriver
SharePoint
SharePoint Online
Signing in the Cloud
Socket/SSL/TLS
Spider
Stream
Tar Archive
ULID/UUID
Upload
WebSocket
XAdES
XML
XML Digital Signatures
XMP
Zip
curl

 

 

 

(Visual FoxPro) Google Drive - Build a Local Cache of Metadata

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 ActiveX Downloads

ActiveX for 32-bit and 64-bit Windows

LOCAL lnSuccess
LOCAL loGAuth
LOCAL loRest
LOCAL lnBAutoReconnect
LOCAL loGdCache
LOCAL lnNumCacheFilesDeleted
LOCAL loDtExpire
LOCAL lcAllFields
LOCAL loJsonMaster
LOCAL loJsonMasterArr
LOCAL loJsonMasterPaths
LOCAL loJson
LOCAL loJsonFileMetadata
LOCAL i
LOCAL lnNumFiles
LOCAL lcJsonResponse
LOCAL lnPageNumber
LOCAL lcPageToken
LOCAL lnBContinueLoop
LOCAL lnBHasMorePages
LOCAL loHashTable
LOCAL loSbPathForFileId
LOCAL loSaFileInfo
LOCAL lcFileId
LOCAL loSbPath
LOCAL lnBFinished
LOCAL lcStrJsonMaster

lnSuccess = 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.

loGAuth = CreateObject('Chilkat_9_5_0.AuthGoogle')
loGAuth.AccessToken = "GOOGLE_DRIVE_ACCESS_TOKEN"

loRest = CreateObject('Chilkat_9_5_0.Rest')

* Connect using TLS.
lnBAutoReconnect = 1
lnSuccess = loRest.Connect("www.googleapis.com",443,1,lnBAutoReconnect)

* Provide the authentication credentials (i.e. the access token)
loRest.SetAuthGoogle(loGAuth)

* -------------------------------------------------------------------
* 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.
loGdCache = CreateObject('Chilkat_9_5_0.Cache')
loGdCache.Level = 0
* Use a root directory that makes sense on your operating system..
loGdCache.AddRoot("C:/ckCache/googleDrive")

* If we are re-building the cache, we can first delete the entire contents of the cache.
lnNumCacheFilesDeleted = loGdCache.DeleteAll()

* Create a date/time object with an time 7 days from the current date/time.
loDtExpire = CreateObject('Chilkat_9_5_0.CkDateTime')
loDtExpire.SetFromCurrentSystemTime()
loDtExpire.AddDays(7)

* Indicate that we want ALL possible fields.
* If no fields are indicated, then only the basic fields are returned.
lcAllFields = "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".
loJsonMaster = CreateObject('Chilkat_9_5_0.JsonObject')
loJsonMasterArr = loJsonMaster.AppendArray("fileIds")
* Also keep a list of file paths.
loJsonMasterPaths = loJsonMaster.AppendArray("filePaths")

* The default page size is 100, with a max of 1000.
loRest.AddQueryParam("pageSize","200")

loJson = CreateObject('Chilkat_9_5_0.JsonObject')

* Send the request for the 1st page.
lcJsonResponse = loRest.FullRequestNoBody("GET","/drive/v3/files")

lnPageNumber = 1

lnBContinueLoop = loRest.LastMethodSuccess AND (loRest.ResponseStatusCode = 200)

DO WHILE lnBContinueLoop = 1

    ? "---- Page " + STR(lnPageNumber) + " ----"
    loJson.Load(lcJsonResponse)

    lnNumFiles = loJson.SizeOfArray("files")
    i = 0
    DO WHILE i < lnNumFiles
        * Add this file ID to the master list.
        loJson.I = i
        loJsonMasterArr.AddStringAt(-1,loJson.StringOf("files[i].id"))

        i = i + 1
    ENDDO

    * 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.
    lcPageToken = loJson.StringOf("nextPageToken")
    lnBContinueLoop = 0
    lnBHasMorePages = loJson.LastMethodSuccess
    IF (lnBHasMorePages = 1) THEN
        loRest.ClearAllQueryParams()
        loRest.AddQueryParam("pageSize","200")
        loRest.AddQueryParam("pageToken",lcPageToken)
        lcJsonResponse = loRest.FullRequestNoBody("GET","/drive/v3/files")
        lnBContinueLoop = loRest.LastMethodSuccess AND (loRest.ResponseStatusCode = 200)
        lnPageNumber = lnPageNumber + 1
    ENDIF

ENDDO

RELEASE loJsonMasterArr

* Check to see if the above loop exited with errors...
IF (loRest.LastMethodSuccess <> 1) THEN
    ? loRest.LastErrorText
    RELEASE loGAuth
    RELEASE loRest
    RELEASE loGdCache
    RELEASE loDtExpire
    RELEASE loJsonMaster
    RELEASE loJson
    CANCEL
ENDIF

* Check to see if the above loop exited with errors...
* A successful response will have a status code equal to 200.
IF (loRest.ResponseStatusCode <> 200) THEN
    ? "response status code = " + STR(loRest.ResponseStatusCode)
    ? "response status text = " + loRest.ResponseStatusText
    ? "response header: " + loRest.ResponseHeader
    ? "response JSON: " + lcJsonResponse
    RELEASE loGAuth
    RELEASE loRest
    RELEASE loGdCache
    RELEASE loDtExpire
    RELEASE loJsonMaster
    RELEASE loJson
    CANCEL
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.)
loHashTable = CreateObject('Chilkat_9_5_0.Hashtable')
* Set the capacity of the hash table to something reasonable for the number of files
* to be hashed.
loHashTable.ClearWithNewCapacity(521)

loSbPathForFileId = CreateObject('Chilkat_9_5_0.StringBuilder')

* Used for storing the file name and parents[0] in the hashTable.
loSaFileInfo = CreateObject('Chilkat_9_5_0.StringArray')
loSaFileInfo.Unique = 0

lnNumFiles = loJsonMaster.SizeOfArray("fileIds")
i = 0
DO WHILE i < lnNumFiles
    loJsonMaster.I = i
    lcFileId = loJsonMaster.StringOf("fileIds[i]")
    loSbPathForFileId.SetString("/drive/v3/files/")
    loSbPathForFileId.Append(lcFileId)

    loRest.ClearAllQueryParams()
    loRest.AddQueryParam("fields",lcAllFields)
    lcJsonResponse = loRest.FullRequestNoBody("GET",loSbPathForFileId.GetAsString())
    IF ((loRest.LastMethodSuccess <> 1) OR (loRest.ResponseStatusCode <> 200)) THEN
        * Force an exit of this loop..
        lnNumFiles = 0
    ENDIF

    * Save this file's metadata to the local cache.
    * The lookup key is the fileId.
    loGdCache.SaveTextDt(lcFileId,loDtExpire,"",lcJsonResponse)

    * Get this file's name and parent[0], and put this information
    * in our in-memory hashtable to be used below..
    loJson.Load(lcJsonResponse)

    loSaFileInfo.Clear()
    loSaFileInfo.Append(loJson.StringOf("name"))
    loSaFileInfo.Append(loJson.StringOf("parents[0]"))
    loHashTable.AddStr(lcFileId,loSaFileInfo.Serialize())

    ? loJson.StringOf("name") + ", " + loJson.StringOf("parents[0]")

    i = i + 1
ENDDO

* Check to see if the above loop exited with errors...
IF (loRest.LastMethodSuccess <> 1) THEN
    ? loRest.LastErrorText
    RELEASE loGAuth
    RELEASE loRest
    RELEASE loGdCache
    RELEASE loDtExpire
    RELEASE loJsonMaster
    RELEASE loJson
    RELEASE loHashTable
    RELEASE loSbPathForFileId
    RELEASE loSaFileInfo
    CANCEL
ENDIF

* Check to see if the above loop exited with errors...
* A successful response will have a status code equal to 200.
IF (loRest.ResponseStatusCode <> 200) THEN
    ? "response status code = " + STR(loRest.ResponseStatusCode)
    ? "response status text = " + loRest.ResponseStatusText
    ? "response header: " + loRest.ResponseHeader
    ? "response JSON: " + lcJsonResponse
    RELEASE loGAuth
    RELEASE loRest
    RELEASE loGdCache
    RELEASE loDtExpire
    RELEASE loJsonMaster
    RELEASE loJson
    RELEASE loHashTable
    RELEASE loSbPathForFileId
    RELEASE loSaFileInfo
    CANCEL
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"
* 

? "---- building paths ----"

loSbPath = CreateObject('Chilkat_9_5_0.StringBuilder')
lnNumFiles = loJsonMaster.SizeOfArray("fileIds")
i = 0
DO WHILE i < lnNumFiles
    loJsonMaster.I = i

    loSbPath.Clear()

    lcFileId = loJsonMaster.StringOf("fileIds[i]")
    lnBFinished = 0
    DO WHILE (lnBFinished = 0)
        loSaFileInfo.Clear()
        loSaFileInfo.AppendSerialized(loHashTable.LookupStr(lcFileId))
        * Append this file or directory name.
        loSbPath.Prepend(loSaFileInfo.GetString(0))
        * Get the parent fileId
        lcFileId = loSaFileInfo.GetString(1)
        * If this fileId is not in the hashtable, then it's the fileId for "My Drive", and we are finished.
        IF (loHashTable.Contains(lcFileId) = 0) THEN
            lnBFinished = 1
        ELSE
            loSbPath.Prepend("/")
        ENDIF

    ENDDO

    ? STR(i) + ": " + loSbPath.GetAsString()

    * Store the filePath --> fileId mapping in our local cache.
    lcFileId = loJsonMaster.StringOf("fileIds[i]")
    loGdCache.SaveTextDt(loSbPath.GetAsString(),loDtExpire,"",lcFileId)

    loJsonMasterPaths.AddStringAt(-1,loSbPath.GetAsString())

    i = i + 1
ENDDO

RELEASE loJsonMasterPaths

* Save the master list of file IDs and file paths to the local cache.
loJsonMaster.EmitCompact = 0
lcStrJsonMaster = loJsonMaster.Emit()
loGdCache.SaveTextNoExpire("AllGoogleDriveFileIds","",lcStrJsonMaster)
? "JSON Master Record:"
? lcStrJsonMaster

* 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",
*   ]
* }

? "Entire cache rebuilt..."

RELEASE loGAuth
RELEASE loRest
RELEASE loGdCache
RELEASE loDtExpire
RELEASE loJsonMaster
RELEASE loJson
RELEASE loHashTable
RELEASE loSbPathForFileId
RELEASE loSaFileInfo
RELEASE loSbPath


 

© 2000-2024 Chilkat Software, Inc. All Rights Reserved.