diff --git a/VERSION b/VERSION index 1eacb0b..232f41f 100755 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -4.1.11-develop1 +4.1.11-develop2 diff --git a/modules/util.py b/modules/util.py index 52aab3d..fa130c8 100755 --- a/modules/util.py +++ b/modules/util.py @@ -652,7 +652,7 @@ def get_root_files(root_dir, remote_dir, exclude_dir=None): def load_json(file): """Load json file if exists""" - if os.path.isfile(file): + if os.path.isfile(truncate_filename(file)): file = open(file) data = json.load(file) file.close() @@ -661,10 +661,48 @@ def load_json(file): return data +def truncate_filename(filename, max_length=255, offset=0): + """ + Truncate filename if necessary. + + Args: + filename (str): The original filename. + max_length (int, optional): The maximum length of the truncated filename. Defaults to 255. + offset (int, optional): The number of characters to keep from the end of the base name. Defaults to 0. + + Returns: + str: The truncated filename. + + """ + base, ext = os.path.splitext(filename) + if len(filename) > max_length: + max_base_length = max_length - len(ext) - offset + truncated_base = base[:max_base_length] + truncated_base_offset = base[-offset:] if offset > 0 else "" + truncated_filename = f"{truncated_base}{truncated_base_offset}{ext}" + else: + truncated_filename = filename + return truncated_filename + + def save_json(torrent_json, dest): - """Save json file to destination""" - with open(dest, "w", encoding="utf-8") as file: - json.dump(torrent_json, file, ensure_ascii=False, indent=4) + """Save json file to destination, truncating filename if necessary.""" + max_filename_length = 255 # Typical maximum filename length on many filesystems + directory, filename = os.path.split(dest) + filename, ext = os.path.splitext(filename) + + if len(filename) > (max_filename_length - len(ext)): + truncated_filename = truncate_filename(filename, max_filename_length) + dest = os.path.join(directory, truncated_filename) + logger.warning(f"Filename too long, truncated to: {dest}") + + try: + with open(dest, "w", encoding="utf-8") as file: + json.dump(torrent_json, file, ensure_ascii=False, indent=4) + except FileNotFoundError as e: + logger.error(f"Failed to save JSON file: {e.filename} - {e.strerror}.") + except OSError as e: + logger.error(f"OS error occurred: {e.filename} - {e.strerror}.") class GracefulKiller: