Ensure we drive a useable filename for saving items whose URL does not provide one.

This commit is contained in:
Solderpunk 2023-11-19 14:38:55 +01:00
parent c8c12cab86
commit 4df88896a8
1 changed files with 24 additions and 2 deletions

26
av98.py
View File

@ -149,6 +149,28 @@ class GeminiItem():
else:
return "=> {}\n".format(self.url)
def derive_filename(self, mime=None):
# Simplest option it to use the end of the URL, if there is one.
filename = os.path.basename(self.path)
if filename:
return filename
# If there's not, try to pretty up the GeminiItem name
if self.name:
filename = self.name.lower().replace(" ","_")
# Otherwise, use something generic.
else:
filename = "av98_download_" + time.strftime("%Y%m%d%H%M%S")
# Add an extension
if mime == "text/gemini":
return filename + ".gmi"
elif mime:
ext = mimetypes.guess_extension(mime)
if ext:
return filename + ext
return filename + ".file"
@classmethod
def from_map_line(cls, line, origin_gi):
assert line.startswith("=>")
@ -1226,9 +1248,9 @@ Use 'ls -l' to see URLs."""
gi = self.gi
saving_current = True
# Derive filename from current GI's path, if one hasn't been set
# Derive a filename if one hasn't been set
if not filename:
filename = os.path.basename(gi.path)
filename = gi.derive_filename(self.mime if saving_current else None)
# Check for filename collisions
if os.path.exists(filename):