-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetup_google_drive.py
More file actions
80 lines (68 loc) · 2.67 KB
/
setup_google_drive.py
File metadata and controls
80 lines (68 loc) · 2.67 KB
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
77
78
79
80
from pathlib import Path
from typing import Any, Dict
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
ROOT = Path(__file__).absolute().parent
CLIENT_SECRETS_FILE = ROOT / "secrets" / "google.json"
SCOPES = [
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive.readonly",
]
API_SERVICE_NAME = "drive"
API_VERSION = "v3"
DEFAULT_TEMPLATE_ID = "1nLYIP41PKy_rQbCNNvR3QwVk6EYSccj1"
def get_authenticated_service():
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
credentials = flow.run_console()
return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
def copy_directory_to(service, from_id, to_id, make_private=False):
result = service.files().list(q=f"'{from_id}' in parents").execute()
command = None
for file in result.get("files"):
if file.get("mimeType") == "application/vnd.google-apps.folder":
p = make_private or file.get("name").lower() == "private"
d = make_directory(service, file.get("name"), to_id)
copy_directory_to(service, file.get("id"), d.get("id"), make_private=p)
if not p:
(
service.permissions()
.create(
fileId=d.get("id"),
body={"role": "reader", "type": "anyone"},
)
.execute()
)
else:
if command is None:
command = service.files()
command = command.copy(
fileId=file.get("id"),
fields="id",
body=dict(name=file.get("name"), parents=[to_id]),
)
if command is not None:
command.execute()
def make_directory(service, name, in_id=None):
metadata: Dict[str, Any] = {
"name": name,
"mimeType": "application/vnd.google-apps.folder",
}
if in_id is not None:
metadata["parents"] = [in_id]
return service.files().create(body=metadata, fields="id,webViewLink").execute()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name", type=str, help="The name of your event")
parser.add_argument(
"-t",
"--template",
type=str,
default=DEFAULT_TEMPLATE_ID,
help="The Google drive ID of the template folder that you want to copy",
)
args = parser.parse_args()
service = get_authenticated_service()
d = make_directory(service, args.name)
copy_directory_to(service, args.template, d.get("id"))
print(f"Drive template copied to: {d.get('webViewLink')}")