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 AutoIt Downloads
Local $bSuccess = False
; Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = False
; Obtain a delegated Graph token with this example's file permissions.
; See OneDrive OAuth2 with PKCE.
$oToken = ObjCreate("Chilkat.JsonObject")
$oToken.Strict = True
$bSuccess = $oToken.LoadFile("qa_data/tokens/oneDrive.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not load the private OneDrive token cache." & @CRLF)
Exit
EndIf
If (($oToken.JsonTypeOf("access_token") <> 1) Or ($oToken.StringOfEquals("access_token","",True) = True)) Then
ConsoleWrite("Expected a nonempty access_token in the JSON." & @CRLF)
Exit
EndIf
$oHttp = ObjCreate("Chilkat.Http")
$oHttp.AuthToken = $oToken.StringOf("access_token")
$oHttp.RequireSslCertVerify = True
$oHttp.FollowRedirects = False
$oHttp.ConnectTimeout = 20
$oHttp.ReadTimeout = 120
$oHttp.SetRequestHeader "Accept","application/json"
$oResp = ObjCreate("Chilkat.HttpResponse")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
Local $sDriveId = "YOUR_DRIVE_ID"
; Use a distinct stable application account key and cache path per account.
Local $sAccountKey = "YOUR_LOCAL_ACCOUNT_KEY"
$oFac = ObjCreate("Chilkat.FileAccess")
$bSuccess = $oFac.DirEnsureExists("qa_data/oneDrive")
If ($bSuccess <> True) Then
ConsoleWrite("Could not create the private synchronization directory." & @CRLF)
Exit
EndIf
Local $sCachePath = "qa_data/oneDrive/items-sync.json"
Local $sBackupPath = "qa_data/oneDrive/items-sync.json.bak"
$oState = ObjCreate("Chilkat.JsonObject")
$oState.Strict = True
If ($oFac.FileExists($sCachePath) = True) Then
$bSuccess = $oState.LoadFile($sCachePath)
If ($bSuccess <> True) Then
ConsoleWrite("Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing." & @CRLF)
Exit
EndIf
If (($oState.JsonTypeOf("resumeUrl") <> 1) Or ($oState.StringOfEquals("resumeUrl","",True) = True)) Then
ConsoleWrite("Expected a nonempty resumeUrl in the JSON." & @CRLF)
Exit
EndIf
If (($oState.JsonTypeOf("driveId") <> 1) Or ($oState.StringOfEquals("driveId","",True) = True)) Then
ConsoleWrite("Expected a nonempty driveId in the JSON." & @CRLF)
Exit
EndIf
If ($oState.StringOfEquals("driveId",$sDriveId,True) <> True) Then
ConsoleWrite("This checkpoint belongs to another drive. Use a separate cache." & @CRLF)
Exit
EndIf
If ($oState.StringOfEquals("accountKey",$sAccountKey,True) <> True) Then
ConsoleWrite("This checkpoint belongs to another account; nothing requested." & @CRLF)
Exit
EndIf
If ($oState.JsonTypeOf("items") <> 3) Then
ConsoleWrite("Expected an items object in the checkpoint." & @CRLF)
Exit
EndIf
Else
$oEndpoint = ObjCreate("Chilkat.StringBuilder")
$oEndpoint.Append("https://graph.microsoft.com/v1.0/drives/")
$oEndpoint.Append($oHttp.UrlEncode($sDriveId))
$oEndpoint.Append("/root/delta?$select=id,name,size,parentReference,file,folder,eTag,deleted")
$oState.UpdateString("driveId",$sDriveId)
$oState.UpdateString("accountKey",$sAccountKey)
$oState.UpdateString("resumeUrl",$oEndpoint.GetAsString())
$oState.UpdateNewObject("items")
EndIf
$oHash = ObjCreate("Chilkat.Crypt2")
$oHash.HashAlgorithm = "sha256"
$oHash.Charset = "utf-8"
$oHash.EncodingMode = "hex"
$oLink = ObjCreate("Chilkat.StringBuilder")
$oItemPath = ObjCreate("Chilkat.StringBuilder")
$oSeenLinks = ObjCreate("Chilkat.Hashtable")
$oPrevious = ObjCreate("Chilkat.JsonObject")
$oPrevious.Strict = True
Local $iPageCount = 0
While ($iPageCount < 100)
Local $sUrl = $oState.StringOf("resumeUrl")
$oLink.Clear
$oLink.Append($sUrl)
If ($oLink.StartsWith("https://graph.microsoft.com/v1.0/",True) <> True) Then
ConsoleWrite("Unexpected continuation host or API version; no request sent." & @CRLF)
Exit
EndIf
If ($oSeenLinks.Contains($sUrl) = True) Then
ConsoleWrite("Repeated continuation URL; stopping." & @CRLF)
Exit
EndIf
$oSeenLinks.AddInt($sUrl,1)
$bSuccess = $oHttp.HttpNoBody("GET",$sUrl,$oResp)
; A false result can still include an HTTP error response.
If (($bSuccess <> True) And ($oResp.StatusCode = 0)) Then
ConsoleWrite("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying." & @CRLF)
Exit
EndIf
If ($oResp.StatusCode = 410) Then
ConsoleWrite("Delta state expired. Reconcile local edits and rebuild a fresh drive baseline; preserve the existing cache." & @CRLF)
Exit
EndIf
If ($oResp.StatusCode <> 200) Then
ConsoleWrite("Unexpected HTTP status: " & $oResp.StatusCode & @CRLF)
ConsoleWrite("Request ID: " & $oResp.GetHeaderField("request-id") & @CRLF)
If ($oResp.StatusCode = 429) Then
ConsoleWrite("Retry-After: " & $oResp.GetHeaderField("Retry-After") & @CRLF)
EndIf
If ($oResp.StatusCode = 401) Then
ConsoleWrite("Refresh the Graph access token or authorize again." & @CRLF)
EndIf
Exit
EndIf
$bSuccess = $oResult.Load($oResp.BodyStr)
If ($bSuccess <> True) Then
ConsoleWrite("Expected a well-formed JSON response." & @CRLF)
Exit
EndIf
If ($oResult.JsonTypeOf("value") <> 4) Then
ConsoleWrite("Expected a value array; checkpoint unchanged." & @CRLF)
Exit
EndIf
; Exactly one continuation member must be a nonempty string.
Local $iNextType = $oResult.JsonTypeOf("""@odata.nextLink""")
Local $iDeltaType = $oResult.JsonTypeOf("""@odata.deltaLink""")
Local $bFinished = False
Local $sResumeUrl
If (($iNextType = 1) And ($iDeltaType = -1)) Then
$sResumeUrl = $oResult.StringOf("""@odata.nextLink""")
Else
If (($iDeltaType <> 1) Or ($iNextType <> -1)) Then
ConsoleWrite("Invalid delta continuation; checkpoint unchanged." & @CRLF)
Exit
EndIf
$sResumeUrl = $oResult.StringOf("""@odata.deltaLink""")
$bFinished = True
EndIf
$oLink.Clear
$oLink.Append($sResumeUrl)
If ($oLink.StartsWith("https://graph.microsoft.com/v1.0/",True) <> True) Then
ConsoleWrite("Invalid continuation URL; checkpoint unchanged." & @CRLF)
Exit
EndIf
$bSuccess = $oPrevious.Load($oState.Emit())
If ($bSuccess <> True) Then
ConsoleWrite("Could not snapshot the previous checkpoint." & @CRLF)
Exit
EndIf
Local $i = 0
While ($i < $oResult.SizeOfArray("value"))
$oResult.I = $i
If (($oResult.JsonTypeOf("value[i].id") <> 1) Or ($oResult.StringOfEquals("value[i].id","",True) = True)) Then
ConsoleWrite("Expected a nonempty value[i].id in the JSON." & @CRLF)
Exit
EndIf
Local $sItemId = $oResult.StringOf("value[i].id")
Local $sItemKey = $oHash.HashStringENC($sItemId)
If ($oHash.LastMethodSuccess <> True) Then
ConsoleWrite("Could not form a local record key." & @CRLF)
Exit
EndIf
; Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
$oItemPath.Clear
$oItemPath.Append("items.")
$oItemPath.Append($sItemKey)
If ($oState.JsonTypeOf($oItemPath.GetAsString()) <> 3) Then
$oState.UpdateNewObject($oItemPath.GetAsString())
EndIf
$oItemPath.Append(".")
$oState.PathPrefix = $oItemPath.GetAsString()
$oState.UpdateString("id",$sItemId)
If ($oResult.JsonTypeOf("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.
$oState.UpdateBool("removed",True)
ConsoleWrite("Removed from the local view: " & $sItemId & @CRLF)
Else
$oState.UpdateBool("removed",False)
If ($oResult.HasMember("value[i].name") = True) Then
If (($oResult.JsonTypeOf("value[i].name") <> 1) Or ($oResult.StringOfEquals("value[i].name","",True) = True)) Then
ConsoleWrite("Expected a nonempty value[i].name in the JSON." & @CRLF)
Exit
EndIf
$oState.UpdateString("name",$oResult.StringOf("value[i].name"))
EndIf
If ($oResult.HasMember("value[i].eTag") = True) Then
If (($oResult.JsonTypeOf("value[i].eTag") <> 1) Or ($oResult.StringOfEquals("value[i].eTag","",True) = True)) Then
ConsoleWrite("Expected a nonempty value[i].eTag in the JSON." & @CRLF)
Exit
EndIf
$oState.UpdateString("eTag",$oResult.StringOf("value[i].eTag"))
EndIf
If ($oResult.HasMember("value[i].parentReference.id") = True) Then
If (($oResult.JsonTypeOf("value[i].parentReference.id") <> 1) Or ($oResult.StringOfEquals("value[i].parentReference.id","",True) = True)) Then
ConsoleWrite("Expected a nonempty value[i].parentReference.id in the JSON." & @CRLF)
Exit
EndIf
$oState.UpdateString("parentReference.id",$oResult.StringOf("value[i].parentReference.id"))
EndIf
If ($oResult.HasMember("value[i].parentReference.driveId") = True) Then
If (($oResult.JsonTypeOf("value[i].parentReference.driveId") <> 1) Or ($oResult.StringOfEquals("value[i].parentReference.driveId","",True) = True)) Then
ConsoleWrite("Expected a nonempty value[i].parentReference.driveId in the JSON." & @CRLF)
Exit
EndIf
$oState.UpdateString("parentReference.driveId",$oResult.StringOf("value[i].parentReference.driveId"))
EndIf
; 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 ($oResult.HasMember("value[i].size") = True) Then
$oState.UpdateString("sizeBytes",$oResult.StringOf("value[i].size"))
EndIf
If ($oResult.JsonTypeOf("value[i].folder") = 3) Then
$oState.UpdateString("kind","folder")
EndIf
If ($oResult.JsonTypeOf("value[i].file") = 3) Then
$oState.UpdateString("kind","file")
EndIf
$oState.PathPrefix = ""
ConsoleWrite("Updated local item: " & $sItemId & @CRLF)
EndIf
$oState.PathPrefix = ""
$i = $i + 1
Wend
$oState.UpdateString("resumeUrl",$sResumeUrl)
$oState.UpdateBool("roundComplete",$bFinished)
; Save the data and cursor in one document. The backup contains the matching previous pair.
$bSuccess = $oPrevious.WriteFile($sBackupPath)
If ($bSuccess <> True) Then
ConsoleWrite("Could not back up the previous checkpoint; no replacement attempted." & @CRLF)
Exit
EndIf
$bSuccess = $oState.WriteFile($sCachePath)
If ($bSuccess <> True) Then
ConsoleWrite("Checkpoint write failed. Restore the private .bak before continuing." & @CRLF)
Exit
EndIf
$iPageCount = $iPageCount + 1
If ($bFinished = True) Then
ConsoleWrite("Synchronization round complete; saved the delta link for the next run." & @CRLF)
Exit
EndIf
Wend
ConsoleWrite("Paused after 100 pages; the saved nextLink resumes on the next run." & @CRLF)