rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
desc = '\n'.join(textwrap.wrap(plugin.description, 50))
|
desc = '\n'.join(textwrap.wrap(plugin.description, 100))
|
def data(self, index, role): if not index.isValid(): return NONE if index.internalId() == 0: if role == Qt.DisplayRole: category = self.categories[index.row()] return QVariant(_("%(plugin_type)s %(plugins)s")%\ dict(plugin_type=category, plugins=_('plugins'))) else: plugin = self.index_to_plugin(index) if role == Qt.DisplayRole: ver = '.'.join(map(str, plugin.version)) desc = '\n'.join(textwrap.wrap(plugin.description, 50)) ans='%s (%s) %s %s\n%s'%(plugin.name, ver, _('by'), plugin.author, desc) c = plugin_customization(plugin) if c: ans += _('\nCustomization: ')+c return QVariant(ans) if role == Qt.DecorationRole: return self.disabled_icon if is_disabled(plugin) else self.icon if role == Qt.ForegroundRole and is_disabled(plugin): return QVariant(QBrush(Qt.gray)) if role == Qt.UserRole: return plugin return NONE
|
self.setWindowTitle(self.base_window_title+' - '+title)
|
self.setWindowTitle(self.base_window_title+' - '+title + ' [%s]'%os.path.splitext(pathtoebook)[1][1:].upper())
|
def load_ebook(self, pathtoebook): if self.iterator is not None: self.save_current_position() self.iterator.__exit__() self.iterator = EbookIterator(pathtoebook) self.open_progress_indicator(_('Loading ebook...')) worker = Worker(target=self.iterator.__enter__) worker.start() while worker.isAlive(): worker.join(0.1) QApplication.processEvents() if worker.exception is not None: if isinstance(worker.exception, DRMError): error_dialog(self, _('DRM Error'), _('<p>This book is protected by <a href="%s">DRM</a>') %'http://wiki.mobileread.com/wiki/DRM').exec_() else: r = getattr(worker.exception, 'reason', worker.exception) error_dialog(self, _('Could not open ebook'), unicode(r), det_msg=worker.traceback, show=True) self.close_progress_indicator() else: self.metadata.show_opf(self.iterator.opf, os.path.splitext(pathtoebook)[1][1:]) self.view.current_language = self.iterator.language title = self.iterator.opf.title if not title: title = os.path.splitext(os.path.basename(pathtoebook))[0] if self.iterator.toc: self.toc_model = TOC(self.iterator.toc) self.toc.setModel(self.toc_model) if self.show_toc_on_open: self.action_table_of_contents.setChecked(True) else: self.action_table_of_contents.setChecked(False) self.action_table_of_contents.setDisabled(not self.iterator.toc) self.current_book_has_toc = bool(self.iterator.toc) self.current_title = title self.setWindowTitle(self.base_window_title+' - '+title) self.pos.setMaximum(sum(self.iterator.pages)) self.pos.setSuffix(' / %d'%sum(self.iterator.pages)) self.vertical_scrollbar.setMinimum(100) self.vertical_scrollbar.setMaximum(100*sum(self.iterator.pages)) self.vertical_scrollbar.setSingleStep(10) self.vertical_scrollbar.setPageStep(100) self.set_vscrollbar_value(1) self.current_index = -1 QApplication.instance().alert(self, 5000) previous = self.set_bookmarks(self.iterator.bookmarks) if previous is not None: self.goto_bookmark(previous) else: self.next_document()
|
for i in range(h.count()): if not h.isSectionHidden(i): index = self.model().index(row, i) self.setCurrentIndex(index) if select: sm = self.selectionModel() sm.select(index, sm.ClearAndSelect|sm.Rows) break
|
logical_indices = list(range(h.count())) logical_indices = [x for x in logical_indices if not h.isSectionHidden(x)] pairs = [(x, h.visualIndex(x)) for x in logical_indices if h.visualIndex(x) > -1] if not pairs: pairs = [(0, 0)] pairs.sort(cmp=lambda x,y:cmp(x[1], y[1])) i = pairs[0][0] index = self.model().index(row, i) self.setCurrentIndex(index) if select: sm = self.selectionModel() sm.select(index, sm.ClearAndSelect|sm.Rows)
|
def set_current_row(self, row, select=True): if row > -1: h = self.horizontalHeader() for i in range(h.count()): if not h.isSectionHidden(i): index = self.model().index(row, i) self.setCurrentIndex(index) if select: sm = self.selectionModel() sm.select(index, sm.ClearAndSelect|sm.Rows) break
|
'or the ISBN key.')).exec_()
|
'and/or removing the ISBN.')).exec_() self.reject()
|
def hangcheck(self): if self.fetcher.is_alive() and \ time.time() - self.start_time < self.HANG_TIME: return self._hangcheck.stop() try: if self.fetcher.is_alive(): error_dialog(self, _('Could not find metadata'), _('The metadata download seems to have stalled. ' 'Try again later.')).exec_() self.terminate() return self.queue_reject.emit() self.model = Matches(self.fetcher.results) warnings = [(x[0], unicode(x[1])) for x in \ self.fetcher.exceptions if x[1] is not None] if warnings: warnings='<br>'.join(['<b>%s</b>: %s'%(name, exc) for name,exc in warnings]) self.warning.setText('<p><b>'+ _('Warning')+':</b>'+\ _('Could not fetch metadata from:')+\ '<br>'+warnings+'</p>') self.warning.setVisible(True) if self.model.rowCount() < 1: info_dialog(self, _('No metadata found'), _('No metadata found, try adjusting the title and author ' 'or the ISBN key.')).exec_() return
|
<div class="hr"><blockquote><hr/></blockquote></div>
|
{0}
|
def generateHTMLDescriptionHeader(self, title):
|
'''
|
'''.format(title_border)
|
def generateHTMLDescriptionHeader(self, title):
|
if opts.fmt == 'mobi' and opts.output_profile.startswith("kindle"):
|
if opts.fmt == 'mobi' and opts.output_profile and opts.output_profile.startswith("kindle"):
|
def run(self, path_to_output, opts, db, notification=DummyReporter()): from calibre.utils.logging import Log
|
return cmp(self.title, getattr(other, 'title', ''))
|
return cmp(self.title.lower(), getattr(other, 'title', '').lower())
|
def __cmp__(self, other): return cmp(self.title, getattr(other, 'title', ''))
|
elem.top_gap = None
|
elem.top_gap_ratio = None
|
def collect_stats(self): if len(self.elements) > 1: gaps = [self.elements[i+1].top - self.elements[i].bottom for i in range(0, len(self.elements)-1)] self.average_line_separation = sum(gaps)/len(gaps) for i, elem in enumerate(self.elements): left_margin = elem.left - self.left elem.indent_fraction = left_margin/self.width elem.width_fraction = elem.width/self.width if i == 0: elem.top_gap = None else: elem.top_gap = self.elements[i-1].bottom - elem.top
|
elem.top_gap = self.elements[i-1].bottom - elem.top
|
elem.top_gap_ratio = (self.elements[i-1].bottom - elem.top)/self.average_line_separation
|
def collect_stats(self): if len(self.elements) > 1: gaps = [self.elements[i+1].top - self.elements[i].bottom for i in range(0, len(self.elements)-1)] self.average_line_separation = sum(gaps)/len(gaps) for i, elem in enumerate(self.elements): left_margin = elem.left - self.left elem.indent_fraction = left_margin/self.width elem.width_fraction = elem.width/self.width if i == 0: elem.top_gap = None else: elem.top_gap = self.elements[i-1].bottom - elem.top
|
indented = [i for (i, x) in enumerate(self.elements) if x.indent_fraction >= 0.2]
|
self.boxes = [Box()] for i, elem in enumerate(self.elements): if isinstance(elem, Image): self.boxes.append(ImageBox(elem)) img = Interval(elem.left, elem.right) for j in range(i+1, len(self.elements)): t = self.elements[j] if not isinstance(t, Text): break ti = Interval(t.left, t.right) if not ti.centered_in(img): break self.boxes[-1].append(t) self.boxes.append(Box()) else: is_indented = False if i+1 < len(self.elements): indent_diff = elem.indent_fraction - \ self.elements[i+1].indent_fraction if indent_diff > 0.05: is_indented = True if elem.top_gap_ratio > 1.2 or is_indented: self.boxes.append(Box()) self.boxes[-1].append(elem)
|
def linearize(self): self.elements = [] for x in self.columns: self.elements.extend(x)
|
match = re.search(r'REV_.*?&(\d+)', pnp_id)
|
match = re.search(r'REV_.*?&(\d+)
|
def drive_order(self, pnp_id): order = 0 match = re.search(r'REV_.*?&(\d+)', pnp_id) if match is not None: order = int(match.group(1)) return order
|
with TemporaryDirectory('_chm2oeb', keep=True) as tdir:
|
with TemporaryDirectory('_snb2oeb', keep=True) as tdir:
|
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)
|
'server.socket_host' : '0.0.0.0',
|
'server.socket_host' : listen_on,
|
def __init__(self, db, opts, embedded=False, show_tracebacks=True): self.db = db for item in self.db: item break self.opts = opts self.embedded = embedded self.max_cover_width, self.max_cover_height = \ map(int, self.opts.max_cover.split('x')) self.max_stanza_items = opts.max_opds_items path = P('content_server') self.build_time = fromtimestamp(os.stat(path).st_mtime) self.default_cover = open(P('content_server/default_cover.jpg'), 'rb').read()
|
cherrypy.engine.exit()
|
try: cherrypy.engine.exit() finally: cherrypy.server.httpserver = None
|
def exit(self): cherrypy.engine.exit()
|
answers.sort(cmp=lambda x, y: cmp(int(x.preference), int(y.preference))) return [str(x.exchange) for x in answers]
|
answers.sort(cmp=lambda x, y: cmp(int(getattr(x, 'preference', sys.maxint)), int(getattr(y, 'preference', sys.maxint)))) return [str(x.exchange) for x in answers if hasattr(x, 'exchange')]
|
def get_mx(host, verbose=0): import dns.resolver if verbose: print 'Find mail exchanger for', host answers = list(dns.resolver.query(host, 'MX')) answers.sort(cmp=lambda x, y: cmp(int(x.preference), int(y.preference))) return [str(x.exchange) for x in answers]
|
self.add_format(id, format, stream, index_is_id=True, path=tpath)
|
self.add_format(id, format, stream, index_is_id=True, path=tpath, notify=False)
|
def set_path(self, index, index_is_id=False, commit=True): ''' Set the path to the directory containing this books files based on its current title and author. If there was a previous directory, its contents are copied and it is deleted. ''' id = index if index_is_id else self.id(index) path = self.construct_path_name(id) current_path = self.path(id, index_is_id=True).replace(os.sep, '/') formats = self.formats(id, index_is_id=True) formats = formats.split(',') if formats else [] # Check if the metadata used to construct paths has changed fname = self.construct_file_name(id) changed = False for format in formats: name = self.conn.get('SELECT name FROM data WHERE book=? AND format=?', (id, format), all=False) if name and name != fname: changed = True break if path == current_path and not changed: return
|
images.append('<binary id="%s" content-type="%s">%s\n</binary>' % (self.image_hrefs[item.href], item.media_type, data))
|
images.append('<binary id="%s">%s\n</binary>' % (self.image_hrefs[item.href], data))
|
def fb2mlize_images(self): ''' This function uses the self.image_hrefs dictionary mapping. It is populated by the dump_text function. ''' images = [] for item in self.oeb_book.manifest: # Don't write the image if it's not referenced in the document's text. if item.href not in self.image_hrefs: continue if item.media_type in OEB_RASTER_IMAGES: try: if not item.media_type == types_map['.jpeg'] or not item.media_type == types_map['.jpg']: im = Image() im.load(item.data) im.set_compression_quality(70) data = im.export('jpg') raw_data = b64encode(data) # Don't put the encoded image on a single line. data = '' col = 1 for char in raw_data: if col == 72: data += '\n' col = 1 col += 1 data += char images.append('<binary id="%s" content-type="%s">%s\n</binary>' % (self.image_hrefs[item.href], item.media_type, data)) except Exception as e: self.log.error('Error: Could not include file %s because ' \ '%s.' % (item.href, e)) return ''.join(images)
|
self.timer.start(1500)
|
if self.as_you_type: self.timer.start(1500)
|
def key_pressed(self, event): self.normalize_state() if self._in_a_search: self.emit(SIGNAL('changed()')) self._in_a_search = False if event.key() in (Qt.Key_Return, Qt.Key_Enter): self.do_search() self.timer.start(1500)
|
self.db.clean()
|
l = getattr(self, 'library_view', None) if l: l = getattr(l, 'model', None); if l: l = l().db if l: l.clean()
|
def shutdown(self, write_settings=True): self.db.clean() for action in self.iactions.values(): if not action.shutting_down(): return if write_settings: self.write_settings() self.check_messages_timer.stop() self.update_checker.terminate() self.listener.close() self.job_manager.server.close() while self.spare_servers: self.spare_servers.pop().close() self.device_manager.keep_going = False cc = self.library_view.model().cover_cache if cc is not None: cc.stop() self.hide_windows() self.emailer.stop() try: try: if self.content_server is not None: s = self.content_server self.content_server = None s.exit() except: pass time.sleep(2) except KeyboardInterrupt: pass self.hide_windows() return True
|
book.author_sort = self.db.author_sort_from_authors(book.authors)
|
book.author_sort = self.library_view.model().db.author_sort_from_authors(book.authors)
|
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':{}, '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 self.db_book_title_cache[title]['db_ids'][mi.application_id] = mi self.db_book_uuid_cache.add(mi.uuid)
|
else: self.select_format(db, book_id)
|
elif not self.select_format(db, book_id): self.cancelled = True return self.cancelled = False
|
def __init__(self, db, book_id, regex, *args): QDialog.__init__(self, *args) self.setupUi(self)
|
error_dialog(self, _('No formats available'), _('Cannot build regex using the GUI builder without a book.')) QDialog.reject() else: self.open_book(db.format_abspath(book_id, format, index_is_id=True))
|
error_dialog(self, _('No formats available'), _('Cannot build regex using the GUI builder without a book.'), show=True) return False self.open_book(db.format_abspath(book_id, format, index_is_id=True)) return True
|
def select_format(self, db, book_id): format = None formats = db.formats(book_id, index_is_id=True).upper().split(',') if len(formats) == 1: format = formats[0] elif len(formats) > 1: d = ChooseFormatDialog(self, _('Choose the format to view'), formats) d.exec_() if d.result() == QDialog.Accepted: format = d.format()
|
'search', 'date',
|
def set_search_restriction(self, s): self.db.data.set_search_restriction(s)
|
|
if c.get('textconvert', True) and mi.comments is not None \ and html_check.search(mi.comments) is not None: mi.comments = html2text(mi.comments)
|
def _fetch(self): try: self.fetch() if self.results: c = self.config_store().get(self.name, {}) res = self.results if hasattr(res, 'authors'): res = [res] for mi in res: if not c.get('rating', True): mi.rating = None if not c.get('comments', True): mi.comments = None if c.get('textconvert', True) and mi.comments is not None \ and html_check.search(mi.comments) is not None: mi.comments = html2text(mi.comments) if not c.get('tags', True): mi.tags = [] if self.has_html_comments and mi.comments and \ c.get('textcomments', False): try: mi.comments = html2text(mi.comments) except: traceback.print_exc() mi.comments = None
|
|
cb = QCheckBox(_('Convert comments downloaded from %s to plain text')%(self.name)) setattr(w, '_textcomments', cb) cb.setChecked(c.get('textcomments', False)) w._layout.addWidget(cb)
|
if self.has_html_comments: cb = QCheckBox(_('Convert comments downloaded from %s to plain text')%(self.name)) setattr(w, '_textcomments', cb) cb.setChecked(c.get('textcomments', False)) w._layout.addWidget(cb)
|
def config_widget(self): from PyQt4.Qt import QWidget, QVBoxLayout, QLabel, Qt, QLineEdit, \ QCheckBox from calibre.customize.ui import config w = QWidget() w._layout = QVBoxLayout(w) w.setLayout(w._layout) if self.string_customization_help is not None: w._sc_label = QLabel(self.string_customization_help, w) w._layout.addWidget(w._sc_label) customization = config['plugin_customization'] def_sc = customization.get(self.name, '') if not def_sc: def_sc = '' w._sc = QLineEdit(def_sc, w) w._layout.addWidget(w._sc) w._sc_label.setWordWrap(True) w._sc_label.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard) w._sc_label.setOpenExternalLinks(True) c = self.config_store() c = c.get(self.name, {}) for x, l in {'rating':_('ratings'), 'tags':_('tags'), 'comments':_('description/reviews')}.items(): cb = QCheckBox(_('Download %s from %s')%(l, self.name)) setattr(w, '_'+x, cb) cb.setChecked(c.get(x, True)) w._layout.addWidget(cb)
|
for x in ('rating', 'tags', 'comments', 'textcomments'):
|
for x in ('rating', 'tags', 'comments'):
|
def save_settings(self, w): dl_settings = {} for x in ('rating', 'tags', 'comments', 'textcomments'): dl_settings[x] = getattr(w, '_'+x).isChecked() c = self.config_store() c.set(self.name, dl_settings) if hasattr(w, '_sc'): sc = unicode(w._sc.text()).strip() from calibre.customize.ui import customize_plugin customize_plugin(self, sc)
|
* Connect to the search() and cleared() signals from this widget
|
* Connect to the search() and cleared() signals from this widget. * Connect to the cleared() signal to know when the box content changes
|
def paste(self, *args): if self.parent().help_state: self.parent().normalize_state() return QLineEdit.paste(self)
|
cssdict['font-size'] = fnums[esize]
|
font_size = fnums[esize]
|
def force_int(raw): return int(re.search(r'([0-9+-]+)', raw).group(1))
|
cssdict['font-size'] = fnums[force_int(size)]
|
font_size = fnums[force_int(size)]
|
def force_int(raw): return int(re.search(r'([0-9+-]+)', raw).group(1))
|
cssdict['font-size'] = fnums[3]
|
font_size = fnums[3] cssdict['font-size'] = '%.1fpt'%font_size
|
def force_int(raw): return int(re.search(r'([0-9+-]+)', raw).group(1))
|
fsize = self.fmap[style['font-size']]
|
fsize = self.fmap[font_size]
|
def force_int(raw): return int(re.search(r'([0-9+-]+)', raw).group(1))
|
attachment_names = [mi.title+os.path.splitext(attachment)[1]]
|
attachment_names = [ascii_filename(mi.title)+os.path.splitext(attachment)[1]]
|
def email_news(self, id): opts = email_config().parse() accounts = [(account, [x.strip().lower() for x in x[0].split(',')]) for account, x in opts.accounts.items() if x[1]] sent_mails = [] for account, fmts in accounts: files, auto = self.library_view.model().\ get_preferred_formats_from_ids([id], fmts) files = [f for f in files if f is not None] if not files: continue attachment = files[0] mi = self.library_view.model().db.get_metadata(id, index_is_id=True) to_s = [account] subjects = [_('News:')+' '+mi.title] texts = [_('Attached is the')+' '+mi.title] attachment_names = [mi.title+os.path.splitext(attachment)[1]] attachments = [attachment] jobnames = ['%s:%s'%(id, mi.title)] remove = [id] if config['delete_news_from_library_on_upload']\ else [] self.emailer.send_mails(jobnames, Dispatcher(partial(self.emails_sent, remove=remove)), attachments, to_s, subjects, texts, attachment_names) sent_mails.append(to_s[0]) if sent_mails: self.status_bar.show_message(_('Sent news to')+' '+\ ', '.join(sent_mails), 3000)
|
'format':lambda x: os.path.splitext(x.path)[1].lower()
|
'format':lambda x: os.path.splitext(x.path)[1].lower(), 'formats':lambda x: os.path.splitext(x.path)[1].lower()
|
def get_matches(self, location, query): location = location.lower().strip() if location == 'authors': location = 'author'
|
self.log.info(" looking for %s" % str(p_book['lib_book'])[-9:])
|
self.log.info(" looking for '%s' by %s uuid:%s" % (p_book['title'],p_book['author'], p_book['uuid']))
|
def add_books_to_metadata(self, locations, metadata, booklists): ''' Add locations to the booklists. This function must not communicate with the device. @param locations: Result of a call to L{upload_books} @param metadata: List of MetaInformation objects, same as for :method:`upload_books`. @param booklists: A tuple containing the result of calls to (L{books}(oncard=None), L{books}(oncard='carda'), L{books}(oncard='cardb')). ''' if DEBUG: self.log.info("ITUNES.add_books_to_metadata()")
|
this_book.uuid = book.album()
|
this_book.uuid = book.composer()
|
def books(self, oncard=None, end_session=True): """ Return a list of ebooks on the device. @param oncard: If 'carda' or 'cardb' return a list of ebooks on the specific storage card, otherwise return list of ebooks in main memory of device. If a card is specified and no books are on the card return empty list. @return: A BookList.
|
self.log.info(" looking for '%s' by '%s' (%s)" %
|
self.log.info(" looking for '%s' by '%s' uuid:%s" %
|
def remove_books_from_metadata(self, paths, booklists): ''' Remove books from the metadata list. This function must not communicate with the device. @param paths: paths to books on the device. @param booklists: A tuple containing the result of calls to (L{books}(oncard=None), L{books}(oncard='carda'), L{books}(oncard='cardb')).
|
if False: self.log.info(" evaluating '%s' by '%s' (%s)" %
|
if DEBUG: self.log.info(" evaluating '%s' by '%s' uuid:%s" %
|
def remove_books_from_metadata(self, paths, booklists): ''' Remove books from the metadata list. This function must not communicate with the device. @param paths: paths to books on the device. @param booklists: A tuple containing the result of calls to (L{books}(oncard=None), L{books}(oncard='carda'), L{books}(oncard='cardb')).
|
else: if DEBUG: self.log.error(" unable to find '%s' by '%s' (%s)" % (bl_book.title, bl_book.author,bl_book.uuid))
|
def remove_books_from_metadata(self, paths, booklists): ''' Remove books from the metadata list. This function must not communicate with the device. @param paths: paths to books on the device. @param booklists: A tuple containing the result of calls to (L{books}(oncard=None), L{books}(oncard='carda'), L{books}(oncard='cardb')).
|
|
self.log.info(" adding '%s' by '%s' ['%s'] to self.cached_books" %
|
self.log.info("ITUNES.upload_books()") self.log.info(" adding '%s' by '%s' uuid:%s to self.cached_books" %
|
def upload_books(self, files, names, on_card=None, end_session=True, metadata=None): ''' Upload a list of books to the device. If a file already exists on the device, it should be replaced. This method should raise a L{FreeSpaceError} if there is not enough free space on the device. The text of the FreeSpaceError must contain the word "card" if C{on_card} is not None otherwise it must contain the word "memory". :files: A list of paths and/or file-like objects. :names: A list of file names that the books should have once uploaded to the device. len(names) == len(files) :return: A list of 3-element tuples. The list is meant to be passed to L{add_books_to_metadata}. :metadata: If not None, it is a list of :class:`MetaInformation` objects. The idea is to use the metadata to determine where on the device to put the book. len(metadata) == len(files). Apart from the regular cover (path to cover), there may also be a thumbnail attribute, which should be used in preference. The thumbnail attribute is of the form (width, height, cover_data as jpeg). '''
|
if DEBUG: self.log.info("ITUNES.upload_books()") self.log.info(" adding '%s' by '%s' uuid:%s to self.cached_books" % ( metadata[i].title, metadata[i].author, metadata[i].uuid))
|
def upload_books(self, files, names, on_card=None, end_session=True, metadata=None): ''' Upload a list of books to the device. If a file already exists on the device, it should be replaced. This method should raise a L{FreeSpaceError} if there is not enough free space on the device. The text of the FreeSpaceError must contain the word "card" if C{on_card} is not None otherwise it must contain the word "memory". :files: A list of paths and/or file-like objects. :names: A list of file names that the books should have once uploaded to the device. len(names) == len(files) :return: A list of 3-element tuples. The list is meant to be passed to L{add_books_to_metadata}. :metadata: If not None, it is a list of :class:`MetaInformation` objects. The idea is to use the metadata to determine where on the device to put the book. len(metadata) == len(files). Apart from the regular cover (path to cover), there may also be a thumbnail attribute, which should be used in preference. The thumbnail attribute is of the form (width, height, cover_data as jpeg). '''
|
|
self.log.info("%s%-40.40s %-30.30s %-10.10s" % (' '*indent,book.title, book.author, str(book.library_id)[-9:]))
|
self.log.info("%s%-40.40s %-30.30s %-10.10s %s" % (' '*indent,book.title, book.author, str(book.library_id)[-9:], book.uuid))
|
def _dump_booklist(self, booklist, header=None,indent=0): ''' ''' if header: msg = '\n%sbooklist %s:' % (' '*indent,header) self.log.info(msg) self.log.info('%s%s' % (' '*indent,'-' * len(msg)))
|
self.log.info("%s%-40.40s %-30.30s %-10.10s" %
|
self.log.info("%s%-40.40s %-30.30s %-10.10s %s" %
|
def _dump_update_list(self,header=None,indent=0): if header: msg = '\n%sself.update_list %s' % (' '*indent,header) self.log.info(msg) self.log.info( "%s%s" % (' '*indent,'-' * len(msg)))
|
str(ub['lib_book'])[-9:]))
|
str(ub['lib_book'])[-9:], ub['uuid']))
|
def _dump_update_list(self,header=None,indent=0): if header: msg = '\n%sself.update_list %s' % (' '*indent,header) self.log.info(msg) self.log.info( "%s%s" % (' '*indent,'-' * len(msg)))
|
this_book.uuid = library_books[book].album()
|
this_book.uuid = library_books[book].composer()
|
def books(self, oncard=None, end_session=True): """ Return a list of ebooks on the device. @param oncard: If 'carda' or 'cardb' return a list of ebooks on the specific storage card, otherwise return list of ebooks in main memory of device. If a card is specified and no books are on the card return empty list. @return: A BookList.
|
color=istate.fgcolor)
|
color=unicode(istate.fgcolor))
|
def mobimlize_content(self, tag, text, bstate, istates): 'Convert text content' if text or tag != 'br': bstate.content = True istate = istates[-1] para = bstate.para if tag in SPECIAL_TAGS and not text: para = para if para is not None else bstate.body elif para is None or tag in ('td', 'th'): body = bstate.body if bstate.pbreak: etree.SubElement(body, MBP('pagebreak')) bstate.pbreak = False bstate.istate = None bstate.anchor = None parent = bstate.nested[-1] if bstate.nested else bstate.body indent = istate.indent left = istate.left if indent < 0 and abs(indent) < left: left += indent indent = 0 elif indent != 0 and abs(indent) < self.profile.fbase: indent = (indent / abs(indent)) * self.profile.fbase if tag in NESTABLE_TAGS and not istate.rendered: para = wrapper = etree.SubElement( parent, XHTML(tag), attrib=istate.attrib) bstate.nested.append(para) if tag == 'li' and len(istates) > 1: istates[-2].list_num += 1 para.attrib['value'] = str(istates[-2].list_num) elif tag in NESTABLE_TAGS and istate.rendered: para = wrapper = bstate.nested[-1] elif left > 0 and indent >= 0: para = wrapper = etree.SubElement(parent, XHTML('blockquote')) para = wrapper emleft = int(round(left / self.profile.fbase)) - 1 emleft = min((emleft, 10)) while emleft > 0: para = etree.SubElement(para, XHTML('blockquote')) emleft -= 1 else: para = wrapper = etree.SubElement(parent, XHTML('p')) bstate.inline = bstate.para = para vspace = bstate.vpadding + bstate.vmargin bstate.vpadding = bstate.vmargin = 0 if tag not in TABLE_TAGS: wrapper.attrib['height'] = self.mobimlize_measure(vspace) para.attrib['width'] = self.mobimlize_measure(indent) elif tag == 'table' and vspace > 0: vspace = int(round(vspace / self.profile.fbase)) while vspace > 0: wrapper.addprevious(etree.Element(XHTML('br'))) vspace -= 1 if istate.halign != 'auto' and isinstance(istate.halign, (str, unicode)): para.attrib['align'] = istate.halign istate.rendered = True pstate = bstate.istate if tag in CONTENT_TAGS: bstate.inline = para pstate = bstate.istate = None etree.SubElement(para, XHTML(tag), attrib=istate.attrib) elif tag in TABLE_TAGS: para.attrib['valign'] = 'top' if istate.ids: last = bstate.body[-1] for id in istate.ids: last.addprevious(etree.Element(XHTML('a'), attrib={'id': id})) istate.ids.clear() if not text: return if not pstate or istate != pstate: inline = para valign = istate.valign fsize = istate.fsize href = istate.href if not href: bstate.anchor = None elif pstate and pstate.href == href: inline = bstate.anchor else: inline = etree.SubElement(inline, XHTML('a'), href=href) bstate.anchor = inline if valign == 'super': inline = etree.SubElement(inline, XHTML('sup')) elif valign == 'sub': inline = etree.SubElement(inline, XHTML('sub')) elif fsize != 3: inline = etree.SubElement(inline, XHTML('font'), size=str(fsize)) if istate.family == 'monospace': inline = etree.SubElement(inline, XHTML('tt')) if istate.italic: inline = etree.SubElement(inline, XHTML('i')) if istate.bold: inline = etree.SubElement(inline, XHTML('b')) if istate.bgcolor is not None and istate.bgcolor != 'transparent' : inline = etree.SubElement(inline, XHTML('span'), bgcolor=istate.bgcolor) if istate.fgcolor != 'black': inline = etree.SubElement(inline, XHTML('font'), color=istate.fgcolor) if istate.strikethrough: inline = etree.SubElement(inline, XHTML('s')) bstate.inline = inline bstate.istate = istate inline = bstate.inline content = self.preize_text(text) if istate.preserve else [text] for item in content: if isinstance(item, basestring): if len(inline) == 0: inline.text = (inline.text or '') + item else: last = inline[-1] last.tail = (last.tail or '') + item else: inline.append(item)
|
if DEBUG:
|
if False:
|
def remove_books_from_metadata(self, paths, booklists): ''' Remove books from the metadata list. This function must not communicate with the device. @param paths: paths to books on the device. @param booklists: A tuple containing the result of calls to (L{books}(oncard=None), L{books}(oncard='carda'), L{books}(oncard='cardb')).
|
cherrypy.response.headers['Content-Type'] = {
|
fname = posixpath.basename(name) try: cherrypy.response.headers['Content-Type'] = {
|
def static(self, name): 'Serves static content' name = name.lower() cherrypy.response.headers['Content-Type'] = { 'js' : 'text/javascript', 'css' : 'text/css', 'png' : 'image/png', 'gif' : 'image/gif', 'html' : 'text/html', '' : 'application/octet-stream', }[name.rpartition('.')[-1].lower()] cherrypy.response.headers['Last-Modified'] = self.last_modified(self.build_time) path = P('content_server/'+name) if not os.path.exists(path): raise cherrypy.HTTPError(404, '%s not found'%name) if self.opts.develop: lm = fromtimestamp(os.stat(path).st_mtime) cherrypy.response.headers['Last-Modified'] = self.last_modified(lm) with open(path, 'rb') as f: ans = f.read() if path.endswith('.css'): ans = ans.replace('/static/', self.opts.url_prefix + '/static/') return ans
|
'' : 'application/octet-stream', }[name.rpartition('.')[-1].lower()]
|
}[fname.rpartition('.')[-1].lower()] except KeyError: raise cherrypy.HTTPError(404, '%r not a valid resource type'%name)
|
def static(self, name): 'Serves static content' name = name.lower() cherrypy.response.headers['Content-Type'] = { 'js' : 'text/javascript', 'css' : 'text/css', 'png' : 'image/png', 'gif' : 'image/gif', 'html' : 'text/html', '' : 'application/octet-stream', }[name.rpartition('.')[-1].lower()] cherrypy.response.headers['Last-Modified'] = self.last_modified(self.build_time) path = P('content_server/'+name) if not os.path.exists(path): raise cherrypy.HTTPError(404, '%s not found'%name) if self.opts.develop: lm = fromtimestamp(os.stat(path).st_mtime) cherrypy.response.headers['Last-Modified'] = self.last_modified(lm) with open(path, 'rb') as f: ans = f.read() if path.endswith('.css'): ans = ans.replace('/static/', self.opts.url_prefix + '/static/') return ans
|
path = P('content_server/'+name) if not os.path.exists(path):
|
basedir = os.path.abspath(P('content_server')) path = os.path.join(basedir, name.replace('/', os.sep)) path = os.path.abspath(path) if not path.startswith(basedir): raise cherrypy.HTTPError(403, 'Access to %s is forbidden'%name) if not os.path.exists(path) or not os.path.isfile(path):
|
def static(self, name): 'Serves static content' name = name.lower() cherrypy.response.headers['Content-Type'] = { 'js' : 'text/javascript', 'css' : 'text/css', 'png' : 'image/png', 'gif' : 'image/gif', 'html' : 'text/html', '' : 'application/octet-stream', }[name.rpartition('.')[-1].lower()] cherrypy.response.headers['Last-Modified'] = self.last_modified(self.build_time) path = P('content_server/'+name) if not os.path.exists(path): raise cherrypy.HTTPError(404, '%s not found'%name) if self.opts.develop: lm = fromtimestamp(os.stat(path).st_mtime) cherrypy.response.headers['Last-Modified'] = self.last_modified(lm) with open(path, 'rb') as f: ans = f.read() if path.endswith('.css'): ans = ans.replace('/static/', self.opts.url_prefix + '/static/') return ans
|
navbar.append(HR()) text = 'This article was downloaded by ' p = PT(text, STRONG(__appname__), A(url, href=url), style='text-align:left; max-width: 100%; overflow: hidden;') p[0].tail = ' from ' navbar.append(p) navbar.append(BR())
|
if not url.startswith('file://'): navbar.append(HR()) text = 'This article was downloaded by ' p = PT(text, STRONG(__appname__), A(url, href=url), style='text-align:left; max-width: 100%; overflow: hidden;') p[0].tail = ' from ' navbar.append(p) navbar.append(BR())
|
def _generate(self, bottom, feed, art, number_of_articles_in_feed, two_levels, url, __appname__, prefix='', center=True, extra_css=None, style=None): head = HEAD(TITLE('navbar')) if style: head.append(STYLE(style, type='text/css')) if extra_css: head.append(STYLE(extra_css, type='text/css'))
|
if os.sep in unicode(path):
|
path = unicode(path) if os.sep in path:
|
def open_book_path(self, path): if os.sep in unicode(path): open_local_file(path) else: format = unicode(path) path = self.view.model().db.format_abspath(self.current_row, format) if path is not None: open_local_file(path)
|
format = unicode(path) path = self.view.model().db.format_abspath(self.current_row, format)
|
path = self.view.model().db.format_abspath(self.current_row, path)
|
def open_book_path(self, path): if os.sep in unicode(path): open_local_file(path) else: format = unicode(path) path = self.view.model().db.format_abspath(self.current_row, format) if path is not None: open_local_file(path)
|
self.topaz_headers = self.get_headers(offset)
|
self.topaz_headers, self.th_seq = self.get_headers(offset)
|
def __init__(self, stream): self.stream = stream self.data = StreamSlicer(stream)
|
return topaz_headers
|
return topaz_headers, th_seq
|
def get_headers(self, offset): # Build a dict of topaz_header records topaz_headers = {} for x in range(self.header_records): offset += 1 taglen, consumed = self.decode_vwi(self.data[offset:offset+4]) offset += consumed tag = self.data[offset:offset+taglen] offset += taglen num_vals, consumed = self.decode_vwi(self.data[offset:offset+4]) offset += consumed blocks = {} for val in range(num_vals): hdr_offset, consumed = self.decode_vwi(self.data[offset:offset+4]) offset += consumed len_uncomp, consumed = self.decode_vwi(self.data[offset:offset+4]) offset += consumed len_comp, consumed = self.decode_vwi(self.data[offset:offset+4]) offset += consumed blocks[val] = dict(offset=hdr_offset,len_uncomp=len_uncomp,len_comp=len_comp) topaz_headers[tag] = dict(blocks=blocks) self.eoth = self.data[offset] offset += 1 self.base = offset return topaz_headers
|
for tag in self.metadata:
|
for tag in self.md_seq:
|
def generate_metadata_stream(self): ms = StringIO.StringIO() ms.write(self.encode_vwi(len(self.md_header['tag'])).encode('iso-8859-1')) ms.write(self.md_header['tag']) ms.write(chr(self.md_header['flags'])) ms.write(chr(len(self.metadata)))
|
headers = {} for tag in self.topaz_headers: if self.topaz_headers[tag]['blocks']: headers[tag] = self.topaz_headers[tag]['blocks'][0]['offset'] else: headers[tag] = None
|
def regenerate_headers(self, updated_md_len):
|
|
for tag in headers.keys():
|
for tag in self.th_seq:
|
def regenerate_headers(self, updated_md_len):
|
head = self.regenerate_headers(len(updated_metadata))
|
prefix = len('metadata') + 2 um_buf_len = len(updated_metadata) - prefix head = self.regenerate_headers(um_buf_len)
|
def update(self,mi): # Collect the original metadata self.get_original_metadata()
|
chunk2 = self.data[self.original_md_start + self.original_md_len:]
|
chunk2 = self.data[prefix + self.original_md_start + self.original_md_len:]
|
def update(self,mi): # Collect the original metadata self.get_original_metadata()
|
mi = MetaInformation(title="A Marvelously Long Title", authors=['Riker, Gregory; Riker, Charles'])
|
mi = MetaInformation(title="Updated Title", authors=['Author, Random'])
|
def set_metadata(stream, mi): mu = MetadataUpdater(stream) mu.update(mi) return
|
def toggle_cover_browser(self):
|
def toggle_cover_browser(self, *args):
|
def toggle_cover_browser(self): cbd = getattr(self, 'cb_dialog', None) if cbd is not None: self.hide_cover_browser() else: self.show_cover_browser()
|
d.finished.connect(self.cb_splitter.button.set_state_to_show)
|
d.finished.connect(self.cover_browser_closed)
|
def show_cover_browser(self): d = QDialog(self) ah, aw = available_height(), available_width() d.resize(int(aw/1.5), ah-60) d._layout = QStackedLayout() d.setLayout(d._layout) d.setWindowTitle(_('Browse by covers')) d.layout().addWidget(self.cover_flow) self.cover_flow.setVisible(True) self.cover_flow.setFocus(Qt.OtherFocusReason) d.show() self.cb_splitter.button.set_state_to_hide() d.finished.connect(self.cb_splitter.button.set_state_to_show) self.cb_dialog = d
|
def hide_cover_browser(self):
|
self.cb_splitter.button.set_state_to_hide() def cover_browser_closed(self, *args): self.cb_dialog = None self.cb_splitter.button.set_state_to_show() def hide_cover_browser(self, *args):
|
def show_cover_browser(self): d = QDialog(self) ah, aw = available_height(), available_width() d.resize(int(aw/1.5), ah-60) d._layout = QStackedLayout() d.setLayout(d._layout) d.setWindowTitle(_('Browse by covers')) d.layout().addWidget(self.cover_flow) self.cover_flow.setVisible(True) self.cover_flow.setFocus(Qt.OtherFocusReason) d.show() self.cb_splitter.button.set_state_to_hide() d.finished.connect(self.cb_splitter.button.set_state_to_show) self.cb_dialog = d
|
self.column_map = config['column_map'][:]
|
cmap = config['column_map'][:]
|
def read_config(self): self.use_roman_numbers = config['use_roman_numerals_for_series_number'] self.column_map = config['column_map'][:] # force a copy self.headers = {} for i in self.column_map: # take out any columns no longer in the db if not i in self.orig_headers and not i in self.custom_columns: self.column_map.remove(i) for i in self.column_map: if i in self.orig_headers: self.headers[i] = self.orig_headers[i] elif i in self.custom_columns: self.headers[i] = self.custom_columns[i]['name'] self.build_data_convertors() self.reset() self.emit(SIGNAL('columns_sorted()'))
|
for i in self.column_map: if not i in self.orig_headers and not i in self.custom_columns: self.column_map.remove(i) for i in self.column_map: if i in self.orig_headers: self.headers[i] = self.orig_headers[i] elif i in self.custom_columns: self.headers[i] = self.custom_columns[i]['name']
|
self.column_map = [] for col in cmap: if col in self.orig_headers or col in self.custom_columns: self.column_map.append(col) for col in self.column_map: if col in self.orig_headers: self.headers[col] = self.orig_headers[col] elif col in self.custom_columns: self.headers[col] = self.custom_columns[col]['name']
|
def read_config(self): self.use_roman_numbers = config['use_roman_numerals_for_series_number'] self.column_map = config['column_map'][:] # force a copy self.headers = {} for i in self.column_map: # take out any columns no longer in the db if not i in self.orig_headers and not i in self.custom_columns: self.column_map.remove(i) for i in self.column_map: if i in self.orig_headers: self.headers[i] = self.orig_headers[i] elif i in self.custom_columns: self.headers[i] = self.custom_columns[i]['name'] self.build_data_convertors() self.reset() self.emit(SIGNAL('columns_sorted()'))
|
key = str(item.text).rpartition(':')[-1] key = list(map(ord, uuid.UUID(key).bytes))
|
try: key = str(item.text).rpartition(':')[-1] key = list(map(ord, uuid.UUID(key).bytes)) except: import traceback traceback.print_exc() key = None
|
def process_encryption(self, encfile, opf, log): key = None for item in opf.identifier_iter(): scheme = None for xkey in item.attrib.keys(): if xkey.endswith('scheme'): scheme = item.get(xkey) if (scheme and scheme.lower() == 'uuid') or \ (item.text and item.text.startswith('urn:uuid:')): key = str(item.text).rpartition(':')[-1] key = list(map(ord, uuid.UUID(key).bytes))
|
if os.path.exists(path):
|
if key is not None and os.path.exists(path):
|
def process_encryption(self, encfile, opf, log): key = None for item in opf.identifier_iter(): scheme = None for xkey in item.attrib.keys(): if xkey.endswith('scheme'): scheme = item.get(xkey) if (scheme and scheme.lower() == 'uuid') or \ (item.text and item.text.startswith('urn:uuid:')): key = str(item.text).rpartition(':')[-1] key = list(map(ord, uuid.UUID(key).bytes))
|
if self.booksByTitle is None:
|
if not len(self.booksByTitle):
|
def buildSources(self): if self.booksByTitle is None: self.fetchBooksByTitle() if self.booksByTitle is None: return False self.fetchBooksByAuthor() self.generateHTMLDescriptions() self.generateHTMLByAuthor() if self.opts.generate_titles: self.generateHTMLByTitle() if self.opts.generate_recently_added: self.generateHTMLByDateAdded() self.generateHTMLByTags()
|
f.seek(0) for i in range(1024): f.write(chr(ord(data[i]) ^ key[i%16]))
|
if len(data) >= 1024: f.seek(0) for i in range(1024): f.write(chr(ord(data[i]) ^ key[i%16])) else: self.log.warn('Font', path, 'is invalid, ignoring')
|
def encrypt_fonts(self, uris, tdir, uuid): # {{{ from binascii import unhexlify
|
imagename = self.normalize_path(prefix + '.kobo/images/' + ImageID + ' - NickelBookCover.parsed')
|
imagename = self.normalize_path(self._main_prefix + '.kobo/images/' + ImageID + ' - NickelBookCover.parsed')
|
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('\\', '/')
|
try: self.results = search(self.title, self.book_author, self.publisher, self.isbn, max_results=5, verbose=self.verbose, lang='all')
|
if not self.isbn: return try: self.results = get_social_metadata(self.title, self.book_author, self.publisher, self.isbn, verbose=self.verbose, lang='all')[0]
|
def fetch(self): try: self.results = search(self.title, self.book_author, self.publisher, self.isbn, max_results=5, verbose=self.verbose, lang='all') except Exception, e: self.exception = e self.tb = traceback.format_exc()
|
title = unicode(self.title.text())
|
title = unicode(self.title.text()).strip()
|
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()) self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()) if au: self.db.set_authors(self.id, string_to_authors(au), notify=False) aus = unicode(self.author_sort.text()) if aus: self.db.set_author_sort(self.id, aus, notify=False, commit=False) self.db.set_isbn(self.id, re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text())), notify=False, commit=False) self.db.set_rating(self.id, 2*self.rating.value(), notify=False, commit=False) self.db.set_publisher(self.id, unicode(self.publisher.currentText()), notify=False, commit=False) self.db.set_tags(self.id, [x.strip() for x in unicode(self.tags.text()).split(',')], notify=False, commit=False) self.db.set_series(self.id, unicode(self.series.currentText()).strip(), notify=False, commit=False) self.db.set_series_index(self.id, self.series_index.value(), notify=False, commit=False) self.db.set_comment(self.id, unicode(self.comments.toPlainText()), notify=False, commit=False) d = self.pubdate.date() d = qt_to_dt(d) self.db.set_pubdate(self.id, d, notify=False, commit=False) d = self.date.date() d = qt_to_dt(d) if d.date() != self.orig_timestamp.date(): self.db.set_timestamp(self.id, d, notify=False, commit=False) self.db.commit()
|
au = unicode(self.authors.text())
|
au = unicode(self.authors.text()).strip()
|
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()) self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()) if au: self.db.set_authors(self.id, string_to_authors(au), notify=False) aus = unicode(self.author_sort.text()) if aus: self.db.set_author_sort(self.id, aus, notify=False, commit=False) self.db.set_isbn(self.id, re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text())), notify=False, commit=False) self.db.set_rating(self.id, 2*self.rating.value(), notify=False, commit=False) self.db.set_publisher(self.id, unicode(self.publisher.currentText()), notify=False, commit=False) self.db.set_tags(self.id, [x.strip() for x in unicode(self.tags.text()).split(',')], notify=False, commit=False) self.db.set_series(self.id, unicode(self.series.currentText()).strip(), notify=False, commit=False) self.db.set_series_index(self.id, self.series_index.value(), notify=False, commit=False) self.db.set_comment(self.id, unicode(self.comments.toPlainText()), notify=False, commit=False) d = self.pubdate.date() d = qt_to_dt(d) self.db.set_pubdate(self.id, d, notify=False, commit=False) d = self.date.date() d = qt_to_dt(d) if d.date() != self.orig_timestamp.date(): self.db.set_timestamp(self.id, d, notify=False, commit=False) self.db.commit()
|
aus = unicode(self.author_sort.text())
|
aus = unicode(self.author_sort.text()).strip()
|
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()) self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()) if au: self.db.set_authors(self.id, string_to_authors(au), notify=False) aus = unicode(self.author_sort.text()) if aus: self.db.set_author_sort(self.id, aus, notify=False, commit=False) self.db.set_isbn(self.id, re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text())), notify=False, commit=False) self.db.set_rating(self.id, 2*self.rating.value(), notify=False, commit=False) self.db.set_publisher(self.id, unicode(self.publisher.currentText()), notify=False, commit=False) self.db.set_tags(self.id, [x.strip() for x in unicode(self.tags.text()).split(',')], notify=False, commit=False) self.db.set_series(self.id, unicode(self.series.currentText()).strip(), notify=False, commit=False) self.db.set_series_index(self.id, self.series_index.value(), notify=False, commit=False) self.db.set_comment(self.id, unicode(self.comments.toPlainText()), notify=False, commit=False) d = self.pubdate.date() d = qt_to_dt(d) self.db.set_pubdate(self.id, d, notify=False, commit=False) d = self.date.date() d = qt_to_dt(d) if d.date() != self.orig_timestamp.date(): self.db.set_timestamp(self.id, d, notify=False, commit=False) self.db.commit()
|
re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text())),
|
re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text()).strip()),
|
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()) self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()) if au: self.db.set_authors(self.id, string_to_authors(au), notify=False) aus = unicode(self.author_sort.text()) if aus: self.db.set_author_sort(self.id, aus, notify=False, commit=False) self.db.set_isbn(self.id, re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text())), notify=False, commit=False) self.db.set_rating(self.id, 2*self.rating.value(), notify=False, commit=False) self.db.set_publisher(self.id, unicode(self.publisher.currentText()), notify=False, commit=False) self.db.set_tags(self.id, [x.strip() for x in unicode(self.tags.text()).split(',')], notify=False, commit=False) self.db.set_series(self.id, unicode(self.series.currentText()).strip(), notify=False, commit=False) self.db.set_series_index(self.id, self.series_index.value(), notify=False, commit=False) self.db.set_comment(self.id, unicode(self.comments.toPlainText()), notify=False, commit=False) d = self.pubdate.date() d = qt_to_dt(d) self.db.set_pubdate(self.id, d, notify=False, commit=False) d = self.date.date() d = qt_to_dt(d) if d.date() != self.orig_timestamp.date(): self.db.set_timestamp(self.id, d, notify=False, commit=False) self.db.commit()
|
self.db.set_publisher(self.id, unicode(self.publisher.currentText()),
|
self.db.set_publisher(self.id, unicode(self.publisher.currentText()).strip(),
|
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()) self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()) if au: self.db.set_authors(self.id, string_to_authors(au), notify=False) aus = unicode(self.author_sort.text()) if aus: self.db.set_author_sort(self.id, aus, notify=False, commit=False) self.db.set_isbn(self.id, re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text())), notify=False, commit=False) self.db.set_rating(self.id, 2*self.rating.value(), notify=False, commit=False) self.db.set_publisher(self.id, unicode(self.publisher.currentText()), notify=False, commit=False) self.db.set_tags(self.id, [x.strip() for x in unicode(self.tags.text()).split(',')], notify=False, commit=False) self.db.set_series(self.id, unicode(self.series.currentText()).strip(), notify=False, commit=False) self.db.set_series_index(self.id, self.series_index.value(), notify=False, commit=False) self.db.set_comment(self.id, unicode(self.comments.toPlainText()), notify=False, commit=False) d = self.pubdate.date() d = qt_to_dt(d) self.db.set_pubdate(self.id, d, notify=False, commit=False) d = self.date.date() d = qt_to_dt(d) if d.date() != self.orig_timestamp.date(): self.db.set_timestamp(self.id, d, notify=False, commit=False) self.db.commit()
|
self.db.set_comment(self.id, unicode(self.comments.toPlainText()),
|
self.db.set_comment(self.id, unicode(self.comments.toPlainText()).strip(),
|
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()) self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()) if au: self.db.set_authors(self.id, string_to_authors(au), notify=False) aus = unicode(self.author_sort.text()) if aus: self.db.set_author_sort(self.id, aus, notify=False, commit=False) self.db.set_isbn(self.id, re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text())), notify=False, commit=False) self.db.set_rating(self.id, 2*self.rating.value(), notify=False, commit=False) self.db.set_publisher(self.id, unicode(self.publisher.currentText()), notify=False, commit=False) self.db.set_tags(self.id, [x.strip() for x in unicode(self.tags.text()).split(',')], notify=False, commit=False) self.db.set_series(self.id, unicode(self.series.currentText()).strip(), notify=False, commit=False) self.db.set_series_index(self.id, self.series_index.value(), notify=False, commit=False) self.db.set_comment(self.id, unicode(self.comments.toPlainText()), notify=False, commit=False) d = self.pubdate.date() d = qt_to_dt(d) self.db.set_pubdate(self.id, d, notify=False, commit=False) d = self.date.date() d = qt_to_dt(d) if d.date() != self.orig_timestamp.date(): self.db.set_timestamp(self.id, d, notify=False, commit=False) self.db.commit()
|
spine.append(E.itemref(idref=ref.id))
|
if ref.id is not None: spine.append(E.itemref(idref=ref.id))
|
def CAL_ELEM(name, content): return M.meta(name=name, content=content)
|
handle = ctypes.c_int(0)
|
handle = ctypes.c_void_p(0)
|
def BambookConnect(ip = DEFAULT_BAMBOOK_IP, timeout = 0): if isinstance(ip, unicode): ip = ip.encode('ascii') handle = ctypes.c_int(0) if lib_handle == None: raise Exception(_('Bambook SDK has not been installed.')) ret = lib_handle.BambookConnect(ip, timeout, ctypes.byref(handle)) if ret == BR_SUCC: return handle else: return None
|
if mult in ['k', 'm', 'g']:
|
mult = {'k':1024.,'m': 1024.**2, 'g': 1024.**3}.get(mult, 1.0) if mult != 1.0:
|
def get_numeric_matches(self, location, query): matches = set([]) if len(query) == 0: return matches if query == 'false': query = '0' elif query == 'true': query = '!=0' relop = None for k in self.numeric_search_relops.keys(): if query.startswith(k): (p, relop) = self.numeric_search_relops[k] query = query[p:] if relop is None: (p, relop) = self.numeric_search_relops['=']
|
mult = {'k':1024., 'm': 1024.*1024, 'g': 1024.*1024*1024}[mult]
|
else: mult = 1.0
|
def get_numeric_matches(self, location, query): matches = set([]) if len(query) == 0: return matches if query == 'false': query = '0' elif query == 'true': query = '!=0' relop = None for k in self.numeric_search_relops.keys(): if query.startswith(k): (p, relop) = self.numeric_search_relops[k] query = query[p:] if relop is None: (p, relop) = self.numeric_search_relops['=']
|
if cname in ('title', 'authors') or (cname == 'collection' and \ self.db.supports_collections()):
|
if cname in ('title', 'authors') or \ (cname == 'collections' and self.db.supports_collections()):
|
def flags(self, index): if self.map[index.row()] in self.indices_to_be_deleted(): return Qt.ItemIsUserCheckable # Can't figure out how to get the disabled flag in python flags = QAbstractTableModel.flags(self, index) if index.isValid() and self.editable: cname = self.column_map[index.column()] if cname in ('title', 'authors') or (cname == 'collection' and \ self.db.supports_collections()): flags |= Qt.ItemIsEditable return flags
|
if comments and comments != u'None': self.renderer.queue.put((rows, comments))
|
if not comments or comments == u'None': comments = '' self.renderer.queue.put((rows, comments))
|
def show_data(self, data): rows = render_rows(data) rows = u'\n'.join([u'<tr><td valign="top"><b>%s:</b></td><td valign="top">%s</td></tr>'%(k,t) for k, t in rows]) comments = data.get(_('Comments'), '') if comments and comments != u'None': self.renderer.queue.put((rows, comments)) self._show_data(rows, '')
|
from cherrypy.process.plugins import Daemonizer d = Daemonizer(cherrypy.engine) d.subscribe()
|
daemonize()
|
def main(args=sys.argv): from calibre.library.database2 import LibraryDatabase2 parser = option_parser() opts, args = parser.parse_args(args) if opts.daemonize and not iswindows: from cherrypy.process.plugins import Daemonizer d = Daemonizer(cherrypy.engine) d.subscribe() if opts.pidfile is not None: from cherrypy.process.plugins import PIDFile PIDFile(cherrypy.engine, opts.pidfile).subscribe() cherrypy.log.screen = True from calibre.utils.config import prefs if opts.with_library is None: opts.with_library = prefs['library_path'] db = LibraryDatabase2(opts.with_library) server = LibraryServer(db, opts) server.start() return 0
|
self.orig_timestamp = timestamp.astimezone(utc_tz)
|
def __init__(self, window, row, db, accepted_callback=None, cancel_all=False): ResizableDialog.__init__(self, window) self.bc_box.layout().setAlignment(self.cover, Qt.AlignCenter|Qt.AlignHCenter) self.cancel_all = False base = unicode(self.author_sort.toolTip()) self.ok_aus_tooltip = '<p>' + textwrap.fill(base+'<br><br>'+ _(' The green color indicates that the current ' 'author sort matches the current author')) self.bad_aus_tooltip = '<p>'+textwrap.fill(base + '<br><br>'+ _(' The red color indicates that the current ' 'author sort does not match the current author'))
|
|
if d.date() != self.orig_timestamp.date():
|
if d != self.orig_date:
|
def accept(self): cf = getattr(self, 'cover_fetcher', None) if cf is not None and hasattr(cf, 'terminate'): cf.terminate() cf.wait() try: if self.formats_changed: self.sync_formats() title = unicode(self.title.text()).strip() self.db.set_title(self.id, title, notify=False) au = unicode(self.authors.text()).strip() if au: self.db.set_authors(self.id, string_to_authors(au), notify=False) aus = unicode(self.author_sort.text()).strip() if aus: self.db.set_author_sort(self.id, aus, notify=False, commit=False) self.db.set_isbn(self.id, re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text()).strip()), notify=False, commit=False) self.db.set_rating(self.id, 2*self.rating.value(), notify=False, commit=False) self.db.set_publisher(self.id, unicode(self.publisher.currentText()).strip(), notify=False, commit=False) self.db.set_tags(self.id, [x.strip() for x in unicode(self.tags.text()).split(',')], notify=False, commit=False) self.db.set_series(self.id, unicode(self.series.currentText()).strip(), notify=False, commit=False) self.db.set_series_index(self.id, self.series_index.value(), notify=False, commit=False) self.db.set_comment(self.id, unicode(self.comments.toPlainText()).strip(), notify=False, commit=False) d = self.pubdate.date() d = qt_to_dt(d) self.db.set_pubdate(self.id, d, notify=False, commit=False) d = self.date.date() d = qt_to_dt(d) if d.date() != self.orig_timestamp.date(): self.db.set_timestamp(self.id, d, notify=False, commit=False) self.db.commit()
|
qd = parse_date(query)
|
qd = parse_date(query, as_utc=False)
|
def get_dates_matches(self, location, query): matches = set([]) if len(query) < 2: return matches
|
self.books.append({ 'mi': mi, 'timestamp': timestamp, 'formats': list(zip(fmts, sizes, names)), 'id': int(book_id), 'dirpath': dirpath, 'path': path, })
|
if int(mi.application_id) == book_id: self.books.append({ 'mi': mi, 'timestamp': timestamp, 'formats': list(zip(fmts, sizes, names)), 'id': book_id, 'dirpath': dirpath, 'path': path, }) else: self.ignored_dirs.append(dirpath)
|
def process_dir(self, dirpath, filenames, book_id): formats = filter(self.is_ebook_file, filenames) fmts = [os.path.splitext(x)[1][1:].upper() for x in formats] sizes = [os.path.getsize(os.path.join(dirpath, x)) for x in formats] names = [os.path.splitext(x)[0] for x in formats] opf = os.path.join(dirpath, 'metadata.opf') mi = OPF(opf).to_book_metadata() timestamp = os.path.getmtime(opf) path = os.path.relpath(dirpath, self.src_library_path).replace(os.sep, '/')
|
db = LibraryDatabase2(self.library_path)
|
db = RestoreDatabase(self.library_path)
|
def create_cc_metadata(self): self.books.sort(key=itemgetter('timestamp')) m = {} fields = ('label', 'name', 'datatype', 'is_multiple', 'editable', 'display') for b in self.books: args = [] for x in fields: if x in b: args.append(b[x]) if len(args) == len(fields): # TODO: Do series type columns need special handling? label = b['label'] if label in m and args != m[label]: if label not in self.conflicting_custom_cols: self.conflicting_custom_cols[label] = set([m[label]]) self.conflicting_custom_cols[label].add(args) m[b['label']] = args
|
if category == 'series':
|
if category == 'series' and not sort_on_count:
|
def get_categories(self, sort_on_count=False, ids=None, icon_map=None): self.books_list_filter.change([] if not ids else ids)
|
occasion = {'import':_on_import, 'preprocess':_on_preprocess,
|
occasion_plugins = {'import':_on_import, 'preprocess':_on_preprocess,
|
def _run_filetype_plugins(path_to_file, ft=None, occasion='preprocess'): occasion = {'import':_on_import, 'preprocess':_on_preprocess, 'postprocess':_on_postprocess}[occasion] customization = config['plugin_customization'] if ft is None: ft = os.path.splitext(path_to_file)[-1].lower().replace('.', '') nfp = path_to_file for plugin in occasion.get(ft, []): if is_disabled(plugin): continue plugin.site_customization = customization.get(plugin.name, '') with plugin: try: nfp = plugin.run(path_to_file) if not nfp: nfp = path_to_file except: print 'Running file type plugin %s failed with traceback:'%plugin.name traceback.print_exc() x = lambda j : os.path.normpath(os.path.normcase(j)) if occasion == 'postprocess' and x(nfp) != x(path_to_file): shutil.copyfile(nfp, path_to_file) nfp = path_to_file return nfp
|
for plugin in occasion.get(ft, []):
|
for plugin in occasion_plugins.get(ft, []):
|
def _run_filetype_plugins(path_to_file, ft=None, occasion='preprocess'): occasion = {'import':_on_import, 'preprocess':_on_preprocess, 'postprocess':_on_postprocess}[occasion] customization = config['plugin_customization'] if ft is None: ft = os.path.splitext(path_to_file)[-1].lower().replace('.', '') nfp = path_to_file for plugin in occasion.get(ft, []): if is_disabled(plugin): continue plugin.site_customization = customization.get(plugin.name, '') with plugin: try: nfp = plugin.run(path_to_file) if not nfp: nfp = path_to_file except: print 'Running file type plugin %s failed with traceback:'%plugin.name traceback.print_exc() x = lambda j : os.path.normpath(os.path.normcase(j)) if occasion == 'postprocess' and x(nfp) != x(path_to_file): shutil.copyfile(nfp, path_to_file) nfp = path_to_file return nfp
|
record.set('title', book.title)
|
title = book.title if book.title else _('Unknown') record.set('title', title)
|
def update_text_record(self, record, book, path, bl_index): timestamp = os.path.getctime(path) date = strftime(timestamp) if date != record.get('date', None): if DEBUG: prints('Changing date of', path, 'from', record.get('date', ''), 'to', date) prints('\tctime', strftime(os.path.getctime(path))) prints('\tmtime', strftime(os.path.getmtime(path))) record.set('date', date) record.set('size', str(os.stat(path).st_size)) record.set('title', book.title) ts = book.title_sort if not ts: ts = title_sort(book.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))
|
ts = title_sort(book.title)
|
ts = title_sort(title)
|
def update_text_record(self, record, book, path, bl_index): timestamp = os.path.getctime(path) date = strftime(timestamp) if date != record.get('date', None): if DEBUG: prints('Changing date of', path, 'from', record.get('date', ''), 'to', date) prints('\tctime', strftime(os.path.getctime(path))) prints('\tmtime', strftime(os.path.getmtime(path))) record.set('date', date) record.set('size', str(os.stat(path).st_size)) record.set('title', book.title) ts = book.title_sort if not ts: ts = title_sort(book.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))
|
'state', 'city', 'street', 'address', 'content'): tag.tag = 'div' if tag.tag == 'content' else 'span'
|
'state', 'city', 'street', 'address', 'content', 'form'): tag.tag = 'div' if tag.tag in ('content', 'form') else 'span'
|
def upshift_markup(self, root): self.log.debug('Converting style information to CSS...') size_map = { 'xx-small': '0.5', 'x-small': '1', 'small': '2', 'medium': '3', 'large': '4', 'x-large': '5', 'xx-large': '6', } mobi_version = self.book_header.mobi_version for x in root.xpath('//ncx'): x.getparent().remove(x) for i, tag in enumerate(root.iter(etree.Element)): tag.attrib.pop('xmlns', '') for x in tag.attrib: if ':' in x: del tag.attrib[x] if tag.tag in ('country-region', 'place', 'placetype', 'placename', 'state', 'city', 'street', 'address', 'content'): tag.tag = 'div' if tag.tag == 'content' else 'span' for key in tag.attrib.keys(): tag.attrib.pop(key) continue styles, attrib = [], tag.attrib if attrib.has_key('style'): style = attrib.pop('style').strip() if style: styles.append(style) if attrib.has_key('height'): height = attrib.pop('height').strip() if height and '<' not in height and '>' not in height and \ re.search(r'\d+', height): if tag.tag in ('table', 'td', 'tr'): pass elif tag.tag == 'img': tag.set('height', height) else: styles.append('margin-top: %s' % self.ensure_unit(height)) if attrib.has_key('width'): width = attrib.pop('width').strip() if width and re.search(r'\d+', width): if tag.tag in ('table', 'td', 'tr'): pass elif tag.tag == 'img': tag.set('width', width) else: styles.append('text-indent: %s' % self.ensure_unit(width)) if width.startswith('-'): styles.append('margin-left: %s' % self.ensure_unit(width[1:])) if attrib.has_key('align'): align = attrib.pop('align').strip() if align: align = align.lower() if align == 'baseline': styles.append('vertical-align: '+align) else: styles.append('text-align: %s' % align) if tag.tag == 'hr': if mobi_version == 1: tag.tag = 'div' styles.append('page-break-before: always') styles.append('display: block') styles.append('margin: 0') elif tag.tag == 'i': tag.tag = 'span' tag.attrib['class'] = 'italic' elif tag.tag == 'b': tag.tag = 'span' tag.attrib['class'] = 'bold' elif tag.tag == 'font': sz = tag.get('size', '').lower() try: float(sz) except ValueError: if sz in size_map.keys(): attrib['size'] = size_map[sz] elif tag.tag == 'img': recindex = None for attr in self.IMAGE_ATTRS: recindex = attrib.pop(attr, None) or recindex if recindex is not None: attrib['src'] = 'images/%s.jpg' % recindex for attr in ('width', 'height'): if attr in attrib: val = attrib[attr] if val.lower().endswith('em'): try: nval = float(val[:-2]) nval *= 16 * (168.451/72) # Assume this was set using the Kindle profile attrib[attr] = "%dpx"%int(nval) except: del attrib[attr] elif val.lower().endswith('%'): del attrib[attr] elif tag.tag == 'pre': if not tag.text: tag.tag = 'div'
|
items = [x for x in items if getattr(x, 'sort', x.name).startswith(which)]
|
def belongs(x, which): return getattr(x, 'sort', x.name).lower().startswith(which.lower()) items = [x for x in items if belongs(x, which)]
|
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')
|
starts = set([getattr(x, 'sort', x.name)[0] for x in items])
|
starts = set([]) for x in items: val = getattr(x, 'sort', x.name) if not val: val = 'A' starts.add(val[0].upper())
|
def __init__(self, text, count): self.text, self.count = text, count
|
return ''.join(random.choice(string.letters) for i in
|
return ''.join(random.choice(letters) for i in
|
def randstr(length): return ''.join(random.choice(string.letters) for i in xrange(length))
|
val = pat.sub('', val)
|
val = pat.sub('', val).strip()
|
def setData(self, index, value, role): if role == Qt.EditRole: row, col = index.row(), index.column() column = self.column_map[col] if column not in self.editable_cols: return False val = int(value.toInt()[0]) if column == 'rating' else \ value.toDate() if column in ('timestamp', 'pubdate') else \ unicode(value.toString()) id = self.db.id(row) if column == 'rating': val = 0 if val < 0 else 5 if val > 5 else val val *= 2 self.db.set_rating(id, val) elif column == 'series': val = val.strip() pat = re.compile(r'\[([.0-9]+)\]') match = pat.search(val) if match is not None: self.db.set_series_index(id, float(match.group(1))) val = pat.sub('', val) elif val: ni = self.db.get_next_series_num_for(val) if ni != 1: self.db.set_series_index(id, ni) if val: self.db.set_series(id, val) elif column == 'timestamp': if val.isNull() or not val.isValid(): return False dt = datetime(val.year(), val.month(), val.day()) + timedelta(seconds=time.timezone) - timedelta(hours=time.daylight) self.db.set_timestamp(id, dt) elif column == 'pubdate': if val.isNull() or not val.isValid(): return False dt = datetime(val.year(), val.month(), val.day()) + timedelta(seconds=time.timezone) - timedelta(hours=time.daylight) self.db.set_pubdate(id, dt) else: self.db.set(row, column, val) self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), \ index, index) if column == self.sorted_on[0]: self.resort()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.