-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·334 lines (279 loc) · 9.56 KB
/
main.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
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/env python3
import argparse
import logging
import re
import time
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
location_url = lambda parent_id: f"https://drive.google.com/drive/folders/{parent_id}"
def main(
credentials_file,
drive_id,
spreadsheet_id,
list_folders,
list_trashed,
sheet_output,
rootFolder,
):
scopes = ["https://www.googleapis.com/auth/drive"]
credentials = service_account.Credentials.from_service_account_file(
credentials_file, scopes=scopes
)
drive_service = build("drive", "v3", credentials=credentials, cache_discovery=False)
sheets_service = build(
"sheets", "v4", credentials=credentials, cache_discovery=False
)
# Define kwargs (key word arguments) for file search
# Written this way to aviod defining parameters for file search twice due to pagination
kwargs = {
"corpora": "drive",
"driveId": drive_id,
"fields": "files(id, mimeType, name, createdTime, modifiedTime, lastModifyingUser(displayName), trashedTime, webViewLink, parents), nextPageToken",
"includeItemsFromAllDrives": True,
"pageSize": 1000,
"supportsAllDrives": True,
"q": "trashed = false",
}
if list_trashed:
del kwargs["q"]
# Recursively find all files in drive
files = []
while True:
try:
results = drive_service.files().list(**kwargs).execute()
except HttpError as e:
logging.error(e)
raise
files.extend(results["files"])
# If no next page, break out of loop
if "nextPageToken" not in results:
break
# Add next page token to kwargs
kwargs["pageToken"] = results["nextPageToken"]
logging.info(f"Found {len(files)} total files")
for file in files:
file["path"] = build_file_path(files, file["parents"][0])
file["location"] = location_url(file["parents"][0])
if file["path"] == "":
file["path"] = "/"
if "lastModifyingUser" in file:
file["lastModifyingUser"] = file.pop("lastModifyingUser")["displayName"]
if file["mimeType"] != "application/vnd.google-apps.folder":
file["nameFailedCheck"] = validate_file_name(file)
else:
file["nameFailedCheck"] = ""
sheet_name = None
root_folder_name = get_folder_name(files, rootFolder)
if sheet_output:
sheet_name = create_sheet(
drive_service, sheets_service, drive_id, spreadsheet_id, root_folder_name
)
body = build_sheet_body(files, list_folders, root_folder_name)
output_to_sheet(sheets_service, spreadsheet_id, body, sheet_name)
def validate_file_name(file):
special_characters = '^*<>/\|}{~:?"'
# Pattern matches string with only digits and/or special characters we allow.
# Some special chars need to be escaped because regex
regex_pattern = f"^[0-9\.@$\(\)\[\]%&\-_]+$"
failures = []
name = file["name"]
# List of dicts to store validation conditions
conditions = [
{"cond": len(name) <= 8, "val": "name too short"},
{
"cond": any(char in special_characters for char in name),
"val": "contains invalid characters",
},
{
"cond": (name[0] in " _-" or name[-1] == " _-"),
"val": "leading or trailing spaces or dashes",
},
{"cond": "untitled" in name.lower(), "val": "unnamed document"},
{
"cond": re.match(regex_pattern, name.rsplit(".", 1)[0]),
"val": "name may not contain words",
},
]
# Iterate over condition list, append val to failures list if applicable
for condition in conditions:
if condition["cond"]:
failures.append(condition["val"])
failure_string = " | ".join(failures)
return failure_string
def get_folder_name(files, folder_id):
file_dict = {file["id"]: file for file in files}
folder = file_dict.get(folder_id)
return folder["name"] if folder is not None else None
def build_file_path(files, parent_id, path="", file_dict=None):
if file_dict is None:
# Create a dictionary to store the files by their IDs
file_dict = {file["id"]: file for file in files}
parent_folder = file_dict.get(parent_id)
if parent_folder is None:
return path
path = f"{parent_folder['name']}/{path}"
return build_file_path(files, parent_folder["parents"][0], path, file_dict)
def create_sheet(
drive_service, sheets_service, drive_id, spreadsheet_id, root_folder_name
):
try:
drive = drive_service.drives().get(driveId=drive_id).execute()
spreadsheet = (
sheets_service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
)
except HttpError as e:
logging.error(e)
raise
drive_name = drive["name"]
if root_folder_name:
drive_name += f"/{root_folder_name}"
sheets = spreadsheet["sheets"]
sheet_names = [sheet["properties"]["title"] for sheet in sheets]
if drive_name not in sheet_names:
request = {"addSheet": {"properties": {"title": drive_name}}}
try:
sheets_service.spreadsheets().batchUpdate(
spreadsheetId=spreadsheet_id, body={"requests": [request]}
).execute()
except HttpError as e:
logging.error(e)
raise
return drive_name
def build_sheet_body(files, list_folders, root_folder_name):
# Use pandas to build values for sheet (instead of manually formatting)
df = pd.DataFrame(files)
if root_folder_name is not None:
df = df.loc[df["path"].str.startswith(root_folder_name)]
# Build hyperlinks for name and path
df["name"] = '=HYPERLINK("' + df["webViewLink"] + '", "' + df["name"] + '")'
df["path"] = '=HYPERLINK("' + df["location"] + '", "' + df["path"] + '")'
if not list_folders:
df = df[~df["mimeType"].str.contains("folder", case=False)]
col_order = [
"name",
"createdTime",
"modifiedTime",
"lastModifyingUser",
"path",
"nameFailedCheck",
]
time_cols = ["createdTime", "modifiedTime"]
if "trashedTime" in df:
col_order.append("trashedTime")
time_cols.append("trashedTime")
for time_col in time_cols:
df[time_col] = pd.to_datetime(df[time_col]).dt.strftime("%Y-%m-%d %H:%M:%S")
df = df[col_order]
df = df.fillna("")
values = [df.keys().tolist()]
values.extend(df.values.tolist())
# Write new data to sheet
body = {"values": values}
return body
def output_to_sheet(sheets_service, spreadsheet_id, body, sheet_name):
range = "A:ZZ"
if sheet_name is not None:
range = f"'{sheet_name}'!{range}"
try:
sheets_service.spreadsheets().values().clear(
spreadsheetId=spreadsheet_id, range=range
).execute()
logging.info(f"Cleared sheet {spreadsheet_id}")
except HttpError as e:
logging.error(e)
raise
try:
result = (
sheets_service.spreadsheets()
.values()
.update(
spreadsheetId=spreadsheet_id,
valueInputOption="USER_ENTERED",
range=range,
body=body,
)
.execute()
)
logging.info(
f"Written {result.get('updatedCells')} cells to sheet {spreadsheet_id}"
)
except HttpError as e:
logging.error(e)
raise
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Google Shared Drive file audit", add_help=True
)
parser.add_argument("credentials", help="Service Account Credentials JSON File")
parser.add_argument("drive", help="Google Shared Drive ID")
parser.add_argument("sheet", help="Output Google Sheet ID")
parser.add_argument(
"-v",
"--verbose",
help="Enable more verbose logging",
action="store_const",
dest="logLevel",
const=logging.INFO,
default=logging.WARN,
)
parser.add_argument(
"-l",
"--logfile",
help="Specify log file location",
dest="logFile",
default="/var/log/file_audit.log",
)
parser.add_argument(
"-f",
"--folders",
help="List folders as well as files",
dest="listFolders",
action="store_true",
default=False,
)
parser.add_argument(
"-t",
"--trashed",
help="List trashed items",
dest="listTrashed",
action="store_true",
default=False,
)
parser.add_argument(
"-s",
"--sheet",
help="Output to separate sheet in spreadsheet",
dest="sheetOutput",
action="store_true",
default=False,
)
parser.add_argument(
"-r",
"--root",
help="Specify root folder for output",
dest="rootFolder",
)
args = parser.parse_args()
logging.basicConfig(
filename=args.logFile,
format="%(asctime)s %(levelname)-4s %(message)s",
datefmt="%b %d %H:%M:%S",
level=args.logLevel,
)
logging.info(f"Starting file audit on drive {args.drive}")
start = time.time()
main(
args.credentials,
args.drive,
args.sheet,
args.listFolders,
args.listTrashed,
args.sheetOutput,
args.rootFolder,
)
end = time.time()
logging.info(
f"File audit complete on drive {args.drive} in {round(end - start, 2)} seconds"
)