| 564 | |
| 565 | |
| 566 | class OneDriveFileStorage(FileStorageInterface): |
| 567 | def __init__(self): |
| 568 | try: |
| 569 | import msal |
| 570 | from office365.graph_client import GraphClient |
| 571 | from office365.runtime.client_request_exception import ( |
| 572 | ClientRequestException, |
| 573 | ) |
| 574 | except ImportError: |
| 575 | raise ImportError("请先安装`msal`和`Office365-REST-Python-Client`") |
| 576 | self.msal = msal |
| 577 | self.domain = settings.onedrive_domain |
| 578 | self.client_id = settings.onedrive_client_id |
| 579 | self.username = settings.onedrive_username |
| 580 | self.password = settings.onedrive_password |
| 581 | self.proxy = settings.onedrive_proxy |
| 582 | self._ClientRequestException = ClientRequestException |
| 583 | |
| 584 | try: |
| 585 | client = GraphClient(self.acquire_token_pwd) |
| 586 | self.root_path = ( |
| 587 | client.me.drive.root.get_by_path(settings.onedrive_root_path) |
| 588 | .get() |
| 589 | .execute_query() |
| 590 | ) |
| 591 | except ClientRequestException as e: |
| 592 | if e.code == "itemNotFound": |
| 593 | client.me.drive.root.create_folder(settings.onedrive_root_path) |
| 594 | self.root_path = ( |
| 595 | client.me.drive.root.get_by_path( |
| 596 | settings.onedrive_root_path) |
| 597 | .get() |
| 598 | .execute_query() |
| 599 | ) |
| 600 | else: |
| 601 | raise e |
| 602 | except Exception as e: |
| 603 | raise Exception("OneDrive验证失败,请检查配置是否正确\n" + str(e)) |
| 604 | |
| 605 | def acquire_token_pwd(self): |
| 606 | authority_url = f"https://login.microsoftonline.com/{self.domain}" |
| 607 | app = self.msal.PublicClientApplication( |
| 608 | authority=authority_url, client_id=self.client_id |
| 609 | ) |
| 610 | result = app.acquire_token_by_username_password( |
| 611 | username=self.username, |
| 612 | password=self.password, |
| 613 | scopes=["https://graph.microsoft.com/.default"], |
| 614 | ) |
| 615 | return result |
| 616 | |
| 617 | def _get_path_str(self, path): |
| 618 | if isinstance(path, str): |
| 619 | path = path.replace("\\", "/").replace("//", "/").split("/") |
| 620 | elif isinstance(path, Path): |
| 621 | path = str(path).replace("\\", "/").replace("//", "/").split("/") |
| 622 | else: |
| 623 | raise TypeError("path must be str or Path") |
nothing calls this directly
no outgoing calls
no test coverage detected