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.
Chilkat DataFlex Downloads
Use ChilkatAx-win32.pkg
Procedure Test
Boolean iSuccess
Handle hoToken
Handle hoHttp
Variant vResp
Handle hoResp
Handle hoResult
String sDriveId
String sAccountKey
Handle hoFac
String sCachePath
String sBackupPath
Handle hoState
Handle hoEndpoint
Handle hoHash
Handle hoLink
Handle hoItemPath
Handle hoSeenLinks
Handle hoPrevious
Integer iPageCount
String sUrl
Integer iNextType
Integer iDeltaType
Boolean iFinished
String sResumeUrl
Integer i
String sItemId
String sItemKey
String sTemp1
Integer iTemp1
Boolean bTemp1
Move False To iSuccess
// Assumes Chilkat is unlocked. See Global Unlock Sample.
Move False To iSuccess
// Obtain a delegated Graph token with this example's file permissions.
// See OneDrive OAuth2 with PKCE.
Get Create (RefClass(cComChilkatJsonObject)) To hoToken
If (Not(IsComObjectCreated(hoToken))) Begin
Send CreateComObject of hoToken
End
Set ComStrict Of hoToken To True
Get ComLoadFile Of hoToken "qa_data/tokens/oneDrive.json" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not load the private OneDrive token cache."
Procedure_Return
End
Get ComJsonTypeOf Of hoToken "access_token" To iTemp1
Get ComStringOfEquals Of hoToken "access_token" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty access_token in the JSON."
Procedure_Return
End
Get Create (RefClass(cComChilkatHttp)) To hoHttp
If (Not(IsComObjectCreated(hoHttp))) Begin
Send CreateComObject of hoHttp
End
Get ComStringOf Of hoToken "access_token" To sTemp1
Set ComAuthToken Of hoHttp To sTemp1
Set ComRequireSslCertVerify Of hoHttp To True
Set ComFollowRedirects Of hoHttp To False
Set ComConnectTimeout Of hoHttp To 20
Set ComReadTimeout Of hoHttp To 120
Send ComSetRequestHeader To hoHttp "Accept" "application/json"
Get Create (RefClass(cComChilkatHttpResponse)) To hoResp
If (Not(IsComObjectCreated(hoResp))) Begin
Send CreateComObject of hoResp
End
Get Create (RefClass(cComChilkatJsonObject)) To hoResult
If (Not(IsComObjectCreated(hoResult))) Begin
Send CreateComObject of hoResult
End
Set ComStrict Of hoResult To True
Move "YOUR_DRIVE_ID" To sDriveId
// Use a distinct stable application account key and cache path per account.
Move "YOUR_LOCAL_ACCOUNT_KEY" To sAccountKey
Get Create (RefClass(cComCkFileAccess)) To hoFac
If (Not(IsComObjectCreated(hoFac))) Begin
Send CreateComObject of hoFac
End
Get ComDirEnsureExists Of hoFac "qa_data/oneDrive" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not create the private synchronization directory."
Procedure_Return
End
Move "qa_data/oneDrive/items-sync.json" To sCachePath
Move "qa_data/oneDrive/items-sync.json.bak" To sBackupPath
Get Create (RefClass(cComChilkatJsonObject)) To hoState
If (Not(IsComObjectCreated(hoState))) Begin
Send CreateComObject of hoState
End
Set ComStrict Of hoState To True
Get ComFileExists Of hoFac sCachePath To bTemp1
If (bTemp1 = True) Begin
Get ComLoadFile Of hoState sCachePath To iSuccess
If (iSuccess <> True) Begin
Showln "Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing."
Procedure_Return
End
Get ComJsonTypeOf Of hoState "resumeUrl" To iTemp1
Get ComStringOfEquals Of hoState "resumeUrl" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty resumeUrl in the JSON."
Procedure_Return
End
Get ComJsonTypeOf Of hoState "driveId" To iTemp1
Get ComStringOfEquals Of hoState "driveId" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty driveId in the JSON."
Procedure_Return
End
Get ComStringOfEquals Of hoState "driveId" sDriveId True To bTemp1
If (bTemp1 <> True) Begin
Showln "This checkpoint belongs to another drive. Use a separate cache."
Procedure_Return
End
Get ComStringOfEquals Of hoState "accountKey" sAccountKey True To bTemp1
If (bTemp1 <> True) Begin
Showln "This checkpoint belongs to another account; nothing requested."
Procedure_Return
End
Get ComJsonTypeOf Of hoState "items" To iTemp1
If (iTemp1 <> 3) Begin
Showln "Expected an items object in the checkpoint."
Procedure_Return
End
End
Else Begin
Get Create (RefClass(cComChilkatStringBuilder)) To hoEndpoint
If (Not(IsComObjectCreated(hoEndpoint))) Begin
Send CreateComObject of hoEndpoint
End
Get ComAppend Of hoEndpoint "https://graph.microsoft.com/v1.0/drives/" To iSuccess
Get ComUrlEncode Of hoHttp sDriveId To sTemp1
Get ComAppend Of hoEndpoint sTemp1 To iSuccess
Get ComAppend Of hoEndpoint "/root/delta?$select=id,name,size,parentReference,file,folder,eTag,deleted" To iSuccess
Get ComUpdateString Of hoState "driveId" sDriveId To iSuccess
Get ComUpdateString Of hoState "accountKey" sAccountKey To iSuccess
Get ComGetAsString Of hoEndpoint To sTemp1
Get ComUpdateString Of hoState "resumeUrl" sTemp1 To iSuccess
Get ComUpdateNewObject Of hoState "items" To iSuccess
End
Get Create (RefClass(cComChilkatCrypt2)) To hoHash
If (Not(IsComObjectCreated(hoHash))) Begin
Send CreateComObject of hoHash
End
Set ComHashAlgorithm Of hoHash To "sha256"
Set ComCharset Of hoHash To "utf-8"
Set ComEncodingMode Of hoHash To "hex"
Get Create (RefClass(cComChilkatStringBuilder)) To hoLink
If (Not(IsComObjectCreated(hoLink))) Begin
Send CreateComObject of hoLink
End
Get Create (RefClass(cComChilkatStringBuilder)) To hoItemPath
If (Not(IsComObjectCreated(hoItemPath))) Begin
Send CreateComObject of hoItemPath
End
Get Create (RefClass(cComChilkatHashtable)) To hoSeenLinks
If (Not(IsComObjectCreated(hoSeenLinks))) Begin
Send CreateComObject of hoSeenLinks
End
Get Create (RefClass(cComChilkatJsonObject)) To hoPrevious
If (Not(IsComObjectCreated(hoPrevious))) Begin
Send CreateComObject of hoPrevious
End
Set ComStrict Of hoPrevious To True
Move 0 To iPageCount
While (iPageCount < 100)
Get ComStringOf Of hoState "resumeUrl" To sUrl
Send ComClear To hoLink
Get ComAppend Of hoLink sUrl To iSuccess
Get ComStartsWith Of hoLink "https://graph.microsoft.com/v1.0/" True To bTemp1
If (bTemp1 <> True) Begin
Showln "Unexpected continuation host or API version; no request sent."
Procedure_Return
End
Get ComContains Of hoSeenLinks sUrl To bTemp1
If (bTemp1 = True) Begin
Showln "Repeated continuation URL; stopping."
Procedure_Return
End
Get ComAddInt Of hoSeenLinks sUrl 1 To iSuccess
Get pvComObject of hoResp to vResp
Get ComHttpNoBody Of hoHttp "GET" sUrl vResp To iSuccess
// A false result can still include an HTTP error response.
Get ComStatusCode Of hoResp To iTemp1
If ((iSuccess <> True) And (iTemp1 = 0)) Begin
Showln "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying."
Procedure_Return
End
Get ComStatusCode Of hoResp To iTemp1
If (iTemp1 = 410) Begin
Showln "Delta state expired. Reconcile local edits and rebuild a fresh drive baseline; preserve the existing cache."
Procedure_Return
End
Get ComStatusCode Of hoResp To iTemp1
If (iTemp1 <> 200) Begin
Get ComStatusCode Of hoResp To iTemp1
Showln "Unexpected HTTP status: " iTemp1
Get ComGetHeaderField Of hoResp "request-id" To sTemp1
Showln "Request ID: " sTemp1
Get ComStatusCode Of hoResp To iTemp1
If (iTemp1 = 429) Begin
Get ComGetHeaderField Of hoResp "Retry-After" To sTemp1
Showln "Retry-After: " sTemp1
End
Get ComStatusCode Of hoResp To iTemp1
If (iTemp1 = 401) Begin
Showln "Refresh the Graph access token or authorize again."
End
Procedure_Return
End
Get ComBodyStr Of hoResp To sTemp1
Get ComLoad Of hoResult sTemp1 To iSuccess
If (iSuccess <> True) Begin
Showln "Expected a well-formed JSON response."
Procedure_Return
End
Get ComJsonTypeOf Of hoResult "value" To iTemp1
If (iTemp1 <> 4) Begin
Showln "Expected a value array; checkpoint unchanged."
Procedure_Return
End
// Exactly one continuation member must be a nonempty string.
Get ComJsonTypeOf Of hoResult '"@odata.nextLink"' To iNextType
Get ComJsonTypeOf Of hoResult '"@odata.deltaLink"' To iDeltaType
Move False To iFinished
If ((iNextType = 1) And (iDeltaType = -1)) Begin
Get ComStringOf Of hoResult '"@odata.nextLink"' To sResumeUrl
End
Else Begin
If ((iDeltaType <> 1) Or (iNextType <> -1)) Begin
Showln "Invalid delta continuation; checkpoint unchanged."
Procedure_Return
End
Get ComStringOf Of hoResult '"@odata.deltaLink"' To sResumeUrl
Move True To iFinished
End
Send ComClear To hoLink
Get ComAppend Of hoLink sResumeUrl To iSuccess
Get ComStartsWith Of hoLink "https://graph.microsoft.com/v1.0/" True To bTemp1
If (bTemp1 <> True) Begin
Showln "Invalid continuation URL; checkpoint unchanged."
Procedure_Return
End
Get ComEmit Of hoState To sTemp1
Get ComLoad Of hoPrevious sTemp1 To iSuccess
If (iSuccess <> True) Begin
Showln "Could not snapshot the previous checkpoint."
Procedure_Return
End
Move 0 To i
While (i < (ComSizeOfArray(hoResult, "value")))
Set ComI Of hoResult To i
Get ComJsonTypeOf Of hoResult "value[i].id" To iTemp1
Get ComStringOfEquals Of hoResult "value[i].id" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty value[i].id in the JSON."
Procedure_Return
End
Get ComStringOf Of hoResult "value[i].id" To sItemId
Get ComHashStringENC Of hoHash sItemId To sItemKey
Get ComLastMethodSuccess Of hoHash To bTemp1
If (bTemp1 <> True) Begin
Showln "Could not form a local record key."
Procedure_Return
End
// Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
Send ComClear To hoItemPath
Get ComAppend Of hoItemPath "items." To iSuccess
Get ComAppend Of hoItemPath sItemKey To iSuccess
Get ComJsonTypeOf Of hoState (ComGetAsString(hoItemPath)) To iTemp1
If (iTemp1 <> 3) Begin
Get ComGetAsString Of hoItemPath To sTemp1
Get ComUpdateNewObject Of hoState sTemp1 To iSuccess
End
Get ComAppend Of hoItemPath "." To iSuccess
Get ComGetAsString Of hoItemPath To sTemp1
Set ComPathPrefix Of hoState To sTemp1
Get ComUpdateString Of hoState "id" sItemId To iSuccess
Get ComJsonTypeOf Of hoResult "value[i].deleted" To iTemp1
If (iTemp1 = 3) Begin
// 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.
Get ComUpdateBool Of hoState "removed" True To iSuccess
Showln "Removed from the local view: " sItemId
End
Else Begin
Get ComUpdateBool Of hoState "removed" False To iSuccess
Get ComHasMember Of hoResult "value[i].name" To bTemp1
If (bTemp1 = True) Begin
Get ComJsonTypeOf Of hoResult "value[i].name" To iTemp1
Get ComStringOfEquals Of hoResult "value[i].name" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty value[i].name in the JSON."
Procedure_Return
End
Get ComStringOf Of hoResult "value[i].name" To sTemp1
Get ComUpdateString Of hoState "name" sTemp1 To iSuccess
End
Get ComHasMember Of hoResult "value[i].eTag" To bTemp1
If (bTemp1 = True) Begin
Get ComJsonTypeOf Of hoResult "value[i].eTag" To iTemp1
Get ComStringOfEquals Of hoResult "value[i].eTag" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty value[i].eTag in the JSON."
Procedure_Return
End
Get ComStringOf Of hoResult "value[i].eTag" To sTemp1
Get ComUpdateString Of hoState "eTag" sTemp1 To iSuccess
End
Get ComHasMember Of hoResult "value[i].parentReference.id" To bTemp1
If (bTemp1 = True) Begin
Get ComJsonTypeOf Of hoResult "value[i].parentReference.id" To iTemp1
Get ComStringOfEquals Of hoResult "value[i].parentReference.id" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty value[i].parentReference.id in the JSON."
Procedure_Return
End
Get ComStringOf Of hoResult "value[i].parentReference.id" To sTemp1
Get ComUpdateString Of hoState "parentReference.id" sTemp1 To iSuccess
End
Get ComHasMember Of hoResult "value[i].parentReference.driveId" To bTemp1
If (bTemp1 = True) Begin
Get ComJsonTypeOf Of hoResult "value[i].parentReference.driveId" To iTemp1
Get ComStringOfEquals Of hoResult "value[i].parentReference.driveId" "" True To bTemp1
If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
Showln "Expected a nonempty value[i].parentReference.driveId in the JSON."
Procedure_Return
End
Get ComStringOf Of hoResult "value[i].parentReference.driveId" To sTemp1
Get ComUpdateString Of hoState "parentReference.driveId" sTemp1 To iSuccess
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.
Get ComHasMember Of hoResult "value[i].size" To bTemp1
If (bTemp1 = True) Begin
Get ComStringOf Of hoResult "value[i].size" To sTemp1
Get ComUpdateString Of hoState "sizeBytes" sTemp1 To iSuccess
End
Get ComJsonTypeOf Of hoResult "value[i].folder" To iTemp1
If (iTemp1 = 3) Begin
Get ComUpdateString Of hoState "kind" "folder" To iSuccess
End
Get ComJsonTypeOf Of hoResult "value[i].file" To iTemp1
If (iTemp1 = 3) Begin
Get ComUpdateString Of hoState "kind" "file" To iSuccess
End
Set ComPathPrefix Of hoState To ""
Showln "Updated local item: " sItemId
End
Set ComPathPrefix Of hoState To ""
Move (i + 1) To i
Loop
Get ComUpdateString Of hoState "resumeUrl" sResumeUrl To iSuccess
Get ComUpdateBool Of hoState "roundComplete" iFinished To iSuccess
// Save the data and cursor in one document. The backup contains the matching previous pair.
Get ComWriteFile Of hoPrevious sBackupPath To iSuccess
If (iSuccess <> True) Begin
Showln "Could not back up the previous checkpoint; no replacement attempted."
Procedure_Return
End
Get ComWriteFile Of hoState sCachePath To iSuccess
If (iSuccess <> True) Begin
Showln "Checkpoint write failed. Restore the private .bak before continuing."
Procedure_Return
End
Move (iPageCount + 1) To iPageCount
If (iFinished = True) Begin
Showln "Synchronization round complete; saved the delta link for the next run."
Procedure_Return
End
Loop
Showln "Paused after 100 pages; the saved nextLink resumes on the next run."
End_Procedure