From 59eb9a4ab09daf81db75b0451f5a8bc1b17df9c7 Mon Sep 17 00:00:00 2001 From: Martin Tranberg Date: Fri, 27 Mar 2026 14:11:28 +0100 Subject: [PATCH] =?UTF-8?q?Tilf=C3=B8j=20retries=20til=20URL-refresh=20ved?= =?UTF-8?q?=20manglende=20@microsoft.graph.downloadUrl=20i=20API=20svar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- download_sharepoint.py | 41 ++++++++++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/download_sharepoint.py b/download_sharepoint.py index b44ee22..754f249 100644 --- a/download_sharepoint.py +++ b/download_sharepoint.py @@ -112,22 +112,37 @@ def get_drive_id(app, site_id, drive_name): # --- Punkt 2: Resume / Chunked Download logic --- def get_fresh_download_url(app, drive_id, item_id): - """Fetches a fresh download URL for a specific item ID with token refresh support.""" - url = f"https://graph.microsoft.com/v1.0/drives/{drive_id}/items/{item_id}?$select=id,@microsoft.graph.downloadUrl" + """Fetches a fresh download URL for a specific item ID with retries and robust error handling.""" + url = f"https://graph.microsoft.com/v1.0/drives/{drive_id}/items/{item_id}" - try: - headers = get_headers(app) - response = requests.get(url, headers=headers, timeout=60) - - if response.status_code == 401: - logger.info("Access Token expired. Forcing refresh...") - headers = get_headers(app, force_refresh=True) + for attempt in range(3): + try: + headers = get_headers(app) response = requests.get(url, headers=headers, timeout=60) - response.raise_for_status() - return response.json().get('@microsoft.graph.downloadUrl'), None - except Exception as e: - return None, str(e) + if response.status_code == 401: + logger.info(f"Access Token expired during refresh (Attempt {attempt+1}). Forcing refresh...") + headers = get_headers(app, force_refresh=True) + response = requests.get(url, headers=headers, timeout=60) + + response.raise_for_status() + data = response.json() + download_url = data.get('@microsoft.graph.downloadUrl') + + if download_url: + return download_url, None + + # If item exists but URL is missing, it might be a transient SharePoint issue + logger.warning(f"Attempt {attempt+1}: '@microsoft.graph.downloadUrl' missing for {item_id}. Retrying in 1s...") + time.sleep(1) + + except Exception as e: + if attempt == 2: + return None, str(e) + logger.warning(f"Attempt {attempt+1} failed: {e}. Retrying...") + time.sleep(1) + + return None, "Item returned but '@microsoft.graph.downloadUrl' was missing after 3 attempts." def download_single_file(app, drive_id, item_id, local_path, expected_size, display_name, remote_hash=None, initial_url=None): try: