Skip to content

Commit 951ad25

Browse files
committed
Improve readability of the download logic
1 parent dbfb0d8 commit 951ad25

1 file changed

Lines changed: 17 additions & 20 deletions

File tree

nxc/modules/recyclebin.py

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -67,29 +67,26 @@ def on_admin_login(self, context, connection):
6767
# $I files are metadata while $R are actual files so we split the path from the SID
6868
# And check that the filename contains $R only to prevent downloading useless stuff
6969

70-
if "$R" in path.split(sid_directory.get_longname())[1] and not path.endswith(false_positiv):
70+
if "$R" in path.split(sid_directory.get_longname())[1] and not path.endswith(false_positive):
71+
# Create the export path
72+
export_path = join(NXC_PATH, "modules", "recyclebin")
73+
makedirs(export_path, exist_ok=True)
74+
75+
# Formatting the destination filename
76+
file_path = path.split("$")[-1].replace("/", "_")
77+
filename = f"{connection.host}_{username if username else sid_directory.get_longname()}_recyclebin_{file_path}"
78+
dest_path = abspath(join(export_path, filename))
7179
try:
72-
buf = BytesIO()
73-
connection.conn.getFile("C$", path, buf.write)
74-
context.log.highlight(f"\t{path}")
75-
found += 1
76-
buf.seek(0)
77-
file_path = path.split("$")[-1].replace("/", "_")
78-
if username: # noqa: SIM108
79-
filename = f"{connection.host}_{username}_recyclebin_{file_path}"
80+
with open(dest_path, "wb+") as file:
81+
connection.conn.getFile("C$", path, file.write)
82+
except Exception as e:
83+
if "STATUS_FILE_IS_A_DIRECTORY" in str(e):
84+
context.log.debug(f"Couldn't open {dest_path} because of {e}")
8085
else:
81-
filename = f"{connection.host}_{sid_directory.get_longname()}_recyclebin_{file_path}"
82-
export_path = join(NXC_PATH, "modules", "recyclebin")
83-
path = abspath(join(export_path, filename))
84-
makedirs(export_path, exist_ok=True)
85-
try:
86-
with open(path, "w+") as file:
87-
file.write(buf.read().decode("utf-8", errors="ignore"))
88-
except Exception as e:
8986
context.log.fail(f"Failed to write recyclebin file to {filename}: {e}")
90-
except Exception as e:
91-
# Probably trying to getFile a directory which won't work
92-
context.log.debug(f"Couldn't open {path} because of {e}")
87+
else:
88+
context.log.highlight(f"\t{dest_path}")
89+
found += 1
9390
except DCERPCSessionError as e:
9491
if "ERROR_FILE_NOT_FOUND" in str(e):
9592
continue

0 commit comments

Comments
 (0)