-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbulk_reassign_docs.py
More file actions
executable file
·182 lines (158 loc) · 6.92 KB
/
bulk_reassign_docs.py
File metadata and controls
executable file
·182 lines (158 loc) · 6.92 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/usr/bin/env python3
import argparse
import requests
from utils import SigmaClient
def get_member_id(client, user_email):
""" Update member
:access_token: Generated access token
:user_email: Users email
:returns: ID associated with the user_email
"""
try:
response = client.get(
f"v2/members?search={user_email}"
)
response.raise_for_status()
# HTTP and other errors are handled generally by raising them as exceptions to be surfaced in downstream code
except requests.exceptions.HTTPError as errh:
# The API response's message value is sent in lieu of the full response to display to the user for clarity
raise Exception(errh.response.status_code,
f"API message: {errh.response.json()['message']}")
except requests.exceptions.ConnectionError as errc:
raise Exception(
f"Connection Error: {errc}, API response: {errc.response.text}")
except requests.exceptions.Timeout as errt:
raise Exception(
f"Timeout Error: {errt}, API response: {errt.response.text}")
except requests.exceptions.RequestException as err:
raise Exception(
f"Other Error: {err}, API response: {err.response.text}")
else:
data = response.json()
if len(data['entries']) == 0:
print("No users found with this email:", user_email)
raise SystemExit("Script aborted")
elif len(data['entries']) > 1:
print("More than one user found with the provided email:", user_email)
raise SystemExit("Script aborted")
else:
return data['entries'][0]['memberId']
def get_member_files(client, user_id):
""" Update member
:user_id: id of current owner
:returns: an array of file objects
"""
data = []
moreResults = True
nextPage = ''
while moreResults:
try:
# currently looks for workbooks and datasets but can be changed as needed
response = client.get(
f"v2/members/{user_id}/files?typeFilters=workbook&typeFilters=dataset&limit=1000{nextPage}"
)
response.raise_for_status()
except requests.exceptions.HTTPError as errh:
raise Exception(
f"Connection Error: {errh}, API response: {errh.response.text}")
except requests.exceptions.ConnectionError as errc:
raise Exception(
f"Connection Error: {errc}, API response: {errc.response.text}")
except requests.exceptions.Timeout as errt:
raise Exception(
f"Timeout Error: {errt}, API response: {errt.response.text}")
except requests.exceptions.RequestException as err:
raise Exception(
f"Other Error: {err}, API response: {err.response.text}")
else:
resp = response.json()
data = data + resp['entries']
if resp['nextPage'] is None:
moreResults = False
else:
pageID = str(resp['nextPage'])
nextPage = f'&page={pageID}'
return data
def update_file(client, user_id, file_id, folderID):
""" Update file
:access_token: Generated access token
:userId: ID of the new owner
:file_id: File to transfer ownership of
:returns: Response JSON
"""
updateFileBody={"ownerId": user_id}
if folderID:
updateFileBody["parentId"] = folderID
try:
response = client.patch(
f"v2/files/{file_id}",
json=updateFileBody
)
response.raise_for_status()
# HTTP and other errors are handled generally by raising them as exceptions to be surfaced in downstream code
except requests.exceptions.HTTPError as errh:
# The API response's message value is sent in lieu of the full response to display to the user for clarity
# Certain error response messages are useful for the user troubleshoot common issues, such as invalid Member Type or New Email already in use
raise Exception(errh.response.status_code,
f"API message: {errh.response.json()['message']}")
except requests.exceptions.ConnectionError as errc:
raise Exception(
f"Connection Error: {errc}, API response: {errc.response.text}")
except requests.exceptions.Timeout as errt:
raise Exception(
f"Timeout Error: {errt}, API response: {errt.response.text}")
except requests.exceptions.RequestException as err:
raise Exception(
f"Other Error: {err}, API response: {err.response.text}")
else:
data = response.json()
print("transfer of document:", file_id, "---", response)
return data
def main():
parser = argparse.ArgumentParser(
description='Transfer all a users documents to another user')
parser.add_argument(
'--env', type=str, required=True, help='env to use: [production | staging].')
parser.add_argument(
'--cloud', type=str, required=True, help='Cloud to use: [aws | gcp | azure]')
parser.add_argument(
'--client_id', type=str, required=True, help='Client ID generated from within Sigma')
parser.add_argument(
'--client_secret', type=str, required=True, help='Client secret API token generated from within Sigma')
parser.add_argument(
'--curr_owner', type=str, required=True, help='Email of Org Member who currently owns the documents')
parser.add_argument(
'--new_owner', type=str, required=True, help='Email of Org Member who you want to transfer the documents to')
parser.add_argument(
'--new_folder', type=str, required=False, help='Optional folder to place the files in')
args = parser.parse_args()
client = SigmaClient(args.env, args.cloud,
args.client_id, args.client_secret)
# we need to confirm that both the existing user and new user are valid "check_users" fn
try:
curr_owner_id = get_member_id(client, args.curr_owner)
except Exception as e:
print(f"{e}")
raise SystemExit("Script aborted")
try:
new_owner_id = get_member_id(client, args.new_owner)
except Exception as e:
print(f"{e}")
raise SystemExit("Script aborted")
# get files of curr_user
try:
member_files = get_member_files(client, curr_owner_id)
except Exception as e:
print(f"{e}")
raise SystemExit("Script aborted")
# filter to only docs they own
filtered_arr = [file for file in member_files if file['ownerId'] == curr_owner_id]
# loop through and reassign ownership
for ownedDoc in filtered_arr:
try:
update_member_response = update_file(client, new_owner_id, ownedDoc['id'], args.new_folder)
except Exception as e:
print(f"{e}")
raise SystemExit("Script aborted")
if __name__ == '__main__':
main()