From fea6571d32746d34758a06ff6ce05912b207d274 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Tue, 27 Nov 2007 17:42:03 +0000 Subject: [PATCH] Fix #338 --- src/libprs500/__init__.py | 12 ++++++++++-- src/libprs500/library/database.py | 7 ++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/libprs500/__init__.py b/src/libprs500/__init__.py index 031d170c2b..4b3d80dbdc 100644 --- a/src/libprs500/__init__.py +++ b/src/libprs500/__init__.py @@ -18,7 +18,7 @@ __docformat__ = "epytext" __author__ = "Kovid Goyal " __appname__ = 'libprs500' -import sys, os, logging, mechanize, locale, cStringIO +import sys, os, logging, mechanize, locale, cStringIO, re from gettext import GNUTranslations from math import floor @@ -152,4 +152,12 @@ def get_font_families(): if wt == 400 and italic == 0: family = describe.shortName(font)[1].strip() zlist.append((family, ff)) - return dict(zlist) \ No newline at end of file + return dict(zlist) + +def sanitize_file_name(name): + ''' + Remove characters that are illegal in filenames from name. + Also remove path separators. ALl illegal characters are replaced by + underscores. + ''' + return re.sub(r'[:\?\\\/]|^-', '_', name.strip()) \ No newline at end of file diff --git a/src/libprs500/library/database.py b/src/libprs500/library/database.py index e919b35eba..6a0a1b2918 100644 --- a/src/libprs500/library/database.py +++ b/src/libprs500/library/database.py @@ -19,6 +19,7 @@ import sqlite3 as sqlite import datetime, re, os, cPickle, traceback from zlib import compress, decompress +from libprs500 import sanitize_file_name from libprs500.ebooks.metadata.meta import set_metadata from libprs500.ebooks.metadata import MetaInformation @@ -1103,12 +1104,12 @@ ALTER TABLE books ADD COLUMN isbn TEXT DEFAULT "" COLLATE NOCASE; by_author[au] = [] by_author[au].append(index) for au in by_author.keys(): - apath = os.path.join(dir, au.replace(os.sep, '_').strip()) + apath = os.path.join(dir, sanitize_file_name(au)) if not os.path.exists(apath): os.mkdir(apath) for idx in by_author[au]: title = re.sub(r'\s', ' ', self.title(idx)) - tpath = os.path.join(apath, title.replace(os.sep, '_').strip()) + tpath = os.path.join(apath, sanitize_file_name(title)) id = str(self.id(idx)) if not os.path.exists(tpath): os.mkdir(tpath) @@ -1116,7 +1117,7 @@ ALTER TABLE books ADD COLUMN isbn TEXT DEFAULT "" COLLATE NOCASE; data = self.format(idx, fmt) name = au + ' - ' + title if byauthor else title + ' - ' + au fname = name +'_'+id+'.'+fmt.lower() - f = open(os.path.join(tpath, fname.replace(os.sep, '_').strip()), 'w+b') + f = open(os.path.join(tpath, sanitize_file_name(fname)), 'w+b') f.write(data) f.flush() aum = self.authors(idx)