Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.0.0+

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

Lua
local chilkat = require("chilkat")

local success = 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.

local gAuth = chilkat.AuthGoogle.new()
gAuth.access_token = "GOOGLE_DRIVE_ACCESS_TOKEN"

local rest = chilkat.Rest.new()

-- Connect using TLS.
local bAutoReconnect = true
success = rest:connect("www.googleapis.com", 443, true, bAutoReconnect)

-- Provide the authentication credentials (i.e. the access token)
rest:set_auth_google(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.
local gdCache = chilkat.Cache.new()
gdCache.level = 0
-- Use a root directory that makes sense on your operating system..
gdCache:add_root("C:/ckCache/googleDrive")

-- If we are re-building the cache, we can first delete the entire contents of the cache.
local numCacheFilesDeleted = gdCache:delete_all()

-- Create a date/time object with an time 7 days from the current date/time.
local dtExpire = chilkat.DateTime.new()
dtExpire:set_from_current_system_time()
dtExpire:add_days(7)

-- Indicate that we want ALL possible fields.
-- If no fields are indicated, then only the basic fields are returned.
local 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".
local jsonMaster = chilkat.JsonObject.new()

local jsonMasterArr = chilkat.JsonArray.new()
jsonMaster:append_array2("fileIds", jsonMasterArr)

-- Also keep a list of file paths.
local jsonMasterPaths = chilkat.JsonArray.new()
jsonMaster:append_array2("filePaths", jsonMasterPaths)

-- The default page size is 100, with a max of 1000.
rest:add_query_param("pageSize", "200")

local json = chilkat.JsonObject.new()
local jsonFileMetadata = chilkat.JsonObject.new()
local i = 0
local numFiles = 0

-- Send the request for the 1st page.
local jsonResponse = rest:full_request_no_body("GET", "/drive/v3/files")

local pageNumber = 1
local pageToken = ""
local bContinueLoop = rest.last_method_success and (rest.response_status_code == 200)

while bContinueLoop do
    print("---- Page " .. pageNumber .. " ----")
    json:load(jsonResponse)

    numFiles = json:size_of_array("files")
    i = 0
    while i < numFiles do
        -- Add this file ID to the master list.
        json.i = i
        jsonMasterArr:add_string_at(-1, json:string_of("files[i].id"))

        i = i + 1
    end

    -- 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.
    pageToken = json:string_of("nextPageToken")
    bContinueLoop = false
    local bHasMorePages = json.last_method_success
    if bHasMorePages then
        rest:clear_all_query_params()
        rest:add_query_param("pageSize", "200")
        rest:add_query_param("pageToken", pageToken)
        jsonResponse = rest:full_request_no_body("GET", "/drive/v3/files")
        bContinueLoop = rest.last_method_success and (rest.response_status_code == 200)
        pageNumber = pageNumber + 1
    end
end

-- Check to see if the above loop exited with errors...
if not rest.last_method_success then
    print(rest.last_error_text)
    return
end

-- Check to see if the above loop exited with errors...
-- A successful response will have a status code equal to 200.
if rest.response_status_code ~= 200 then
    print("response status code = " .. rest.response_status_code)
    print("response status text = " .. rest.response_status_text)
    print("response header: " .. rest.response_header)
    print("response JSON: " .. jsonResponse)
    return
end

-- 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.)
local hashTable = chilkat.Hashtable.new()
-- Set the capacity of the hash table to something reasonable for the number of files
-- to be hashed.
hashTable:clear_with_new_capacity(521)

local sbPathForFileId = chilkat.StringBuilder.new()

-- Used for storing the file name and parents[0] in the hashTable.
local saFileInfo = chilkat.StringArray.new()
saFileInfo.unique = false

local fileId = ""
numFiles = jsonMaster:size_of_array("fileIds")
i = 0
while i < numFiles do
    jsonMaster.i = i
    fileId = jsonMaster:string_of("fileIds[i]")
    sbPathForFileId:set_string("/drive/v3/files/")
    sbPathForFileId:append(fileId)

    rest:clear_all_query_params()
    rest:add_query_param("fields", allFields)
    jsonResponse = rest:full_request_no_body("GET", sbPathForFileId:get_as_string())
    if (not rest.last_method_success) or (rest.response_status_code ~= 200) then
        -- Force an exit of this loop..
        numFiles = 0
    end

    -- Save this file's metadata to the local cache.
    -- The lookup key is the fileId.
    gdCache:save_text_dt(fileId, dtExpire, "", jsonResponse)

    -- Get this file's name and parent[0], and put this information
    -- in our in-memory hashtable to be used below..
    json:load(jsonResponse)

    saFileInfo:clear()
    saFileInfo:append(json:string_of("name"))
    saFileInfo:append(json:string_of("parents[0]"))
    hashTable:add_str(fileId, saFileInfo:serialize())

    print(json:string_of("name") .. ", " .. json:string_of("parents[0]"))

    i = i + 1
end

-- Check to see if the above loop exited with errors...
if not rest.last_method_success then
    print(rest.last_error_text)
    return
end

-- Check to see if the above loop exited with errors...
-- A successful response will have a status code equal to 200.
if rest.response_status_code ~= 200 then
    print("response status code = " .. rest.response_status_code)
    print("response status text = " .. rest.response_status_text)
    print("response header: " .. rest.response_header)
    print("response JSON: " .. jsonResponse)
    return
end

-- 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"
--

print("---- building paths ----")

local sbPath = chilkat.StringBuilder.new()
numFiles = jsonMaster:size_of_array("fileIds")
i = 0
while i < numFiles do
    jsonMaster.i = i

    sbPath:clear()

    fileId = jsonMaster:string_of("fileIds[i]")
    local bFinished = false
    while not bFinished do
        saFileInfo:clear()
        saFileInfo:append_serialized(hashTable:lookup_str(fileId))
        -- Append this file or directory name.
        sbPath:prepend(saFileInfo:get_string(0))
        -- Get the parent fileId
        fileId = saFileInfo:get_string(1)
        -- If this fileId is not in the hashtable, then it's the fileId for "My Drive", and we are finished.
        if not hashTable:contains(fileId) then
            bFinished = true
        else
            sbPath:prepend("/")
        end
    end

    print(i .. ": " .. sbPath:get_as_string())

    -- Store the filePath --> fileId mapping in our local cache.
    fileId = jsonMaster:string_of("fileIds[i]")
    gdCache:save_text_dt(sbPath:get_as_string(), dtExpire, "", fileId)

    jsonMasterPaths:add_string_at(-1, sbPath:get_as_string())

    i = i + 1
end

-- Save the master list of file IDs and file paths to the local cache.
jsonMaster.emit_compact = false
local strJsonMaster = jsonMaster:emit()
gdCache:save_text_no_expire("AllGoogleDriveFileIds", "", strJsonMaster)
print("JSON Master Record:")
print(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",
--   ]
-- }

print("Entire cache rebuilt...")