Is there any way to download files or folders from the public share URL of OneDrive belonging to other users (external resources)?

Rishabh Meena 0 Reputation points
2024-06-25T07:15:41.2166667+00:00

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)
OneDrive
OneDrive
A Microsoft file hosting and synchronization service.
939 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Emi Zhang-MSFT 23,351 Reputation points Microsoft Vendor
    2024-06-26T02:12:54.2+00:00

    Hi,

    I suggest you post this thread to OneDrive for Developer forum:

    https://techcommunity.microsoft.com/t5/onedrive-developer/bd-p/OneDriveDeveloper

    The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners who read the forums regularly can either share their knowledge or learn from your interaction with us. Thank you for your understanding.


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments