onedrive.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from pathlib import Path
  2. from O365 import Account
  3. from O365.drive import Folder
  4. CLIENT_ID = "925f74dc-f96a-4718-9ca7-d6cc3fa43e1e"
  5. CLIENT_SECRET = "SS~8Q~QpBZV9toZuwkzW1XGGen2Hn833spNMtdq5"
  6. FLOW_TYPE = "credentials"
  7. TENANT_ID = "2ad0dff5-07ce-4cc2-a852-99ce8b91c218"
  8. USER_ID = "bedner@global-cube.net"
  9. # password = "Platinum512!!"
  10. def get_remote_files(folder: Folder, prefix=""):
  11. res = {}
  12. for item in folder.get_items():
  13. name = item.name
  14. if prefix != "":
  15. name = prefix + "\\" + name
  16. if item.is_file:
  17. res[name] = item.object_id
  18. if item.is_folder:
  19. res.update(get_remote_files(item, name))
  20. return res
  21. def get_or_create_subfolder(remote_folder: Folder, folder: str):
  22. if folder == "":
  23. return remote_folder
  24. if "\\" in folder:
  25. folder, subfolder = folder.split("\\", 1)
  26. else:
  27. subfolder = ""
  28. for f in remote_folder.get_child_folders():
  29. if f.name == folder:
  30. return get_or_create_subfolder(f, subfolder)
  31. new_folder = remote_folder.create_child_folder(folder)
  32. return get_or_create_subfolder(new_folder, subfolder)
  33. def main():
  34. account = Account((CLIENT_ID, CLIENT_SECRET), auth_flow_type=FLOW_TYPE, tenant_id=TENANT_ID)
  35. account.authenticate()
  36. storage = account.storage(resource=USER_ID)
  37. my_drive = storage.get_default_drive()
  38. remote_folder = my_drive.get_item_by_path("/Keyloop_Datentransfer")
  39. # folder.create_child_folder
  40. local_folder = Path("datev/export")
  41. local_files = set([str(p.relative_to(local_folder)) for p in local_folder.rglob("*") if p.is_file()])
  42. # uploaded_file = remote_folder.upload_file(item="tox.ini")
  43. remote_files_dict = get_remote_files(remote_folder)
  44. remote_files = set(remote_files_dict.keys())
  45. delete_candidates = remote_files.difference(local_files)
  46. create_candidates = local_files.difference(remote_files)
  47. for filename in delete_candidates:
  48. print(filename)
  49. my_drive.get_item(remote_files_dict[filename]).delete()
  50. for filename in sorted(create_candidates):
  51. print(filename)
  52. full_filename = local_folder / filename
  53. subfolder = ""
  54. if "\\" in filename:
  55. subfolder, filename = filename.rsplit("\\", 1)
  56. remote_subfolder = get_or_create_subfolder(remote_folder, subfolder)
  57. remote_subfolder.upload_file(item=full_filename)
  58. if __name__ == "__main__":
  59. main()