rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
sort_val = None cookie = cherrypy.request.cookie if cookie.has_key(eself.sort_cookie_name): sort_val = cookie[eself.sort_cookie_name].value kwargs[eself.sort_kwarg] = sort_val
if 'json' not in eself.mimetype: sort_val = None cookie = cherrypy.request.cookie if cookie.has_key(eself.sort_cookie_name): sort_val = cookie[eself.sort_cookie_name].value kwargs[eself.sort_kwarg] = sort_val
def do(self, *args, **kwargs): sort_val = None cookie = cherrypy.request.cookie if cookie.has_key(eself.sort_cookie_name): sort_val = cookie[eself.sort_cookie_name].value kwargs[eself.sort_kwarg] = sort_val
def browse_category_group(self, category=None, group=None, category_sort=None): sort = category_sort
def browse_category_group(self, category=None, group=None, sort=None): if sort == 'null': sort = None
def browse_category_group(self, category=None, group=None, category_sort=None): sort = category_sort if sort not in ('rating', 'name', 'popularity'): sort = 'name' categories = self.categories_cache() if category not in categories: raise cherrypy.HTTPError(404, 'category not found')
@Endpoint(mimetype='application/json; charset=utf-8', sort_type='list') def browse_booklist_page(self, ids=None, list_sort=None):
@Endpoint(mimetype='application/json; charset=utf-8') def browse_booklist_page(self, ids=None, sort=None): if sort == 'null': sort = None
def browse_matches(self, category=None, cid=None, list_sort=None): if not cid: raise cherrypy.HTTPError(404, 'invalid category id: %r'%cid) categories = self.categories_cache()
if f.lower().endswith('.opf'):
if f.lower().endswith('.opf') and '__MACOSX' not in f:
def convert(self, stream, options, file_ext, log, accelerators): from calibre.utils.zipfile import ZipFile from calibre import walk from calibre.ebooks import DRMError from calibre.ebooks.metadata.opf2 import OPF zf = ZipFile(stream) zf.extractall(os.getcwd()) encfile = os.path.abspath(os.path.join('META-INF', 'encryption.xml')) opf = None for f in walk(u'.'): if f.lower().endswith('.opf'): opf = os.path.abspath(f) break path = getattr(stream, 'name', 'stream')
mi.title = mdata[0] mi.authors = [mdata[1]] mi.publisher = mdata[3] mi.isbn = mdata[4]
mi.title = re.sub(r'[^a-zA-Z0-9 \._=\+\-!\?,\'\"]', '', mdata[0]) mi.authors = [re.sub(r'[^a-zA-Z0-9 \._=\+\-!\?,\'\"]', '', mdata[1])] mi.publisher = re.sub(r'[^a-zA-Z0-9 \._=\+\-!\?,\'\"]', '', mdata[3]) mi.isbn = re.sub(r'[^a-zA-Z0-9 \._=\+\-!\?,\'\"]', '', mdata[4])
def get_metadata(stream, extract_cover=True): """ Return metadata as a L{MetaInfo} object """ mi = MetaInformation(None, [_('Unknown')]) stream.seek(0) pheader = PdbHeaderReader(stream) # Only Dropbook produced 132 byte record0 files are supported if len(pheader.section_data(0)) == 132: hr = HeaderRecord(pheader.section_data(0)) if hr.compression in (2, 10) and hr.has_metadata == 1: try: mdata = pheader.section_data(hr.metadata_offset) mdata = mdata.split('\x00') mi.title = mdata[0] mi.authors = [mdata[1]] mi.publisher = mdata[3] mi.isbn = mdata[4] except: pass if extract_cover: mi.cover_data = get_cover(pheader, hr) if not mi.title: mi.title = pheader.title if pheader.title else _('Unknown') return mi
name = path.rpartition(getattr(self.device, 'path_sep', '/'))[2]
name = path.rpartition(os.sep)[2]
def _save_books(self, paths, target): '''Copy books from device to disk''' for path in paths: name = path.rpartition(getattr(self.device, 'path_sep', '/'))[2] dest = os.path.join(target, name) if os.path.abspath(dest) != os.path.abspath(path): f = open(dest, 'wb') self.device.get_file(path, f) f.close()
text.append(u'%s%s\n\n' % (CALIBRE_SNB_BM_TAG, self.curSubItem))
text.append(u'\n\n%s%s\n\n' % (CALIBRE_SNB_BM_TAG, self.curSubItem))
def dump_text(self, subitems, elem, stylizer, end='', pre=False, li = ''):
text.append(u'%s%s' % (CALIBRE_SNB_IMG_TAG, ProcessFileName(elem.attrib['src'])))
text.append(u'\n\n%s%s\n\n' % (CALIBRE_SNB_IMG_TAG, ProcessFileName(elem.attrib['src'])))
def dump_text(self, subitems, elem, stylizer, end='', pre=False, li = ''):
li = '-- '
li = '- '
def dump_text(self, subitems, elem, stylizer, end='', pre=False, li = ''):
t[0].extract()
try: alt = t[0].img['alt'].lower() if alt.find('prev') != -1 or alt.find('next') != -1 or alt.find('team') != -1: t[0].extract() except: pass
def _reformat(self, data): try: data = xml_to_unicode(data, strip_encoding_pats=True)[0] soup = BeautifulSoup(data) except ValueError: # hit some strange encoding problems... print "Unable to parse html for cleaning, leaving it :(" return data # nuke javascript... [s.extract() for s in soup('script')] # remove forward and back nav bars from the top/bottom of each page # cos they really fuck with the flow of things and generally waste space # since we can't use [a,b] syntax to select arbitrary items from a list # we'll have to do this manually... t = soup('table') if t: if (t[0].previousSibling is None or t[0].previousSibling.previousSibling is None): t[0].extract() if (t[-1].nextSibling is None or t[-1].nextSibling.nextSibling is None): t[-1].extract() # for some very odd reason each page's content appears to be in a table # too. and this table has sub-tables for random asides... grr.
t[-1].extract()
try: alt = t[-1].img['alt'].lower() if alt.find('prev') != -1 or alt.find('next') != -1 or alt.find('team') != -1: t[-1].extract() except: pass
def _reformat(self, data): try: data = xml_to_unicode(data, strip_encoding_pats=True)[0] soup = BeautifulSoup(data) except ValueError: # hit some strange encoding problems... print "Unable to parse html for cleaning, leaving it :(" return data # nuke javascript... [s.extract() for s in soup('script')] # remove forward and back nav bars from the top/bottom of each page # cos they really fuck with the flow of things and generally waste space # since we can't use [a,b] syntax to select arbitrary items from a list # we'll have to do this manually... t = soup('table') if t: if (t[0].previousSibling is None or t[0].previousSibling.previousSibling is None): t[0].extract() if (t[-1].nextSibling is None or t[-1].nextSibling.nextSibling is None): t[-1].extract() # for some very odd reason each page's content appears to be in a table # too. and this table has sub-tables for random asides... grr.
return soup.prettify('utf-8')
try: tables = soup.body.findAll('table', recursive=False) if tables and len(tables) == 1: trs = tables[0].findAll('tr', recursive=False) if trs and len(trs) == 1: tds = trs[0].findAll('td', recursive=False) if tds and len(tds) == 1: tdContents = tds[0].contents tableIdx = soup.body.contents.index(tables[0]) tables[0].extract() while tdContents: soup.body.insert(tableIdx, tdContents.pop()) except: pass return str(soup)
def _reformat(self, data): try: data = xml_to_unicode(data, strip_encoding_pats=True)[0] soup = BeautifulSoup(data) except ValueError: # hit some strange encoding problems... print "Unable to parse html for cleaning, leaving it :(" return data # nuke javascript... [s.extract() for s in soup('script')] # remove forward and back nav bars from the top/bottom of each page # cos they really fuck with the flow of things and generally waste space # since we can't use [a,b] syntax to select arbitrary items from a list # we'll have to do this manually... t = soup('table') if t: if (t[0].previousSibling is None or t[0].previousSibling.previousSibling is None): t[0].extract() if (t[-1].nextSibling is None or t[-1].nextSibling.nextSibling is None): t[-1].extract() # for some very odd reason each page's content appears to be in a table # too. and this table has sub-tables for random asides... grr.
subprocess.Popen([exe, '--gui-debug', logpath], stdout=fd, stderr=fd) time.sleep(1)
creationflags = 0 if iswindows: import win32process creationflags = win32process.CREATE_NO_WINDOW subprocess.Popen([exe, '--gui-debug', logpath], stdout=open(logpath, 'w'), stderr=subprocess.STDOUT, stdin=open(os.devnull, 'r'), creationflags=creationflags)
def run_in_debug_mode(logpath=None): e = sys.executable if getattr(sys, 'frozen', False) else sys.argv[0] import tempfile, subprocess fd, logpath = tempfile.mkstemp('.txt') if hasattr(sys, 'frameworks_dir'): base = os.path.dirname(sys.frameworks_dir) if 'console.app' not in base: base = os.path.join(base, 'console.app', 'Contents') exe = os.path.basename(e) exe = os.path.join(base, 'MacOS', exe+'-debug') else: base, ext = os.path.splitext(e) exe = base + '-debug' + ext print 'Starting debug executable:', exe subprocess.Popen([exe, '--gui-debug', logpath], stdout=fd, stderr=fd) time.sleep(1) # Give subprocess a change to launch, before fd is closed
subprocess.Popen([e, '--show-gui-debug', runner.main.gui_debug])
creationflags = 0 if iswindows: import win32process creationflags = win32process.CREATE_NO_WINDOW subprocess.Popen([e, '--show-gui-debug', runner.main.gui_debug], creationflags=creationflags, stdout=open(os.devnull, 'w'), stderr=subprocess.PIPE, stdin=open(os.devnull, 'r'))
def run_gui(opts, args, actions, listener, app, gui_debug=None): initialize_file_icon_provider() if not dynamic.get('welcome_wizard_was_run', False): from calibre.gui2.wizard import wizard wizard().exec_() dynamic.set('welcome_wizard_was_run', True) runner = GuiRunner(opts, args, actions, listener, app, gui_debug=gui_debug) ret = app.exec_() if getattr(runner.main, 'run_wizard_b4_shutdown', False): from calibre.gui2.wizard import wizard wizard().exec_() if getattr(runner.main, 'restart_after_quit', False): e = sys.executable if getattr(sys, 'frozen', False) else sys.argv[0] if getattr(runner.main, 'debug_on_restart', False): run_in_debug_mode() else: print 'Restarting with:', e, sys.argv if hasattr(sys, 'frameworks_dir'): app = os.path.dirname(os.path.dirname(sys.frameworks_dir)) import subprocess subprocess.Popen('sleep 3s; open '+app, shell=True) else: os.execvp(e, sys.argv) else: if iswindows: try: runner.main.system_tray_icon.hide() except: pass if runner.main.gui_debug is not None: e = sys.executable if getattr(sys, 'frozen', False) else sys.argv[0] import subprocess subprocess.Popen([e, '--show-gui-debug', runner.main.gui_debug]) return ret
self.setFocus(Qt.OtherFocusReason) if not txt: self.clear() else: self.normalize_state() self.setEditText(txt) self.line_edit.end(False) if emit_changed: self.changed.emit() self._do_search(store_in_history=store_in_history) self.focus_to_library.emit()
if not store_in_history: self.activated.disconnect() try: self.setFocus(Qt.OtherFocusReason) if not txt: self.clear() else: self.normalize_state() self.setEditText(txt) self.line_edit.end(False) if emit_changed: self.changed.emit() self._do_search(store_in_history=store_in_history) self.focus_to_library.emit() finally: if not store_in_history: self.activated.connect(self.history_selected)
def set_search_string(self, txt, store_in_history=False, emit_changed=True): self.setFocus(Qt.OtherFocusReason) if not txt: self.clear() else: self.normalize_state() self.setEditText(txt) self.line_edit.end(False) if emit_changed: self.changed.emit() self._do_search(store_in_history=store_in_history) self.focus_to_library.emit()
chapter_index += self.index_item(r'(?s)\\X(?P<val>[0-4])(?P<text>.+?)\\X[0-4]', pml) chapter_index += self.index_item(r'(?s)\\x(?P<text>.+?)\\x', pml)
chapter_index += self._index_item(r'(?s)\\X(?P<val>[0-4])(?P<text>.+?)\\X[0-4]', pml) chapter_index += self._index_item(r'(?s)\\x(?P<text>.+?)\\x', pml)
def write_content(self, oeb_book, out_stream, metadata=None): pmlmlizer = PMLMLizer(self.log) pml = unicode(pmlmlizer.extract_content(oeb_book, self.opts)).encode('cp1252', 'replace')
html = re.sub(r'<p>\s*</p>', '', html)
html = re.sub(r'(?imu)<p>\s*</p>', '', html)
def cleanup_html_remove_redundant(self, html): for key in self.STATES_TAGS.keys(): open, close = self.STATES_TAGS[key] if key in self.STATES_VALUE_REQ: html = re.sub(r'(?u)%s\s*%s' % (open % '.*?', close), '', html) else: html = re.sub(r'(?u)%s\s*%s' % (open, close), '', html) html = re.sub(r'<p>\s*</p>', '', html) return html
def __init__(self, server, path):
def __init__(self, server, path, interface):
def __init__(self, server, path): self.ok, self.err = True, None try: import dbus self.dbus = dbus self._notify = dbus.SessionBus().get_object(server, path) except Exception, err: self.ok = False self.err = str(err)
self._notify = dbus.SessionBus().get_object(server, path)
self._notify = dbus.Interface(dbus.SessionBus().get_object(server, path), interface)
def __init__(self, server, path): self.ok, self.err = True, None try: import dbus self.dbus = dbus self._notify = dbus.SessionBus().get_object(server, path) except Exception, err: self.ok = False self.err = str(err)
'/VisualNotifications')
'/VisualNotifications', 'org.kde.VisualNotifications')
def __init__(self): DBUSNotifier.__init__(self, 'org.kde.VisualNotifications', '/VisualNotifications')
'/org/freedesktop/Notifications')
'/org/freedesktop/Notifications', 'org.freedesktop.Notifications')
def __init__(self): DBUSNotifier.__init__(self, 'org.freedesktop.Notifications', '/org/freedesktop/Notifications')
series_start_value, do_title_case, clear_series = self.args
series_start_value, do_title_case, cover_action, clear_series = self.args
def do_one(self, id): remove_all, remove, add, au, aus, do_aus, rating, pub, do_series, \ do_autonumber, do_remove_format, remove_format, do_swap_ta, \ do_remove_conv, do_auto_author, series, do_series_restart, \ series_start_value, do_title_case, clear_series = self.args
series_start_value, do_title_case, clear_series)
series_start_value, do_title_case, cover_action, clear_series)
def accept(self): if len(self.ids) < 1: return QDialog.accept(self)
g.setToolTip('\n'.join(w.wrap(help))) g.setWhatsThis('\n'.join(w.wrap(help)))
htext = u'<div>%s</div>'%prepare_string_for_xml( '\n'.join(w.wrap(help))) g.setToolTip(htext) g.setWhatsThis(htext)
def setup_help(self, help_provider): w = textwrap.TextWrapper(80) for name in self._options: g = getattr(self, 'opt_'+name, None) if g is None: continue help = help_provider(name) if not help: continue g._help = help g.setToolTip('\n'.join(w.wrap(help))) g.setWhatsThis('\n'.join(w.wrap(help))) g.__class__.enterEvent = lambda obj, event: self.set_help(getattr(obj, '_help', obj.toolTip()))
if get_cover and mi.cover is None:
if get_cover:
def get_metadata(self, idx, index_is_id=False, get_cover=False): ''' Convenience method to return metadata as a :class:`Metadata` object. Note that the list of formats is not verified. ''' self.gm_count += 1 mi = self.data.get(idx, self.FIELD_MAP['all_metadata'], row_is_id = index_is_id) if mi is not None: if get_cover and mi.cover is None: mi.cover = self.cover(idx, index_is_id=index_is_id, as_path=True) return mi
elif mi.cover is not None and os.access(mi.cover, os.R_OK): doit(self.set_cover, id, lopen(mi.cover, 'rb'))
elif mi.cover is not None: if os.access(mi.cover, os.R_OK): with lopen(mi.cover, 'rb') as f: doit(self.set_cover, id, f)
def doit(func, *args, **kwargs): try: func(*args, **kwargs) except: if ignore_errors: traceback.print_exc() else: raise
(re.compile(u'˛\s*(<br.*?>)*\s*a', re.UNICODE), lambda match: u'ą'), (re.compile(u'˛\s*(<br.*?>)*\s*A', re.UNICODE), lambda match: u'Ą'),
(re.compile(u'\s*˛\s*(<br.*?>)*\s*a', re.UNICODE), lambda match: u'ą'), (re.compile(u'\s*˛\s*(<br.*?>)*\s*A', re.UNICODE), lambda match: u'Ą'),
def __call__(self, data, add_namespace=False): from calibre.ebooks.oeb.base import XHTML_CSS_NAMESPACE data = self.PAGE_PAT.sub('', data) if not add_namespace: return data ans, namespaced = [], False for line in data.splitlines(): ll = line.lstrip() if not (namespaced or ll.startswith('@import') or ll.startswith('@charset')): ans.append(XHTML_CSS_NAMESPACE.strip()) namespaced = True ans.append(line)
self.oeb.warn('Ignoring toc item: %s not found in document.' % item)
self.oeb_book.warn('Ignoring toc item: %s not found in document.' % item)
def get_toc(self): ''' Generation of inline TOC '''
if self.as_you_type: self.timer.start(1500)
def mouse_released(self, event): self.normalize_state() if self.as_you_type: self.timer.start(1500)
self.authors_delegate.set_auto_complete_function(db.all_authors)
self.authors_delegate.set_auto_complete_function( lambda: [(x, y.replace('|', ',')) for (x, y) in db.all_authors()])
def set_database(self, db): self.save_state() self._model.set_database(db) self.tags_delegate.set_database(db) self.authors_delegate.set_auto_complete_function(db.all_authors) self.series_delegate.set_auto_complete_function(db.all_series) self.publisher_delegate.set_auto_complete_function(db.all_publishers)
all_ids = self.search_cache('') if category == 'newest': ids = all_ids hide_sort = 'true' elif category == 'allbooks': ids = all_ids
def browse_matches(self, category=None, cid=None, list_sort=None): if list_sort: list_sort = unquote(list_sort) if not cid: raise cherrypy.HTTPError(404, 'invalid category id: %r'%cid) categories = self.categories_cache()
q = category if q == 'news': q = 'tags' ids = self.db.get_books_for_category(q, cid) ids = [x for x in ids if x in all_ids]
all_ids = self.search_cache('') if category == 'newest': ids = all_ids hide_sort = 'true' elif category == 'allbooks': ids = all_ids else: q = category if q == 'news': q = 'tags' ids = self.db.get_books_for_category(q, cid) ids = [x for x in ids if x in all_ids]
def browse_matches(self, category=None, cid=None, list_sort=None): if list_sort: list_sort = unquote(list_sort) if not cid: raise cherrypy.HTTPError(404, 'invalid category id: %r'%cid) categories = self.categories_cache()
self.processed_html = re.sub(r'<?xml[^>]*>', '', self.processed_html)
self.processed_html = re.sub(r'<\?xml[^>]*>', '', self.processed_html)
def cleanup_html(self): self.log.debug('Cleaning up HTML...') self.processed_html = re.sub(r'<div height="0(pt|px|ex|em|%){0,1}"></div>', '', self.processed_html) if self.book_header.ancient and '<html' not in self.mobi_html[:300].lower(): self.processed_html = '<html><p>' + self.processed_html.replace('\n\n', '<p>') + '</html>' self.processed_html = self.processed_html.replace('\r\n', '\n') self.processed_html = self.processed_html.replace('> <', '>\n<') self.processed_html = self.processed_html.replace('<mbp: ', '<mbp:') self.processed_html = re.sub(r'<?xml[^>]*>', '', self.processed_html) # Swap inline and block level elements, and order block level elements according to priority # - lxml and beautifulsoup expect/assume a specific order based on xhtml spec self.processed_html = re.sub(r'(?i)(?P<styletags>(<(h\d+|i|b|u|em|small|big|strong|tt)>\s*){1,})(?P<para><p[^>]*>)', '\g<para>'+'\g<styletags>', self.processed_html) self.processed_html = re.sub(r'(?i)(?P<para></p[^>]*>)\s*(?P<styletags>(</(h\d+|i|b|u|em|small|big|strong|tt)>\s*){1,})', '\g<styletags>'+'\g<para>', self.processed_html) self.processed_html = re.sub(r'(?i)(?P<blockquote>(</blockquote[^>]*>\s*){1,})(?P<para></p[^>]*>)', '\g<para>'+'\g<blockquote>', self.processed_html) self.processed_html = re.sub(r'(?i)(?P<para><p[^>]*>)\s*(?P<blockquote>(<blockquote[^>]*>\s*){1,})', '\g<blockquote>'+'\g<para>', self.processed_html)
log.debug('Output the modified chapter again: %s' % lastName)
def convert(self, oeb_book, output_path, input_plugin, opts, log): # Create temp dir with TemporaryDirectory('_snb_output') as tdir: # Create stub directories snbfDir = os.path.join(tdir, 'snbf') snbcDir = os.path.join(tdir, 'snbc') snbiDir = os.path.join(tdir, 'snbc/images') os.mkdir(snbfDir) os.mkdir(snbcDir) os.mkdir(snbiDir)
if q.lower().strip() != 'y':
if q.lower().strip() != _('y'):
def do_remove_custom_column(db, label, force): if not force: q = raw_input(_('You will lose all data in the column: %r.' ' Are you sure (y/n)? ')%label) if q.lower().strip() != 'y': return db.delete_custom_column(label=label) prints('Column %r removed.'%label)
if hrefs[path].media_type not in OEB_DOCS:
if path not in hrefs or hrefs[path].media_type not in OEB_DOCS:
def serialize_guide(self): buffer = self.buffer hrefs = self.oeb.manifest.hrefs buffer.write('<guide>') for ref in self.oeb.guide.values(): path = urldefrag(ref.href)[0] if hrefs[path].media_type not in OEB_DOCS: continue
numerator = float(re.search('[0-9.]+', numerator).group())
numerator = float(re.search('[0-9.\-]+', numerator).group())
def divide_num(self, numerator, denominator): try: numerator = float(re.search('[0-9.]+', numerator).group()) except TypeError, msg: if self.__run_level > 3: msg = 'no number to process?\n' msg += 'this indicates that the token ' msg += ' \(\\li\) should have a number and does not\n' msg += 'numerator is "%s"\n' % numerator msg += 'denominator is "%s"\n' % denominator raise self.__bug_handler, msg if 5 > self.__return_code: self.__return_code = 5 return 0 num = '%0.2f' % round(numerator/denominator, 2) return num string_num = str(num) if string_num[-2:] == ".0": string_num = string_num[:-2] return string_num
(_('Books in this series'), 'books_in_series.svg', 'series', _('Alt+S')),
(_('Books in this series'), 'books_in_series.svg', 'series', _('Alt+Shift+S')),
def genesis(self): m = QMenu(self.gui) for text, icon, target, shortcut in [ (_('Books by same author'), 'user_profile.svg', 'authors', _('Alt+A')), (_('Books in this series'), 'books_in_series.svg', 'series', _('Alt+S')), (_('Books by this publisher'), 'publisher.png', 'publisher', _('Alt+P')), (_('Books with the same tags'), 'tags.svg', 'tag', _('Alt+T')),]: ac = self.create_action(spec=(text, icon, None, shortcut), attr=target) m.addAction(ac) ac.triggered.connect(partial(self.show_similar_books, target)) self.qaction.setMenu(m) self.similar_menu = m
page.mainFrame().load(QUrl.fromLocalFile(path_to_html))
page.mainFrame().setContent(open(path_to_html, 'rb').read(), 'application/xhtml+xml', QUrl.fromLocalFile(path_to_html))
def render_html(path_to_html, width=590, height=750): from PyQt4.QtWebKit import QWebPage from PyQt4.Qt import QEventLoop, QPalette, Qt, SIGNAL, QUrl, QSize from calibre.gui2 import is_ok_to_use_qt if not is_ok_to_use_qt(): return None path_to_html = os.path.abspath(path_to_html) with CurrentDir(os.path.dirname(path_to_html)): page = QWebPage() pal = page.palette() pal.setBrush(QPalette.Background, Qt.white) page.setPalette(pal) page.setViewportSize(QSize(width, height)) page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) loop = QEventLoop() renderer = HTMLRenderer(page, loop) page.connect(page, SIGNAL('loadFinished(bool)'), renderer, Qt.QueuedConnection) page.mainFrame().load(QUrl.fromLocalFile(path_to_html)) loop.exec_() renderer.loop = renderer.page = None del page del loop return renderer
print "Filename: " + filename
def update_booklist(mountpath, ContentID, filename, title, authors, mime, date, ContentType, ImageID): changed = False # if path_to_ext(filename) in self.FORMATS: try: # lpath = os.path.join(path, filename).partition(self.normalize_path(prefix))[2] # if lpath.startswith(os.sep): # lpath = lpath[len(os.sep):] # lpath = lpath.replace('\\', '/') print "Filename: " + filename filename = self.normalize_path(filename) print "Normalized FileName: " + filename
print "Normalized FileName: " + filename
def update_booklist(mountpath, ContentID, filename, title, authors, mime, date, ContentType, ImageID): changed = False # if path_to_ext(filename) in self.FORMATS: try: # lpath = os.path.join(path, filename).partition(self.normalize_path(prefix))[2] # if lpath.startswith(os.sep): # lpath = lpath[len(os.sep):] # lpath = lpath.replace('\\', '/') print "Filename: " + filename filename = self.normalize_path(filename) print "Normalized FileName: " + filename
print "Image name Normalized: " + imagename
def update_booklist(mountpath, ContentID, filename, title, authors, mime, date, ContentType, ImageID): changed = False # if path_to_ext(filename) in self.FORMATS: try: # lpath = os.path.join(path, filename).partition(self.normalize_path(prefix))[2] # if lpath.startswith(os.sep): # lpath = lpath[len(os.sep):] # lpath = lpath.replace('\\', '/') print "Filename: " + filename filename = self.normalize_path(filename) print "Normalized FileName: " + filename
print "Delete file normalized path: " + path
def delete_books(self, paths, end_session=True): for i, path in enumerate(paths): self.report_progress((i+1) / float(len(paths)), _('Removing books from device...')) path = self.normalize_path(path) print "Delete file normalized path: " + path extension = os.path.splitext(path)[1]
title['title_sort'][0:40])).encode('utf-8'))
title['title_sort'][0:40])).decode('mac-roman'))
def fetchBooksByTitle(self):
href = '/browse/matches/%s/%s'%(category, id_)
q = i.category if not q: q = category href = '/browse/matches/%s/%s'%(q, id_)
def item(i): templ = (u'<div title="{4}" class="category-item">' '<div class="category-name">{0}</div><div>{1}</div>' '<div>{2}' '<span class="href">{3}</span></div></div>') rating, rstring = render_rating(i.avg_rating) name = xml(i.name) if datatype == 'rating': name = xml(_('%d stars')%int(i.avg_rating)) id_ = i.id if id_ is None: id_ = hexlify(force_unicode(name).encode('utf-8')) id_ = xml(str(id_)) desc = '' if i.count > 0: desc += '[' + _('%d books')%i.count + ']' href = '/browse/matches/%s/%s'%(category, id_) return templ.format(xml(name), rating, xml(desc), xml(href), rstring)
if oncard != 'carda' and oncard != 'cardb':
if oncard != 'carda' and oncard != 'cardb' and not row[3].startswith("file:///mnt/sd/"): changed = update_booklist(self._main_prefix, path, row[0], row[1], mime, row[2], row[5], row[6])
def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID): changed = False # if path_to_ext(path) in self.FORMATS: try: lpath = path.partition(self.normalize_path(prefix))[2] if lpath.startswith(os.sep): lpath = lpath[len(os.sep):] lpath = lpath.replace('\\', '/')
changed = update_booklist(self._main_prefix, path, row[0], row[1], mime, row[2], row[5], row[6]) elif oncard == 'carda':
elif oncard == 'carda' and row[3].startswith("file:///mnt/sd/"):
def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID): changed = False # if path_to_ext(path) in self.FORMATS: try: lpath = path.partition(self.normalize_path(prefix))[2] if lpath.startswith(os.sep): lpath = lpath[len(os.sep):] lpath = lpath.replace('\\', '/')
else: print "Add card b support"
def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID): changed = False # if path_to_ext(path) in self.FORMATS: try: lpath = path.partition(self.normalize_path(prefix))[2] if lpath.startswith(os.sep): lpath = lpath[len(os.sep):] lpath = lpath.replace('\\', '/')
if oncard != 'carda' and oncard != 'cardb':
if oncard == 'cardb': print 'path from_contentid cardb' elif oncard == 'carda': path = path.replace("file:///mnt/sd/", self._card_a_prefix) else:
def path_from_contentid(self, ContentID, ContentType, oncard): path = ContentID
path = self._main_prefix + os.sep + path + '.kobo'
path = self._main_prefix + path + '.kobo'
def path_from_contentid(self, ContentID, ContentType, oncard): path = ContentID
if path.startswith("file:///mnt/onboard/"): path = path.replace("file:///mnt/onboard/", self._main_prefix)
path = path.replace("file:///mnt/onboard/", self._main_prefix)
def path_from_contentid(self, ContentID, ContentType, oncard): path = ContentID
elif oncard == 'carda': if path.startswith("file:///mnt/sd/"): path = path.replace("file:///mnt/sd/", self._card_a_prefix)
def path_from_contentid(self, ContentID, ContentType, oncard): path = ContentID
self.options = options
self.opts = options
def convert(self, stream, options, file_ext, log, accelerators): from calibre.ebooks.metadata.meta import get_metadata from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.ebooks.rtf2xml.ParseRtf import RtfInvalidCodeException self.options = options self.log = log self.log('Converting RTF to XML...') #Name of the preprocesssed RTF file fname = self.preprocess(stream.name) try: xml = self.generate_xml(fname) except RtfInvalidCodeException, e: raise ValueError(_('This RTF file has a feature calibre does not ' 'support. Convert it to HTML first and then try it.\n%s')%e)
if not getattr(self.options, 'remove_paragraph_spacing', False):
if not getattr(self.opts, 'remove_paragraph_spacing', False):
def convert(self, stream, options, file_ext, log, accelerators): from calibre.ebooks.metadata.meta import get_metadata from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.ebooks.rtf2xml.ParseRtf import RtfInvalidCodeException self.options = options self.log = log self.log('Converting RTF to XML...') #Name of the preprocesssed RTF file fname = self.preprocess(stream.name) try: xml = self.generate_xml(fname) except RtfInvalidCodeException, e: raise ValueError(_('This RTF file has a feature calibre does not ' 'support. Convert it to HTML first and then try it.\n%s')%e)
if self.options.preprocess_html: preprocessor = PreProcessor(self.options, log=getattr(self, 'log', None))
if self.opts.preprocess_html: preprocessor = PreProcessor(self.opts, log=getattr(self, 'log', None))
def convert(self, stream, options, file_ext, log, accelerators): from calibre.ebooks.metadata.meta import get_metadata from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.ebooks.rtf2xml.ParseRtf import RtfInvalidCodeException self.options = options self.log = log self.log('Converting RTF to XML...') #Name of the preprocesssed RTF file fname = self.preprocess(stream.name) try: xml = self.generate_xml(fname) except RtfInvalidCodeException, e: raise ValueError(_('This RTF file has a feature calibre does not ' 'support. Convert it to HTML first and then try it.\n%s')%e)
def smart_update(self, other):
def smart_update(self, other, replace_metadata=False):
def smart_update(self, other): ''' Merge the information in C{other} into self. In case of conflicts, the information in C{other} takes precedence, unless the information in C{other} is NULL. '''
MetaInformation.smart_update(self, other, replace_metadata=True)
MetaInformation.smart_update(self, other, replace_metadata)
def smart_update(self, other): ''' Merge the information in C{other} into self. In case of conflicts, the information in C{other} takes precedence, unless the information in C{other} is NULL. '''
self[b].smart_update(book)
self[b].smart_update(book, replace_metadata=True)
def add_book(self, book, replace_metadata): try: b = self.index(book) except (ValueError, IndexError): b = None if b is None: self.append(book) return True if replace_metadata: self[b].smart_update(book) return True return False
root = soupparser.fromstring(raw)
try: root = soupparser.fromstring(raw) except: return False
def get_metadata(br, asin, mi): q = 'http://amzn.com/'+asin try: raw = br.open_novisit(q).read() except Exception, e: if callable(getattr(e, 'getcode', None)) and \ e.getcode() == 404: return False raise if '<title>404 - ' in raw: return False raw = xml_to_unicode(raw, strip_encoding_pats=True, resolve_entities=True)[0] root = soupparser.fromstring(raw) ratings = root.xpath('//form[@id="handleBuy"]/descendant::*[@class="asinReviewsSummary"]') if ratings: pat = re.compile(r'([0-9.]+) out of (\d+) stars') r = ratings[0] for elem in r.xpath('descendant::*[@title]'): t = elem.get('title') m = pat.match(t) if m is not None: try: mi.rating = float(m.group(1))/float(m.group(2)) * 5 break except: pass desc = root.xpath('//div[@id="productDescription"]/*[@class="content"]') if desc: desc = desc[0] for c in desc.xpath('descendant::*[@class="seeAll" or' ' @class="emptyClear" or @href]'): c.getparent().remove(c) desc = html.tostring(desc, method='html', encoding=unicode).strip() # remove all attributes from tags desc = re.sub(r'<([a-zA-Z0-9]+)\s[^>]+>', r'<\1>', desc) # Collapse whitespace #desc = re.sub('\n+', '\n', desc) #desc = re.sub(' +', ' ', desc) # Remove the notice about text referring to out of print editions desc = re.sub(r'(?s)<em>--This text ref.*?</em>', '', desc) # Remove comments desc = re.sub(r'(?s)<!--.*?-->', '', desc) mi.comments = sanitize_comments_html(desc) return True
oeb.metadata.add('title', meta.find('.//head/name').text) oeb.metadata.add('creator', meta.find('.//head/author').text, attrib={'role':'aut'}) oeb.metadata.add('language', meta.find('.//head/language').text.lower().replace('_', '-')) oeb.metadata.add('creator', meta.find('.//head/generator').text) oeb.metadata.add('publisher', meta.find('.//head/publisher').text) cover = meta.find('.//head/cover') if cover != None and cover.text != None: oeb.guide.add('cover', 'Cover', cover.text)
l = { 'title' : './/head/name', 'creator' : './/head/author', 'language' : './/head/language', 'generator': './/head/generator', 'publisher': './/head/publisher', 'cover' : './/head/cover', } d = {} for item in l: node = meta.find(l[item]) if node != None: d[item] = node.text if node.text != None else '' else: d[item] = '' oeb.metadata.add('title', d['title']) oeb.metadata.add('creator', d['creator'], attrib={'role':'aut'}) oeb.metadata.add('language', d['language'].lower().replace('_', '-')) oeb.metadata.add('generator', d['generator']) oeb.metadata.add('publisher', d['publisher']) if d['cover'] != '': oeb.guide.add('cover', 'Cover', d['cover'])
def convert(self, stream, options, file_ext, log, accelerators): log.debug("Parsing SNB file...") snbFile = SNBFile() try: snbFile.Parse(stream) except: raise ValueError("Invalid SNB file") if not snbFile.IsValid(): log.debug("Invaild SNB file") raise ValueError("Invalid SNB file") log.debug("Handle meta data ...") from calibre.ebooks.conversion.plumber import create_oebbook oeb = create_oebbook(log, None, options, self, encoding=options.input_encoding, populate=False) meta = snbFile.GetFileStream('snbf/book.snbf') if meta != None: meta = etree.fromstring(meta) oeb.metadata.add('title', meta.find('.//head/name').text) oeb.metadata.add('creator', meta.find('.//head/author').text, attrib={'role':'aut'}) oeb.metadata.add('language', meta.find('.//head/language').text.lower().replace('_', '-')) oeb.metadata.add('creator', meta.find('.//head/generator').text) oeb.metadata.add('publisher', meta.find('.//head/publisher').text) cover = meta.find('.//head/cover') if cover != None and cover.text != None: oeb.guide.add('cover', 'Cover', cover.text)
deb_dir = 'D:\\calibre\\pierre\\debug\\rtfdebug',
deb_dir = 'H:\\Temp\\Calibre\\rtfdebug',
def generate_xml(self, stream): from calibre.ebooks.rtf2xml.ParseRtf import ParseRtf ofile = 'out.xml' parser = ParseRtf( in_file = stream, out_file = ofile,
typical_chapters = r".?(Introduction|Synopsis|Acknowledgements|Chapter|Epilogue|Volume\s|Prologue|Book\s|Part\s|Dedication)\s*([\d\w-]+\:?\s*){0,4}"
typical_chapters = r".?(Introduction|Synopsis|Acknowledgements|Chapter|Kapitel|Epilogue|Volume\s|Prologue|Book\s|Part\s|Dedication)\s*([\d\w-]+\:?\s*){0,4}"
def __call__(self, html): self.log("********* Preprocessing HTML *********")
unwrap = re.compile(r"(?<=.{%i}([a-z,;):\IA]|(?<!\&\w{4});))\s*</(span|p|div)>\s*(</(p|span|div)>)?\s*(?P<up2threeblanks><(p|span|div)[^>]*>\s*(<(p|span|div)[^>]*>\s*</(span|p|div)>\s*)</(span|p|div)>\s*){0,3}\s*<(span|div|p)[^>]*>\s*(<(span|div|p)[^>]*>)?\s*" % length, re.UNICODE)
unwrap = re.compile(u"(?<=.{%i}([a-z,:)\IA\u00DF]|(?<!\&\w{4});))\s*</(span|p|div)>\s*(</(p|span|div)>)?\s*(?P<up2threeblanks><(p|span|div)[^>]*>\s*(<(p|span|div)[^>]*>\s*</(span|p|div)>\s*)</(span|p|div)>\s*){0,3}\s*<(span|div|p)[^>]*>\s*(<(span|div|p)[^>]*>)?\s*" % length, re.UNICODE)
def __call__(self, html): self.log("********* Preprocessing HTML *********")
self.db_book_title_cache[title] = {'authors':{}, 'db_ids':{}} authors = authors_to_string(mi.authors).lower() if mi.authors else '' authors = re.sub('(?u)\W|[_]', '', authors) self.db_book_title_cache[title]['authors'][authors] = mi
self.db_book_title_cache[title] = \ {'authors':{}, 'author_sort':{}, 'db_ids':{}} if mi.authors: authors = authors_to_string(mi.authors).lower() authors = re.sub('(?u)\W|[_]', '', authors) self.db_book_title_cache[title]['authors'][authors] = mi if mi.author_sort: aus = mi.author_sort.lower() aus = re.sub('(?u)\W|[_]', '', aus) self.db_book_title_cache[title]['author_sort'][aus] = mi
def set_books_in_library(self, booklists, reset=False): if reset: # First build a cache of the library, so the search isn't On**2 self.db_book_title_cache = {} self.db_book_uuid_cache = set() db = self.library_view.model().db for id in db.data.iterallids(): mi = db.get_metadata(id, index_is_id=True) title = re.sub('(?u)\W|[_]', '', mi.title.lower()) if title not in self.db_book_title_cache: self.db_book_title_cache[title] = {'authors':{}, 'db_ids':{}} authors = authors_to_string(mi.authors).lower() if mi.authors else '' authors = re.sub('(?u)\W|[_]', '', authors) self.db_book_title_cache[title]['authors'][authors] = mi self.db_book_title_cache[title]['db_ids'][mi.application_id] = mi self.db_book_uuid_cache.add(mi.uuid)
book_authors = authors_to_string(book.authors).lower() if book.authors else '' book_authors = re.sub('(?u)\W|[_]', '', book_authors) if book_authors in d['authors']: book.in_library = True book.smart_update(d['authors'][book_authors]) resend_metadata = True
if book.authors: book_authors = authors_to_string(book.authors).lower() book_authors = re.sub('(?u)\W|[_]', '', book_authors) if book_authors in d['authors']: book.in_library = True book.smart_update(d['authors'][book_authors]) resend_metadata = True elif book_authors in d['author_sort']: book.in_library = True book.smart_update(d['author_sort'][book_authors]) resend_metadata = True
def set_books_in_library(self, booklists, reset=False): if reset: # First build a cache of the library, so the search isn't On**2 self.db_book_title_cache = {} self.db_book_uuid_cache = set() db = self.library_view.model().db for id in db.data.iterallids(): mi = db.get_metadata(id, index_is_id=True) title = re.sub('(?u)\W|[_]', '', mi.title.lower()) if title not in self.db_book_title_cache: self.db_book_title_cache[title] = {'authors':{}, 'db_ids':{}} authors = authors_to_string(mi.authors).lower() if mi.authors else '' authors = re.sub('(?u)\W|[_]', '', authors) self.db_book_title_cache[title]['authors'][authors] = mi self.db_book_title_cache[title]['db_ids'][mi.application_id] = mi self.db_book_uuid_cache.add(mi.uuid)
return self.path == getattr(other, 'lpath', None)
return self.lpath == getattr(other, 'lpath', None)
def __eq__(self, other): # use lpath because the prefix can change, changing path return self.path == getattr(other, 'lpath', None)
OptionRecommendation(name='unwrap_factor', recommended_value=0.0, help=_('Average line length for line breaking if the HTML is from a ' 'previous partial conversion of a PDF file. Default is %default ' 'which disables this.')),
def get_filelist(htmlfile, dir, opts, log): ''' Build list of files referenced by html file or try to detect and use an OPF file instead. ''' log.info('Building file list...') filelist = traverse(htmlfile, max_levels=int(opts.max_levels), verbose=opts.verbose, encoding=opts.input_encoding)\ [0 if opts.breadth_first else 1] if opts.verbose: log.debug('\tFound files...') for f in filelist: log.debug('\t\t', f) return filelist
cherrypy.response.headers['Content-Type'] = 'text/xml'
cherrypy.response.headers['Content-Type'] = 'application/atom+xml;profile=opds-catalog'
def get_opds_acquisition_feed(self, ids, offset, page_url, up_url, id_, sort_by='title', ascending=True, version=0): idx = self.db.FIELD_MAP['id'] ids &= self.get_opds_allowed_ids_for_version(version) if not ids: raise cherrypy.HTTPError(404, 'No books found') items = [x for x in self.db.data.iterall() if x[idx] in ids] self.sort(items, sort_by, ascending) max_items = self.opts.max_opds_items offsets = OPDSOffsets(offset, max_items, len(items)) items = items[offsets.offset:offsets.offset+max_items] updated = self.db.last_modified() cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' return str(AcquisitionFeed(updated, id_, items, offsets, page_url, up_url, version, self.db.FIELD_MAP))
cherrypy.response.headers['Content-Type'] = 'text/xml'
cherrypy.response.headers['Content-Type'] = 'application/atom+xml'
def opds_category_group(self, category=None, which=None, version=0, offset=0): try: offset = int(offset) version = int(version) except: raise cherrypy.HTTPError(404, 'Not found')
cherrypy.response.headers['Content-Type'] = 'text/xml'
cherrypy.response.headers['Content-Type'] = 'application/atom+xml'
def __init__(self, text, count): self.text, self.count = text, count
cherrypy.response.headers['Content-Type'] = 'text/xml'
cherrypy.response.headers['Content-Type'] = 'application/atom+xml'
def opds(self, version=0): version = int(version) if version not in BASE_HREFS: raise cherrypy.HTTPError(404, 'Not found') categories = self.categories_cache( self.get_opds_allowed_ids_for_version(version)) category_meta = self.db.field_metadata cats = [ (_('Newest'), _('Date'), 'Onewest'), (_('Title'), _('Title'), 'Otitle'), ] for category in categories: if category == 'formats': continue meta = category_meta.get(category, None) if meta is None: continue cats.append((meta['name'], meta['name'], 'N'+category)) updated = self.db.last_modified()
if book.publisher: self.publisher.setEditText(book.publisher) if book.isbn: self.isbn.setText(book.isbn)
def fetch_metadata(self): isbn = re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text())) title = unicode(self.title.text()) try: author = string_to_authors(unicode(self.authors.text()))[0] except: author = '' publisher = unicode(self.publisher.currentText()) if isbn or title or author or publisher: d = FetchMetadata(self, isbn, title, author, publisher, self.timeout) self._fetch_metadata_scope = d with d: if d.exec_() == QDialog.Accepted: book = d.selected_book() if book: if d.opt_get_social_metadata.isChecked(): d2 = SocialMetadata(book, self) d2.exec_() if d2.exceptions: det = '\n'.join([x[0]+'\n\n'+x[-1]+'\n\n\n' for x in d2.exceptions]) warning_dialog(self, _('There were errors'), _('There were errors downloading social metadata'), det_msg=det, show=True) else: book.tags = [] if d.opt_overwrite_author_title_metadata.isChecked(): self.title.setText(book.title) self.authors.setText(authors_to_string(book.authors)) if book.author_sort: self.author_sort.setText(book.author_sort) if d.opt_overwrite_cover_image.isChecked() and book.has_cover: self.fetch_cover() if book.publisher: self.publisher.setEditText(book.publisher) if book.isbn: self.isbn.setText(book.isbn) if book.pubdate: d = book.pubdate self.pubdate.setDate(QDate(d.year, d.month, d.day)) summ = book.comments if summ: prefix = unicode(self.comments.toPlainText()) if prefix: prefix += '\n' self.comments.setPlainText(prefix + summ) if book.rating is not None: self.rating.setValue(int(book.rating)) if book.tags: self.tags.setText(', '.join(book.tags)) if book.series is not None: if self.series.text() is None or self.series.text() == '': self.series.setText(book.series) if book.series_index is not None: self.series_index.setValue(book.series_index) # Needed because of Qt focus bug on OS X self.fetch_cover_button.setFocus(Qt.OtherFocusReason) else: error_dialog(self, _('Cannot fetch metadata'), _('You must specify at least one of ISBN, Title, ' 'Authors or Publisher'), show=True) self.title.setFocus(Qt.OtherFocusReason)
timestamp = os.path.getctime(path)
timestamp = os.path.getmtime(path) if iswindows and time.daylight: timestamp -= time.altzone - time.timezone
def update_text_record(self, record, book, path, bl_index): timestamp = os.path.getctime(path) date = strftime(timestamp) if date != record.get('date', None): record.set('date', date) record.set('size', str(os.stat(path).st_size)) title = book.title if book.title else _('Unknown') record.set('title', title) ts = book.title_sort if not ts: ts = title_sort(title) record.set('titleSorter', ts) record.set('author', authors_to_string(book.authors)) ext = os.path.splitext(path)[1] if ext: ext = ext[1:].lower() mime = MIME_MAP.get(ext, None) if mime is None: mime = guess_type('a.'+ext)[0] if mime is not None: record.set('mime', mime) if 'sourceid' not in record.attrib: record.set('sourceid', '1') if 'id' not in record.attrib: num = self.max_id(record.getroottree().getroot()) record.set('id', str(num+1))
matches = selector(tree)
try: matches = selector(tree) except etree.XPathEvalError: continue
def __init__(self, tree, path, oeb, opts, profile=PROFILES['PRS505'], extra_css='', user_css=''): self.oeb, self.opts = oeb, opts self.profile = profile self.logger = oeb.logger item = oeb.manifest.hrefs[path] basename = os.path.basename(path) cssname = os.path.splitext(basename)[0] + '.css' stylesheets = [html_css_stylesheet()] head = xpath(tree, '/h:html/h:head') if head: head = head[0] else: head = []
ContentID = ContentID.replace(self._main_prefix + '.kobo/kepub/', '')
ContentID = ContentID.replace(self._main_prefix + self.normalize_path('.kobo/kepub/'), '')
def contentid_from_path(self, path, ContentType): if ContentType == 6: if self.dbversion < 8: ContentID = os.path.splitext(path)[0] # Remove the prefix on the file. it could be either ContentID = ContentID.replace(self._main_prefix, '') else: ContentID = path ContentID = ContentID.replace(self._main_prefix + '.kobo/kepub/', '')
datelastread = result[0] if result[0] is not None else '1970-01-01T00:00:00'
if result is None: datelastread = '1970-01-01T00:00:00' else: datelastread = result[0] if result[0] is not None else '1970-01-01T00:00:00'
def update_device_database_collections(self, booklists, collections_attributes, oncard):
hrefs = set(xpath(ncx, '//ncx:content/@src'))
hrefs = set(map(urlnormalize, xpath(ncx, '//ncx:content/@src')))
def _update_playorder(self, ncx): hrefs = set(xpath(ncx, '//ncx:content/@src')) playorder = {} next = 1 selector = XPath('h:body//*[@id or @name]') for item in self.spine: base = item.href if base in hrefs: playorder[base] = next next += 1 for elem in selector(item.data): added = False for attr in ('id', 'name'): id = elem.get(attr) if not id: continue href = '#'.join([base, id]) if href in hrefs: playorder[href] = next added = True if added: next += 1 selector = XPath('ncx:content/@src') for elem in xpath(ncx, '//*[@playOrder and ./ncx:content[@src]]'): href = selector(elem)[0] order = playorder.get(href, 0) elem.attrib['playOrder'] = str(order) return
for elem in xpath(ncx, '//*[@playOrder and ./ncx:content[@src]]'): href = selector(elem)[0] order = playorder.get(href, 0)
for i, elem in enumerate(xpath(ncx, '//*[@playOrder and ./ncx:content[@src]]')): href = urlnormalize(selector(elem)[0]) order = playorder.get(href, i)
def _update_playorder(self, ncx): hrefs = set(xpath(ncx, '//ncx:content/@src')) playorder = {} next = 1 selector = XPath('h:body//*[@id or @name]') for item in self.spine: base = item.href if base in hrefs: playorder[base] = next next += 1 for elem in selector(item.data): added = False for attr in ('id', 'name'): id = elem.get(attr) if not id: continue href = '#'.join([base, id]) if href in hrefs: playorder[href] = next added = True if added: next += 1 selector = XPath('ncx:content/@src') for elem in xpath(ncx, '//*[@playOrder and ./ncx:content[@src]]'): href = selector(elem)[0] order = playorder.get(href, 0) elem.attrib['playOrder'] = str(order) return
files = os.listdir(output_dir)
files = [x for x in os.listdir(output_dir) if os.path.isfile(os.path.join(output_dir, x))]
def ExtractFiles(self, output_dir=os.getcwdu()): for path in self.Contents(): lpath = os.path.join(output_dir, path) self._ensure_dir(lpath) try: data = self.GetFile(path) except: self.log.exception('Failed to extract %s from CHM, ignoring'%path) continue if lpath.find(';') != -1: # fix file names with ";<junk>" at the end, see _reformat() lpath = lpath.split(';')[0] try: with open(lpath, 'wb') as f: if guess_mimetype(path)[0] == ('text/html'): data = self._reformat(data) f.write(data) except: if iswindows and len(lpath) > 250: self.log.warn('%r filename too long, skipping'%path) continue raise self._extracted = True files = os.listdir(output_dir) if self.hhc_path not in files: for f in files: if f.lower() == self.hhc_path.lower(): self.hhc_path = f break if self.hhc_path not in files and files: self.hhc_path = files[0]
item = QListWidgetItem(model.headers[col], self.columns)
item = QListWidgetItem(model.orig_headers[col], self.columns)
def __init__(self, parent, model, server=None): ResizableDialog.__init__(self, parent) self.ICON_SIZES = {0:QSize(48, 48), 1:QSize(32,32), 2:QSize(24,24)} self._category_model = CategoryModel()
r.id = bl.rating and r.rating <> 0) avg_rating
r.id = bl.rating and r.rating <> 0) avg_rating, value AS sort
def create_custom_column(self, label, name, datatype, is_multiple, editable=True, display={}): if datatype not in self.CUSTOM_DATA_TYPES: raise ValueError('%r is not a supported data type'%datatype) normalized = datatype not in ('datetime', 'comments', 'int', 'bool', 'float') is_multiple = is_multiple and datatype in ('text',) num = self.conn.execute( ('INSERT INTO ' 'custom_columns(label,name,datatype,is_multiple,editable,display,normalized)' 'VALUES (?,?,?,?,?,?,?)'), (label, name, datatype, is_multiple, editable, json.dumps(display), normalized)).lastrowid
books_list_filter(bl.book)) avg_rating
books_list_filter(bl.book)) avg_rating, value AS sort
def create_custom_column(self, label, name, datatype, is_multiple, editable=True, display={}): if datatype not in self.CUSTOM_DATA_TYPES: raise ValueError('%r is not a supported data type'%datatype) normalized = datatype not in ('datetime', 'comments', 'int', 'bool', 'float') is_multiple = is_multiple and datatype in ('text',) num = self.conn.execute( ('INSERT INTO ' 'custom_columns(label,name,datatype,is_multiple,editable,display,normalized)' 'VALUES (?,?,?,?,?,?,?)'), (label, name, datatype, is_multiple, editable, json.dumps(display), normalized)).lastrowid
if role == Qt.FontRole:
if not isosx and role == Qt.FontRole:
def data(self, index, role): try: family = self.families[index.row()] except: traceback.print_exc() return NONE if role == Qt.DisplayRole: return QVariant(family) if role == Qt.FontRole: return QVariant(QFont(family)) return NONE
if isinstance(ans, unicode): ans = ans.encode('utf-8')
def browse_template(self, sort, category=True, initial_search=''):
val = rule.style.removeProperty('margin-left') pval = rule.style.getProperty('padding-left') if val and not pval: rule.style.setProperty('padding-left', val)
rule.style.removeProperty('margin-left') rule.style.removeProperty('padding-left')
def workaround_ade_quirks(self): # {{{ ''' Perform various markup transforms to get the output to render correctly in the quirky ADE. ''' from calibre.ebooks.oeb.base import XPath, XHTML, OEB_STYLES, barename, urlunquote
self.setMinimumSize(self.sizeHint())
try: self.setMinimumSize(self.sizeHint()) except: self.setMinimumSize(QSize(w+5, h+5))
def set_normal_icon_size(self, w, h): self.normal_icon_size = QSize(w, h) self.setIconSize(self.normal_icon_size) self.setMinimumSize(self.sizeHint())
return etree.fromstring(xml_to_unicode(raw, strip_encoding_pats=True, assume_utf8=True)[0], parser=parser)
raw = xml_to_unicode(raw, strip_encoding_pats=True, assume_utf8=True, resolve_entities=True)[0].strip() idx = raw.find('<html') if idx == -1: idx = raw.find('<HTML') if idx > -1: pre = raw[:idx] raw = raw[idx:] if '<!DOCTYPE' in pre: user_entities = {} for match in re.finditer(r'<!ENTITY\s+(\S+)\s+([^>]+)', pre): val = match.group(2) if val.startswith('"') and val.endswith('"'): val = val[1:-1] user_entities[match.group(1)] = val if user_entities: pat = re.compile(r'&(%s);'%('|'.join(user_entities.keys()))) raw = pat.sub(lambda m:user_entities[m.group(1)], raw) return etree.fromstring(raw, parser=parser)
def _parse(self, raw, mimetype): mt = mimetype.lower() if mt.endswith('+xml'): parser = etree.XMLParser(no_network=True, huge_tree=not iswindows) return etree.fromstring(xml_to_unicode(raw, strip_encoding_pats=True, assume_utf8=True)[0], parser=parser) return raw
print "has_cover called"
def has_cover(self, mi, ans, timeout=5.): print "has_cover called" if not mi.isbn: return False br = browser() try: if self.get_cover_url(mi.isbn, br, timeout=timeout) != None: self.debug('cover for', mi.isbn, 'found') ans.set() except Exception, e: self.debug(e)
root[-1].tail = '\n' + '\t'
if len(root) > 0: root[-1].tail = '\n\t' else: root.text = '\n\t'
def create_ext_text_record(self, root, bl_id, lpath, thumbnail): namespace = root.nsmap[None] attrib = { 'path': lpath } ans = root.makeelement('{%s}text'%namespace, attrib=attrib, nsmap=root.nsmap) ans.tail = '\n' root[-1].tail = '\n' + '\t' root.append(ans) if thumbnail and thumbnail[-1]: ans.text = '\n' + '\t\t' t = root.makeelement('{%s}thumbnail'%namespace, attrib={'width':str(thumbnail[0]), 'height':str(thumbnail[1])}, nsmap=root.nsmap) t.text = 'main_thumbnail.jpg' ans.append(t) t.tail = '\n\t' return ans
w = TagsLineEdit(parent, values) w.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
w = RemoveTags(parent, values)
def setup_ui(self, parent): values = self.all_values = list(self.db.all_custom(num=self.col_id)) values.sort(cmp = lambda x,y: cmp(x.lower(), y.lower())) if self.col_metadata['is_multiple']: w = TagsLineEdit(parent, values) w.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) self.widgets = [QLabel('&'+self.col_metadata['name']+': ' + _('tags to add'), parent), w] self.adding_widget = w
if self.removing_widget.text() == '*':
if self.removing_widget.checkbox.isChecked():
def getter(self, original_value = None): if self.col_metadata['is_multiple']: if self.removing_widget.text() == '*': ans = set() else: ans = set(original_value) ans -= set([v.strip() for v in unicode(self.removing_widget.text()).split(',')]) ans |= set([v.strip() for v in unicode(self.adding_widget.text()).split(',')]) return ans # returning a set instead of a list works, for now at least. val = unicode(self.widgets[1].currentText()).strip() if not val: val = None return val
unicode(self.removing_widget.text()).split(',')])
unicode(self.removing_widget.tags_box.text()).split(',')])
def getter(self, original_value = None): if self.col_metadata['is_multiple']: if self.removing_widget.text() == '*': ans = set() else: ans = set(original_value) ans -= set([v.strip() for v in unicode(self.removing_widget.text()).split(',')]) ans |= set([v.strip() for v in unicode(self.adding_widget.text()).split(',')]) return ans # returning a set instead of a list works, for now at least. val = unicode(self.widgets[1].currentText()).strip() if not val: val = None return val
self.setEditTriggers(self.SelectedClicked|self.EditKeyPressed)
self.setEditTriggers(self.EditKeyPressed)
def __init__(self, parent, modelcls=BooksModel): QTableView.__init__(self, parent)
WARNING: This completely regenerates your datbase. You will
WARNING: This completely regenerates your database. You will
def restore_database_option_parser(): parser = get_parser(_( ''' %prog restore_database [options] Restore this database from the metadata stored in OPF files in each directory of the calibre library. This is useful if your metadata.db file has been corrupted. WARNING: This completely regenerates your datbase. You will lose stored per-book conversion settings and custom recipes. ''')) return parser
parser = saved_searches_option_parser()
parser = restore_database_option_parser()
def command_restore_database(args, dbpath): from calibre.library.restore import Restore parser = saved_searches_option_parser() opts, args = parser.parse_args(args) if len(args) != 0: parser.print_help() return 1 if opts.library_path is not None: dbpath = opts.library_path if isbytestring(dbpath): dbpath = dbpath.decode(preferred_encoding) class Progress(object): def __init__(self): self.total = 1 def __call__(self, msg, step): if msg is None: self.total = float(step) else: prints(msg, '...', '%d%%'%int(100*(step/self.total))) r = Restore(dbpath, progress_callback=Progress()) r.start() r.join() if r.tb is not None: prints('Restoring database failed with error:') prints(r.tb) else: prints('Restoring database succeeded') prints('old database saved as', r.olddb) if r.errors_occurred: name = 'calibre_db_restore_report.txt' open('calibre_db_restore_report.txt', 'wb').write(r.report.encode('utf-8')) prints('Some errors occurred. A detailed report was ' 'saved to', name)
ids = self.search_cache(which)
ids = self.search_cache('search:"%s"'%which)
def opds_category(self, category=None, which=None, version=0, offset=0): try: offset = int(offset) version = int(version) except: raise cherrypy.HTTPError(404, 'Not found')
return '_'+name+'()'+\
fname = name.replace('-', '_') return '_'+fname+'()'+\
def opts_and_exts(name, op, exts): opts = ' '.join(options(op)) exts.extend([i.upper() for i in exts]) exts='|'.join(exts) return '_'+name+'()'+\
complete -o filenames -F _'''%(opts,exts) + name + ' ' + name +"\n\n"
complete -o filenames -F _'''%(opts,exts) + fname + ' ' + name +"\n\n"
def opts_and_exts(name, op, exts): opts = ' '.join(options(op)) exts.extend([i.upper() for i in exts]) exts='|'.join(exts) return '_'+name+'()'+\
if Covers(isbn)(entry).check_cover():
if Covers(mi.isbn)(entry).check_cover():
def has_cover(self, mi, ans, timeout=5.): if not mi.isbn: return False br = browser() try: entry = Query(isbn=mi.isbn, max_results=1)(br, False, timeout)[0] if Covers(isbn)(entry).check_cover(): self.debug('cover for', mi.isbn, 'found') ans.set() except Exception, e: self.debug(e)
cover_data, ext = Covers(isbn)(entry).get_cover(br, timeout)
cover_data, ext = Covers(mi.isbn)(entry).get_cover(br, timeout)
def get_covers(self, mi, result_queue, abort, timeout=5.): if not mi.isbn: return br = browser() try: entry = Query(isbn=mi.isbn, max_results=1)(br, False, timeout)[0] cover_data, ext = Covers(isbn)(entry).get_cover(br, timeout) if not ext: ext = 'jpg' result_queue.put((True, cover_data, ext, self.name)) except Exception, e: result_queue.put((False, self.exception_to_string(e), traceback.format_exc(), self.name))