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

OneDrive: Synchronize a Local File Index with Delta Queries

See more OneDrive Examples

Build and maintain a local metadata index for one drive. The first run follows root/delta to a deltaLink; later runs start at that saved URL. Keep a separate checkpoint for each account, drive, and projection. Empty pages still have to be followed. OneDrive reports deletion with the deleted facet, not Outlook's @removed annotation.

Repeated item IDs are applied in received order, with the last occurrence winning. Partial updates preserve omitted fields; parent IDs support renames and moves without relying on returned paths. IDs remain strings and large sizes are stored as decimal text. Tombstones are retained rather than deleting local data. A real file synchronizer must download changed content, reconcile local edits, and remove a deleted folder only after the round is complete and it is empty.

The checkpoint stores data and continuation together, with a private matching backup before replacement. Use atomic durable storage and one writer in production. Intermediate pages are not a completed snapshot; roundComplete becomes true only at deltaLink. An expired state (410) requires reconciliation and a fresh baseline, not silent loss of local changes. The 100-page execution bound saves progress for the next run. Continuation URLs are private and must not be edited.

Keep drive IDs and item IDs as opaque strings, retaining the drive context with each item. Encode individual path segments, not an entire URL or a slash-separated path in one call. An item ID remains stable across rename/move within its drive; a name-based path changes. OneDrive does not use Outlook's ImmutableId preference.

Permission: Files.Read.

Uses direct Chilkat.Http requests to Microsoft Graph v1.0 in the global cloud. The delegated token is read from the private qa_data/tokens/oneDrive.json file created by the PKCE authorization example. Personal Microsoft accounts and Microsoft 365 work/school accounts can use delegated authorization when the app registration supports them. Refresh expired tokens; scopes and actual file access both matter.

For app-only Microsoft 365 access, use client credentials with administrator-approved application permissions. /me requires a signed-in user; app-only calls must address an authorized user, site, or drive explicitly. Client credentials do not grant access to personal OneDrive accounts. National clouds use their own authority and Graph hosts.

Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.

Microsoft documentation

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- Obtain a delegated Graph token with this example's file permissions.
-- See OneDrive OAuth2 with PKCE.
local token = chilkat.JsonObject.new()
token.strict = true
success = token:load_file("qa_data/tokens/oneDrive.json")
if not success then
    print("Could not load the private OneDrive token cache.")
    return
end

if (token:json_type_of("access_token") ~= 1) or (token:string_of_equals("access_token", "", true)) then
    print("Expected a nonempty access_token in the JSON.")
    return
end

local http = chilkat.Http.new()
http.auth_token = token:string_of("access_token")
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 20
http.read_timeout = 120
http:set_request_header("Accept", "application/json")
local resp = chilkat.HttpResponse.new()
local result = chilkat.JsonObject.new()
result.strict = true
local driveId = "YOUR_DRIVE_ID"
-- Use a distinct stable application account key and cache path per account.
local accountKey = "YOUR_LOCAL_ACCOUNT_KEY"
local fac = chilkat.FileAccess.new()
success = fac:dir_ensure_exists("qa_data/oneDrive")
if not success then
    print("Could not create the private synchronization directory.")
    return
end

local cachePath = "qa_data/oneDrive/items-sync.json"
local backupPath = "qa_data/oneDrive/items-sync.json.bak"
local state = chilkat.JsonObject.new()
state.strict = true
if fac:file_exists(cachePath) then
    success = state:load_file(cachePath)
    if not success then
        print("Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing.")
        return
    end

    if (state:json_type_of("resumeUrl") ~= 1) or (state:string_of_equals("resumeUrl", "", true)) then
        print("Expected a nonempty resumeUrl in the JSON.")
        return
    end

    if (state:json_type_of("driveId") ~= 1) or (state:string_of_equals("driveId", "", true)) then
        print("Expected a nonempty driveId in the JSON.")
        return
    end

    if not state:string_of_equals("driveId", driveId, true) then
        print("This checkpoint belongs to another drive. Use a separate cache.")
        return
    end

    if not state:string_of_equals("accountKey", accountKey, true) then
        print("This checkpoint belongs to another account; nothing requested.")
        return
    end

    if state:json_type_of("items") ~= 3 then
        print("Expected an items object in the checkpoint.")
        return
    end
else
    local endpoint = chilkat.StringBuilder.new()
    endpoint:append("https://graph.microsoft.com/v1.0/drives/")
    endpoint:append(http:url_encode(driveId))
    endpoint:append("/root/delta?$select=id,name,size,parentReference,file,folder,eTag,deleted")
    state:update_string("driveId", driveId)
    state:update_string("accountKey", accountKey)
    state:update_string("resumeUrl", endpoint:get_as_string())
    state:update_new_object("items")
end

