File size: 2,087 Bytes
e1fb2f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import os

import aiofiles
import httpx


class SharepointClient:
    def __init__(self):
        self.access_token_url = f"https://login.microsoftonline.com/{os.getenv('AZURE_TENANT_ID')}/oauth2/v2.0/token"
        self.access_token_data = {
            "grant_type": "client_credentials",
            "client_id": os.getenv("AZURE_CLIENT_ID"),
            "client_secret": os.getenv("AZURE_CLIENT_SECRET"),
            "scope": os.getenv("AZURE_SCOPE"),
        }
        self.token = None

    async def __aenter__(self):
        async with httpx.AsyncClient() as client:
            token_response = await client.post(
                self.access_token_url, data=self.access_token_data
            )
            self.token = token_response.json()["access_token"]
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        pass

    async def upload_file(self, file_path: str):
        async with httpx.AsyncClient() as client:
            headers = {
                "Authorization": f"Bearer {self.token}",
                "Content-Type": "application/json",
            }
            file_name = os.path.basename(file_path)
            async with aiofiles.open(file_path, "rb") as file:
                file_data = await file.read()
            upload_url = f"https://graph.microsoft.com/v1.0/drives/{os.getenv('AZURE_DRIVE_ID')}/root:/{file_name}:/content"
            response = await client.put(
                upload_url, headers=headers, content=file_data
            )
        uploaded_response = response.json()
        web_url = uploaded_response["webUrl"]
        return web_url
    
    async def get_files(self):
        async with httpx.AsyncClient() as client:
            headers = {
                "Authorization": f"Bearer {self.token}",
                "Content-Type": "application/json",
            }
            files_url = f"https://graph.microsoft.com/v1.0/drives/{os.getenv('AZURE_DRIVE_ID')}/root/children"
            response = await client.get(files_url, headers=headers)
        files = response.json()
        return files