mirror of
https://github.com/kovidgoyal/calibre.git
synced 2025-07-09 03:04:10 -04:00
perform various automated cleanups of python2-compatible code
performed using: ``` pyupgrade --keep-percent-format --py3-only ``` and committing the results. This changes various things, including: - remove u from u'' strings, since python3 strings are always unicode - consolidate on OSError for various exceptions that are deprecated aliases - dict/set literals and comprehensions - yield from - remove extraneous () produced by accident by some modernization code - modern super() - remove __future__ imports etc.
This commit is contained in:
parent
39a22268b9
commit
fd467c4527
@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
''' E-book management software'''
|
''' E-book management software'''
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal <kovid@kovidgoyal.net>'
|
__copyright__ = '2008, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||||
@ -13,7 +12,7 @@ if not hasenv('CALIBRE_SHOW_DEPRECATION_WARNINGS'):
|
|||||||
warnings.simplefilter('ignore', DeprecationWarning)
|
warnings.simplefilter('ignore', DeprecationWarning)
|
||||||
try:
|
try:
|
||||||
os.getcwd()
|
os.getcwd()
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
os.chdir(os.path.expanduser('~'))
|
os.chdir(os.path.expanduser('~'))
|
||||||
|
|
||||||
from calibre.constants import (iswindows, ismacos, islinux, isfrozen,
|
from calibre.constants import (iswindows, ismacos, islinux, isfrozen,
|
||||||
@ -372,7 +371,7 @@ class CurrentDir:
|
|||||||
def __exit__(self, *args):
|
def __exit__(self, *args):
|
||||||
try:
|
try:
|
||||||
os.chdir(self.cwd)
|
os.chdir(self.cwd)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
# The previous CWD no longer exists
|
# The previous CWD no longer exists
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -118,7 +118,7 @@ def _get_cache_dir():
|
|||||||
confcache = os.path.join(config_dir, 'caches')
|
confcache = os.path.join(config_dir, 'caches')
|
||||||
try:
|
try:
|
||||||
os.makedirs(confcache)
|
os.makedirs(confcache)
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
if err.errno != errno.EEXIST:
|
if err.errno != errno.EEXIST:
|
||||||
raise
|
raise
|
||||||
if isportable:
|
if isportable:
|
||||||
@ -129,7 +129,7 @@ def _get_cache_dir():
|
|||||||
try:
|
try:
|
||||||
os.makedirs(ans)
|
os.makedirs(ans)
|
||||||
return ans
|
return ans
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
if err.errno == errno.EEXIST:
|
if err.errno == errno.EEXIST:
|
||||||
return ans
|
return ans
|
||||||
|
|
||||||
@ -151,7 +151,7 @@ def _get_cache_dir():
|
|||||||
candidate = confcache
|
candidate = confcache
|
||||||
try:
|
try:
|
||||||
os.makedirs(candidate)
|
os.makedirs(candidate)
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
if err.errno != errno.EEXIST:
|
if err.errno != errno.EEXIST:
|
||||||
candidate = confcache
|
candidate = confcache
|
||||||
return candidate
|
return candidate
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
||||||
|
|
||||||
|
@ -1814,7 +1814,7 @@ class StoreWeightlessBooksStore(StoreBase):
|
|||||||
class StoreWHSmithUKStore(StoreBase):
|
class StoreWHSmithUKStore(StoreBase):
|
||||||
name = 'WH Smith UK'
|
name = 'WH Smith UK'
|
||||||
author = 'Charles Haley'
|
author = 'Charles Haley'
|
||||||
description = u"Shop for savings on Books, discounted Magazine subscriptions and great prices on Stationery, Toys & Games"
|
description = "Shop for savings on Books, discounted Magazine subscriptions and great prices on Stationery, Toys & Games"
|
||||||
actual_plugin = 'calibre.gui2.store.stores.whsmith_uk_plugin:WHSmithUKStore'
|
actual_plugin = 'calibre.gui2.store.stores.whsmith_uk_plugin:WHSmithUKStore'
|
||||||
|
|
||||||
headquarters = 'UK'
|
headquarters = 'UK'
|
||||||
|
@ -31,8 +31,8 @@ class Plugin(_Plugin):
|
|||||||
self.fsizes = []
|
self.fsizes = []
|
||||||
for (name, num), size in zip(FONT_SIZES, fsizes):
|
for (name, num), size in zip(FONT_SIZES, fsizes):
|
||||||
self.fsizes.append((name, num, float(size)))
|
self.fsizes.append((name, num, float(size)))
|
||||||
self.fnames = dict((name, sz) for name, _, sz in self.fsizes if name)
|
self.fnames = {name: sz for name, _, sz in self.fsizes if name}
|
||||||
self.fnums = dict((num, sz) for _, num, sz in self.fsizes if num)
|
self.fnums = {num: sz for _, num, sz in self.fsizes if num}
|
||||||
self.width_pts = self.width * 72./self.dpi
|
self.width_pts = self.width * 72./self.dpi
|
||||||
self.height_pts = self.height * 72./self.dpi
|
self.height_pts = self.height * 72./self.dpi
|
||||||
|
|
||||||
@ -486,7 +486,7 @@ class SonyReaderOutput(OutputProfile):
|
|||||||
dpi = 168.451
|
dpi = 168.451
|
||||||
fbase = 12
|
fbase = 12
|
||||||
fsizes = [7.5, 9, 10, 12, 15.5, 20, 22, 24]
|
fsizes = [7.5, 9, 10, 12, 15.5, 20, 22, 24]
|
||||||
unsupported_unicode_chars = [u'\u201f', u'\u201b']
|
unsupported_unicode_chars = ['\u201f', '\u201b']
|
||||||
|
|
||||||
epub_periodical_format = 'sony'
|
epub_periodical_format = 'sony'
|
||||||
# periodical_date_in_title = False
|
# periodical_date_in_title = False
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
||||||
|
|
||||||
@ -769,8 +768,7 @@ initialize_plugins()
|
|||||||
|
|
||||||
|
|
||||||
def initialized_plugins():
|
def initialized_plugins():
|
||||||
for plugin in _initialized_plugins:
|
yield from _initialized_plugins
|
||||||
yield plugin
|
|
||||||
|
|
||||||
# }}}
|
# }}}
|
||||||
|
|
||||||
@ -786,7 +784,7 @@ def build_plugin(path):
|
|||||||
if '__init__.py' not in names:
|
if '__init__.py' not in names:
|
||||||
prints(path, ' is not a valid plugin')
|
prints(path, ' is not a valid plugin')
|
||||||
raise SystemExit(1)
|
raise SystemExit(1)
|
||||||
t = PersistentTemporaryFile(u'.zip')
|
t = PersistentTemporaryFile('.zip')
|
||||||
with ZipFile(t, 'w', ZIP_STORED) as zf:
|
with ZipFile(t, 'w', ZIP_STORED) as zf:
|
||||||
zf.add_dir(path, simple_filter=lambda x:x in {'.git', '.bzr', '.svn', '.hg'})
|
zf.add_dir(path, simple_filter=lambda x:x in {'.git', '.bzr', '.svn', '.hg'})
|
||||||
t.close()
|
t.close()
|
||||||
@ -852,7 +850,7 @@ def main(args=sys.argv):
|
|||||||
for plugin in initialized_plugins():
|
for plugin in initialized_plugins():
|
||||||
type_len, name_len = max(type_len, len(plugin.type)), max(name_len, len(plugin.name))
|
type_len, name_len = max(type_len, len(plugin.type)), max(name_len, len(plugin.name))
|
||||||
fmt = '%-{}s%-{}s%-15s%-15s%s'.format(type_len+1, name_len+1)
|
fmt = '%-{}s%-{}s%-15s%-15s%s'.format(type_len+1, name_len+1)
|
||||||
print(fmt%tuple(('Type|Name|Version|Disabled|Site Customization'.split('|'))))
|
print(fmt%tuple('Type|Name|Version|Disabled|Site Customization'.split('|')))
|
||||||
print()
|
print()
|
||||||
for plugin in initialized_plugins():
|
for plugin in initialized_plugins():
|
||||||
print(fmt%(
|
print(fmt%(
|
||||||
|
@ -340,9 +340,9 @@ class CalibrePluginFinder:
|
|||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
if self._identifier_pat.match(plugin_name) is None:
|
if self._identifier_pat.match(plugin_name) is None:
|
||||||
raise InvalidPlugin((
|
raise InvalidPlugin(
|
||||||
'The plugin at %r uses an invalid import name: %r' %
|
'The plugin at %r uses an invalid import name: %r' %
|
||||||
(path_to_zip_file, plugin_name)))
|
(path_to_zip_file, plugin_name))
|
||||||
|
|
||||||
pynames = [x for x in names if x.endswith('.py')]
|
pynames = [x for x in names if x.endswith('.py')]
|
||||||
|
|
||||||
|
@ -77,10 +77,10 @@ def get_data_as_dict(self, prefix=None, authors_as_string=False, ids=None, conve
|
|||||||
prefix = backend.library_path
|
prefix = backend.library_path
|
||||||
fdata = backend.custom_column_num_map
|
fdata = backend.custom_column_num_map
|
||||||
|
|
||||||
FIELDS = set(['title', 'sort', 'authors', 'author_sort', 'publisher',
|
FIELDS = {'title', 'sort', 'authors', 'author_sort', 'publisher',
|
||||||
'rating', 'timestamp', 'size', 'tags', 'comments', 'series',
|
'rating', 'timestamp', 'size', 'tags', 'comments', 'series',
|
||||||
'series_index', 'uuid', 'pubdate', 'last_modified', 'identifiers',
|
'series_index', 'uuid', 'pubdate', 'last_modified', 'identifiers',
|
||||||
'languages']).union(set(fdata))
|
'languages'}.union(set(fdata))
|
||||||
for x, data in iteritems(fdata):
|
for x, data in iteritems(fdata):
|
||||||
if data['datatype'] == 'series':
|
if data['datatype'] == 'series':
|
||||||
FIELDS.add('%d_index'%x)
|
FIELDS.add('%d_index'%x)
|
||||||
|
@ -93,7 +93,7 @@ def listdir(root, sort_by_mtime=False):
|
|||||||
def safe_mtime(x):
|
def safe_mtime(x):
|
||||||
try:
|
try:
|
||||||
return os.path.getmtime(x)
|
return os.path.getmtime(x)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
return time.time()
|
return time.time()
|
||||||
items = sorted(items, key=safe_mtime)
|
items = sorted(items, key=safe_mtime)
|
||||||
|
|
||||||
@ -230,8 +230,7 @@ def cdb_find_in_dir(dirpath, single_book_per_directory, compiled_rules):
|
|||||||
def cdb_recursive_find(root, single_book_per_directory=True, compiled_rules=()):
|
def cdb_recursive_find(root, single_book_per_directory=True, compiled_rules=()):
|
||||||
root = os.path.abspath(root)
|
root = os.path.abspath(root)
|
||||||
for dirpath in os.walk(root):
|
for dirpath in os.walk(root):
|
||||||
for formats in cdb_find_in_dir(dirpath[0], single_book_per_directory, compiled_rules):
|
yield from cdb_find_in_dir(dirpath[0], single_book_per_directory, compiled_rules)
|
||||||
yield formats
|
|
||||||
|
|
||||||
|
|
||||||
def add_catalog(cache, path, title, dbapi=None):
|
def add_catalog(cache, path, title, dbapi=None):
|
||||||
|
@ -151,18 +151,18 @@ class DBPrefs(dict): # {{{
|
|||||||
self.__setitem__(key, val)
|
self.__setitem__(key, val)
|
||||||
|
|
||||||
def get_namespaced(self, namespace, key, default=None):
|
def get_namespaced(self, namespace, key, default=None):
|
||||||
key = u'namespaced:%s:%s'%(namespace, key)
|
key = 'namespaced:%s:%s'%(namespace, key)
|
||||||
try:
|
try:
|
||||||
return dict.__getitem__(self, key)
|
return dict.__getitem__(self, key)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
return default
|
return default
|
||||||
|
|
||||||
def set_namespaced(self, namespace, key, val):
|
def set_namespaced(self, namespace, key, val):
|
||||||
if u':' in key:
|
if ':' in key:
|
||||||
raise KeyError('Colons are not allowed in keys')
|
raise KeyError('Colons are not allowed in keys')
|
||||||
if u':' in namespace:
|
if ':' in namespace:
|
||||||
raise KeyError('Colons are not allowed in the namespace')
|
raise KeyError('Colons are not allowed in the namespace')
|
||||||
key = u'namespaced:%s:%s'%(namespace, key)
|
key = 'namespaced:%s:%s'%(namespace, key)
|
||||||
self[key] = val
|
self[key] = val
|
||||||
|
|
||||||
def write_serialized(self, library_path):
|
def write_serialized(self, library_path):
|
||||||
@ -261,7 +261,7 @@ def IdentifiersConcat():
|
|||||||
'''String concatenation aggregator for the identifiers map'''
|
'''String concatenation aggregator for the identifiers map'''
|
||||||
|
|
||||||
def step(ctxt, key, val):
|
def step(ctxt, key, val):
|
||||||
ctxt.append(u'%s:%s'%(key, val))
|
ctxt.append('%s:%s'%(key, val))
|
||||||
|
|
||||||
def finalize(ctxt):
|
def finalize(ctxt):
|
||||||
try:
|
try:
|
||||||
@ -402,7 +402,7 @@ def set_global_state(backend):
|
|||||||
def rmtree_with_retry(path, sleep_time=1):
|
def rmtree_with_retry(path, sleep_time=1):
|
||||||
try:
|
try:
|
||||||
shutil.rmtree(path)
|
shutil.rmtree(path)
|
||||||
except EnvironmentError as e:
|
except OSError as e:
|
||||||
if e.errno == errno.ENOENT and not os.path.exists(path):
|
if e.errno == errno.ENOENT and not os.path.exists(path):
|
||||||
return
|
return
|
||||||
time.sleep(sleep_time) # In case something has temporarily locked a file
|
time.sleep(sleep_time) # In case something has temporarily locked a file
|
||||||
@ -645,7 +645,7 @@ class DB:
|
|||||||
prints('found user category case overlap', catmap[uc])
|
prints('found user category case overlap', catmap[uc])
|
||||||
cat = catmap[uc][0]
|
cat = catmap[uc][0]
|
||||||
suffix = 1
|
suffix = 1
|
||||||
while icu_lower((cat + str(suffix))) in catmap:
|
while icu_lower(cat + str(suffix)) in catmap:
|
||||||
suffix += 1
|
suffix += 1
|
||||||
prints('Renaming user category %s to %s'%(cat, cat+str(suffix)))
|
prints('Renaming user category %s to %s'%(cat, cat+str(suffix)))
|
||||||
user_cats[cat + str(suffix)] = user_cats[cat]
|
user_cats[cat + str(suffix)] = user_cats[cat]
|
||||||
@ -759,7 +759,7 @@ class DB:
|
|||||||
x = [y.strip() for y in x if y.strip()]
|
x = [y.strip() for y in x if y.strip()]
|
||||||
x = [y.decode(preferred_encoding, 'replace') if not isinstance(y,
|
x = [y.decode(preferred_encoding, 'replace') if not isinstance(y,
|
||||||
str) else y for y in x]
|
str) else y for y in x]
|
||||||
return [u' '.join(y.split()) for y in x]
|
return [' '.join(y.split()) for y in x]
|
||||||
else:
|
else:
|
||||||
return x if x is None or isinstance(x, str) else \
|
return x if x is None or isinstance(x, str) else \
|
||||||
x.decode(preferred_encoding, 'replace')
|
x.decode(preferred_encoding, 'replace')
|
||||||
@ -824,7 +824,7 @@ class DB:
|
|||||||
else:
|
else:
|
||||||
is_category = False
|
is_category = False
|
||||||
is_m = v['multiple_seps']
|
is_m = v['multiple_seps']
|
||||||
tn = 'custom_column_{0}'.format(v['num'])
|
tn = 'custom_column_{}'.format(v['num'])
|
||||||
self.field_metadata.add_custom_field(label=v['label'],
|
self.field_metadata.add_custom_field(label=v['label'],
|
||||||
table=tn, column='value', datatype=v['datatype'],
|
table=tn, column='value', datatype=v['datatype'],
|
||||||
colnum=v['num'], name=v['name'], display=v['display'],
|
colnum=v['num'], name=v['name'], display=v['display'],
|
||||||
@ -1428,7 +1428,7 @@ class DB:
|
|||||||
path = os.path.abspath(os.path.join(self.library_path, path, 'cover.jpg'))
|
path = os.path.abspath(os.path.join(self.library_path, path, 'cover.jpg'))
|
||||||
try:
|
try:
|
||||||
return utcfromtimestamp(os.stat(path).st_mtime)
|
return utcfromtimestamp(os.stat(path).st_mtime)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
pass # Cover doesn't exist
|
pass # Cover doesn't exist
|
||||||
|
|
||||||
def copy_cover_to(self, path, dest, windows_atomic_move=None, use_hardlink=False, report_file_size=None):
|
def copy_cover_to(self, path, dest, windows_atomic_move=None, use_hardlink=False, report_file_size=None):
|
||||||
@ -1444,11 +1444,11 @@ class DB:
|
|||||||
if os.access(path, os.R_OK):
|
if os.access(path, os.R_OK):
|
||||||
try:
|
try:
|
||||||
f = lopen(path, 'rb')
|
f = lopen(path, 'rb')
|
||||||
except (IOError, OSError):
|
except OSError:
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
try:
|
try:
|
||||||
f = lopen(path, 'rb')
|
f = lopen(path, 'rb')
|
||||||
except (IOError, OSError) as e:
|
except OSError as e:
|
||||||
# Ensure the path that caused this error is reported
|
# Ensure the path that caused this error is reported
|
||||||
raise Exception('Failed to open %r with error: %s' % (path, e))
|
raise Exception('Failed to open %r with error: %s' % (path, e))
|
||||||
|
|
||||||
@ -1478,13 +1478,13 @@ class DB:
|
|||||||
path = os.path.abspath(os.path.join(self.library_path, path, 'cover.jpg'))
|
path = os.path.abspath(os.path.join(self.library_path, path, 'cover.jpg'))
|
||||||
try:
|
try:
|
||||||
stat = os.stat(path)
|
stat = os.stat(path)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
return False, None, None
|
return False, None, None
|
||||||
if abs(timestamp - stat.st_mtime) < 0.1:
|
if abs(timestamp - stat.st_mtime) < 0.1:
|
||||||
return True, None, None
|
return True, None, None
|
||||||
try:
|
try:
|
||||||
f = lopen(path, 'rb')
|
f = lopen(path, 'rb')
|
||||||
except (IOError, OSError):
|
except OSError:
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
f = lopen(path, 'rb')
|
f = lopen(path, 'rb')
|
||||||
with f:
|
with f:
|
||||||
@ -1519,7 +1519,7 @@ class DB:
|
|||||||
if os.path.exists(path):
|
if os.path.exists(path):
|
||||||
try:
|
try:
|
||||||
os.remove(path)
|
os.remove(path)
|
||||||
except (IOError, OSError):
|
except OSError:
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
os.remove(path)
|
os.remove(path)
|
||||||
else:
|
else:
|
||||||
@ -1529,7 +1529,7 @@ class DB:
|
|||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
save_cover_data_to(data, path)
|
save_cover_data_to(data, path)
|
||||||
except (IOError, OSError):
|
except OSError:
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
save_cover_data_to(data, path)
|
save_cover_data_to(data, path)
|
||||||
|
|
||||||
@ -1615,7 +1615,7 @@ class DB:
|
|||||||
# wrong in the rest of this function, at least the file is
|
# wrong in the rest of this function, at least the file is
|
||||||
# not deleted
|
# not deleted
|
||||||
os.rename(old_path, dest)
|
os.rename(old_path, dest)
|
||||||
except EnvironmentError as e:
|
except OSError as e:
|
||||||
if getattr(e, 'errno', None) != errno.ENOENT:
|
if getattr(e, 'errno', None) != errno.ENOENT:
|
||||||
# Failing to rename the old format will at worst leave a
|
# Failing to rename the old format will at worst leave a
|
||||||
# harmless orphan, so log and ignore the error
|
# harmless orphan, so log and ignore the error
|
||||||
@ -1727,11 +1727,11 @@ class DB:
|
|||||||
try:
|
try:
|
||||||
with lopen(path, 'wb') as f:
|
with lopen(path, 'wb') as f:
|
||||||
f.write(raw)
|
f.write(raw)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
exc_info = sys.exc_info()
|
exc_info = sys.exc_info()
|
||||||
try:
|
try:
|
||||||
os.makedirs(os.path.dirname(path))
|
os.makedirs(os.path.dirname(path))
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
if err.errno == errno.EEXIST:
|
if err.errno == errno.EEXIST:
|
||||||
# Parent directory already exists, re-raise original exception
|
# Parent directory already exists, re-raise original exception
|
||||||
reraise(*exc_info)
|
reraise(*exc_info)
|
||||||
@ -1810,8 +1810,7 @@ class DB:
|
|||||||
return frozenset(r[0] for r in self.execute('SELECT book FROM books_plugin_data WHERE name=?', (name,)))
|
return frozenset(r[0] for r in self.execute('SELECT book FROM books_plugin_data WHERE name=?', (name,)))
|
||||||
|
|
||||||
def annotations_for_book(self, book_id, fmt, user_type, user):
|
def annotations_for_book(self, book_id, fmt, user_type, user):
|
||||||
for x in annotations_for_book(self.conn, book_id, fmt, user_type, user):
|
yield from annotations_for_book(self.conn, book_id, fmt, user_type, user)
|
||||||
yield x
|
|
||||||
|
|
||||||
def search_annotations(self,
|
def search_annotations(self,
|
||||||
fts_engine_query, use_stemming, highlight_start, highlight_end, snippet_size, annotation_type,
|
fts_engine_query, use_stemming, highlight_start, highlight_end, snippet_size, annotation_type,
|
||||||
@ -2080,18 +2079,18 @@ class DB:
|
|||||||
for loc in old_dirs:
|
for loc in old_dirs:
|
||||||
try:
|
try:
|
||||||
rmtree_with_retry(loc)
|
rmtree_with_retry(loc)
|
||||||
except EnvironmentError as e:
|
except OSError as e:
|
||||||
if os.path.exists(loc):
|
if os.path.exists(loc):
|
||||||
prints('Failed to delete:', loc, 'with error:', as_unicode(e))
|
prints('Failed to delete:', loc, 'with error:', as_unicode(e))
|
||||||
for loc in old_files:
|
for loc in old_files:
|
||||||
try:
|
try:
|
||||||
os.remove(loc)
|
os.remove(loc)
|
||||||
except EnvironmentError as e:
|
except OSError as e:
|
||||||
if e.errno != errno.ENOENT:
|
if e.errno != errno.ENOENT:
|
||||||
prints('Failed to delete:', loc, 'with error:', as_unicode(e))
|
prints('Failed to delete:', loc, 'with error:', as_unicode(e))
|
||||||
try:
|
try:
|
||||||
os.rmdir(odir)
|
os.rmdir(odir)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
self.conn # Connect to the moved metadata.db
|
self.conn # Connect to the moved metadata.db
|
||||||
progress(_('Completed'), total, total)
|
progress(_('Completed'), total, total)
|
||||||
|
@ -1327,7 +1327,7 @@ class Cache:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
return self.backend.read_backup(path)
|
return self.backend.read_backup(path)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@write_api
|
@write_api
|
||||||
|
@ -44,7 +44,7 @@ class Tag:
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def string_representation(self):
|
def string_representation(self):
|
||||||
return u'%s:%s:%s:%s:%s'%(self.name, self.count, self.id, self.state, self.category)
|
return '%s:%s:%s:%s:%s'%(self.name, self.count, self.id, self.state, self.category)
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.string_representation
|
return self.string_representation
|
||||||
|
@ -263,7 +263,7 @@ def do_add(
|
|||||||
try:
|
try:
|
||||||
with lopen(mi.cover, 'rb') as f:
|
with lopen(mi.cover, 'rb') as f:
|
||||||
cover_data = f.read()
|
cover_data = f.read()
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
book_title, ids, mids, dups = dbctx.run(
|
book_title, ids, mids, dups = dbctx.run(
|
||||||
@ -462,8 +462,8 @@ def main(opts, args, dbctx):
|
|||||||
lcodes = [canonicalize_lang(x) for x in (opts.languages or '').split(',')]
|
lcodes = [canonicalize_lang(x) for x in (opts.languages or '').split(',')]
|
||||||
lcodes = [x for x in lcodes if x]
|
lcodes = [x for x in lcodes if x]
|
||||||
identifiers = (x.partition(':')[::2] for x in opts.identifier)
|
identifiers = (x.partition(':')[::2] for x in opts.identifier)
|
||||||
identifiers = dict((k.strip(), v.strip()) for k, v in identifiers
|
identifiers = {k.strip(): v.strip() for k, v in identifiers
|
||||||
if k.strip() and v.strip())
|
if k.strip() and v.strip()}
|
||||||
if opts.empty:
|
if opts.empty:
|
||||||
do_add_empty(
|
do_add_empty(
|
||||||
dbctx, opts.title, aut, opts.isbn, tags, opts.series, opts.series_index,
|
dbctx, opts.title, aut, opts.isbn, tags, opts.series, opts.series_index,
|
||||||
|
@ -54,7 +54,7 @@ class BackupProgress:
|
|||||||
else:
|
else:
|
||||||
self.count += 1
|
self.count += 1
|
||||||
prints(
|
prints(
|
||||||
u'%.1f%% %s - %s' % ((self.count * 100) / float(self.total), book_id,
|
'%.1f%% %s - %s' % ((self.count * 100) / float(self.total), book_id,
|
||||||
getattr(mi, 'title', 'Unknown'))
|
getattr(mi, 'title', 'Unknown'))
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -88,7 +88,7 @@ class DeleteService(Thread):
|
|||||||
basename = '%d - %s' % (c, os.path.basename(path))
|
basename = '%d - %s' % (c, os.path.basename(path))
|
||||||
try:
|
try:
|
||||||
shutil.move(path, dest)
|
shutil.move(path, dest)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
if os.path.isdir(path):
|
if os.path.isdir(path):
|
||||||
# shutil.move may have partially copied the directory,
|
# shutil.move may have partially copied the directory,
|
||||||
# so the subsequent call to move() will fail as the
|
# so the subsequent call to move() will fail as the
|
||||||
|
@ -328,8 +328,7 @@ class CompositeField(OneToOneField):
|
|||||||
for v in vals:
|
for v in vals:
|
||||||
if v:
|
if v:
|
||||||
val_map[v].add(book_id)
|
val_map[v].add(book_id)
|
||||||
for val, book_ids in iteritems(val_map):
|
yield from iteritems(val_map)
|
||||||
yield val, book_ids
|
|
||||||
|
|
||||||
def iter_counts(self, candidates, get_metadata=None):
|
def iter_counts(self, candidates, get_metadata=None):
|
||||||
val_map = defaultdict(set)
|
val_map = defaultdict(set)
|
||||||
@ -343,8 +342,7 @@ class CompositeField(OneToOneField):
|
|||||||
else:
|
else:
|
||||||
length = 0
|
length = 0
|
||||||
val_map[length].add(book_id)
|
val_map[length].add(book_id)
|
||||||
for val, book_ids in iteritems(val_map):
|
yield from iteritems(val_map)
|
||||||
yield val, book_ids
|
|
||||||
|
|
||||||
def get_composite_categories(self, tag_class, book_rating_map, book_ids,
|
def get_composite_categories(self, tag_class, book_rating_map, book_ids,
|
||||||
is_multiple, get_metadata):
|
is_multiple, get_metadata):
|
||||||
@ -437,8 +435,7 @@ class OnDeviceField(OneToOneField):
|
|||||||
val_map = defaultdict(set)
|
val_map = defaultdict(set)
|
||||||
for book_id in candidates:
|
for book_id in candidates:
|
||||||
val_map[self.for_book(book_id, default_value=default_value)].add(book_id)
|
val_map[self.for_book(book_id, default_value=default_value)].add(book_id)
|
||||||
for val, book_ids in iteritems(val_map):
|
yield from iteritems(val_map)
|
||||||
yield val, book_ids
|
|
||||||
|
|
||||||
|
|
||||||
class LazySortMap:
|
class LazySortMap:
|
||||||
@ -562,8 +559,7 @@ class ManyToManyField(Field):
|
|||||||
cbm = self.table.book_col_map
|
cbm = self.table.book_col_map
|
||||||
for book_id in candidates:
|
for book_id in candidates:
|
||||||
val_map[len(cbm.get(book_id, ()))].add(book_id)
|
val_map[len(cbm.get(book_id, ()))].add(book_id)
|
||||||
for count, book_ids in iteritems(val_map):
|
yield from iteritems(val_map)
|
||||||
yield count, book_ids
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def book_value_map(self):
|
def book_value_map(self):
|
||||||
|
@ -29,7 +29,7 @@ def cleanup_tags(tags):
|
|||||||
tags = [x.strip().replace(',', ';') for x in tags if x.strip()]
|
tags = [x.strip().replace(',', ';') for x in tags if x.strip()]
|
||||||
tags = [x.decode(preferred_encoding, 'replace')
|
tags = [x.decode(preferred_encoding, 'replace')
|
||||||
if isbytestring(x) else x for x in tags]
|
if isbytestring(x) else x for x in tags]
|
||||||
tags = [u' '.join(x.split()) for x in tags]
|
tags = [' '.join(x.split()) for x in tags]
|
||||||
ans, seen = [], set()
|
ans, seen = [], set()
|
||||||
for tag in tags:
|
for tag in tags:
|
||||||
if tag.lower() not in seen:
|
if tag.lower() not in seen:
|
||||||
@ -684,8 +684,7 @@ class LibraryDatabase:
|
|||||||
self.new_api.refresh_ondevice()
|
self.new_api.refresh_ondevice()
|
||||||
|
|
||||||
def tags_older_than(self, tag, delta, must_have_tag=None, must_have_authors=None):
|
def tags_older_than(self, tag, delta, must_have_tag=None, must_have_authors=None):
|
||||||
for book_id in sorted(self.new_api.tags_older_than(tag, delta=delta, must_have_tag=must_have_tag, must_have_authors=must_have_authors)):
|
yield from sorted(self.new_api.tags_older_than(tag, delta=delta, must_have_tag=must_have_tag, must_have_authors=must_have_authors))
|
||||||
yield book_id
|
|
||||||
|
|
||||||
def sizeof_format(self, index, fmt, index_is_id=False):
|
def sizeof_format(self, index, fmt, index_is_id=False):
|
||||||
book_id = index if index_is_id else self.id(index)
|
book_id = index if index_is_id else self.id(index)
|
||||||
@ -848,8 +847,7 @@ class LibraryDatabase:
|
|||||||
|
|
||||||
# Private interface {{{
|
# Private interface {{{
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
for row in self.data.iterall():
|
yield from self.data.iterall()
|
||||||
yield row
|
|
||||||
|
|
||||||
def _get_next_series_num_for_list(self, series_indices):
|
def _get_next_series_num_for_list(self, series_indices):
|
||||||
return _get_next_series_num_for_list(series_indices)
|
return _get_next_series_num_for_list(series_indices)
|
||||||
|
@ -42,7 +42,7 @@ class Restorer(Cache):
|
|||||||
class Restore(Thread):
|
class Restore(Thread):
|
||||||
|
|
||||||
def __init__(self, library_path, progress_callback=None):
|
def __init__(self, library_path, progress_callback=None):
|
||||||
super(Restore, self).__init__()
|
super().__init__()
|
||||||
if isbytestring(library_path):
|
if isbytestring(library_path):
|
||||||
library_path = library_path.decode(filesystem_encoding)
|
library_path = library_path.decode(filesystem_encoding)
|
||||||
self.src_library_path = os.path.abspath(library_path)
|
self.src_library_path = os.path.abspath(library_path)
|
||||||
@ -107,7 +107,7 @@ class Restore(Thread):
|
|||||||
try:
|
try:
|
||||||
tdir = TemporaryDirectory('_rlib', dir=basedir)
|
tdir = TemporaryDirectory('_rlib', dir=basedir)
|
||||||
tdir.__enter__()
|
tdir.__enter__()
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
# In case we dont have permissions to create directories in the
|
# In case we dont have permissions to create directories in the
|
||||||
# parent folder of the src library
|
# parent folder of the src library
|
||||||
tdir = TemporaryDirectory('_rlib')
|
tdir = TemporaryDirectory('_rlib')
|
||||||
@ -279,7 +279,7 @@ class Restore(Thread):
|
|||||||
if os.path.exists(dbpath):
|
if os.path.exists(dbpath):
|
||||||
try:
|
try:
|
||||||
os.rename(dbpath, save_path)
|
os.rename(dbpath, save_path)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
time.sleep(30) # Wait a little for dropbox or the antivirus or whatever to release the file
|
time.sleep(30) # Wait a little for dropbox or the antivirus or whatever to release the file
|
||||||
shutil.copyfile(dbpath, save_path)
|
shutil.copyfile(dbpath, save_path)
|
||||||
os.remove(dbpath)
|
os.remove(dbpath)
|
||||||
|
@ -103,7 +103,7 @@ class OneToOneTable(Table):
|
|||||||
|
|
||||||
def read(self, db):
|
def read(self, db):
|
||||||
idcol = 'id' if self.metadata['table'] == 'books' else 'book'
|
idcol = 'id' if self.metadata['table'] == 'books' else 'book'
|
||||||
query = db.execute('SELECT {0}, {1} FROM {2}'.format(idcol,
|
query = db.execute('SELECT {}, {} FROM {}'.format(idcol,
|
||||||
self.metadata['column'], self.metadata['table']))
|
self.metadata['column'], self.metadata['table']))
|
||||||
if self.unserialize is None:
|
if self.unserialize is None:
|
||||||
try:
|
try:
|
||||||
@ -111,7 +111,7 @@ class OneToOneTable(Table):
|
|||||||
except UnicodeDecodeError:
|
except UnicodeDecodeError:
|
||||||
# The db is damaged, try to work around it by ignoring
|
# The db is damaged, try to work around it by ignoring
|
||||||
# failures to decode utf-8
|
# failures to decode utf-8
|
||||||
query = db.execute('SELECT {0}, cast({1} as blob) FROM {2}'.format(idcol,
|
query = db.execute('SELECT {}, cast({} as blob) FROM {}'.format(idcol,
|
||||||
self.metadata['column'], self.metadata['table']))
|
self.metadata['column'], self.metadata['table']))
|
||||||
self.book_col_map = {k:bytes(val).decode('utf-8', 'replace') for k, val in query}
|
self.book_col_map = {k:bytes(val).decode('utf-8', 'replace') for k, val in query}
|
||||||
else:
|
else:
|
||||||
@ -205,7 +205,7 @@ class ManyToOneTable(Table):
|
|||||||
self.read_maps(db)
|
self.read_maps(db)
|
||||||
|
|
||||||
def read_id_maps(self, db):
|
def read_id_maps(self, db):
|
||||||
query = db.execute('SELECT id, {0} FROM {1}'.format(
|
query = db.execute('SELECT id, {} FROM {}'.format(
|
||||||
self.metadata['column'], self.metadata['table']))
|
self.metadata['column'], self.metadata['table']))
|
||||||
if self.unserialize is None:
|
if self.unserialize is None:
|
||||||
self.id_map = dict(query)
|
self.id_map = dict(query)
|
||||||
@ -217,7 +217,7 @@ class ManyToOneTable(Table):
|
|||||||
cbm = self.col_book_map
|
cbm = self.col_book_map
|
||||||
bcm = self.book_col_map
|
bcm = self.book_col_map
|
||||||
for book, item_id in db.execute(
|
for book, item_id in db.execute(
|
||||||
'SELECT book, {0} FROM {1}'.format(
|
'SELECT book, {} FROM {}'.format(
|
||||||
self.metadata['link_column'], self.link_table)):
|
self.metadata['link_column'], self.link_table)):
|
||||||
cbm[item_id].add(book)
|
cbm[item_id].add(book)
|
||||||
bcm[book] = item_id
|
bcm[book] = item_id
|
||||||
@ -230,7 +230,7 @@ class ManyToOneTable(Table):
|
|||||||
book_ids = self.col_book_map.pop(item_id, ())
|
book_ids = self.col_book_map.pop(item_id, ())
|
||||||
for book_id in book_ids:
|
for book_id in book_ids:
|
||||||
self.book_col_map.pop(book_id, None)
|
self.book_col_map.pop(book_id, None)
|
||||||
db.executemany('DELETE FROM {0} WHERE {1}=?'.format(
|
db.executemany('DELETE FROM {} WHERE {}=?'.format(
|
||||||
self.link_table, self.metadata['link_column']), tuple((x,) for x in extra_item_ids))
|
self.link_table, self.metadata['link_column']), tuple((x,) for x in extra_item_ids))
|
||||||
|
|
||||||
def fix_case_duplicates(self, db):
|
def fix_case_duplicates(self, db):
|
||||||
@ -250,7 +250,7 @@ class ManyToOneTable(Table):
|
|||||||
db.executemany('UPDATE {0} SET {1}=? WHERE {1}=?'.format(
|
db.executemany('UPDATE {0} SET {1}=? WHERE {1}=?'.format(
|
||||||
self.link_table, self.metadata['link_column']),
|
self.link_table, self.metadata['link_column']),
|
||||||
tuple((main_id, x) for x in v))
|
tuple((main_id, x) for x in v))
|
||||||
db.executemany('DELETE FROM {0} WHERE id=?'.format(self.metadata['table']),
|
db.executemany('DELETE FROM {} WHERE id=?'.format(self.metadata['table']),
|
||||||
tuple((x,) for x in v))
|
tuple((x,) for x in v))
|
||||||
|
|
||||||
def remove_books(self, book_ids, db):
|
def remove_books(self, book_ids, db):
|
||||||
@ -270,7 +270,7 @@ class ManyToOneTable(Table):
|
|||||||
clean.add(item_id)
|
clean.add(item_id)
|
||||||
if clean:
|
if clean:
|
||||||
db.executemany(
|
db.executemany(
|
||||||
'DELETE FROM {0} WHERE id=?'.format(self.metadata['table']),
|
'DELETE FROM {} WHERE id=?'.format(self.metadata['table']),
|
||||||
[(x,) for x in clean])
|
[(x,) for x in clean])
|
||||||
return clean
|
return clean
|
||||||
|
|
||||||
@ -296,7 +296,7 @@ class ManyToOneTable(Table):
|
|||||||
# this is a many-to-one mapping we know that we can delete
|
# this is a many-to-one mapping we know that we can delete
|
||||||
# links without checking the item ID
|
# links without checking the item ID
|
||||||
db.executemany(
|
db.executemany(
|
||||||
'DELETE FROM {0} WHERE book=?'.format(self.link_table), tuple((x,) for x in books_to_delete))
|
'DELETE FROM {} WHERE book=?'.format(self.link_table), tuple((x,) for x in books_to_delete))
|
||||||
affected_books |= books_to_delete
|
affected_books |= books_to_delete
|
||||||
else:
|
else:
|
||||||
# Process normally any items where the VL was not significant
|
# Process normally any items where the VL was not significant
|
||||||
@ -314,8 +314,8 @@ class ManyToOneTable(Table):
|
|||||||
self.book_col_map.pop(book_id, None)
|
self.book_col_map.pop(book_id, None)
|
||||||
affected_books.update(book_ids)
|
affected_books.update(book_ids)
|
||||||
item_ids = tuple((x,) for x in item_ids)
|
item_ids = tuple((x,) for x in item_ids)
|
||||||
db.executemany('DELETE FROM {0} WHERE {1}=?'.format(self.link_table, self.metadata['link_column']), item_ids)
|
db.executemany('DELETE FROM {} WHERE {}=?'.format(self.link_table, self.metadata['link_column']), item_ids)
|
||||||
db.executemany('DELETE FROM {0} WHERE id=?'.format(self.metadata['table']), item_ids)
|
db.executemany('DELETE FROM {} WHERE id=?'.format(self.metadata['table']), item_ids)
|
||||||
return affected_books
|
return affected_books
|
||||||
|
|
||||||
def rename_item(self, item_id, new_name, db):
|
def rename_item(self, item_id, new_name, db):
|
||||||
@ -327,7 +327,7 @@ class ManyToOneTable(Table):
|
|||||||
if existing_item is None or existing_item == item_id:
|
if existing_item is None or existing_item == item_id:
|
||||||
# A simple rename will do the trick
|
# A simple rename will do the trick
|
||||||
self.id_map[item_id] = new_name
|
self.id_map[item_id] = new_name
|
||||||
db.execute('UPDATE {0} SET {1}=? WHERE id=?'.format(table, col), (new_name, item_id))
|
db.execute('UPDATE {} SET {}=? WHERE id=?'.format(table, col), (new_name, item_id))
|
||||||
else:
|
else:
|
||||||
# We have to replace
|
# We have to replace
|
||||||
new_id = existing_item
|
new_id = existing_item
|
||||||
@ -353,9 +353,9 @@ class RatingTable(ManyToOneTable):
|
|||||||
bad_ids = {item_id for item_id, rating in iteritems(self.id_map) if rating == 0}
|
bad_ids = {item_id for item_id, rating in iteritems(self.id_map) if rating == 0}
|
||||||
if bad_ids:
|
if bad_ids:
|
||||||
self.id_map = {item_id:rating for item_id, rating in iteritems(self.id_map) if rating != 0}
|
self.id_map = {item_id:rating for item_id, rating in iteritems(self.id_map) if rating != 0}
|
||||||
db.executemany('DELETE FROM {0} WHERE {1}=?'.format(self.link_table, self.metadata['link_column']),
|
db.executemany('DELETE FROM {} WHERE {}=?'.format(self.link_table, self.metadata['link_column']),
|
||||||
tuple((x,) for x in bad_ids))
|
tuple((x,) for x in bad_ids))
|
||||||
db.execute('DELETE FROM {0} WHERE {1}=0'.format(
|
db.execute('DELETE FROM {} WHERE {}=0'.format(
|
||||||
self.metadata['table'], self.metadata['column']))
|
self.metadata['table'], self.metadata['column']))
|
||||||
|
|
||||||
|
|
||||||
@ -389,7 +389,7 @@ class ManyToManyTable(ManyToOneTable):
|
|||||||
book_ids = self.col_book_map.pop(item_id, ())
|
book_ids = self.col_book_map.pop(item_id, ())
|
||||||
for book_id in book_ids:
|
for book_id in book_ids:
|
||||||
self.book_col_map[book_id] = tuple(iid for iid in self.book_col_map.pop(book_id, ()) if iid not in extra_item_ids)
|
self.book_col_map[book_id] = tuple(iid for iid in self.book_col_map.pop(book_id, ()) if iid not in extra_item_ids)
|
||||||
db.executemany('DELETE FROM {0} WHERE {1}=?'.format(
|
db.executemany('DELETE FROM {} WHERE {}=?'.format(
|
||||||
self.link_table, self.metadata['link_column']), tuple((x,) for x in extra_item_ids))
|
self.link_table, self.metadata['link_column']), tuple((x,) for x in extra_item_ids))
|
||||||
|
|
||||||
def remove_books(self, book_ids, db):
|
def remove_books(self, book_ids, db):
|
||||||
@ -409,7 +409,7 @@ class ManyToManyTable(ManyToOneTable):
|
|||||||
clean.add(item_id)
|
clean.add(item_id)
|
||||||
if clean and self.do_clean_on_remove:
|
if clean and self.do_clean_on_remove:
|
||||||
db.executemany(
|
db.executemany(
|
||||||
'DELETE FROM {0} WHERE id=?'.format(self.metadata['table']),
|
'DELETE FROM {} WHERE id=?'.format(self.metadata['table']),
|
||||||
[(x,) for x in clean])
|
[(x,) for x in clean])
|
||||||
return clean
|
return clean
|
||||||
|
|
||||||
@ -436,7 +436,7 @@ class ManyToManyTable(ManyToOneTable):
|
|||||||
# Delete book/item pairs from the link table. We don't need to do
|
# Delete book/item pairs from the link table. We don't need to do
|
||||||
# anything with the main table because books with the old ID are
|
# anything with the main table because books with the old ID are
|
||||||
# still in the library.
|
# still in the library.
|
||||||
db.executemany('DELETE FROM {0} WHERE {1}=? and {2}=?'.format(
|
db.executemany('DELETE FROM {} WHERE {}=? and {}=?'.format(
|
||||||
self.link_table, 'book', self.metadata['link_column']),
|
self.link_table, 'book', self.metadata['link_column']),
|
||||||
[(b, i) for b in affected_books for i in item_ids])
|
[(b, i) for b in affected_books for i in item_ids])
|
||||||
# Take care of any items where the VL was not significant
|
# Take care of any items where the VL was not significant
|
||||||
@ -453,8 +453,8 @@ class ManyToManyTable(ManyToOneTable):
|
|||||||
self.book_col_map[book_id] = tuple(x for x in self.book_col_map.get(book_id, ()) if x != item_id)
|
self.book_col_map[book_id] = tuple(x for x in self.book_col_map.get(book_id, ()) if x != item_id)
|
||||||
affected_books.update(book_ids)
|
affected_books.update(book_ids)
|
||||||
item_ids = tuple((x,) for x in item_ids)
|
item_ids = tuple((x,) for x in item_ids)
|
||||||
db.executemany('DELETE FROM {0} WHERE {1}=?'.format(self.link_table, self.metadata['link_column']), item_ids)
|
db.executemany('DELETE FROM {} WHERE {}=?'.format(self.link_table, self.metadata['link_column']), item_ids)
|
||||||
db.executemany('DELETE FROM {0} WHERE id=?'.format(self.metadata['table']), item_ids)
|
db.executemany('DELETE FROM {} WHERE id=?'.format(self.metadata['table']), item_ids)
|
||||||
return affected_books
|
return affected_books
|
||||||
|
|
||||||
def rename_item(self, item_id, new_name, db):
|
def rename_item(self, item_id, new_name, db):
|
||||||
@ -466,7 +466,7 @@ class ManyToManyTable(ManyToOneTable):
|
|||||||
if existing_item is None or existing_item == item_id:
|
if existing_item is None or existing_item == item_id:
|
||||||
# A simple rename will do the trick
|
# A simple rename will do the trick
|
||||||
self.id_map[item_id] = new_name
|
self.id_map[item_id] = new_name
|
||||||
db.execute('UPDATE {0} SET {1}=? WHERE id=?'.format(table, col), (new_name, item_id))
|
db.execute('UPDATE {} SET {}=? WHERE id=?'.format(table, col), (new_name, item_id))
|
||||||
else:
|
else:
|
||||||
# We have to replace
|
# We have to replace
|
||||||
new_id = existing_item
|
new_id = existing_item
|
||||||
@ -478,7 +478,7 @@ class ManyToManyTable(ManyToOneTable):
|
|||||||
for book_id in books:
|
for book_id in books:
|
||||||
self.book_col_map[book_id] = tuple((existing_item if x == item_id else x) for x in self.book_col_map.get(book_id, ()) if x != existing_item)
|
self.book_col_map[book_id] = tuple((existing_item if x == item_id else x) for x in self.book_col_map.get(book_id, ()) if x != existing_item)
|
||||||
self.col_book_map[existing_item].update(books)
|
self.col_book_map[existing_item].update(books)
|
||||||
db.executemany('DELETE FROM {0} WHERE book=? AND {1}=?'.format(self.link_table, lcol), [
|
db.executemany('DELETE FROM {} WHERE book=? AND {}=?'.format(self.link_table, lcol), [
|
||||||
(book_id, existing_item) for book_id in books])
|
(book_id, existing_item) for book_id in books])
|
||||||
db.execute('UPDATE {0} SET {1}=? WHERE {1}=?; DELETE FROM {2} WHERE id=?'.format(
|
db.execute('UPDATE {0} SET {1}=? WHERE {1}=?; DELETE FROM {2} WHERE id=?'.format(
|
||||||
self.link_table, lcol, table), (existing_item, item_id, item_id))
|
self.link_table, lcol, table), (existing_item, item_id, item_id))
|
||||||
@ -515,11 +515,11 @@ class ManyToManyTable(ManyToOneTable):
|
|||||||
tuple((main_id, x, book_id) for x in v))
|
tuple((main_id, x, book_id) for x in v))
|
||||||
else:
|
else:
|
||||||
# duplicates
|
# duplicates
|
||||||
db.execute('DELETE FROM {0} WHERE book=?'.format(self.link_table), (book_id,))
|
db.execute('DELETE FROM {} WHERE book=?'.format(self.link_table), (book_id,))
|
||||||
db.executemany(
|
db.executemany(
|
||||||
'INSERT INTO {0} (book,{1}) VALUES (?,?)'.format(self.link_table, self.metadata['link_column']),
|
'INSERT INTO {} (book,{}) VALUES (?,?)'.format(self.link_table, self.metadata['link_column']),
|
||||||
tuple((book_id, x) for x in vals))
|
tuple((book_id, x) for x in vals))
|
||||||
db.executemany('DELETE FROM {0} WHERE id=?'.format(self.metadata['table']),
|
db.executemany('DELETE FROM {} WHERE id=?'.format(self.metadata['table']),
|
||||||
tuple((x,) for x in v))
|
tuple((x,) for x in v))
|
||||||
|
|
||||||
|
|
||||||
|
@ -32,7 +32,7 @@ class BaseTest(unittest.TestCase):
|
|||||||
gc.collect(), gc.collect()
|
gc.collect(), gc.collect()
|
||||||
try:
|
try:
|
||||||
shutil.rmtree(self.library_path)
|
shutil.rmtree(self.library_path)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
# Try again in case something transient has a file lock on windows
|
# Try again in case something transient has a file lock on windows
|
||||||
gc.collect(), gc.collect()
|
gc.collect(), gc.collect()
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
|
@ -62,7 +62,7 @@ def run_funcs(self, db, ndb, funcs):
|
|||||||
if meth[0] in {'!', '@', '#', '+', '$', '-', '%'}:
|
if meth[0] in {'!', '@', '#', '+', '$', '-', '%'}:
|
||||||
if meth[0] != '+':
|
if meth[0] != '+':
|
||||||
fmt = {'!':dict, '@':lambda x:frozenset(x or ()), '#':lambda x:set((x or '').split(',')),
|
fmt = {'!':dict, '@':lambda x:frozenset(x or ()), '#':lambda x:set((x or '').split(',')),
|
||||||
'$':lambda x:set(tuple(y) for y in x), '-':lambda x:None,
|
'$':lambda x:{tuple(y) for y in x}, '-':lambda x:None,
|
||||||
'%':lambda x: set((x or '').split(','))}[meth[0]]
|
'%':lambda x: set((x or '').split(','))}[meth[0]]
|
||||||
else:
|
else:
|
||||||
fmt = args[-1]
|
fmt = args[-1]
|
||||||
@ -516,7 +516,7 @@ class LegacyTest(BaseTest):
|
|||||||
T = partial(ET, 'get_all_custom_book_data', old=old, legacy=legacy)
|
T = partial(ET, 'get_all_custom_book_data', old=old, legacy=legacy)
|
||||||
T((name, object()))
|
T((name, object()))
|
||||||
T = partial(ET, 'delete_all_custom_book_data', old=old, legacy=legacy)
|
T = partial(ET, 'delete_all_custom_book_data', old=old, legacy=legacy)
|
||||||
T((name))
|
T(name)
|
||||||
T = partial(ET, 'get_all_custom_book_data', old=old, legacy=legacy)
|
T = partial(ET, 'get_all_custom_book_data', old=old, legacy=legacy)
|
||||||
T((name, object()))
|
T((name, object()))
|
||||||
|
|
||||||
|
@ -136,7 +136,7 @@ class ThumbnailCache:
|
|||||||
def _do_delete(self, path):
|
def _do_delete(self, path):
|
||||||
try:
|
try:
|
||||||
os.remove(path)
|
os.remove(path)
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
self.log('Failed to delete cached thumbnail file:', as_unicode(err))
|
self.log('Failed to delete cached thumbnail file:', as_unicode(err))
|
||||||
|
|
||||||
def _load_index(self):
|
def _load_index(self):
|
||||||
@ -153,7 +153,7 @@ class ThumbnailCache:
|
|||||||
def listdir(*args):
|
def listdir(*args):
|
||||||
try:
|
try:
|
||||||
return os.listdir(os.path.join(*args))
|
return os.listdir(os.path.join(*args))
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
return () # not a directory or no permission or whatever
|
return () # not a directory or no permission or whatever
|
||||||
entries = ('/'.join((parent, subdir, entry))
|
entries = ('/'.join((parent, subdir, entry))
|
||||||
for parent in listdir(self.location)
|
for parent in listdir(self.location)
|
||||||
@ -164,13 +164,13 @@ class ThumbnailCache:
|
|||||||
try:
|
try:
|
||||||
with open(os.path.join(self.location, 'invalidate'), 'rb') as f:
|
with open(os.path.join(self.location, 'invalidate'), 'rb') as f:
|
||||||
raw = f.read().decode('utf-8')
|
raw = f.read().decode('utf-8')
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
if getattr(err, 'errno', None) != errno.ENOENT:
|
if getattr(err, 'errno', None) != errno.ENOENT:
|
||||||
self.log('Failed to read thumbnail invalidate data:', as_unicode(err))
|
self.log('Failed to read thumbnail invalidate data:', as_unicode(err))
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
os.remove(os.path.join(self.location, 'invalidate'))
|
os.remove(os.path.join(self.location, 'invalidate'))
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
self.log('Failed to remove thumbnail invalidate data:', as_unicode(err))
|
self.log('Failed to remove thumbnail invalidate data:', as_unicode(err))
|
||||||
else:
|
else:
|
||||||
def record(line):
|
def record(line):
|
||||||
@ -198,7 +198,7 @@ class ThumbnailCache:
|
|||||||
self.total_size += size
|
self.total_size += size
|
||||||
else:
|
else:
|
||||||
self._do_delete(path)
|
self._do_delete(path)
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
self.log('Failed to read thumbnail cache dir:', as_unicode(err))
|
self.log('Failed to read thumbnail cache dir:', as_unicode(err))
|
||||||
|
|
||||||
self.items = OrderedDict(sorted(items, key=lambda x:order.get(x[0], 0)))
|
self.items = OrderedDict(sorted(items, key=lambda x:order.get(x[0], 0)))
|
||||||
@ -230,7 +230,7 @@ class ThumbnailCache:
|
|||||||
data = '\n'.join(group_id + ' ' + str(book_id) for (group_id, book_id) in self.items)
|
data = '\n'.join(group_id + ' ' + str(book_id) for (group_id, book_id) in self.items)
|
||||||
with lopen(os.path.join(self.location, 'order'), 'wb') as f:
|
with lopen(os.path.join(self.location, 'order'), 'wb') as f:
|
||||||
f.write(data.encode('utf-8'))
|
f.write(data.encode('utf-8'))
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
self.log('Failed to save thumbnail cache order:', as_unicode(err))
|
self.log('Failed to save thumbnail cache order:', as_unicode(err))
|
||||||
|
|
||||||
def _read_order(self):
|
def _read_order(self):
|
||||||
@ -281,14 +281,14 @@ class ThumbnailCache:
|
|||||||
try:
|
try:
|
||||||
with open(path, 'wb') as f:
|
with open(path, 'wb') as f:
|
||||||
f.write(data)
|
f.write(data)
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
d = os.path.dirname(path)
|
d = os.path.dirname(path)
|
||||||
if not os.path.exists(d):
|
if not os.path.exists(d):
|
||||||
try:
|
try:
|
||||||
os.makedirs(d)
|
os.makedirs(d)
|
||||||
with open(path, 'wb') as f:
|
with open(path, 'wb') as f:
|
||||||
f.write(data)
|
f.write(data)
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
self.log('Failed to write cached thumbnail:', path, as_unicode(err))
|
self.log('Failed to write cached thumbnail:', path, as_unicode(err))
|
||||||
return self._apply_size()
|
return self._apply_size()
|
||||||
else:
|
else:
|
||||||
@ -326,7 +326,7 @@ class ThumbnailCache:
|
|||||||
if entry.thumbnail_size != self.thumbnail_size:
|
if entry.thumbnail_size != self.thumbnail_size:
|
||||||
try:
|
try:
|
||||||
os.remove(entry.path)
|
os.remove(entry.path)
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
if getattr(err, 'errno', None) != errno.ENOENT:
|
if getattr(err, 'errno', None) != errno.ENOENT:
|
||||||
self.log('Failed to remove cached thumbnail:', entry.path, as_unicode(err))
|
self.log('Failed to remove cached thumbnail:', entry.path, as_unicode(err))
|
||||||
self.total_size -= entry.size
|
self.total_size -= entry.size
|
||||||
@ -335,7 +335,7 @@ class ThumbnailCache:
|
|||||||
try:
|
try:
|
||||||
with open(entry.path, 'rb') as f:
|
with open(entry.path, 'rb') as f:
|
||||||
data = f.read()
|
data = f.read()
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
self.log('Failed to read cached thumbnail:', entry.path, as_unicode(err))
|
self.log('Failed to read cached thumbnail:', entry.path, as_unicode(err))
|
||||||
return None, None
|
return None, None
|
||||||
return data, entry.timestamp
|
return data, entry.timestamp
|
||||||
@ -350,7 +350,7 @@ class ThumbnailCache:
|
|||||||
raw = '\n'.join('%s %d' % (self.group_id, book_id) for book_id in book_ids)
|
raw = '\n'.join('%s %d' % (self.group_id, book_id) for book_id in book_ids)
|
||||||
with open(os.path.join(self.location, 'invalidate'), 'ab') as f:
|
with open(os.path.join(self.location, 'invalidate'), 'ab') as f:
|
||||||
f.write(raw.encode('ascii'))
|
f.write(raw.encode('ascii'))
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
self.log('Failed to write invalidate thumbnail record:', as_unicode(err))
|
self.log('Failed to write invalidate thumbnail record:', as_unicode(err))
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@ -364,7 +364,7 @@ class ThumbnailCache:
|
|||||||
with self.lock:
|
with self.lock:
|
||||||
try:
|
try:
|
||||||
os.remove(os.path.join(self.location, 'order'))
|
os.remove(os.path.join(self.location, 'order'))
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
if not hasattr(self, 'total_size'):
|
if not hasattr(self, 'total_size'):
|
||||||
self._load_index()
|
self._load_index()
|
||||||
|
@ -174,8 +174,7 @@ class View:
|
|||||||
yield TableRow(book_id, self)
|
yield TableRow(book_id, self)
|
||||||
|
|
||||||
def iterallids(self):
|
def iterallids(self):
|
||||||
for book_id in sorted(self._map):
|
yield from sorted(self._map)
|
||||||
yield book_id
|
|
||||||
|
|
||||||
def tablerow_for_id(self, book_id):
|
def tablerow_for_id(self, book_id):
|
||||||
return TableRow(book_id, self)
|
return TableRow(book_id, self)
|
||||||
@ -280,7 +279,7 @@ class View:
|
|||||||
def _build_restriction_string(self, restriction):
|
def _build_restriction_string(self, restriction):
|
||||||
if self.base_restriction:
|
if self.base_restriction:
|
||||||
if restriction:
|
if restriction:
|
||||||
return u'(%s) and (%s)' % (self.base_restriction, restriction)
|
return '(%s) and (%s)' % (self.base_restriction, restriction)
|
||||||
else:
|
else:
|
||||||
return self.base_restriction
|
return self.base_restriction
|
||||||
else:
|
else:
|
||||||
@ -296,7 +295,7 @@ class View:
|
|||||||
else:
|
else:
|
||||||
q = query
|
q = query
|
||||||
if search_restriction:
|
if search_restriction:
|
||||||
q = u'(%s) and (%s)' % (search_restriction, query)
|
q = '(%s) and (%s)' % (search_restriction, query)
|
||||||
if not q:
|
if not q:
|
||||||
if set_restriction_count:
|
if set_restriction_count:
|
||||||
self.search_restriction_book_count = len(self._map)
|
self.search_restriction_book_count = len(self._map)
|
||||||
@ -373,7 +372,7 @@ class View:
|
|||||||
old_marked_ids = set(self.marked_ids)
|
old_marked_ids = set(self.marked_ids)
|
||||||
if not hasattr(id_dict, 'items'):
|
if not hasattr(id_dict, 'items'):
|
||||||
# Simple list. Make it a dict of string 'true'
|
# Simple list. Make it a dict of string 'true'
|
||||||
self.marked_ids = dict.fromkeys(id_dict, u'true')
|
self.marked_ids = dict.fromkeys(id_dict, 'true')
|
||||||
else:
|
else:
|
||||||
# Ensure that all the items in the dict are text
|
# Ensure that all the items in the dict are text
|
||||||
self.marked_ids = {k: str(v) for k, v in iteritems(id_dict)}
|
self.marked_ids = {k: str(v) for k, v in iteritems(id_dict)}
|
||||||
|
@ -471,7 +471,7 @@ def many_many(book_id_val_map, db, field, allow_case_change, *args):
|
|||||||
)
|
)
|
||||||
db.executemany('DELETE FROM %s WHERE book=?'%table.link_table,
|
db.executemany('DELETE FROM %s WHERE book=?'%table.link_table,
|
||||||
((k,) for k in updated))
|
((k,) for k in updated))
|
||||||
db.executemany('INSERT INTO {0}(book,{1}) VALUES(?, ?)'.format(
|
db.executemany('INSERT INTO {}(book,{}) VALUES(?, ?)'.format(
|
||||||
table.link_table, m['link_column']), vals)
|
table.link_table, m['link_column']), vals)
|
||||||
if is_authors:
|
if is_authors:
|
||||||
aus_map = {book_id:field.author_sort_for_book(book_id) for book_id
|
aus_map = {book_id:field.author_sort_for_book(book_id) for book_id
|
||||||
|
@ -208,7 +208,7 @@ def print_basic_debug_info(out=None):
|
|||||||
from calibre.customize.ui import has_external_plugins, initialized_plugins
|
from calibre.customize.ui import has_external_plugins, initialized_plugins
|
||||||
if has_external_plugins():
|
if has_external_plugins():
|
||||||
from calibre.customize import PluginInstallationType
|
from calibre.customize import PluginInstallationType
|
||||||
names = ('{0} {1}'.format(p.name, p.version) for p in initialized_plugins()
|
names = ('{} {}'.format(p.name, p.version) for p in initialized_plugins()
|
||||||
if getattr(p, 'installation_type', None) is not PluginInstallationType.BUILTIN)
|
if getattr(p, 'installation_type', None) is not PluginInstallationType.BUILTIN)
|
||||||
out('Successfully initialized third party plugins:', ' && '.join(names))
|
out('Successfully initialized third party plugins:', ' && '.join(names))
|
||||||
|
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
||||||
|
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL 3'
|
__license__ = 'GPL 3'
|
||||||
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2011, Ken <ken at szboeye.com>'
|
__copyright__ = '2011, Ken <ken at szboeye.com>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
@ -301,7 +301,7 @@ def main():
|
|||||||
outfile = os.path.join(outfile, path[path.rfind("/")+1:])
|
outfile = os.path.join(outfile, path[path.rfind("/")+1:])
|
||||||
try:
|
try:
|
||||||
outfile = lopen(outfile, "wb")
|
outfile = lopen(outfile, "wb")
|
||||||
except IOError as e:
|
except OSError as e:
|
||||||
print(e, file=sys.stderr)
|
print(e, file=sys.stderr)
|
||||||
parser.print_help()
|
parser.print_help()
|
||||||
return 1
|
return 1
|
||||||
@ -311,7 +311,7 @@ def main():
|
|||||||
elif args[1].startswith("dev:"):
|
elif args[1].startswith("dev:"):
|
||||||
try:
|
try:
|
||||||
infile = lopen(args[0], "rb")
|
infile = lopen(args[0], "rb")
|
||||||
except IOError as e:
|
except OSError as e:
|
||||||
print(e, file=sys.stderr)
|
print(e, file=sys.stderr)
|
||||||
parser.print_help()
|
parser.print_help()
|
||||||
return 1
|
return 1
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2009, John Schember <john at nachtimwald.com>'
|
__copyright__ = '2009, John Schember <john at nachtimwald.com>'
|
||||||
'''
|
'''
|
||||||
|
@ -1 +0,0 @@
|
|||||||
|
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
||||||
"""
|
"""
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
'''
|
'''
|
||||||
Created on 15 May 2010
|
Created on 15 May 2010
|
||||||
|
|
||||||
@ -63,7 +61,7 @@ class FOLDER_DEVICE(USBMS):
|
|||||||
|
|
||||||
def __init__(self, path):
|
def __init__(self, path):
|
||||||
if not os.path.isdir(path):
|
if not os.path.isdir(path):
|
||||||
raise IOError('Path is not a folder')
|
raise OSError('Path is not a folder')
|
||||||
path = USBMS.normalize_path(path)
|
path = USBMS.normalize_path(path)
|
||||||
if path.endswith(os.sep):
|
if path.endswith(os.sep):
|
||||||
self._main_prefix = path
|
self._main_prefix = path
|
||||||
|
@ -1,4 +1,2 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2009, Tijmen Ruizendaal <tijmen at mybebook.com>'
|
__copyright__ = '2009, Tijmen Ruizendaal <tijmen at mybebook.com>'
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
||||||
import os
|
import os
|
||||||
|
@ -1 +0,0 @@
|
|||||||
|
|
@ -154,7 +154,7 @@ class Bookmark(): # {{{
|
|||||||
split = my_clippings.find('documents') + len('documents/')
|
split = my_clippings.find('documents') + len('documents/')
|
||||||
my_clippings = my_clippings[:split] + "My Clippings.txt"
|
my_clippings = my_clippings[:split] + "My Clippings.txt"
|
||||||
try:
|
try:
|
||||||
with io.open(my_clippings, encoding='utf-8', errors='replace') as f2:
|
with open(my_clippings, encoding='utf-8', errors='replace') as f2:
|
||||||
marker_found = 0
|
marker_found = 0
|
||||||
text = ''
|
text = ''
|
||||||
search_str1 = '%s' % (mi.title)
|
search_str1 = '%s' % (mi.title)
|
||||||
|
@ -232,7 +232,7 @@ class KINDLE(USBMS):
|
|||||||
pr=percent_read)
|
pr=percent_read)
|
||||||
else:
|
else:
|
||||||
markup = _("%(time)s<br />Last page read: Location %(loc)d (%(pr)d%%)") % dict(
|
markup = _("%(time)s<br />Last page read: Location %(loc)d (%(pr)d%%)") % dict(
|
||||||
time=strftime(u'%x', timestamp.timetuple()),
|
time=strftime('%x', timestamp.timetuple()),
|
||||||
loc=last_read_location,
|
loc=last_read_location,
|
||||||
pr=percent_read)
|
pr=percent_read)
|
||||||
spanTag = BeautifulSoup('<span style="font-weight:bold">' + markup + '</span>').find('span')
|
spanTag = BeautifulSoup('<span style="font-weight:bold">' + markup + '</span>').find('span')
|
||||||
@ -313,7 +313,7 @@ class KINDLE(USBMS):
|
|||||||
bm.value.path, index_is_id=True)
|
bm.value.path, index_is_id=True)
|
||||||
elif bm.type == 'kindle_clippings':
|
elif bm.type == 'kindle_clippings':
|
||||||
# Find 'My Clippings' author=Kindle in database, or add
|
# Find 'My Clippings' author=Kindle in database, or add
|
||||||
last_update = 'Last modified %s' % strftime(u'%x %X',bm.value['timestamp'].timetuple())
|
last_update = 'Last modified %s' % strftime('%x %X',bm.value['timestamp'].timetuple())
|
||||||
mc_id = list(db.data.search_getting_ids('title:"My Clippings"', '', sort_results=False))
|
mc_id = list(db.data.search_getting_ids('title:"My Clippings"', '', sort_results=False))
|
||||||
if mc_id:
|
if mc_id:
|
||||||
db.add_format_with_hooks(mc_id[0], 'TXT', bm.value['path'],
|
db.add_format_with_hooks(mc_id[0], 'TXT', bm.value['path'],
|
||||||
@ -524,7 +524,7 @@ class KINDLE2(KINDLE):
|
|||||||
cache_dir = self.amazon_cover_bug_cache_dir()
|
cache_dir = self.amazon_cover_bug_cache_dir()
|
||||||
try:
|
try:
|
||||||
os.mkdir(cache_dir)
|
os.mkdir(cache_dir)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
with lopen(os.path.join(cache_dir, os.path.basename(tp)), 'wb') as f:
|
with lopen(os.path.join(cache_dir, os.path.basename(tp)), 'wb') as f:
|
||||||
f.write(coverdata[2])
|
f.write(coverdata[2])
|
||||||
@ -545,7 +545,7 @@ class KINDLE2(KINDLE):
|
|||||||
dest_path = os.path.join(dest_dir, name)
|
dest_path = os.path.join(dest_dir, name)
|
||||||
try:
|
try:
|
||||||
dest_stat_result = os.lstat(dest_path)
|
dest_stat_result = os.lstat(dest_path)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
needs_sync = True
|
needs_sync = True
|
||||||
else:
|
else:
|
||||||
needs_sync = src_stat_result.st_size != dest_stat_result.st_size
|
needs_sync = src_stat_result.st_size != dest_stat_result.st_size
|
||||||
@ -567,7 +567,7 @@ class KINDLE2(KINDLE):
|
|||||||
for tp in (tp1, tp2):
|
for tp in (tp1, tp2):
|
||||||
try:
|
try:
|
||||||
os.remove(tp)
|
os.remove(tp)
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
if err.errno != errno.ENOENT:
|
if err.errno != errno.ENOENT:
|
||||||
prints('Failed to delete thumbnail for {!r} at {!r} with error: {}'.format(path, tp, err))
|
prints('Failed to delete thumbnail for {!r} at {!r} with error: {}'.format(path, tp, err))
|
||||||
except Exception:
|
except Exception:
|
||||||
|
@ -57,7 +57,7 @@ class Bookmark(): # {{{
|
|||||||
'ORDER BY bm.ContentID, bm.chapterprogress'
|
'ORDER BY bm.ContentID, bm.chapterprogress'
|
||||||
)
|
)
|
||||||
|
|
||||||
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub chapters: contentId={0}".format(self.contentId))
|
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub chapters: contentId={}".format(self.contentId))
|
||||||
cursor.execute(kepub_chapter_query, book_query_values)
|
cursor.execute(kepub_chapter_query, book_query_values)
|
||||||
kepub_chapters = {}
|
kepub_chapters = {}
|
||||||
if self.kepub:
|
if self.kepub:
|
||||||
@ -69,7 +69,7 @@ class Bookmark(): # {{{
|
|||||||
'chapter_title': chapter_row['Title'],
|
'chapter_title': chapter_row['Title'],
|
||||||
'chapter_index': chapter_row['VolumeIndex']
|
'chapter_index': chapter_row['VolumeIndex']
|
||||||
}
|
}
|
||||||
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub chapter: kepub chapters={0}".format(kepub_chapters))
|
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub chapter: kepub chapters={}".format(kepub_chapters))
|
||||||
except:
|
except:
|
||||||
debug_print("Kobo::Bookmark::get_bookmark_data - No chapters found")
|
debug_print("Kobo::Bookmark::get_bookmark_data - No chapters found")
|
||||||
|
|
||||||
@ -83,20 +83,20 @@ class Bookmark(): # {{{
|
|||||||
# For kepubs on newer firmware, the title needs to come from an 899 row.
|
# For kepubs on newer firmware, the title needs to come from an 899 row.
|
||||||
if self.kepub:
|
if self.kepub:
|
||||||
chapter_contentID = row['ContentID']
|
chapter_contentID = row['ContentID']
|
||||||
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub: chapter chapter_contentID='{0}'".format(chapter_contentID))
|
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub: chapter chapter_contentID='{}'".format(chapter_contentID))
|
||||||
filename_index = chapter_contentID.find('!')
|
filename_index = chapter_contentID.find('!')
|
||||||
book_contentID_part = chapter_contentID[:filename_index]
|
book_contentID_part = chapter_contentID[:filename_index]
|
||||||
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub: chapter book_contentID_part='{0}'".format(book_contentID_part))
|
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub: chapter book_contentID_part='{}'".format(book_contentID_part))
|
||||||
file_contentID_part = chapter_contentID[filename_index + 1:]
|
file_contentID_part = chapter_contentID[filename_index + 1:]
|
||||||
filename_index = file_contentID_part.find('!')
|
filename_index = file_contentID_part.find('!')
|
||||||
opf_reference = file_contentID_part[:filename_index]
|
opf_reference = file_contentID_part[:filename_index]
|
||||||
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub: chapter opf_reference='{0}'".format(opf_reference))
|
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub: chapter opf_reference='{}'".format(opf_reference))
|
||||||
file_contentID_part = file_contentID_part[filename_index + 1:]
|
file_contentID_part = file_contentID_part[filename_index + 1:]
|
||||||
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub: chapter file_contentID_part='{0}'".format(file_contentID_part))
|
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub: chapter file_contentID_part='{}'".format(file_contentID_part))
|
||||||
# from urllib import quote
|
# from urllib import quote
|
||||||
# file_contentID_part = quote(file_contentID_part)
|
# file_contentID_part = quote(file_contentID_part)
|
||||||
chapter_contentID = book_contentID_part + "!" + opf_reference + "!" + file_contentID_part
|
chapter_contentID = book_contentID_part + "!" + opf_reference + "!" + file_contentID_part
|
||||||
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub chapter chapter_contentID='{0}'".format(chapter_contentID))
|
debug_print("Kobo::Bookmark::get_bookmark_data - getting kepub chapter chapter_contentID='{}'".format(chapter_contentID))
|
||||||
kepub_chapter = kepub_chapters.get(chapter_contentID, None)
|
kepub_chapter = kepub_chapters.get(chapter_contentID, None)
|
||||||
if kepub_chapter is not None:
|
if kepub_chapter is not None:
|
||||||
chapter_title = kepub_chapter['chapter_title']
|
chapter_title = kepub_chapter['chapter_title']
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2010-2012, , Timothy Legge <timlegge at gmail.com> and David Forrester <davidfor@internode.on.net>'
|
__copyright__ = '2010-2012, , Timothy Legge <timlegge at gmail.com> and David Forrester <davidfor@internode.on.net>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
@ -29,7 +28,7 @@ class Book(Book_):
|
|||||||
if show_debug:
|
if show_debug:
|
||||||
debug_print("Book::__init__ - title=", title, 'authors=', authors)
|
debug_print("Book::__init__ - title=", title, 'authors=', authors)
|
||||||
debug_print("Book::__init__ - other=", other)
|
debug_print("Book::__init__ - other=", other)
|
||||||
super(Book, self).__init__(prefix, lpath, size, other)
|
super().__init__(prefix, lpath, size, other)
|
||||||
|
|
||||||
if title is not None and len(title) > 0:
|
if title is not None and len(title) > 0:
|
||||||
self.title = title
|
self.title = title
|
||||||
@ -117,7 +116,7 @@ class Book(Book_):
|
|||||||
|
|
||||||
ans = '\n'.join(ans)
|
ans = '\n'.join(ans)
|
||||||
|
|
||||||
return super(Book,self).__str__() + "\n" + ans
|
return super().__str__() + "\n" + ans
|
||||||
|
|
||||||
|
|
||||||
class ImageWrapper:
|
class ImageWrapper:
|
||||||
@ -129,7 +128,7 @@ class ImageWrapper:
|
|||||||
class KTCollectionsBookList(CollectionsBookList):
|
class KTCollectionsBookList(CollectionsBookList):
|
||||||
|
|
||||||
def __init__(self, oncard, prefix, settings):
|
def __init__(self, oncard, prefix, settings):
|
||||||
super(KTCollectionsBookList, self).__init__(oncard, prefix, settings)
|
super().__init__(oncard, prefix, settings)
|
||||||
self.set_device_managed_collections([])
|
self.set_device_managed_collections([])
|
||||||
|
|
||||||
def get_collections(self, collection_attributes):
|
def get_collections(self, collection_attributes):
|
||||||
|
@ -203,7 +203,7 @@ class KOBO(USBMS):
|
|||||||
try:
|
try:
|
||||||
with lopen(self.normalize_path(self._main_prefix + '.kobo/version'), 'rb') as f:
|
with lopen(self.normalize_path(self._main_prefix + '.kobo/version'), 'rb') as f:
|
||||||
fwversion = f.readline().split(b',')[2]
|
fwversion = f.readline().split(b',')[2]
|
||||||
fwversion = tuple((int(x) for x in fwversion.split(b'.')))
|
fwversion = tuple(int(x) for x in fwversion.split(b'.'))
|
||||||
except Exception:
|
except Exception:
|
||||||
debug_print("Kobo::get_firmware_version - didn't get firmware version from file'")
|
debug_print("Kobo::get_firmware_version - didn't get firmware version from file'")
|
||||||
fwversion = (0,0,0)
|
fwversion = (0,0,0)
|
||||||
@ -1138,7 +1138,7 @@ class KOBO(USBMS):
|
|||||||
|
|
||||||
def get_annotations(self, path_map):
|
def get_annotations(self, path_map):
|
||||||
from calibre.devices.kobo.bookmark import Bookmark
|
from calibre.devices.kobo.bookmark import Bookmark
|
||||||
EPUB_FORMATS = [u'epub']
|
EPUB_FORMATS = ['epub']
|
||||||
epub_formats = set(EPUB_FORMATS)
|
epub_formats = set(EPUB_FORMATS)
|
||||||
|
|
||||||
def get_storage():
|
def get_storage():
|
||||||
@ -1519,21 +1519,21 @@ class KOBOTOUCH(KOBO):
|
|||||||
self.plugboards = self.plugboard_func = None
|
self.plugboards = self.plugboard_func = None
|
||||||
|
|
||||||
def initialize(self):
|
def initialize(self):
|
||||||
super(KOBOTOUCH, self).initialize()
|
super().initialize()
|
||||||
self.bookshelvelist = []
|
self.bookshelvelist = []
|
||||||
|
|
||||||
def get_device_information(self, end_session=True):
|
def get_device_information(self, end_session=True):
|
||||||
self.set_device_name()
|
self.set_device_name()
|
||||||
return super(KOBOTOUCH, self).get_device_information(end_session)
|
return super().get_device_information(end_session)
|
||||||
|
|
||||||
def open_linux(self):
|
def open_linux(self):
|
||||||
super(KOBOTOUCH, self).open_linux()
|
super().open_linux()
|
||||||
|
|
||||||
self.swap_drives_if_needed()
|
self.swap_drives_if_needed()
|
||||||
|
|
||||||
def open_osx(self):
|
def open_osx(self):
|
||||||
# Just dump some info to the logs.
|
# Just dump some info to the logs.
|
||||||
super(KOBOTOUCH, self).open_osx()
|
super().open_osx()
|
||||||
|
|
||||||
# Wrap some debugging output in a try/except so that it is unlikely to break things completely.
|
# Wrap some debugging output in a try/except so that it is unlikely to break things completely.
|
||||||
try:
|
try:
|
||||||
@ -2049,7 +2049,7 @@ class KOBOTOUCH(KOBO):
|
|||||||
path = ContentID
|
path = ContentID
|
||||||
|
|
||||||
if not externalId:
|
if not externalId:
|
||||||
return super(KOBOTOUCH, self).path_from_contentid(ContentID, ContentType, MimeType, oncard)
|
return super().path_from_contentid(ContentID, ContentType, MimeType, oncard)
|
||||||
|
|
||||||
if oncard == 'cardb':
|
if oncard == 'cardb':
|
||||||
print('path from_contentid cardb')
|
print('path from_contentid cardb')
|
||||||
@ -2099,13 +2099,13 @@ class KOBOTOUCH(KOBO):
|
|||||||
from css_parser import parseFile as cssparseFile
|
from css_parser import parseFile as cssparseFile
|
||||||
try:
|
try:
|
||||||
extra_sheet = cssparseFile(extra_css_path)
|
extra_sheet = cssparseFile(extra_css_path)
|
||||||
debug_print("KoboTouch:get_extra_css: Using extra CSS in {0} ({1} rules)".format(extra_css_path, len(extra_sheet.cssRules)))
|
debug_print("KoboTouch:get_extra_css: Using extra CSS in {} ({} rules)".format(extra_css_path, len(extra_sheet.cssRules)))
|
||||||
if len(extra_sheet.cssRules) ==0:
|
if len(extra_sheet.cssRules) ==0:
|
||||||
debug_print("KoboTouch:get_extra_css: Extra CSS file has no valid rules. CSS will not be modified.")
|
debug_print("KoboTouch:get_extra_css: Extra CSS file has no valid rules. CSS will not be modified.")
|
||||||
extra_sheet = None
|
extra_sheet = None
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
debug_print("KoboTouch:get_extra_css: Problem parsing extra CSS file {0}".format(extra_css_path))
|
debug_print("KoboTouch:get_extra_css: Problem parsing extra CSS file {}".format(extra_css_path))
|
||||||
debug_print("KoboTouch:get_extra_css: Exception {0}".format(e))
|
debug_print("KoboTouch:get_extra_css: Exception {}".format(e))
|
||||||
|
|
||||||
# create dictionary of features enabled in kobo extra css
|
# create dictionary of features enabled in kobo extra css
|
||||||
self.extra_css_options = {}
|
self.extra_css_options = {}
|
||||||
@ -2136,16 +2136,16 @@ class KOBOTOUCH(KOBO):
|
|||||||
self.extra_sheet = self.get_extra_css()
|
self.extra_sheet = self.get_extra_css()
|
||||||
i = 0
|
i = 0
|
||||||
for file, n, mi in zip(files, names, metadata):
|
for file, n, mi in zip(files, names, metadata):
|
||||||
debug_print("KoboTouch:upload_books: Processing book: {0} by {1}".format(mi.title, " and ".join(mi.authors)))
|
debug_print("KoboTouch:upload_books: Processing book: {} by {}".format(mi.title, " and ".join(mi.authors)))
|
||||||
debug_print("KoboTouch:upload_books: file=%s, name=%s" % (file, n))
|
debug_print("KoboTouch:upload_books: file=%s, name=%s" % (file, n))
|
||||||
self.report_progress(i / float(len(files)), "Processing book: {0} by {1}".format(mi.title, " and ".join(mi.authors)))
|
self.report_progress(i / float(len(files)), "Processing book: {} by {}".format(mi.title, " and ".join(mi.authors)))
|
||||||
mi.kte_calibre_name = n
|
mi.kte_calibre_name = n
|
||||||
self._modify_epub(file, mi)
|
self._modify_epub(file, mi)
|
||||||
i += 1
|
i += 1
|
||||||
|
|
||||||
self.report_progress(0, 'Working...')
|
self.report_progress(0, 'Working...')
|
||||||
|
|
||||||
result = super(KOBOTOUCH, self).upload_books(files, names, on_card, end_session, metadata)
|
result = super().upload_books(files, names, on_card, end_session, metadata)
|
||||||
# debug_print('KoboTouch:upload_books - result=', result)
|
# debug_print('KoboTouch:upload_books - result=', result)
|
||||||
|
|
||||||
if self.dbversion >= 53:
|
if self.dbversion >= 53:
|
||||||
@ -2179,7 +2179,7 @@ class KOBOTOUCH(KOBO):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
def _modify_epub(self, book_file, metadata, container=None):
|
def _modify_epub(self, book_file, metadata, container=None):
|
||||||
debug_print("KoboTouch:_modify_epub:Processing {0} - {1}".format(metadata.author_sort, metadata.title))
|
debug_print("KoboTouch:_modify_epub:Processing {} - {}".format(metadata.author_sort, metadata.title))
|
||||||
|
|
||||||
# Currently only modifying CSS, so if no stylesheet, don't do anything
|
# Currently only modifying CSS, so if no stylesheet, don't do anything
|
||||||
if not self.extra_sheet:
|
if not self.extra_sheet:
|
||||||
@ -2200,9 +2200,9 @@ class KOBOTOUCH(KOBO):
|
|||||||
|
|
||||||
# future css mods may be epub/kepub specific, so pass file extension arg
|
# future css mods may be epub/kepub specific, so pass file extension arg
|
||||||
fileext = os.path.splitext(book_file)[-1].lower()
|
fileext = os.path.splitext(book_file)[-1].lower()
|
||||||
debug_print("KoboTouch:_modify_epub: Modifying {0}".format(cssname))
|
debug_print("KoboTouch:_modify_epub: Modifying {}".format(cssname))
|
||||||
if self._modify_stylesheet(newsheet, fileext):
|
if self._modify_stylesheet(newsheet, fileext):
|
||||||
debug_print("KoboTouch:_modify_epub:CSS rules {0} -> {1} ({2})".format(oldrules, len(newsheet.cssRules), cssname))
|
debug_print("KoboTouch:_modify_epub:CSS rules {} -> {} ({})".format(oldrules, len(newsheet.cssRules), cssname))
|
||||||
container.dirty(cssname)
|
container.dirty(cssname)
|
||||||
is_dirty = True
|
is_dirty = True
|
||||||
|
|
||||||
@ -2256,8 +2256,8 @@ class KOBOTOUCH(KOBO):
|
|||||||
container = get_container(book_file)
|
container = get_container(book_file)
|
||||||
container.css_preprocessor = DummyCSSPreProcessor()
|
container.css_preprocessor = DummyCSSPreProcessor()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
debug_print("KoboTouch:create_container: exception from get_container {0} - {1}".format(metadata.author_sort, metadata.title))
|
debug_print("KoboTouch:create_container: exception from get_container {} - {}".format(metadata.author_sort, metadata.title))
|
||||||
debug_print("KoboTouch:create_container: exception is: {0}".format(e))
|
debug_print("KoboTouch:create_container: exception is: {}".format(e))
|
||||||
else:
|
else:
|
||||||
commit_container = False
|
commit_container = False
|
||||||
debug_print("KoboTouch:create_container: received container")
|
debug_print("KoboTouch:create_container: received container")
|
||||||
@ -2277,7 +2277,7 @@ class KOBOTOUCH(KOBO):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
def delete_via_sql(self, ContentID, ContentType):
|
def delete_via_sql(self, ContentID, ContentType):
|
||||||
imageId = super(KOBOTOUCH, self).delete_via_sql(ContentID, ContentType)
|
imageId = super().delete_via_sql(ContentID, ContentType)
|
||||||
|
|
||||||
if self.dbversion >= 53:
|
if self.dbversion >= 53:
|
||||||
debug_print('KoboTouch:delete_via_sql: ContentID="%s"'%ContentID, 'ContentType="%s"'%ContentType)
|
debug_print('KoboTouch:delete_via_sql: ContentID="%s"'%ContentID, 'ContentType="%s"'%ContentType)
|
||||||
@ -2383,7 +2383,7 @@ class KOBOTOUCH(KOBO):
|
|||||||
def get_content_type_from_path(self, path):
|
def get_content_type_from_path(self, path):
|
||||||
ContentType = 6
|
ContentType = 6
|
||||||
if self.fwversion < (1, 9, 17):
|
if self.fwversion < (1, 9, 17):
|
||||||
ContentType = super(KOBOTOUCH, self).get_content_type_from_path(path)
|
ContentType = super().get_content_type_from_path(path)
|
||||||
return ContentType
|
return ContentType
|
||||||
|
|
||||||
def get_content_type_from_extension(self, extension):
|
def get_content_type_from_extension(self, extension):
|
||||||
@ -2391,7 +2391,7 @@ class KOBOTOUCH(KOBO):
|
|||||||
# With new firmware, ContentType appears to be 6 for all types of sideloaded books.
|
# With new firmware, ContentType appears to be 6 for all types of sideloaded books.
|
||||||
ContentType = 6
|
ContentType = 6
|
||||||
if self.fwversion < (1,9,17):
|
if self.fwversion < (1,9,17):
|
||||||
ContentType = super(KOBOTOUCH, self).get_content_type_from_extension(extension)
|
ContentType = super().get_content_type_from_extension(extension)
|
||||||
return ContentType
|
return ContentType
|
||||||
|
|
||||||
def set_plugboards(self, plugboards, pb_func):
|
def set_plugboards(self, plugboards, pb_func):
|
||||||
@ -3329,7 +3329,7 @@ class KOBOTOUCH(KOBO):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _config(cls):
|
def _config(cls):
|
||||||
c = super(KOBOTOUCH, cls)._config()
|
c = super()._config()
|
||||||
|
|
||||||
c.add_opt('manage_collections', default=True)
|
c.add_opt('manage_collections', default=True)
|
||||||
c.add_opt('collections_columns', default='')
|
c.add_opt('collections_columns', default='')
|
||||||
@ -3819,7 +3819,7 @@ class KOBOTOUCH(KOBO):
|
|||||||
try:
|
try:
|
||||||
is_debugging = len(self.debugging_title) > 0 and title.lower().find(self.debugging_title.lower()) >= 0 or len(title) == 0
|
is_debugging = len(self.debugging_title) > 0 and title.lower().find(self.debugging_title.lower()) >= 0 or len(title) == 0
|
||||||
except:
|
except:
|
||||||
debug_print(("KoboTouch::is_debugging_title - Exception checking debugging title for title '{0}'.").format(title))
|
debug_print(("KoboTouch::is_debugging_title - Exception checking debugging title for title '{}'.").format(title))
|
||||||
is_debugging = False
|
is_debugging = False
|
||||||
|
|
||||||
return is_debugging
|
return is_debugging
|
||||||
@ -3864,7 +3864,7 @@ class KOBOTOUCH(KOBO):
|
|||||||
|
|
||||||
def __str__(self, *args, **kwargs):
|
def __str__(self, *args, **kwargs):
|
||||||
options = ', '.join(['%s: %s' % (x.name, self.get_pref(x.name)) for x in self._config().preferences])
|
options = ', '.join(['%s: %s' % (x.name, self.get_pref(x.name)) for x in self._config().preferences])
|
||||||
return u"Driver:%s, Options - %s" % (self.name, options)
|
return "Driver:%s, Options - %s" % (self.name, options)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
@ -39,7 +39,7 @@ class KOBOTOUCHConfig(TabbedDeviceConfig):
|
|||||||
must_read_metadata, supports_use_author_sort,
|
must_read_metadata, supports_use_author_sort,
|
||||||
extra_customization_message, device, extra_customization_choices=None, parent=None):
|
extra_customization_message, device, extra_customization_choices=None, parent=None):
|
||||||
|
|
||||||
super(KOBOTOUCHConfig, self).__init__(device_settings, all_formats, supports_subdirs,
|
super().__init__(device_settings, all_formats, supports_subdirs,
|
||||||
must_read_metadata, supports_use_author_sort,
|
must_read_metadata, supports_use_author_sort,
|
||||||
extra_customization_message, device, extra_customization_choices, parent)
|
extra_customization_message, device, extra_customization_choices, parent)
|
||||||
|
|
||||||
@ -65,7 +65,7 @@ class KOBOTOUCHConfig(TabbedDeviceConfig):
|
|||||||
return self._device()
|
return self._device()
|
||||||
|
|
||||||
def validate(self):
|
def validate(self):
|
||||||
validated = super(KOBOTOUCHConfig, self).validate()
|
validated = super().validate()
|
||||||
validated &= self.tab2.validate()
|
validated &= self.tab2.validate()
|
||||||
return validated
|
return validated
|
||||||
|
|
||||||
@ -95,7 +95,7 @@ class KOBOTOUCHConfig(TabbedDeviceConfig):
|
|||||||
|
|
||||||
def commit(self):
|
def commit(self):
|
||||||
debug_print("KOBOTOUCHConfig::commit: start")
|
debug_print("KOBOTOUCHConfig::commit: start")
|
||||||
p = super(KOBOTOUCHConfig, self).commit()
|
p = super().commit()
|
||||||
|
|
||||||
p['manage_collections'] = self.manage_collections
|
p['manage_collections'] = self.manage_collections
|
||||||
p['create_collections'] = self.create_collections
|
p['create_collections'] = self.create_collections
|
||||||
@ -135,7 +135,7 @@ class KOBOTOUCHConfig(TabbedDeviceConfig):
|
|||||||
class Tab1Config(DeviceConfigTab): # {{{
|
class Tab1Config(DeviceConfigTab): # {{{
|
||||||
|
|
||||||
def __init__(self, parent, device):
|
def __init__(self, parent, device):
|
||||||
super(Tab1Config, self).__init__(parent)
|
super().__init__(parent)
|
||||||
|
|
||||||
self.l = QVBoxLayout(self)
|
self.l = QVBoxLayout(self)
|
||||||
self.setLayout(self.l)
|
self.setLayout(self.l)
|
||||||
@ -159,7 +159,7 @@ class Tab1Config(DeviceConfigTab): # {{{
|
|||||||
class Tab2Config(DeviceConfigTab): # {{{
|
class Tab2Config(DeviceConfigTab): # {{{
|
||||||
|
|
||||||
def __init__(self, parent, device):
|
def __init__(self, parent, device):
|
||||||
super(Tab2Config, self).__init__(parent)
|
super().__init__(parent)
|
||||||
|
|
||||||
self.l = QVBoxLayout(self)
|
self.l = QVBoxLayout(self)
|
||||||
self.setLayout(self.l)
|
self.setLayout(self.l)
|
||||||
@ -187,7 +187,7 @@ class Tab2Config(DeviceConfigTab): # {{{
|
|||||||
class BookUploadsGroupBox(DeviceOptionsGroupBox):
|
class BookUploadsGroupBox(DeviceOptionsGroupBox):
|
||||||
|
|
||||||
def __init__(self, parent, device):
|
def __init__(self, parent, device):
|
||||||
super(BookUploadsGroupBox, self).__init__(parent, device)
|
super().__init__(parent, device)
|
||||||
self.setTitle(_("Uploading of books"))
|
self.setTitle(_("Uploading of books"))
|
||||||
|
|
||||||
self.options_layout = QGridLayout()
|
self.options_layout = QGridLayout()
|
||||||
@ -229,7 +229,7 @@ class BookUploadsGroupBox(DeviceOptionsGroupBox):
|
|||||||
class CollectionsGroupBox(DeviceOptionsGroupBox):
|
class CollectionsGroupBox(DeviceOptionsGroupBox):
|
||||||
|
|
||||||
def __init__(self, parent, device):
|
def __init__(self, parent, device):
|
||||||
super(CollectionsGroupBox, self).__init__(parent, device)
|
super().__init__(parent, device)
|
||||||
self.setTitle(_("Collections"))
|
self.setTitle(_("Collections"))
|
||||||
|
|
||||||
self.options_layout = QGridLayout()
|
self.options_layout = QGridLayout()
|
||||||
@ -296,7 +296,7 @@ class CollectionsGroupBox(DeviceOptionsGroupBox):
|
|||||||
class CoversGroupBox(DeviceOptionsGroupBox):
|
class CoversGroupBox(DeviceOptionsGroupBox):
|
||||||
|
|
||||||
def __init__(self, parent, device):
|
def __init__(self, parent, device):
|
||||||
super(CoversGroupBox, self).__init__(parent, device)
|
super().__init__(parent, device)
|
||||||
self.setTitle(_("Upload covers"))
|
self.setTitle(_("Upload covers"))
|
||||||
|
|
||||||
self.options_layout = QGridLayout()
|
self.options_layout = QGridLayout()
|
||||||
@ -415,7 +415,7 @@ class CoversGroupBox(DeviceOptionsGroupBox):
|
|||||||
class DeviceListGroupBox(DeviceOptionsGroupBox):
|
class DeviceListGroupBox(DeviceOptionsGroupBox):
|
||||||
|
|
||||||
def __init__(self, parent, device):
|
def __init__(self, parent, device):
|
||||||
super(DeviceListGroupBox, self).__init__(parent, device)
|
super().__init__(parent, device)
|
||||||
self.setTitle(_("Show as on device"))
|
self.setTitle(_("Show as on device"))
|
||||||
|
|
||||||
self.options_layout = QGridLayout()
|
self.options_layout = QGridLayout()
|
||||||
@ -465,7 +465,7 @@ class DeviceListGroupBox(DeviceOptionsGroupBox):
|
|||||||
class AdvancedGroupBox(DeviceOptionsGroupBox):
|
class AdvancedGroupBox(DeviceOptionsGroupBox):
|
||||||
|
|
||||||
def __init__(self, parent, device):
|
def __init__(self, parent, device):
|
||||||
super(AdvancedGroupBox, self).__init__(parent, device, _("Advanced options"))
|
super().__init__(parent, device, _("Advanced options"))
|
||||||
# self.setTitle(_("Advanced Options"))
|
# self.setTitle(_("Advanced Options"))
|
||||||
|
|
||||||
self.options_layout = QGridLayout()
|
self.options_layout = QGridLayout()
|
||||||
@ -514,7 +514,7 @@ class AdvancedGroupBox(DeviceOptionsGroupBox):
|
|||||||
class MetadataGroupBox(DeviceOptionsGroupBox):
|
class MetadataGroupBox(DeviceOptionsGroupBox):
|
||||||
|
|
||||||
def __init__(self, parent, device):
|
def __init__(self, parent, device):
|
||||||
super(MetadataGroupBox, self).__init__(parent, device)
|
super().__init__(parent, device)
|
||||||
self.setTitle(_("Update metadata on the device"))
|
self.setTitle(_("Update metadata on the device"))
|
||||||
|
|
||||||
self.options_layout = QGridLayout()
|
self.options_layout = QGridLayout()
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
__license__ = 'GPL 3'
|
__license__ = 'GPL 3'
|
||||||
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
@ -46,7 +46,7 @@ class Book(Metadata):
|
|||||||
Metadata.__init__(self, _('Unknown'), other=other)
|
Metadata.__init__(self, _('Unknown'), other=other)
|
||||||
self.storage_id, self.lpath = storage_id, lpath
|
self.storage_id, self.lpath = storage_id, lpath
|
||||||
self.lpath = self.path = self.lpath.replace(os.sep, '/')
|
self.lpath = self.path = self.lpath.replace(os.sep, '/')
|
||||||
self.mtp_relpath = tuple([icu_lower(x) for x in self.lpath.split('/')])
|
self.mtp_relpath = tuple(icu_lower(x) for x in self.lpath.split('/'))
|
||||||
self.datetime = utcnow().timetuple()
|
self.datetime = utcnow().timetuple()
|
||||||
self.thumbail = None
|
self.thumbail = None
|
||||||
|
|
||||||
|
@ -108,10 +108,8 @@ class FileOrFolder:
|
|||||||
return tuple(parts)
|
return tuple(parts)
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
for e in self.folders:
|
yield from self.folders
|
||||||
yield e
|
yield from self.files
|
||||||
for e in self.files:
|
|
||||||
yield e
|
|
||||||
|
|
||||||
def add_child(self, entry):
|
def add_child(self, entry):
|
||||||
ans = FileOrFolder(entry, self.fs_cache())
|
ans = FileOrFolder(entry, self.fs_cache())
|
||||||
|
@ -75,7 +75,7 @@ class MTP_DEVICE(MTPDeviceBase):
|
|||||||
traceback.print_stack()
|
traceback.print_stack()
|
||||||
return False
|
return False
|
||||||
if debug is not None and ans:
|
if debug is not None and ans:
|
||||||
debug('Device {0} claims to be an MTP device in the IOKit registry'.format(d))
|
debug('Device {} claims to be an MTP device in the IOKit registry'.format(d))
|
||||||
return bool(ans)
|
return bool(ans)
|
||||||
|
|
||||||
def set_debug_level(self, lvl):
|
def set_debug_level(self, lvl):
|
||||||
|
@ -31,7 +31,7 @@ class MTPDetect:
|
|||||||
try:
|
try:
|
||||||
with lopen(x, 'rb') as f:
|
with lopen(x, 'rb') as f:
|
||||||
return f.read()
|
return f.read()
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
ipath = os.path.join(self.base, '{0}-*/{0}-*/interface'.format(dev.busnum))
|
ipath = os.path.join(self.base, '{0}-*/{0}-*/interface'.format(dev.busnum))
|
||||||
@ -44,7 +44,7 @@ class MTPDetect:
|
|||||||
try:
|
try:
|
||||||
if raw and int(raw) == dev.devnum:
|
if raw and int(raw) == dev.devnum:
|
||||||
if debug is not None:
|
if debug is not None:
|
||||||
debug('Unknown device {0} claims to be an MTP device'
|
debug('Unknown device {} claims to be an MTP device'
|
||||||
.format(dev))
|
.format(dev))
|
||||||
return True
|
return True
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
|
@ -111,7 +111,7 @@ class NOOK_COLOR(NOOK):
|
|||||||
self.EBOOK_DIR_MAIN = 'NOOK/My Files'
|
self.EBOOK_DIR_MAIN = 'NOOK/My Files'
|
||||||
try:
|
try:
|
||||||
os.makedirs(os.path.join(self._main_prefix, *self.EBOOK_DIR_MAIN.split('/')))
|
os.makedirs(os.path.join(self._main_prefix, *self.EBOOK_DIR_MAIN.split('/')))
|
||||||
except EnvironmentError as err:
|
except OSError as err:
|
||||||
if err.errno != errno.EEXIST:
|
if err.errno != errno.EEXIST:
|
||||||
self.EBOOK_DIR_MAIN = 'NOOK'
|
self.EBOOK_DIR_MAIN = 'NOOK'
|
||||||
|
|
||||||
|
@ -1 +0,0 @@
|
|||||||
|
|
@ -110,7 +110,7 @@ class PALADIN(USBMS):
|
|||||||
for i, row in enumerate(cursor):
|
for i, row in enumerate(cursor):
|
||||||
try:
|
try:
|
||||||
comp_date = int(os.path.getmtime(self.normalize_path(prefix + row[0])) * 1000)
|
comp_date = int(os.path.getmtime(self.normalize_path(prefix + row[0])) * 1000)
|
||||||
except (OSError, IOError, TypeError):
|
except (OSError, TypeError):
|
||||||
# In case the db has incorrect path info
|
# In case the db has incorrect path info
|
||||||
continue
|
continue
|
||||||
device_date = int(row[1])
|
device_date = int(row[1])
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
||||||
|
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
@ -758,7 +758,7 @@ class XMLCache:
|
|||||||
return m
|
return m
|
||||||
|
|
||||||
def book_by_lpath(self, lpath, root):
|
def book_by_lpath(self, lpath, root):
|
||||||
matches = root.xpath(u'//*[local-name()="text" and @path="%s"]'%lpath)
|
matches = root.xpath('//*[local-name()="text" and @path="%s"]'%lpath)
|
||||||
if matches:
|
if matches:
|
||||||
return matches[0]
|
return matches[0]
|
||||||
|
|
||||||
|
@ -199,7 +199,7 @@ class PRST1(USBMS):
|
|||||||
for i, row in enumerate(cursor):
|
for i, row in enumerate(cursor):
|
||||||
try:
|
try:
|
||||||
comp_date = int(os.path.getmtime(self.normalize_path(prefix + row[0])) * 1000)
|
comp_date = int(os.path.getmtime(self.normalize_path(prefix + row[0])) * 1000)
|
||||||
except (OSError, IOError, TypeError):
|
except (OSError, TypeError):
|
||||||
# In case the db has incorrect path info
|
# In case the db has incorrect path info
|
||||||
continue
|
continue
|
||||||
device_date = int(row[1])
|
device_date = int(row[1])
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
||||||
'''
|
'''
|
||||||
@ -40,12 +39,12 @@ _USBDevice = namedtuple('USBDevice',
|
|||||||
class USBDevice(_USBDevice):
|
class USBDevice(_USBDevice):
|
||||||
|
|
||||||
def __new__(cls, *args, **kwargs):
|
def __new__(cls, *args, **kwargs):
|
||||||
self = super(USBDevice, cls).__new__(cls, *args)
|
self = super().__new__(cls, *args)
|
||||||
self.busnum = self.devnum = -1
|
self.busnum = self.devnum = -1
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return (u'USBDevice(busnum=%s, devnum=%s, '
|
return ('USBDevice(busnum=%s, devnum=%s, '
|
||||||
'vendor_id=0x%04x, product_id=0x%04x, bcd=0x%04x, '
|
'vendor_id=0x%04x, product_id=0x%04x, bcd=0x%04x, '
|
||||||
'manufacturer=%s, product=%s, serial=%s)')%(
|
'manufacturer=%s, product=%s, serial=%s)')%(
|
||||||
self.busnum, self.devnum, self.vendor_id, self.product_id,
|
self.busnum, self.devnum, self.vendor_id, self.product_id,
|
||||||
@ -141,15 +140,15 @@ class LinuxScanner:
|
|||||||
try:
|
try:
|
||||||
dev.append(read(man).decode('utf-8'))
|
dev.append(read(man).decode('utf-8'))
|
||||||
except Exception:
|
except Exception:
|
||||||
dev.append(u'')
|
dev.append('')
|
||||||
try:
|
try:
|
||||||
dev.append(read(prod_string).decode('utf-8'))
|
dev.append(read(prod_string).decode('utf-8'))
|
||||||
except Exception:
|
except Exception:
|
||||||
dev.append(u'')
|
dev.append('')
|
||||||
try:
|
try:
|
||||||
dev.append(read(serial).decode('utf-8'))
|
dev.append(read(serial).decode('utf-8'))
|
||||||
except Exception:
|
except Exception:
|
||||||
dev.append(u'')
|
dev.append('')
|
||||||
|
|
||||||
dev = USBDevice(*dev)
|
dev = USBDevice(*dev)
|
||||||
try:
|
try:
|
||||||
|
@ -164,7 +164,7 @@ class ConnectionListener(Thread):
|
|||||||
|
|
||||||
except socket.timeout:
|
except socket.timeout:
|
||||||
pass
|
pass
|
||||||
except socket.error:
|
except OSError:
|
||||||
x = sys.exc_info()[1]
|
x = sys.exc_info()[1]
|
||||||
self.driver._debug('unexpected socket exception', x.args[0])
|
self.driver._debug('unexpected socket exception', x.args[0])
|
||||||
self._close_socket(device_socket)
|
self._close_socket(device_socket)
|
||||||
@ -623,9 +623,9 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin):
|
|||||||
amt_sent = sock.send(s[sent_len:])
|
amt_sent = sock.send(s[sent_len:])
|
||||||
sock.settimeout(None)
|
sock.settimeout(None)
|
||||||
if amt_sent <= 0:
|
if amt_sent <= 0:
|
||||||
raise IOError('Bad write on socket')
|
raise OSError('Bad write on socket')
|
||||||
sent_len += amt_sent
|
sent_len += amt_sent
|
||||||
except socket.error as e:
|
except OSError as e:
|
||||||
self._debug('socket error', e, e.errno)
|
self._debug('socket error', e, e.errno)
|
||||||
if e.args[0] != EAGAIN and e.args[0] != EINTR:
|
if e.args[0] != EAGAIN and e.args[0] != EINTR:
|
||||||
self._close_device_socket()
|
self._close_device_socket()
|
||||||
@ -661,7 +661,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin):
|
|||||||
self._debug('timeout communicating with device')
|
self._debug('timeout communicating with device')
|
||||||
self._close_device_socket()
|
self._close_device_socket()
|
||||||
raise TimeoutError('Device did not respond in reasonable time')
|
raise TimeoutError('Device did not respond in reasonable time')
|
||||||
except socket.error:
|
except OSError:
|
||||||
self._debug('device went away')
|
self._debug('device went away')
|
||||||
self._close_device_socket()
|
self._close_device_socket()
|
||||||
raise ControlError(desc='Device closed the network connection')
|
raise ControlError(desc='Device closed the network connection')
|
||||||
@ -689,7 +689,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin):
|
|||||||
self._debug('timeout communicating with device')
|
self._debug('timeout communicating with device')
|
||||||
self._close_device_socket()
|
self._close_device_socket()
|
||||||
raise TimeoutError('Device did not respond in reasonable time')
|
raise TimeoutError('Device did not respond in reasonable time')
|
||||||
except socket.error:
|
except OSError:
|
||||||
self._debug('device went away')
|
self._debug('device went away')
|
||||||
self._close_device_socket()
|
self._close_device_socket()
|
||||||
raise ControlError(desc='Device closed the network connection')
|
raise ControlError(desc='Device closed the network connection')
|
||||||
@ -936,7 +936,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin):
|
|||||||
sock.bind((ip_addr, port))
|
sock.bind((ip_addr, port))
|
||||||
else:
|
else:
|
||||||
sock.bind(('', port))
|
sock.bind(('', port))
|
||||||
except socket.error:
|
except OSError:
|
||||||
self._debug('socket error on port', port)
|
self._debug('socket error on port', port)
|
||||||
port = 0
|
port = 0
|
||||||
except:
|
except:
|
||||||
@ -1213,7 +1213,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin):
|
|||||||
return True
|
return True
|
||||||
except socket.timeout:
|
except socket.timeout:
|
||||||
self._close_device_socket()
|
self._close_device_socket()
|
||||||
except socket.error:
|
except OSError:
|
||||||
x = sys.exc_info()[1]
|
x = sys.exc_info()[1]
|
||||||
self._debug('unexpected socket exception', x.args[0])
|
self._debug('unexpected socket exception', x.args[0])
|
||||||
self._close_device_socket()
|
self._close_device_socket()
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
@ -54,7 +54,7 @@ class CLI:
|
|||||||
with dest:
|
with dest:
|
||||||
try:
|
try:
|
||||||
shutil.copyfileobj(infile, dest)
|
shutil.copyfileobj(infile, dest)
|
||||||
except IOError:
|
except OSError:
|
||||||
print('WARNING: First attempt to send file to device failed')
|
print('WARNING: First attempt to send file to device failed')
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
infile.seek(0)
|
infile.seek(0)
|
||||||
|
@ -296,7 +296,7 @@ class Device(DeviceConfig, DevicePlugin):
|
|||||||
try:
|
try:
|
||||||
return subprocess.Popen(cmd,
|
return subprocess.Popen(cmd,
|
||||||
stdout=subprocess.PIPE).communicate()[0]
|
stdout=subprocess.PIPE).communicate()[0]
|
||||||
except IOError: # Probably an interrupted system call
|
except OSError: # Probably an interrupted system call
|
||||||
if i == 2:
|
if i == 2:
|
||||||
raise
|
raise
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
@ -310,7 +310,7 @@ class Device(DeviceConfig, DevicePlugin):
|
|||||||
try:
|
try:
|
||||||
return subprocess.Popen('mount',
|
return subprocess.Popen('mount',
|
||||||
stdout=subprocess.PIPE).communicate()[0]
|
stdout=subprocess.PIPE).communicate()[0]
|
||||||
except IOError: # Probably an interrupted system call
|
except OSError: # Probably an interrupted system call
|
||||||
if i == 2:
|
if i == 2:
|
||||||
raise
|
raise
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
@ -440,8 +440,7 @@ class Device(DeviceConfig, DevicePlugin):
|
|||||||
isfile = os.path.isfile(p)
|
isfile = os.path.isfile(p)
|
||||||
yield p, isfile
|
yield p, isfile
|
||||||
if not isfile:
|
if not isfile:
|
||||||
for y, q in walk(p):
|
yield from walk(p)
|
||||||
yield y, q
|
|
||||||
|
|
||||||
def raw2num(raw):
|
def raw2num(raw):
|
||||||
raw = raw.lower()
|
raw = raw.lower()
|
||||||
|
@ -68,8 +68,7 @@ def safe_walk(top, topdown=True, onerror=None, followlinks=False, maxdepth=128):
|
|||||||
for name in dirs:
|
for name in dirs:
|
||||||
new_path = join(top, name)
|
new_path = join(top, name)
|
||||||
if followlinks or not islink(new_path):
|
if followlinks or not islink(new_path):
|
||||||
for x in safe_walk(new_path, topdown, onerror, followlinks, maxdepth-1):
|
yield from safe_walk(new_path, topdown, onerror, followlinks, maxdepth-1)
|
||||||
yield x
|
|
||||||
if not topdown:
|
if not topdown:
|
||||||
yield top, dirs, nondirs
|
yield top, dirs, nondirs
|
||||||
|
|
||||||
@ -151,8 +150,8 @@ class USBMS(CLI, Device):
|
|||||||
if self._main_prefix is not None:
|
if self._main_prefix is not None:
|
||||||
try:
|
try:
|
||||||
self.driveinfo['main'] = self._update_driveinfo_file(self._main_prefix, 'main')
|
self.driveinfo['main'] = self._update_driveinfo_file(self._main_prefix, 'main')
|
||||||
except (IOError, OSError) as e:
|
except OSError as e:
|
||||||
raise IOError(_('Failed to access files in the main memory of'
|
raise OSError(_('Failed to access files in the main memory of'
|
||||||
' your device. You should contact the device'
|
' your device. You should contact the device'
|
||||||
' manufacturer for support. Common fixes are:'
|
' manufacturer for support. Common fixes are:'
|
||||||
' try a different USB cable/USB port on your computer.'
|
' try a different USB cable/USB port on your computer.'
|
||||||
@ -164,8 +163,8 @@ class USBMS(CLI, Device):
|
|||||||
self.driveinfo['A'] = self._update_driveinfo_file(self._card_a_prefix, 'A')
|
self.driveinfo['A'] = self._update_driveinfo_file(self._card_a_prefix, 'A')
|
||||||
if self._card_b_prefix is not None:
|
if self._card_b_prefix is not None:
|
||||||
self.driveinfo['B'] = self._update_driveinfo_file(self._card_b_prefix, 'B')
|
self.driveinfo['B'] = self._update_driveinfo_file(self._card_b_prefix, 'B')
|
||||||
except (IOError, OSError) as e:
|
except OSError as e:
|
||||||
raise IOError(_('Failed to access files on the SD card in your'
|
raise OSError(_('Failed to access files on the SD card in your'
|
||||||
' device. This can happen for many reasons. The SD card may be'
|
' device. This can happen for many reasons. The SD card may be'
|
||||||
' corrupted, it may be too large for your device, it may be'
|
' corrupted, it may be too large for your device, it may be'
|
||||||
' write-protected, etc. Try a different SD card, or reformat'
|
' write-protected, etc. Try a different SD card, or reformat'
|
||||||
|
@ -59,8 +59,8 @@ def build_template_regexp(template):
|
|||||||
template = template.rpartition('/')[2]
|
template = template.rpartition('/')[2]
|
||||||
return re.compile(re.sub('{([^}]*)}', f, template) + r'([_\d]*$)')
|
return re.compile(re.sub('{([^}]*)}', f, template) + r'([_\d]*$)')
|
||||||
except:
|
except:
|
||||||
prints(u'Failed to parse template: %r'%template)
|
prints('Failed to parse template: %r'%template)
|
||||||
template = u'{title} - {authors}'
|
template = '{title} - {authors}'
|
||||||
return re.compile(re.sub('{([^}]*)}', f, template) + r'([_\d]*$)')
|
return re.compile(re.sub('{([^}]*)}', f, template) + r'([_\d]*$)')
|
||||||
|
|
||||||
|
|
||||||
@ -90,7 +90,7 @@ def create_upload_path(mdata, fname, template, sanitize,
|
|||||||
except:
|
except:
|
||||||
today = time.localtime()
|
today = time.localtime()
|
||||||
date = (today[0], today[1], today[2])
|
date = (today[0], today[1], today[2])
|
||||||
template = u"{title}_%d-%d-%d" % date
|
template = "{title}_%d-%d-%d" % date
|
||||||
|
|
||||||
fname = sanitize(fname)
|
fname = sanitize(fname)
|
||||||
ext = path_type.splitext(fname)[1]
|
ext = path_type.splitext(fname)[1]
|
||||||
|
@ -507,8 +507,7 @@ def iterchildren(parent_devinst):
|
|||||||
def iterdescendants(parent_devinst):
|
def iterdescendants(parent_devinst):
|
||||||
for child in iterchildren(parent_devinst):
|
for child in iterchildren(parent_devinst):
|
||||||
yield child
|
yield child
|
||||||
for gc in iterdescendants(child):
|
yield from iterdescendants(child)
|
||||||
yield gc
|
|
||||||
|
|
||||||
|
|
||||||
def iterancestors(devinst):
|
def iterancestors(devinst):
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
||||||
|
|
||||||
@ -81,7 +79,7 @@ def extract_calibre_cover(raw, base, log):
|
|||||||
if matches is None:
|
if matches is None:
|
||||||
body = soup.find('body')
|
body = soup.find('body')
|
||||||
if body is not None:
|
if body is not None:
|
||||||
text = u''.join(map(str, body.findAll(text=True)))
|
text = ''.join(map(str, body.findAll(text=True)))
|
||||||
if text.strip():
|
if text.strip():
|
||||||
# Body has text, abort
|
# Body has text, abort
|
||||||
return
|
return
|
||||||
|
@ -33,8 +33,7 @@ class LazyEncodingPats:
|
|||||||
if pats is None:
|
if pats is None:
|
||||||
pats = tuple(compile_pats(binary))
|
pats = tuple(compile_pats(binary))
|
||||||
setattr(self, attr, pats)
|
setattr(self, attr, pats)
|
||||||
for pat in pats:
|
yield from pats
|
||||||
yield pat
|
|
||||||
|
|
||||||
|
|
||||||
lazy_encoding_pats = LazyEncodingPats()
|
lazy_encoding_pats = LazyEncodingPats()
|
||||||
@ -51,7 +50,7 @@ def strip_encoding_declarations(raw, limit=50*1024, preserve_newlines=False):
|
|||||||
else:
|
else:
|
||||||
sub = lambda m: '\n' * m.group().count('\n')
|
sub = lambda m: '\n' * m.group().count('\n')
|
||||||
else:
|
else:
|
||||||
sub = b'' if is_binary else u''
|
sub = b'' if is_binary else ''
|
||||||
for pat in lazy_encoding_pats(is_binary):
|
for pat in lazy_encoding_pats(is_binary):
|
||||||
prefix = pat.sub(sub, prefix)
|
prefix = pat.sub(sub, prefix)
|
||||||
raw = prefix + suffix
|
raw = prefix + suffix
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
|
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL 3'
|
__license__ = 'GPL 3'
|
||||||
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
@ -372,7 +370,7 @@ def main(args=sys.argv):
|
|||||||
parser, plumber = create_option_parser(args, log)
|
parser, plumber = create_option_parser(args, log)
|
||||||
opts, leftover_args = parser.parse_args(args)
|
opts, leftover_args = parser.parse_args(args)
|
||||||
if len(leftover_args) > 3:
|
if len(leftover_args) > 3:
|
||||||
log.error('Extra arguments not understood:', u', '.join(leftover_args[3:]))
|
log.error('Extra arguments not understood:', ', '.join(leftover_args[3:]))
|
||||||
return 1
|
return 1
|
||||||
for x in ('read_metadata_from_opf', 'cover'):
|
for x in ('read_metadata_from_opf', 'cover'):
|
||||||
if getattr(opts, x, None) is not None:
|
if getattr(opts, x, None) is not None:
|
||||||
|
@ -70,7 +70,7 @@ class GuiRecommendations(dict):
|
|||||||
|
|
||||||
def __new__(cls, *args):
|
def __new__(cls, *args):
|
||||||
dict.__new__(cls)
|
dict.__new__(cls)
|
||||||
obj = super(GuiRecommendations, cls).__new__(cls, *args)
|
obj = super().__new__(cls, *args)
|
||||||
obj.disabled_options = set()
|
obj.disabled_options = set()
|
||||||
return obj
|
return obj
|
||||||
|
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
''' CHM File decoding support '''
|
''' CHM File decoding support '''
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>,' \
|
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>,' \
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
|
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL 3'
|
__license__ = 'GPL 3'
|
||||||
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
@ -291,7 +291,7 @@ class EPUBOutput(OutputFormatPlugin):
|
|||||||
from calibre.ebooks.oeb.polish.cover import fix_conversion_titlepage_links_in_nav
|
from calibre.ebooks.oeb.polish.cover import fix_conversion_titlepage_links_in_nav
|
||||||
try:
|
try:
|
||||||
os.mkdir(os.path.join(tdir, 'META-INF'))
|
os.mkdir(os.path.join(tdir, 'META-INF'))
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
with open(os.path.join(tdir, 'META-INF', 'container.xml'), 'wb') as f:
|
with open(os.path.join(tdir, 'META-INF', 'container.xml'), 'wb') as f:
|
||||||
f.write(simple_container_xml(os.path.basename(opf)).encode('utf-8'))
|
f.write(simple_container_xml(os.path.basename(opf)).encode('utf-8'))
|
||||||
@ -307,7 +307,7 @@ class EPUBOutput(OutputFormatPlugin):
|
|||||||
os.remove(f.name)
|
os.remove(f.name)
|
||||||
try:
|
try:
|
||||||
os.rmdir(os.path.join(tdir, 'META-INF'))
|
os.rmdir(os.path.join(tdir, 'META-INF'))
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def encrypt_fonts(self, uris, tdir, uuid): # {{{
|
def encrypt_fonts(self, uris, tdir, uuid): # {{{
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Anatoly Shipitsin <norguhtar at gmail.com>'
|
__copyright__ = '2008, Anatoly Shipitsin <norguhtar at gmail.com>'
|
||||||
"""
|
"""
|
||||||
@ -146,7 +144,7 @@ class FB2Input(InputFormatPlugin):
|
|||||||
break
|
break
|
||||||
|
|
||||||
opf = OPFCreator(os.getcwd(), mi)
|
opf = OPFCreator(os.getcwd(), mi)
|
||||||
entries = [(f2, guess_type(f2)[0]) for f2 in os.listdir(u'.')]
|
entries = [(f2, guess_type(f2)[0]) for f2 in os.listdir('.')]
|
||||||
opf.create_manifest(entries)
|
opf.create_manifest(entries)
|
||||||
opf.create_spine(['index.xhtml'])
|
opf.create_spine(['index.xhtml'])
|
||||||
if cpath:
|
if cpath:
|
||||||
|
@ -284,7 +284,7 @@ class HTMLInput(InputFormatPlugin):
|
|||||||
# Check for the common case, images
|
# Check for the common case, images
|
||||||
try:
|
try:
|
||||||
img = what(link)
|
img = what(link)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
if img:
|
if img:
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL 3'
|
__license__ = 'GPL 3'
|
||||||
__copyright__ = '2010, Fabian Grassl <fg@jusmeum.de>'
|
__copyright__ = '2010, Fabian Grassl <fg@jusmeum.de>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
@ -26,7 +26,7 @@ class HTMLZInput(InputFormatPlugin):
|
|||||||
from calibre.utils.zipfile import ZipFile
|
from calibre.utils.zipfile import ZipFile
|
||||||
|
|
||||||
self.log = log
|
self.log = log
|
||||||
html = u''
|
html = ''
|
||||||
top_levels = []
|
top_levels = []
|
||||||
|
|
||||||
# Extract content from zip archive.
|
# Extract content from zip archive.
|
||||||
@ -35,21 +35,21 @@ class HTMLZInput(InputFormatPlugin):
|
|||||||
|
|
||||||
# Find the HTML file in the archive. It needs to be
|
# Find the HTML file in the archive. It needs to be
|
||||||
# top level.
|
# top level.
|
||||||
index = u''
|
index = ''
|
||||||
multiple_html = False
|
multiple_html = False
|
||||||
# Get a list of all top level files in the archive.
|
# Get a list of all top level files in the archive.
|
||||||
for x in os.listdir(u'.'):
|
for x in os.listdir('.'):
|
||||||
if os.path.isfile(x):
|
if os.path.isfile(x):
|
||||||
top_levels.append(x)
|
top_levels.append(x)
|
||||||
# Try to find an index. file.
|
# Try to find an index. file.
|
||||||
for x in top_levels:
|
for x in top_levels:
|
||||||
if x.lower() in (u'index.html', u'index.xhtml', u'index.htm'):
|
if x.lower() in ('index.html', 'index.xhtml', 'index.htm'):
|
||||||
index = x
|
index = x
|
||||||
break
|
break
|
||||||
# Look for multiple HTML files in the archive. We look at the
|
# Look for multiple HTML files in the archive. We look at the
|
||||||
# top level files only as only they matter in HTMLZ.
|
# top level files only as only they matter in HTMLZ.
|
||||||
for x in top_levels:
|
for x in top_levels:
|
||||||
if os.path.splitext(x)[1].lower() in (u'.html', u'.xhtml', u'.htm'):
|
if os.path.splitext(x)[1].lower() in ('.html', '.xhtml', '.htm'):
|
||||||
# Set index to the first HTML file found if it's not
|
# Set index to the first HTML file found if it's not
|
||||||
# called index.
|
# called index.
|
||||||
if not index:
|
if not index:
|
||||||
@ -86,11 +86,11 @@ class HTMLZInput(InputFormatPlugin):
|
|||||||
setattr(options, opt.option.name, opt.recommended_value)
|
setattr(options, opt.option.name, opt.recommended_value)
|
||||||
options.input_encoding = 'utf-8'
|
options.input_encoding = 'utf-8'
|
||||||
base = os.getcwd()
|
base = os.getcwd()
|
||||||
htmlfile = os.path.join(base, u'index.html')
|
htmlfile = os.path.join(base, 'index.html')
|
||||||
c = 0
|
c = 0
|
||||||
while os.path.exists(htmlfile):
|
while os.path.exists(htmlfile):
|
||||||
c += 1
|
c += 1
|
||||||
htmlfile = u'index%d.html'%c
|
htmlfile = 'index%d.html'%c
|
||||||
with open(htmlfile, 'wb') as f:
|
with open(htmlfile, 'wb') as f:
|
||||||
f.write(html.encode('utf-8'))
|
f.write(html.encode('utf-8'))
|
||||||
odi = options.debug_pipeline
|
odi = options.debug_pipeline
|
||||||
@ -112,7 +112,7 @@ class HTMLZInput(InputFormatPlugin):
|
|||||||
cover_path = None
|
cover_path = None
|
||||||
opf = None
|
opf = None
|
||||||
for x in top_levels:
|
for x in top_levels:
|
||||||
if os.path.splitext(x)[1].lower() == u'.opf':
|
if os.path.splitext(x)[1].lower() == '.opf':
|
||||||
opf = x
|
opf = x
|
||||||
break
|
break
|
||||||
if opf:
|
if opf:
|
||||||
|
@ -72,36 +72,36 @@ class HTMLZOutput(OutputFormatPlugin):
|
|||||||
else:
|
else:
|
||||||
from calibre.ebooks.htmlz.oeb2html import OEB2HTMLClassCSSizer as OEB2HTMLizer
|
from calibre.ebooks.htmlz.oeb2html import OEB2HTMLClassCSSizer as OEB2HTMLizer
|
||||||
|
|
||||||
with TemporaryDirectory(u'_htmlz_output') as tdir:
|
with TemporaryDirectory('_htmlz_output') as tdir:
|
||||||
htmlizer = OEB2HTMLizer(log)
|
htmlizer = OEB2HTMLizer(log)
|
||||||
html = htmlizer.oeb2html(oeb_book, opts)
|
html = htmlizer.oeb2html(oeb_book, opts)
|
||||||
|
|
||||||
fname = u'index'
|
fname = 'index'
|
||||||
if opts.htmlz_title_filename:
|
if opts.htmlz_title_filename:
|
||||||
from calibre.utils.filenames import shorten_components_to
|
from calibre.utils.filenames import shorten_components_to
|
||||||
fname = shorten_components_to(100, (ascii_filename(str(oeb_book.metadata.title[0])),))[0]
|
fname = shorten_components_to(100, (ascii_filename(str(oeb_book.metadata.title[0])),))[0]
|
||||||
with open(os.path.join(tdir, fname+u'.html'), 'wb') as tf:
|
with open(os.path.join(tdir, fname+'.html'), 'wb') as tf:
|
||||||
if isinstance(html, str):
|
if isinstance(html, str):
|
||||||
html = html.encode('utf-8')
|
html = html.encode('utf-8')
|
||||||
tf.write(html)
|
tf.write(html)
|
||||||
|
|
||||||
# CSS
|
# CSS
|
||||||
if opts.htmlz_css_type == 'class' and opts.htmlz_class_style == 'external':
|
if opts.htmlz_css_type == 'class' and opts.htmlz_class_style == 'external':
|
||||||
with open(os.path.join(tdir, u'style.css'), 'wb') as tf:
|
with open(os.path.join(tdir, 'style.css'), 'wb') as tf:
|
||||||
tf.write(htmlizer.get_css(oeb_book).encode('utf-8'))
|
tf.write(htmlizer.get_css(oeb_book).encode('utf-8'))
|
||||||
|
|
||||||
# Images
|
# Images
|
||||||
images = htmlizer.images
|
images = htmlizer.images
|
||||||
if images:
|
if images:
|
||||||
if not os.path.exists(os.path.join(tdir, u'images')):
|
if not os.path.exists(os.path.join(tdir, 'images')):
|
||||||
os.makedirs(os.path.join(tdir, u'images'))
|
os.makedirs(os.path.join(tdir, 'images'))
|
||||||
for item in oeb_book.manifest:
|
for item in oeb_book.manifest:
|
||||||
if item.media_type in OEB_IMAGES and item.href in images:
|
if item.media_type in OEB_IMAGES and item.href in images:
|
||||||
if item.media_type == SVG_MIME:
|
if item.media_type == SVG_MIME:
|
||||||
data = etree.tostring(item.data, encoding='unicode').encode('utf-8')
|
data = etree.tostring(item.data, encoding='unicode').encode('utf-8')
|
||||||
else:
|
else:
|
||||||
data = item.data
|
data = item.data
|
||||||
fname = os.path.join(tdir, u'images', images[item.href])
|
fname = os.path.join(tdir, 'images', images[item.href])
|
||||||
with open(fname, 'wb') as img:
|
with open(fname, 'wb') as img:
|
||||||
img.write(data)
|
img.write(data)
|
||||||
|
|
||||||
@ -114,7 +114,7 @@ class HTMLZOutput(OutputFormatPlugin):
|
|||||||
cover_data = oeb_book.guide[term].item.data
|
cover_data = oeb_book.guide[term].item.data
|
||||||
if cover_data:
|
if cover_data:
|
||||||
from calibre.utils.img import save_cover_data_to
|
from calibre.utils.img import save_cover_data_to
|
||||||
cover_path = os.path.join(tdir, u'cover.jpg')
|
cover_path = os.path.join(tdir, 'cover.jpg')
|
||||||
with lopen(cover_path, 'w') as cf:
|
with lopen(cover_path, 'w') as cf:
|
||||||
cf.write('')
|
cf.write('')
|
||||||
save_cover_data_to(cover_data, cover_path)
|
save_cover_data_to(cover_data, cover_path)
|
||||||
@ -123,11 +123,11 @@ class HTMLZOutput(OutputFormatPlugin):
|
|||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
|
|
||||||
# Metadata
|
# Metadata
|
||||||
with open(os.path.join(tdir, u'metadata.opf'), 'wb') as mdataf:
|
with open(os.path.join(tdir, 'metadata.opf'), 'wb') as mdataf:
|
||||||
opf = OPF(io.BytesIO(etree.tostring(oeb_book.metadata.to_opf1(), encoding='UTF-8')))
|
opf = OPF(io.BytesIO(etree.tostring(oeb_book.metadata.to_opf1(), encoding='UTF-8')))
|
||||||
mi = opf.to_book_metadata()
|
mi = opf.to_book_metadata()
|
||||||
if cover_path:
|
if cover_path:
|
||||||
mi.cover = u'cover.jpg'
|
mi.cover = 'cover.jpg'
|
||||||
mdataf.write(metadata_to_opf(mi))
|
mdataf.write(metadata_to_opf(mi))
|
||||||
|
|
||||||
htmlz = ZipFile(output_path, 'w')
|
htmlz = ZipFile(output_path, 'w')
|
||||||
|
@ -31,7 +31,7 @@ class LRFInput(InputFormatPlugin):
|
|||||||
d.parse()
|
d.parse()
|
||||||
xml = d.to_xml(write_files=True)
|
xml = d.to_xml(write_files=True)
|
||||||
if options.verbose > 2:
|
if options.verbose > 2:
|
||||||
open(u'lrs.xml', 'wb').write(xml.encode('utf-8'))
|
open('lrs.xml', 'wb').write(xml.encode('utf-8'))
|
||||||
doc = safe_xml_fromstring(xml)
|
doc = safe_xml_fromstring(xml)
|
||||||
|
|
||||||
char_button_map = {}
|
char_button_map = {}
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL 3'
|
__license__ = 'GPL 3'
|
||||||
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
|
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL 3'
|
__license__ = 'GPL 3'
|
||||||
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
||||||
|
|
||||||
@ -54,12 +53,12 @@ class RTFInput(InputFormatPlugin):
|
|||||||
|
|
||||||
def generate_xml(self, stream):
|
def generate_xml(self, stream):
|
||||||
from calibre.ebooks.rtf2xml.ParseRtf import ParseRtf
|
from calibre.ebooks.rtf2xml.ParseRtf import ParseRtf
|
||||||
ofile = u'dataxml.xml'
|
ofile = 'dataxml.xml'
|
||||||
run_lev, debug_dir, indent_out = 1, None, 0
|
run_lev, debug_dir, indent_out = 1, None, 0
|
||||||
if getattr(self.opts, 'debug_pipeline', None) is not None:
|
if getattr(self.opts, 'debug_pipeline', None) is not None:
|
||||||
try:
|
try:
|
||||||
os.mkdir(u'rtfdebug')
|
os.mkdir('rtfdebug')
|
||||||
debug_dir = u'rtfdebug'
|
debug_dir = 'rtfdebug'
|
||||||
run_lev = 4
|
run_lev = 4
|
||||||
indent_out = 1
|
indent_out = 1
|
||||||
self.log('Running RTFParser in debug mode')
|
self.log('Running RTFParser in debug mode')
|
||||||
@ -137,7 +136,7 @@ class RTFInput(InputFormatPlugin):
|
|||||||
if fmt is None:
|
if fmt is None:
|
||||||
fmt = 'wmf'
|
fmt = 'wmf'
|
||||||
count += 1
|
count += 1
|
||||||
name = u'%04d.%s' % (count, fmt)
|
name = '%04d.%s' % (count, fmt)
|
||||||
with open(name, 'wb') as f:
|
with open(name, 'wb') as f:
|
||||||
f.write(data)
|
f.write(data)
|
||||||
imap[count] = name
|
imap[count] = name
|
||||||
@ -215,7 +214,7 @@ class RTFInput(InputFormatPlugin):
|
|||||||
for cls, val in iteritems(border_styles):
|
for cls, val in iteritems(border_styles):
|
||||||
css += '\n\n.%s {\n%s\n}'%(cls, val)
|
css += '\n\n.%s {\n%s\n}'%(cls, val)
|
||||||
|
|
||||||
with open(u'styles.css', 'ab') as f:
|
with open('styles.css', 'ab') as f:
|
||||||
f.write(css.encode('utf-8'))
|
f.write(css.encode('utf-8'))
|
||||||
|
|
||||||
def convert_borders(self, doc):
|
def convert_borders(self, doc):
|
||||||
@ -286,7 +285,7 @@ class RTFInput(InputFormatPlugin):
|
|||||||
extensions = {('calibre', 'inline-class') : inline_class}
|
extensions = {('calibre', 'inline-class') : inline_class}
|
||||||
transform = etree.XSLT(styledoc, extensions=extensions)
|
transform = etree.XSLT(styledoc, extensions=extensions)
|
||||||
result = transform(doc)
|
result = transform(doc)
|
||||||
html = u'index.xhtml'
|
html = 'index.xhtml'
|
||||||
with open(html, 'wb') as f:
|
with open(html, 'wb') as f:
|
||||||
res = as_bytes(transform.tostring(result))
|
res = as_bytes(transform.tostring(result))
|
||||||
# res = res[:100].replace('xmlns:html', 'xmlns') + res[100:]
|
# res = res[:100].replace('xmlns:html', 'xmlns') + res[100:]
|
||||||
@ -305,10 +304,10 @@ class RTFInput(InputFormatPlugin):
|
|||||||
if not mi.authors:
|
if not mi.authors:
|
||||||
mi.authors = [_('Unknown')]
|
mi.authors = [_('Unknown')]
|
||||||
opf = OPFCreator(os.getcwd(), mi)
|
opf = OPFCreator(os.getcwd(), mi)
|
||||||
opf.create_manifest([(u'index.xhtml', None)])
|
opf.create_manifest([('index.xhtml', None)])
|
||||||
opf.create_spine([u'index.xhtml'])
|
opf.create_spine(['index.xhtml'])
|
||||||
opf.render(open(u'metadata.opf', 'wb'))
|
opf.render(open('metadata.opf', 'wb'))
|
||||||
return os.path.abspath(u'metadata.opf')
|
return os.path.abspath('metadata.opf')
|
||||||
|
|
||||||
def postprocess_book(self, oeb, opts, log):
|
def postprocess_book(self, oeb, opts, log):
|
||||||
for item in oeb.spine:
|
for item in oeb.spine:
|
||||||
|
@ -561,10 +561,10 @@ class Blocks(Style):
|
|||||||
|
|
||||||
|
|
||||||
def all_styles():
|
def all_styles():
|
||||||
return set(
|
return {
|
||||||
x.NAME for x in itervalues(globals()) if
|
x.NAME for x in itervalues(globals()) if
|
||||||
isinstance(x, type) and issubclass(x, Style) and x is not Style
|
isinstance(x, type) and issubclass(x, Style) and x is not Style
|
||||||
)
|
}
|
||||||
|
|
||||||
|
|
||||||
def load_styles(prefs, respect_disabled=True):
|
def load_styles(prefs, respect_disabled=True):
|
||||||
|
@ -259,7 +259,7 @@ class DOCX:
|
|||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
shutil.rmtree(self.tdir)
|
shutil.rmtree(self.tdir)
|
||||||
except EnvironmentError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@ -54,7 +54,7 @@ null = object()
|
|||||||
|
|
||||||
def parser(name, field_map, default_field_name=None):
|
def parser(name, field_map, default_field_name=None):
|
||||||
|
|
||||||
field_map = dict((x.split(':') for x in field_map.split()))
|
field_map = dict(x.split(':') for x in field_map.split())
|
||||||
|
|
||||||
def parse(raw, log=None):
|
def parse(raw, log=None):
|
||||||
ans = {}
|
ans = {}
|
||||||
|
@ -18,8 +18,7 @@ class Note:
|
|||||||
self.namespace = namespace
|
self.namespace = namespace
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
for p in self.namespace.descendants(self.parent, 'w:p', 'w:tbl'):
|
yield from self.namespace.descendants(self.parent, 'w:p', 'w:tbl')
|
||||||
yield p
|
|
||||||
|
|
||||||
|
|
||||||
class Footnotes:
|
class Footnotes:
|
||||||
|
@ -359,8 +359,6 @@ class Images:
|
|||||||
os.mkdir(dest)
|
os.mkdir(dest)
|
||||||
self.dest_dir, self.docx = dest, docx
|
self.dest_dir, self.docx = dest, docx
|
||||||
if elem.tag.endswith('}drawing'):
|
if elem.tag.endswith('}drawing'):
|
||||||
for tag in self.drawing_to_html(elem, page):
|
yield from self.drawing_to_html(elem, page)
|
||||||
yield tag
|
|
||||||
else:
|
else:
|
||||||
for tag in self.pict_to_html(elem, page):
|
yield from self.pict_to_html(elem, page)
|
||||||
yield tag
|
|
||||||
|
@ -124,8 +124,7 @@ class Styles:
|
|||||||
self.default_paragraph_style = self.default_character_style = None
|
self.default_paragraph_style = self.default_character_style = None
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
for s in itervalues(self.id_map):
|
yield from itervalues(self.id_map)
|
||||||
yield s
|
|
||||||
|
|
||||||
def __getitem__(self, key):
|
def __getitem__(self, key):
|
||||||
return self.id_map[key]
|
return self.id_map[key]
|
||||||
|
@ -615,11 +615,9 @@ class Table:
|
|||||||
tc.getparent().remove(tc)
|
tc.getparent().remove(tc)
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
for p in self.paragraphs:
|
yield from self.paragraphs
|
||||||
yield p
|
|
||||||
for t in itervalues(self.sub_tables):
|
for t in itervalues(self.sub_tables):
|
||||||
for p in t:
|
yield from t
|
||||||
yield p
|
|
||||||
|
|
||||||
def apply_markup(self, rmap, page, parent=None):
|
def apply_markup(self, rmap, page, parent=None):
|
||||||
table = TABLE('\n\t\t')
|
table = TABLE('\n\t\t')
|
||||||
|
@ -311,7 +311,7 @@ class Convert:
|
|||||||
seraw = self.docx.read(sename)
|
seraw = self.docx.read(sename)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
self.log.warn('Settings %s do not exist' % sename)
|
self.log.warn('Settings %s do not exist' % sename)
|
||||||
except EnvironmentError as e:
|
except OSError as e:
|
||||||
if e.errno != errno.ENOENT:
|
if e.errno != errno.ENOENT:
|
||||||
raise
|
raise
|
||||||
self.log.warn('Settings %s file missing' % sename)
|
self.log.warn('Settings %s file missing' % sename)
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
|
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
@ -37,7 +35,7 @@ def initialize_container(path_to_container, opf_name='metadata.opf',
|
|||||||
'''
|
'''
|
||||||
rootfiles = ''
|
rootfiles = ''
|
||||||
for path, mimetype, _ in extra_entries:
|
for path, mimetype, _ in extra_entries:
|
||||||
rootfiles += '<rootfile full-path="{0}" media-type="{1}"/>'.format(
|
rootfiles += '<rootfile full-path="{}" media-type="{}"/>'.format(
|
||||||
path, mimetype)
|
path, mimetype)
|
||||||
CONTAINER = simple_container_xml(opf_name, rootfiles).encode('utf-8')
|
CONTAINER = simple_container_xml(opf_name, rootfiles).encode('utf-8')
|
||||||
zf = ZipFile(path_to_container, 'w')
|
zf = ZipFile(path_to_container, 'w')
|
||||||
|
@ -124,7 +124,7 @@ class FB2MLizer:
|
|||||||
lc = self.oeb_book.metadata.language[0].value
|
lc = self.oeb_book.metadata.language[0].value
|
||||||
metadata['lang'] = lc or 'en'
|
metadata['lang'] = lc or 'en'
|
||||||
else:
|
else:
|
||||||
metadata['lang'] = u'en'
|
metadata['lang'] = 'en'
|
||||||
metadata['id'] = None
|
metadata['id'] = None
|
||||||
metadata['cover'] = self.get_cover()
|
metadata['cover'] = self.get_cover()
|
||||||
metadata['genre'] = self.opts.fb2_genre
|
metadata['genre'] = self.opts.fb2_genre
|
||||||
@ -483,7 +483,7 @@ class FB2MLizer:
|
|||||||
tags += p_tag
|
tags += p_tag
|
||||||
fb2_out.append('<image l:href="#%s"/>' % self.image_hrefs[ihref])
|
fb2_out.append('<image l:href="#%s"/>' % self.image_hrefs[ihref])
|
||||||
else:
|
else:
|
||||||
self.log.warn(u'Ignoring image not in manifest: %s' % ihref)
|
self.log.warn('Ignoring image not in manifest: %s' % ihref)
|
||||||
if tag in ('br', 'hr') or ems >= 1:
|
if tag in ('br', 'hr') or ems >= 1:
|
||||||
if ems < 1:
|
if ems < 1:
|
||||||
multiplier = 1
|
multiplier = 1
|
||||||
|
@ -121,10 +121,10 @@ class HTMLFile:
|
|||||||
self.is_binary = not bool(pat.search(header))
|
self.is_binary = not bool(pat.search(header))
|
||||||
if not self.is_binary:
|
if not self.is_binary:
|
||||||
src += f.read()
|
src += f.read()
|
||||||
except IOError as err:
|
except OSError as err:
|
||||||
msg = 'Could not read from file: %s with error: %s'%(self.path, as_unicode(err))
|
msg = 'Could not read from file: %s with error: %s'%(self.path, as_unicode(err))
|
||||||
if level == 0:
|
if level == 0:
|
||||||
raise IOError(msg)
|
raise OSError(msg)
|
||||||
raise IgnoreFile(msg, err.errno)
|
raise IgnoreFile(msg, err.errno)
|
||||||
|
|
||||||
if not src:
|
if not src:
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL 3'
|
__license__ = 'GPL 3'
|
||||||
__copyright__ = '2010, Fabian Grassl <fg@jusmeum.de>'
|
__copyright__ = '2010, Fabian Grassl <fg@jusmeum.de>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
@ -58,7 +58,7 @@ class OEB2HTML:
|
|||||||
|
|
||||||
def mlize_spine(self, oeb_book):
|
def mlize_spine(self, oeb_book):
|
||||||
output = [
|
output = [
|
||||||
u'<html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title>%s</title></head><body>' % (
|
'<html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title>%s</title></head><body>' % (
|
||||||
prepare_string_for_xml(self.book_title))
|
prepare_string_for_xml(self.book_title))
|
||||||
]
|
]
|
||||||
for item in oeb_book.spine:
|
for item in oeb_book.spine:
|
||||||
@ -139,10 +139,10 @@ class OEB2HTML:
|
|||||||
|
|
||||||
def prepare_string_for_html(self, raw):
|
def prepare_string_for_html(self, raw):
|
||||||
raw = prepare_string_for_xml(raw)
|
raw = prepare_string_for_xml(raw)
|
||||||
raw = raw.replace(u'\u00ad', '­')
|
raw = raw.replace('\u00ad', '­')
|
||||||
raw = raw.replace(u'\u2014', '—')
|
raw = raw.replace('\u2014', '—')
|
||||||
raw = raw.replace(u'\u2013', '–')
|
raw = raw.replace('\u2013', '–')
|
||||||
raw = raw.replace(u'\u00a0', ' ')
|
raw = raw.replace('\u00a0', ' ')
|
||||||
return raw
|
return raw
|
||||||
|
|
||||||
|
|
||||||
@ -340,9 +340,9 @@ class OEB2HTMLClassCSSizer(OEB2HTML):
|
|||||||
css = '<link href="style.css" rel="stylesheet" type="text/css" />'
|
css = '<link href="style.css" rel="stylesheet" type="text/css" />'
|
||||||
else:
|
else:
|
||||||
css = '<style type="text/css">' + self.get_css(oeb_book) + '</style>'
|
css = '<style type="text/css">' + self.get_css(oeb_book) + '</style>'
|
||||||
title = u'<title>%s</title>' % prepare_string_for_xml(self.book_title)
|
title = '<title>%s</title>' % prepare_string_for_xml(self.book_title)
|
||||||
output = [u'<html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" />'] + \
|
output = ['<html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" />'] + \
|
||||||
[css] + [title, u'</head><body>'] + output + [u'</body></html>']
|
[css] + [title, '</head><body>'] + output + ['</body></html>']
|
||||||
return ''.join(output)
|
return ''.join(output)
|
||||||
|
|
||||||
def dump_text(self, elem, stylizer, page):
|
def dump_text(self, elem, stylizer, page):
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
""" Hyphenation, using Frank Liang's algorithm.
|
""" Hyphenation, using Frank Liang's algorithm.
|
||||||
|
|
||||||
This module provides a single function to hyphenate words. hyphenate_word takes
|
This module provides a single function to hyphenate words. hyphenate_word takes
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
|
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
|
||||||
|
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
'''
|
'''
|
||||||
LZX compression/decompression wrapper.
|
LZX compression/decompression wrapper.
|
||||||
'''
|
'''
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
|
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
|
||||||
|
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
|
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
|
||||||
|
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
|
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
|
||||||
|
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user