Sample code for 30+ languages & platforms
Zig 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 Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // 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.

    const g_auth = try chilkat.AuthGoogle.init();
    defer g_auth.deinit();
    g_auth.setAccessToken("GOOGLE_DRIVE_ACCESS_TOKEN");

    const rest = try chilkat.Rest.init();
    defer rest.deinit();

    // Connect using TLS.
    const b_auto_reconnect = true;
    try rest.connect("www.googleapis.com", 443, true, b_auto_reconnect);

    // Provide the authentication credentials (i.e. the access token)
    rest.setAuthGoogle(g_auth) catch {};

    // -------------------------------------------------------------------
    // 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.
    const gd_cache = try chilkat.Cache.init();
    defer gd_cache.deinit();
    gd_cache.setLevel(0);
    // Use a root directory that makes sense on your operating system..
    gd_cache.addRoot("C:/ckCache/googleDrive");

    // If we are re-building the cache, we can first delete the entire contents of the cache.
    _ = gd_cache.deleteAll();

    // Create a date/time object with an time 7 days from the current date/time.
    const dt_expire = try chilkat.DateTime.init();
    defer dt_expire.deinit();
    dt_expire.setFromCurrentSystemTime() catch {};
    dt_expire.addDays(7) catch {};

    // Indicate that we want ALL possible fields.
    // If no fields are indicated, then only the basic fields are returned.
    const all_fields = "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".
    const json_master = try chilkat.JsonObject.init();
    defer json_master.deinit();

    const json_master_arr = try chilkat.JsonArray.init();
    defer json_master_arr.deinit();
    json_master.appendArray2("fileIds", json_master_arr) catch {};

    // Also keep a list of file paths.
    const json_master_paths = try chilkat.JsonArray.init();
    defer json_master_paths.deinit();
    json_master.appendArray2("filePaths", json_master_paths) catch {};

    // The default page size is 100, with a max of 1000.
    rest.addQueryParam("pageSize", "200") catch {};

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    const json_file_metadata = try chilkat.JsonObject.init();
    defer json_file_metadata.deinit();
    var i: i32 = 0;
    var num_files: i32 = 0;

    // Send the request for the 1st page.
    var json_response: [:0]const u8 = try rest.fullRequestNoBody(alloc, "GET", "/drive/v3/files");

    var page_number: i32 = 1;
    var page_token: [:0]const u8 = "";
    var b_continue_loop: bool = rest.getLastMethodSuccess() and (rest.getResponseStatusCode() == 200);

    while (b_continue_loop) {
        std.debug.print("---- Page {d} ----\n", .{page_number});
        json.load(json_response) catch {};

        num_files = json.sizeOfArray("files");
        i = 0;
        while (i < num_files) {
            // Add this file ID to the master list.
            json.setI(i);
            json_master_arr.addStringAt(-1, try json.stringOf(alloc, "files[i].id")) catch {};

            i = i + 1;
        }

        // 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.
        page_token = try json.stringOf(alloc, "nextPageToken");
        b_continue_loop = false;
        const b_has_more_pages = json.getLastMethodSuccess();
        if (b_has_more_pages) {
            rest.clearAllQueryParams() catch {};
            rest.addQueryParam("pageSize", "200") catch {};
            rest.addQueryParam("pageToken", page_token) catch {};
            json_response = try rest.fullRequestNoBody(alloc, "GET", "/drive/v3/files");
            b_continue_loop = rest.getLastMethodSuccess() and (rest.getResponseStatusCode() == 200);
            page_number = page_number + 1;
        }
    }

    // Check to see if the above loop exited with errors...
    if (!rest.getLastMethodSuccess()) {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    }

    // Check to see if the above loop exited with errors...
    // A successful response will have a status code equal to 200.
    if (rest.getResponseStatusCode() != 200) {
        std.debug.print("response status code = {d}\n", .{rest.getResponseStatusCode()});
        std.debug.print("response status text = {s}\n", .{try rest.getResponseStatusText(alloc)});
        std.debug.print("response header: {s}\n", .{try rest.getResponseHeader(alloc)});
        std.debug.print("response JSON: {s}\n", .{json_response});
        return;
    }

    // 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.)
    const hash_table = try chilkat.Hashtable.init();
    defer hash_table.deinit();
    // Set the capacity of the hash table to something reasonable for the number of files
    // to be hashed.
    hash_table.clearWithNewCapacity(521) catch {};

    const sb_path_for_file_id = try chilkat.StringBuilder.init();
    defer sb_path_for_file_id.deinit();

    // Used for storing the file name and parents[0] in the hashTable.
    const sa_file_info = try chilkat.StringArray.init();
    defer sa_file_info.deinit();
    sa_file_info.setUnique(false);

    var file_id: [:0]const u8 = "";
    num_files = json_master.sizeOfArray("fileIds");
    i = 0;
    while (i < num_files) {
        json_master.setI(i);
        file_id = try json_master.stringOf(alloc, "fileIds[i]");
        sb_path_for_file_id.setString("/drive/v3/files/") catch {};
        sb_path_for_file_id.append(file_id) catch {};

        rest.clearAllQueryParams() catch {};
        rest.addQueryParam("fields", all_fields) catch {};
        json_response = try rest.fullRequestNoBody(alloc, "GET", try sb_path_for_file_id.getAsString(alloc));
        if ((!rest.getLastMethodSuccess()) or (rest.getResponseStatusCode() != 200)) {
            // Force an exit of this loop..
            num_files = 0;
        }

        // Save this file's metadata to the local cache.
        // The lookup key is the fileId.
        gd_cache.saveTextDt(file_id, dt_expire, "", json_response) catch {};

        // Get this file's name and parent[0], and put this information
        // in our in-memory hashtable to be used below..
        json.load(json_response) catch {};

        sa_file_info.clear();
        sa_file_info.append(try json.stringOf(alloc, "name")) catch {};
        sa_file_info.append(try json.stringOf(alloc, "parents[0]")) catch {};
        hash_table.addStr(file_id, try sa_file_info.serialize(alloc)) catch {};

        std.debug.print("{s}, {s}\n", .{ try json.stringOf(alloc, "name"), try json.stringOf(alloc, "parents[0]") });

        i = i + 1;
    }

    // Check to see if the above loop exited with errors...
    if (!rest.getLastMethodSuccess()) {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    }

    // Check to see if the above loop exited with errors...
    // A successful response will have a status code equal to 200.
    if (rest.getResponseStatusCode() != 200) {
        std.debug.print("response status code = {d}\n", .{rest.getResponseStatusCode()});
        std.debug.print("response status text = {s}\n", .{try rest.getResponseStatusText(alloc)});
        std.debug.print("response header: {s}\n", .{try rest.getResponseHeader(alloc)});
        std.debug.print("response JSON: {s}\n", .{json_response});
        return;
    }

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

    std.debug.print("---- building paths ----\n", .{});

    const sb_path = try chilkat.StringBuilder.init();
    defer sb_path.deinit();
    num_files = json_master.sizeOfArray("fileIds");
    i = 0;
    while (i < num_files) {
        json_master.setI(i);

        sb_path.clear();

        file_id = try json_master.stringOf(alloc, "fileIds[i]");
        var b_finished: bool = false;
        while (!b_finished) {
            sa_file_info.clear();
            sa_file_info.appendSerialized(try hash_table.lookupStr(alloc, file_id)) catch {};
            // Append this file or directory name.
            sb_path.prepend(try sa_file_info.getString(alloc, 0)) catch {};
            // Get the parent fileId
            file_id = try sa_file_info.getString(alloc, 1);
            // If this fileId is not in the hashtable, then it's the fileId for "My Drive", and we are finished.
            if (!hash_table.contains(file_id)) {
                b_finished = true;
            } else {
                sb_path.prepend("/") catch {};
            }
        }

        std.debug.print("{d}: {s}\n", .{ i, try sb_path.getAsString(alloc) });

        // Store the filePath --> fileId mapping in our local cache.
        file_id = try json_master.stringOf(alloc, "fileIds[i]");
        gd_cache.saveTextDt(try sb_path.getAsString(alloc), dt_expire, "", file_id) catch {};

        json_master_paths.addStringAt(-1, try sb_path.getAsString(alloc)) catch {};

        i = i + 1;
    }

    // Save the master list of file IDs and file paths to the local cache.
    json_master.setEmitCompact(false);
    const str_json_master = try json_master.emit(alloc);
    gd_cache.saveTextNoExpire("AllGoogleDriveFileIds", "", str_json_master) catch {};
    std.debug.print("JSON Master Record:\n", .{});
    std.debug.print("{s}\n", .{str_json_master});

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

    std.debug.print("Entire cache rebuilt...\n", .{});
}