diff --git a/django_app/redbox_app/redbox_core/views/document_views.py b/django_app/redbox_app/redbox_core/views/document_views.py index 6dbe5ff8..008c382f 100644 --- a/django_app/redbox_app/redbox_core/views/document_views.py +++ b/django_app/redbox_app/redbox_core/views/document_views.py @@ -177,38 +177,45 @@ def convert_doc_to_docx(uploaded_file: UploadedFile) -> UploadedFile: with tempfile.NamedTemporaryFile(delete=False, suffix=".doc") as tmp_input: tmp_input.write(uploaded_file.read()) tmp_input.flush() - input_path = tmp_input.name - output_dir = Path(input_path).parent - if not Path.exists(output_dir): - Path(output_dir).mkdir(parents=True, exist_ok=True) + input_path = Path(tmp_input.name) + output_dir = input_path.parent - temp_output_path = str(Path(input_path).with_suffix(".docx")) + if not output_dir.exists(): + output_dir.mkdir(parents=True, exist_ok=True) + + temp_output_path = input_path.with_suffix(".docx") try: result = subprocess.run( # noqa: S603 - ["/usr/bin/libreoffice", "--headless", "--convert-to", "docx", input_path, "--outdir", output_dir], + [ + "/usr/bin/libreoffice", + "--headless", + "--convert-to", + "docx", + str(input_path), + "--outdir", + str(output_dir), + ], check=True, - capture_output=subprocess.PIPE, - stderr=subprocess.PIPE, + capture_output=True, cwd=output_dir, ) logger.info("LibreOffice output: %s", result.stdout.decode()) logger.info("LibreOffice errors: %s", result.stderr.decode()) - if not Path.exists(temp_output_path): + if not temp_output_path.exists(): logger.error("Output file not found: %s", temp_output_path) return uploaded_file logger.info("Output path: %s", temp_output_path) time.sleep(1) - with Path.open(temp_output_path, "rb") as f: + with temp_output_path.open("rb") as f: converted_content = f.read() logger.info("Converted file size: %d bytes", len(converted_content)) if len(converted_content) == 0: logger.error("Converted file is empty - this won't get converted") - # Use the original file's name (with .docx) for the in-memory file output_filename = Path(uploaded_file.name).with_suffix(".docx").name new_file = InMemoryUploadedFile( file=BytesIO(converted_content), @@ -224,9 +231,9 @@ def convert_doc_to_docx(uploaded_file: UploadedFile) -> UploadedFile: new_file = uploaded_file finally: try: - Path.unlink(input_path) - if Path.exists(temp_output_path): - Path.unlink(temp_output_path) + input_path.unlink() + if temp_output_path.exists(): + temp_output_path.unlink() except Exception as cleanup_error: # noqa: BLE001 logger.warning("Error cleaning up temporary files: %s", cleanup_error)