-
Notifications
You must be signed in to change notification settings - Fork 0
/
SDS.py
76 lines (59 loc) · 2.09 KB
/
SDS.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import sys
import os
import yaml
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext
def parseYaml(path):
with open(path, 'r', encoding='utf8') as stream:
try:
obj = yaml.safe_load(stream)
if obj is None:
obj = dict()
return obj
except yaml.YAMLError as exc:
print(exc)
def listFolder(path, ctx):
root = ctx.web.get_folder_by_server_relative_url(
path)
ctx.load(root)
ctx.execute_query()
folders = root.folders
ctx.load(folders)
ctx.execute_query()
files = root.files
ctx.load(files)
ctx.execute_query()
return files
def connectToSite(site_url):
ctx = ClientContext(site_url).with_credentials(
UserCredential(sys.argv[1], sys.argv[2]))
web = ctx.web
ctx.load(web)
ctx.execute_query()
return ctx
def downloadFile(file_url, download_path, ctx):
with open(download_path+".download", "wb") as local_file:
file = ctx.web.get_file_by_server_relative_url(
file_url).download(local_file).execute_query()
os.rename(download_path+".download", download_path)
print("[Ok] file has been downloaded: {0}".format(download_path))
config = parseYaml("config.yaml")
for subject in config:
name = subject["name"]
path = subject["path"]
folder_relative_url = subject["folder_relative_url"]
site_url = subject["site_url"]
ctx = connectToSite(site_url)
if not os.path.exists(path):
print(f"Path {path} does not exist. Creating it now...")
os.mkdir(path)
remote_files = listFolder(folder_relative_url, ctx)
local_files = os.listdir(path)
for remote_file in remote_files:
if remote_file.properties["Name"] in local_files:
continue
print(
f"Downloading {remote_file.properties['Name']} into {path}")
file_url = remote_file.properties['ServerRelativeUrl']
download_path = os.path.join(path, remote_file.properties['Name'])
downloadFile(file_url, download_path, ctx)