local hash = chilkat.Crypt2.new()
hash.hash_algorithm = "sha256"
hash.charset = "utf-8"
hash.encoding_mode = "hex"
local link = chilkat.StringBuilder.new()
local itemPath = chilkat.StringBuilder.new()
local seenLinks = chilkat.Hashtable.new()
local previous = chilkat.JsonObject.new()
previous.strict = true
local pageCount = 0
while pageCount < 100 do
    local url = state:string_of("resumeUrl")
    link:clear()
    link:append(url)
    if not link:starts_with("https://graph.microsoft.com/v1.0/", true) then
        print("Unexpected continuation host or API version; no request sent.")
        return
    end

    if seenLinks:contains(url) then
        print("Repeated continuation URL; stopping.")
        return
    end

    seenLinks:add_int(url, 1)
    success = http:http_no_body("GET", url, resp)
    -- A false result can still include an HTTP error response.
    if (not success) and (resp.status_code == 0) then
        print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
        return
    end

    if resp.status_code == 410 then
        print("Delta state expired. Reconcile local edits and rebuild a fresh drive baseline; preserve the existing cache.")
        return
    end

    if resp.status_code ~= 200 then
        print("Unexpected HTTP status: " .. resp.status_code)
        print("Request ID: " .. resp:get_header_field("request-id"))
        if resp.status_code == 429 then
            print("Retry-After: " .. resp:get_header_field("Retry-After"))
        end

        if resp.status_code == 401 then
            print("Refresh the Graph access token or authorize again.")
        end

        return
    end

    success = result:load(resp.body_str)
    if not success then
        print("Expected a well-formed JSON response.")
        return
    end

    if result:json_type_of("value") ~= 4 then
        print("Expected a value array; checkpoint unchanged.")
        return
    end

    -- Exactly one continuation member must be a nonempty string.
    local nextType = result:json_type_of("\"@odata.nextLink\"")
    local deltaType = result:json_type_of("\"@odata.deltaLink\"")
    local finished = false
    local resumeUrl = ""
    if (nextType == 1) and (deltaType == (-1)) then
        resumeUrl = result:string_of("\"@odata.nextLink\"")
    else
        if (deltaType ~= 1) or (nextType ~= (-1)) then
            print("Invalid delta continuation; checkpoint unchanged.")
            return
        end

        resumeUrl = result:string_of("\"@odata.deltaLink\"")
        finished = true
    end

    link:clear()
    link:append(resumeUrl)
    if not link:starts_with("https://graph.microsoft.com/v1.0/", true) then
        print("Invalid continuation URL; checkpoint unchanged.")
        return
    end

    success = previous:load(state:emit())
    if not success then
        print("Could not snapshot the previous checkpoint.")
        return
    end

    local i = 0
    while i < result:size_of_array("value") do
        result.i = i
        if (result:json_type_of("value[i].id") ~= 1) or (result:string_of_equals("value[i].id", "", true)) then
            print("Expected a nonempty value[i].id in the JSON.")
            return
        end

        local itemId = result:string_of("value[i].id")
        local itemKey = hash:hash_string_enc(itemId)
        if not hash.last_method_success then
            print("Could not form a local record key.")
            return
        end

        -- Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
        itemPath:clear()
        itemPath:append("items.")
        itemPath:append(itemKey)
        if state:json_type_of(itemPath:get_as_string()) ~= 3 then
            state:update_new_object(itemPath:get_as_string())
        end

        itemPath:append(".")
        state.path_prefix = itemPath:get_as_string()
        state:update_string("id", itemId)
        if result:json_type_of("value[i].deleted") == 3 then
            -- Retain a tombstone; this example does not delete local files or folders.
            -- Process folder deletion only after the full round and only when the folder is empty.
            state:update_bool("removed", true)
            print("Removed from the local view: " .. itemId)
        else
            state:update_bool("removed", false)
            if result:has_member("value[i].name") then
                if (result:json_type_of("value[i].name") ~= 1) or (result:string_of_equals("value[i].name", "", true)) then
                    print("Expected a nonempty value[i].name in the JSON.")
                    return
                end

                state:update_string("name", result:string_of("value[i].name"))
            end

            if result:has_member("value[i].eTag") then
                if (result:json_type_of("value[i].eTag") ~= 1) or (result:string_of_equals("value[i].eTag", "", true)) then
                    print("Expected a nonempty value[i].eTag in the JSON.")
                    return
                end

                state:update_string("eTag", result:string_of("value[i].eTag"))
            end

            if result:has_member("value[i].parentReference.id") then
                if (result:json_type_of("value[i].parentReference.id") ~= 1) or (result:string_of_equals("value[i].parentReference.id", "", true)) then
                    print("Expected a nonempty value[i].parentReference.id in the JSON.")
                    return
                end

                state:update_string("parentReference.id", result:string_of("value[i].parentReference.id"))
            end

            if result:has_member("value[i].parentReference.driveId") then
                if (result:json_type_of("value[i].parentReference.driveId") ~= 1) or (result:string_of_equals("value[i].parentReference.driveId", "", true)) then
                    print("Expected a nonempty value[i].parentReference.driveId in the JSON.")
                    return
                end

                state:update_string("parentReference.driveId", result:string_of("value[i].parentReference.driveId"))
            end

            -- Omitted fields are unchanged. Do not erase an earlier name or parent on a partial delta.
            -- Keep large sizes as decimal text in this demonstration's local index.
            if result:has_member("value[i].size") then
                state:update_string("sizeBytes", result:string_of("value[i].size"))
            end

            if result:json_type_of("value[i].folder") == 3 then
                state:update_string("kind", "folder")
            end

            if result:json_type_of("value[i].file") == 3 then
                state:update_string("kind", "file")
            end

            state.path_prefix = ""
            print("Updated local item: " .. itemId)
        end

        state.path_prefix = ""
        i = i + 1
    end

    state:update_string("resumeUrl", resumeUrl)
    state:update_bool("roundComplete", finished)
    -- Save the data and cursor in one document. The backup contains the matching previous pair.
    success = previous:write_file(backupPath)
    if not success then
        print("Could not back up the previous checkpoint; no replacement attempted.")
        return
    end

    success = state:write_file(cachePath)
    if not success then
        print("Checkpoint write failed. Restore the private .bak before continuing.")
        return
    end

    pageCount = pageCount + 1
    if finished then
        print("Synchronization round complete; saved the delta link for the next run.")
        return
    end
end

print("Paused after 100 pages; the saved nextLink resumes on the next run.")