I have a requirement to download files from the public URL of any OneDrive file or folder belonging to another user using the Django framework. I have written the code, but it gives me an error when accessing the file_id.
#code
class DownloadView(APIView):
def post(self, request):
def encode_share_url(share_url):
encoded_url = base64.urlsafe_b64encode(share_url.encode()).decode().rstrip("=")
return f'u!{encoded_url}'
def get_drive_item_id(access_token, share_url):
url = f"https://graph.microsoft.com/v1.0/shares/{share_url}/driveItem"
headers = {
'Authorization': f'Bearer {access_token}'
}
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.json()
def resolve_shortened_url(short_url):
response = requests.head(short_url, allow_redirects=True)
return response.url
AUTHORITY = "https://login.microsoftonline.com/2b0a3b04-16bd-4638-be57-5622527eb55e/"
CLIENT_ID = "client_id"
CLIENT_SECRET = "client_secret"
SCOPES = ["https://graph.microsoft.com/.default"]
link = request.data.get("link")
# Initialize MSAL client application
app = ConfidentialClientApplication(CLIENT_ID, authority=AUTHORITY, client_credential=CLIENT_SECRET)
result = app.acquire_token_for_client(scopes=SCOPES)
if "access_token" in result:
access_token = result['access_token']
headers = {"Authorization": f"Bearer {result['access_token']}"}
encoded_share_url = encode_share_url(link)
file_info = get_drive_item_id(access_token, encoded_share_url)
# Resolve the shortened URL
resolved_url = resolve_shortened_url(link)
# Parse the file ID from the resolved URL
parsed_url = urlparse(resolved_url)
query_params = parse_qs(parsed_url.query)
# Use the file ID to construct the download URL
url = f"https://graph.microsoft.com/v1.0/drive/items/{file_id}/content"
print("url: ", url)
# Download the file
file_response = requests.get(url, headers=headers)
print("status_code: ", file_response.status_code)
if file_response.status_code == 200:
# Save the file locally
file_name = "downloaded_file" # Customize the file name as needed
with open(file_name, 'wb') as file:
file.write(file_response.content)
return success_response(data = file_response, message='DFile downloaded successfully.')
else:
return failure_response(data=file_response.json(), message="Downloading failed")
else:
return success_response(data = file_response, message='Downloaded successfully.')
I am trying to access the file info from below code, but it is now working I have also give the
#permission
"Sites.Read.All",
"Sites.ReadWrite.All",
"Files.ReadWrite.All",
"Files.Read.All"
file_info = get_drive_item_id(access_token, encoded_share_url)