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

Rust

let _ = 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.

let g_auth = chilkat::AuthGoogle::new();
g_auth.set_access_token("GOOGLE_DRIVE_ACCESS_TOKEN");

let rest = chilkat::Rest::new();

// Connect using TLS.
let b_auto_reconnect = true;
let _ = rest.connect("www.googleapis.com", 443, true, b_auto_reconnect).is_ok();

// Provide the authentication credentials (i.e. the access token)
let _ = rest.set_auth_google(&g_auth);

// -------------------------------------------------------------------
// 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.
let gd_cache = chilkat::Cache::new();
gd_cache.set_level(0);
// Use a root directory that makes sense on your operating system..
gd_cache.add_root("C:/ckCache/googleDrive");

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

// Create a date/time object with an time 7 days from the current date/time.
let dt_expire = chilkat::DateTime::new();
let _ = dt_expire.set_from_current_system_time();
let _ = dt_expire.add_days(7);

// Indicate that we want ALL possible fields.
// If no fields are indicated, then only the basic fields are returned.
let 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".to_string();

// 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".
let json_master = chilkat::JsonObject::new();

let json_master_arr = chilkat::JsonArray::new();
let _ = json_master.append_array2("fileIds", &json_master_arr);

// Also keep a list of file paths.
let json_master_paths = chilkat::JsonArray::new();
let _ = json_master.append_array2("filePaths", &json_master_paths);

// The default page size is 100, with a max of 1000.
let _ = rest.add_query_param("pageSize", "200");

let json = chilkat::JsonObject::new();
let json_file_metadata = chilkat::JsonObject::new();
let mut i: i32 = 0;
let mut num_files: i32 = 0;

// Send the request for the 1st page.
let mut json_response = rest.full_request_no_body("GET", "/drive/v3/files").unwrap_or_default();

let mut page_number = 1;
let mut page_token = String::new();
let mut b_continue_loop = rest.last_method_success() && (rest.response_status_code() == 200);

while b_continue_loop {

    println!("---- Page {} ----", page_number);
    let _ = json.load(&json_response);

    num_files = json.size_of_array("files");
    i = 0;
    while i < num_files {
        // Add this file ID to the master list.
        json.set_i(i);
        let _ = json_master_arr.add_string_at(-1, &json.string_of("files[i].id").unwrap_or_default());

        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 = json.string_of("nextPageToken").unwrap_or_default();
    b_continue_loop = false;
    let b_has_more_pages = json.last_method_success();
    if b_has_more_pages {
        let _ = rest.clear_all_query_params();
        let _ = rest.add_query_param("pageSize", "200");
        let _ = rest.add_query_param("pageToken", &page_token);
        json_response = rest.full_request_no_body("GET", "/drive/v3/files").unwrap_or_default();
        b_continue_loop = rest.last_method_success() && (rest.response_status_code() == 200);
        page_number = page_number + 1;
    }

}

// Check to see if the above loop exited with errors...
if !rest.last_method_success() {
    println!("{}", rest.last_error_text());
    return;
}

// 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 {
    println!("response status code = {}", rest.response_status_code());
    println!("response status text = {}", rest.response_status_text());
    println!("response header: {}", rest.response_header());
    println!("response JSON: {}", 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.)
let hash_table = chilkat::Hashtable::new();
// Set the capacity of the hash table to something reasonable for the number of files
// to be hashed.
let _ = hash_table.clear_with_new_capacity(521);

let sb_path_for_file_id = chilkat::StringBuilder::new();

// Used for storing the file name and parents[0] in the hashTable.
let sa_file_info = chilkat::StringArray::new();
sa_file_info.set_unique(false);

let mut file_id = String::new();
num_files = json_master.size_of_array("fileIds");
i = 0;
while i < num_files {
    json_master.set_i(i);
    file_id = json_master.string_of("fileIds[i]").unwrap_or_default();
    let _ = sb_path_for_file_id.set_string("/drive/v3/files/");
    let _ = sb_path_for_file_id.append(&file_id);

    let _ = rest.clear_all_query_params();
    let _ = rest.add_query_param("fields", &all_fields);
    json_response = rest.full_request_no_body("GET", &sb_path_for_file_id.get_as_string().unwrap_or_default()).unwrap_or_default();
    if (!rest.last_method_success()) || (rest.response_status_code() != 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.
    let _ = gd_cache.save_text_dt(&file_id, &dt_expire, "", &json_response);

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

    sa_file_info.clear();
    let _ = sa_file_info.append(&json.string_of("name").unwrap_or_default());
    let _ = sa_file_info.append(&json.string_of("parents[0]").unwrap_or_default());
    let _ = hash_table.add_str(&file_id, &sa_file_info.serialize().unwrap_or_default());

    println!("{}, {}", json.string_of("name").unwrap_or_default(), json.string_of("parents[0]").unwrap_or_default());

    i = i + 1;
}

// Check to see if the above loop exited with errors...
if !rest.last_method_success() {
    println!("{}", rest.last_error_text());
    return;
}

// 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 {
    println!("response status code = {}", rest.response_status_code());
    println!("response status text = {}", rest.response_status_text());
    println!("response header: {}", rest.response_header());
    println!("response JSON: {}", 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"
// 

println!("---- building paths ----");

let sb_path = chilkat::StringBuilder::new();
num_files = json_master.size_of_array("fileIds");
i = 0;
while i < num_files {
    json_master.set_i(i);

    sb_path.clear();

    file_id = json_master.string_of("fileIds[i]").unwrap_or_default();
    let mut b_finished = false;
    while !b_finished {
        sa_file_info.clear();
        let _ = sa_file_info.append_serialized(&hash_table.lookup_str(&file_id).unwrap_or_default());
        // Append this file or directory name.
        let _ = sb_path.prepend(&sa_file_info.get_string(0).unwrap_or_default());
        // Get the parent fileId
        file_id = sa_file_info.get_string(1).unwrap_or_default();
        // 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 {
            let _ = sb_path.prepend("/");
        }

    }

    println!("{}: {}", i, sb_path.get_as_string().unwrap_or_default());

    // Store the filePath --> fileId mapping in our local cache.
    file_id = json_master.string_of("fileIds[i]").unwrap_or_default();
    let _ = gd_cache.save_text_dt(&sb_path.get_as_string().unwrap_or_default(), &dt_expire, "", &file_id);

    let _ = json_master_paths.add_string_at(-1, &sb_path.get_as_string().unwrap_or_default());

    i = i + 1;
}

// Save the master list of file IDs and file paths to the local cache.
json_master.set_emit_compact(false);
let str_json_master = json_master.emit().unwrap_or_default();
let _ = gd_cache.save_text_no_expire("AllGoogleDriveFileIds", "", &str_json_master);
println!("JSON Master Record:");
println!("{}", 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",
//   ]
// }

println!("Entire cache rebuilt...");