rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.self_closing_pat = re.compile(r'<([a-z]+)\s+([^>]+)/>',
self.self_closing_pat = re.compile(r'<([a-z1-6]+)\s+([^>]+)/>',
def __init__(self, *args): QWebView.__init__(self, *args) self.debug_javascript = False self.shortcuts = Shortcuts(SHORTCUTS, 'shortcuts/viewer') self.self_closing_pat = re.compile(r'<([a-z]+)\s+([^>]+)/>', re.IGNORECASE) self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) self._size_hint = QSize(510, 680) self.initial_pos = 0.0 self.to_bottom = False self.document = Document(self.shortcuts, parent=self) self.setPage(self.document) self.manager = None self._reference_mode = False self._ignore_scrollbar_signals = False self.loading_url = None self.loadFinished.connect(self.load_finished) self.connect(self.document, SIGNAL('linkClicked(QUrl)'), self.link_clicked) self.connect(self.document, SIGNAL('linkHovered(QString,QString,QString)'), self.link_hovered) self.connect(self.document, SIGNAL('selectionChanged()'), self.selection_changed) self.connect(self.document, SIGNAL('animated_scroll_done()'), self.animated_scroll_done, Qt.QueuedConnection) copy_action = self.pageAction(self.document.Copy) copy_action.setIcon(QIcon(I('convert.svg'))) d = self.document self.unimplemented_actions = list(map(self.pageAction, [d.DownloadImageToDisk, d.OpenLinkInNewWindow, d.DownloadLinkToDisk, d.OpenImageInNewWindow, d.OpenLink])) self.dictionary_action = QAction(QIcon(I('dictionary.png')), _('&Lookup in dictionary'), self) self.dictionary_action.setShortcut(Qt.CTRL+Qt.Key_L) self.dictionary_action.triggered.connect(self.lookup) self.goto_location_action = QAction(_('Go to...'), self) self.goto_location_menu = m = QMenu(self) self.goto_location_actions = a = { 'Next Page': self.next_page, 'Previous Page': self.previous_page, 'Section Top' : partial(self.scroll_to, 0), 'Document Top': self.goto_document_start, 'Section Bottom':partial(self.scroll_to, 1), 'Document Bottom': self.goto_document_end, 'Next Section': self.goto_next_section, 'Previous Section': self.goto_previous_section, } for name, key in [(_('Next Section'), 'Next Section'), (_('Previous Section'), 'Previous Section'), (None, None), (_('Document Start'), 'Document Top'), (_('Document End'), 'Document Bottom'), (None, None), (_('Section Start'), 'Section Top'), (_('Section End'), 'Section Bottom'), (None, None), (_('Next Page'), 'Next Page'), (_('Previous Page'), 'Previous Page')]: if key is None: m.addSeparator() else: m.addAction(name, a[key], self.shortcuts.get_sequences(key)[0]) self.goto_location_action.setMenu(self.goto_location_menu)
if not safe_encode: raise arg = repr(arg)
try: arg = arg.encode('utf-8') except: if not safe_encode: raise arg = repr(arg)
def prints(*args, **kwargs): ''' Print unicode arguments safely by encoding them to preferred_encoding Has the same signature as the print function from Python 3, except for the additional keyword argument safe_encode, which if set to True will cause the function to use repr when encoding fails. ''' file = kwargs.get('file', sys.stdout) sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') enc = preferred_encoding safe_encode = kwargs.get('safe_encode', False) if 'CALIBRE_WORKER' in os.environ: enc = 'utf-8' for i, arg in enumerate(args): if isinstance(arg, unicode): try: arg = arg.encode(enc) except UnicodeEncodeError: if not safe_encode: raise arg = repr(arg) if not isinstance(arg, str): try: arg = str(arg) except ValueError: arg = unicode(arg) if isinstance(arg, unicode): try: arg = arg.encode(enc) except UnicodeEncodeError: if not safe_encode: raise arg = repr(arg) file.write(arg) if i != len(args)-1: file.write(sep) file.write(end)
if field not in ('title', 'authors', 'rating', 'timestamp', 'tags', 'size', 'series'):
if field not in self.db.field_metadata.field_keys():
def sort(self, items, field, order): field = self.db.data.sanitize_sort_field_name(field) if field not in ('title', 'authors', 'rating', 'timestamp', 'tags', 'size', 'series'): raise cherrypy.HTTPError(400, '%s is not a valid sort field'%field) keyg = CSSortKeyGenerator([(field, order)], self.db.field_metadata) items.sort(key=keyg, reverse=not order)
self.db.set_timestamp(self.id, d)
if d.date() != self.orig_timestamp.date(): self.db.set_timestamp(self.id, d)
def accept(self): 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) self.db.set_isbn(self.id, re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text())), notify=False) self.db.set_rating(self.id, 2*self.rating.value(), notify=False) self.db.set_publisher(self.id, qstring_to_unicode(self.publisher.currentText()), notify=False) self.db.set_tags(self.id, [x.strip() for x in unicode(self.tags.text()).split(',')], notify=False) self.db.set_series(self.id, unicode(self.series.currentText()).strip(), notify=False) self.db.set_series_index(self.id, self.series_index.value(), notify=False) self.db.set_comment(self.id, qstring_to_unicode(self.comments.toPlainText()), notify=False) d = self.pubdate.date() d = qt_to_dt(d) self.db.set_pubdate(self.id, d) d = self.date.date() d = qt_to_dt(d) self.db.set_timestamp(self.id, d)
self.table.setColumnCount(5)
self.table.setColumnCount(7)
def __init__(self, parent, items): QDialog.__init__(self, parent) Ui_DeleteMatchingFromDeviceDialog.__init__(self) self.setupUi(self)
['', _('Location'), _('Title'), _('Author'), _('Date'), _('Format')])
['', _('Location'), _('Title'), _('Author'), _('Date'), _('Format'), _('Path')])
def __init__(self, parent, items): QDialog.__init__(self, parent) Ui_DeleteMatchingFromDeviceDialog.__init__(self) self.setupUi(self)
self.table.setItem(row, 5, tableItem(book.path.rpartition('.')[2]))
self.table.setItem(row, 5, centeredTableItem(book.path.rpartition('.')[2])) self.table.setItem(row, 6, tableItem(book.path))
def __init__(self, parent, items): QDialog.__init__(self, parent) Ui_DeleteMatchingFromDeviceDialog.__init__(self) self.setupUi(self)
idx = self.findText(text, Qt.MatchFixedString)
idx = self.findText(text, Qt.MatchFixedString|Qt.MatchCaseSensitive)
def setText(self, text): idx = self.findText(text, Qt.MatchFixedString) if idx == -1: self.insertItem(0, text) idx = 0 self.setCurrentIndex(idx)
view_box = elem.get('viewBox', elem.get('viewbox', None)) if size.width() == 100 and size.height() == 100 \ and view_box is not None: box = [float(x) for x in view_box.split()] size.setWidth(box[2] - box[0]) size.setHeight(box[3] - box[1])
if size.width() == 100 and size.height() == 100 and sizes: size.setWidth(sizes[0]) size.setHeight(sizes[1])
def rasterize_svg(self, elem, width=0, height=0, format='PNG'): data = QByteArray(xml2str(elem, with_tail=False)) svg = QSvgRenderer(data) size = svg.defaultSize() view_box = elem.get('viewBox', elem.get('viewbox', None)) if size.width() == 100 and size.height() == 100 \ and view_box is not None: box = [float(x) for x in view_box.split()] size.setWidth(box[2] - box[0]) size.setHeight(box[3] - box[1]) if width or height: size.scale(width, height, Qt.KeepAspectRatio) logger = self.oeb.logger logger.info('Rasterizing %r to %dx%d' % (elem, size.width(), size.height())) image = QImage(size, QImage.Format_ARGB32_Premultiplied) image.fill(QColor("white").rgb()) painter = QPainter(image) svg.render(painter) painter.end() array = QByteArray() buffer = QBuffer(array) buffer.open(QIODevice.WriteOnly) image.save(buffer, format) return str(array)
logger = self.oeb.logger
def rasterize_svg(self, elem, width=0, height=0, format='PNG'): data = QByteArray(xml2str(elem, with_tail=False)) svg = QSvgRenderer(data) size = svg.defaultSize() view_box = elem.get('viewBox', elem.get('viewbox', None)) if size.width() == 100 and size.height() == 100 \ and view_box is not None: box = [float(x) for x in view_box.split()] size.setWidth(box[2] - box[0]) size.setHeight(box[3] - box[1]) if width or height: size.scale(width, height, Qt.KeepAspectRatio) logger = self.oeb.logger logger.info('Rasterizing %r to %dx%d' % (elem, size.width(), size.height())) image = QImage(size, QImage.Format_ARGB32_Premultiplied) image.fill(QColor("white").rgb()) painter = QPainter(image) svg.render(painter) painter.end() array = QByteArray() buffer = QBuffer(array) buffer.open(QIODevice.WriteOnly) image.save(buffer, format) return str(array)
del self.hrefs[item.href]
if item.href in self.hrefs: del self.hrefs[item.href]
def remove(self, item): """Removes :param:`item` from the manifest.""" if item in self.ids: item = self.ids[item] del self.ids[item.id] del self.hrefs[item.href] self.items.remove(item) if item in self.oeb.spine: self.oeb.spine.remove(item)
self.line_edit.setPlaceholderText(help_text)
try: self.line_edit.setPlaceholderText(help_text) except: pass
def initialize(self, _search_box, colorize=False, help_text=_('Search')): self.search_box = _search_box self.line_edit.setPlaceholderText(help_text) self.colorize = colorize self.clear()
column = row = 0
column = row = comments_row = 0
def widget_factory(type, col): if bulk: w = bulk_widgets[type](db, col, parent) else: w = widgets[type](db, col, parent) w.initialize(book_id) return w
QThread.__init__(self) self.exception = self.traceback = self.cover_data = None
self.exception = self.traceback = self.cover_data = self.errors = None
def __init__(self, username, password, isbn, timeout, title, author): self.username = username.strip() if username else username self.password = password.strip() if password else password self.timeout = timeout self.isbn = isbn self.title = title self.needs_isbn = False self.author = author QThread.__init__(self) self.exception = self.traceback = self.cover_data = None
self.connect(self._hangcheck, SIGNAL('timeout()'), self.hangcheck)
self._hangcheck.timeout.connect(self.hangcheck, type=Qt.QueuedConnection)
def fetch_cover(self): isbn = re.sub(r'[^0-9a-zA-Z]', '', unicode(self.isbn.text())).strip() self.fetch_cover_button.setEnabled(False) self.setCursor(Qt.WaitCursor) title, author = map(unicode, (self.title.text(), self.authors.text())) self.cover_fetcher = CoverFetcher(None, None, isbn, self.timeout, title, author) self.cover_fetcher.start() self._hangcheck = QTimer(self) self.connect(self._hangcheck, SIGNAL('timeout()'), self.hangcheck) self.cf_start_time = time.time() self.pi.start(_('Downloading cover...')) self._hangcheck.start(100)
if not self.cover_fetcher.isFinished() and \
if self.cover_fetcher.is_alive() and \
def hangcheck(self): if not self.cover_fetcher.isFinished() and \ time.time()-self.cf_start_time < self.COVER_FETCH_TIMEOUT: return
if self.cover_fetcher.isRunning(): self.cover_fetcher.terminate()
if self.cover_fetcher.is_alive():
def hangcheck(self): if not self.cover_fetcher.isFinished() and \ time.time()-self.cf_start_time < self.COVER_FETCH_TIMEOUT: return
self.initialize_dynamic() def initialize_dynamic(self):
def __init__(self, library_path, row_factory=False): if not os.path.exists(library_path): os.makedirs(library_path) self.listeners = set([]) self.library_path = os.path.abspath(library_path) self.row_factory = row_factory self.dbpath = os.path.join(library_path, 'metadata.db') self.dbpath = os.environ.get('CALIBRE_OVERRIDE_DATABASE_PATH', self.dbpath) if isinstance(self.dbpath, unicode): self.dbpath = self.dbpath.encode(filesystem_encoding) self.connect() self.is_case_sensitive = not iswindows and not isosx and \ not os.path.exists(self.dbpath.replace('metadata.db', 'MeTAdAtA.dB')) SchemaUpgrade.__init__(self) CustomColumns.__init__(self) self.initialize_dynamic()
mi.title = m.group(1).strip().decode('cp1252', 'replace')
mi.title = re.sub('[\x00-\x1f]', '', prepare_string_for_xml(m.group(1).strip().decode('cp1252', 'replace')))
def get_metadata(stream, extract_cover=True): """ Return metadata as a L{MetaInfo} object """ mi = MetaInformation(_('Unknown'), [_('Unknown')]) stream.seek(0) pml = '' if stream.name.endswith('.pmlz'): with TemporaryDirectory('_unpmlz') as tdir: zf = ZipFile(stream) zf.extractall(tdir) pmls = glob.glob(os.path.join(tdir, '*.pml')) for p in pmls: with open(p, 'r+b') as p_stream: pml += p_stream.read() if extract_cover: mi.cover_data = get_cover(os.path.splitext(os.path.basename(stream.name))[0], tdir, True) else: pml = stream.read() if extract_cover: mi.cover_data = get_cover(os.path.splitext(os.path.basename(stream.name))[0], os.path.abspath(os.path.dirname(stream.name))) for comment in re.findall(r'(?mus)\\v.*?\\v', pml): m = re.search(r'TITLE="(.*?)"', comment) if m: mi.title = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'AUTHOR="(.*?)"', comment) if m: if mi.authors == [_('Unknown')]: mi.authors = [] mi.authors.append(m.group(1).strip().decode('cp1252', 'replace')) m = re.search(r'PUBLISHER="(.*?)"', comment) if m: mi.publisher = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'COPYRIGHT="(.*?)"', comment) if m: mi.rights = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'ISBN="(.*?)"', comment) if m: mi.isbn = m.group(1).strip().decode('cp1252', 'replace') return mi
mi.authors.append(m.group(1).strip().decode('cp1252', 'replace'))
mi.authors.append(re.sub('[\x00-\x1f]', '', prepare_string_for_xml(m.group(1).strip().decode('cp1252', 'replace'))))
def get_metadata(stream, extract_cover=True): """ Return metadata as a L{MetaInfo} object """ mi = MetaInformation(_('Unknown'), [_('Unknown')]) stream.seek(0) pml = '' if stream.name.endswith('.pmlz'): with TemporaryDirectory('_unpmlz') as tdir: zf = ZipFile(stream) zf.extractall(tdir) pmls = glob.glob(os.path.join(tdir, '*.pml')) for p in pmls: with open(p, 'r+b') as p_stream: pml += p_stream.read() if extract_cover: mi.cover_data = get_cover(os.path.splitext(os.path.basename(stream.name))[0], tdir, True) else: pml = stream.read() if extract_cover: mi.cover_data = get_cover(os.path.splitext(os.path.basename(stream.name))[0], os.path.abspath(os.path.dirname(stream.name))) for comment in re.findall(r'(?mus)\\v.*?\\v', pml): m = re.search(r'TITLE="(.*?)"', comment) if m: mi.title = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'AUTHOR="(.*?)"', comment) if m: if mi.authors == [_('Unknown')]: mi.authors = [] mi.authors.append(m.group(1).strip().decode('cp1252', 'replace')) m = re.search(r'PUBLISHER="(.*?)"', comment) if m: mi.publisher = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'COPYRIGHT="(.*?)"', comment) if m: mi.rights = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'ISBN="(.*?)"', comment) if m: mi.isbn = m.group(1).strip().decode('cp1252', 'replace') return mi
mi.publisher = m.group(1).strip().decode('cp1252', 'replace')
mi.publisher = re.sub('[\x00-\x1f]', '', prepare_string_for_xml(m.group(1).strip().decode('cp1252', 'replace')))
def get_metadata(stream, extract_cover=True): """ Return metadata as a L{MetaInfo} object """ mi = MetaInformation(_('Unknown'), [_('Unknown')]) stream.seek(0) pml = '' if stream.name.endswith('.pmlz'): with TemporaryDirectory('_unpmlz') as tdir: zf = ZipFile(stream) zf.extractall(tdir) pmls = glob.glob(os.path.join(tdir, '*.pml')) for p in pmls: with open(p, 'r+b') as p_stream: pml += p_stream.read() if extract_cover: mi.cover_data = get_cover(os.path.splitext(os.path.basename(stream.name))[0], tdir, True) else: pml = stream.read() if extract_cover: mi.cover_data = get_cover(os.path.splitext(os.path.basename(stream.name))[0], os.path.abspath(os.path.dirname(stream.name))) for comment in re.findall(r'(?mus)\\v.*?\\v', pml): m = re.search(r'TITLE="(.*?)"', comment) if m: mi.title = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'AUTHOR="(.*?)"', comment) if m: if mi.authors == [_('Unknown')]: mi.authors = [] mi.authors.append(m.group(1).strip().decode('cp1252', 'replace')) m = re.search(r'PUBLISHER="(.*?)"', comment) if m: mi.publisher = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'COPYRIGHT="(.*?)"', comment) if m: mi.rights = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'ISBN="(.*?)"', comment) if m: mi.isbn = m.group(1).strip().decode('cp1252', 'replace') return mi
mi.rights = m.group(1).strip().decode('cp1252', 'replace')
mi.rights = re.sub('[\x00-\x1f]', '', prepare_string_for_xml(m.group(1).strip().decode('cp1252', 'replace')))
def get_metadata(stream, extract_cover=True): """ Return metadata as a L{MetaInfo} object """ mi = MetaInformation(_('Unknown'), [_('Unknown')]) stream.seek(0) pml = '' if stream.name.endswith('.pmlz'): with TemporaryDirectory('_unpmlz') as tdir: zf = ZipFile(stream) zf.extractall(tdir) pmls = glob.glob(os.path.join(tdir, '*.pml')) for p in pmls: with open(p, 'r+b') as p_stream: pml += p_stream.read() if extract_cover: mi.cover_data = get_cover(os.path.splitext(os.path.basename(stream.name))[0], tdir, True) else: pml = stream.read() if extract_cover: mi.cover_data = get_cover(os.path.splitext(os.path.basename(stream.name))[0], os.path.abspath(os.path.dirname(stream.name))) for comment in re.findall(r'(?mus)\\v.*?\\v', pml): m = re.search(r'TITLE="(.*?)"', comment) if m: mi.title = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'AUTHOR="(.*?)"', comment) if m: if mi.authors == [_('Unknown')]: mi.authors = [] mi.authors.append(m.group(1).strip().decode('cp1252', 'replace')) m = re.search(r'PUBLISHER="(.*?)"', comment) if m: mi.publisher = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'COPYRIGHT="(.*?)"', comment) if m: mi.rights = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'ISBN="(.*?)"', comment) if m: mi.isbn = m.group(1).strip().decode('cp1252', 'replace') return mi
mi.isbn = m.group(1).strip().decode('cp1252', 'replace')
mi.isbn = re.sub('[\x00-\x1f]', '', prepare_string_for_xml(m.group(1).strip().decode('cp1252', 'replace')))
def get_metadata(stream, extract_cover=True): """ Return metadata as a L{MetaInfo} object """ mi = MetaInformation(_('Unknown'), [_('Unknown')]) stream.seek(0) pml = '' if stream.name.endswith('.pmlz'): with TemporaryDirectory('_unpmlz') as tdir: zf = ZipFile(stream) zf.extractall(tdir) pmls = glob.glob(os.path.join(tdir, '*.pml')) for p in pmls: with open(p, 'r+b') as p_stream: pml += p_stream.read() if extract_cover: mi.cover_data = get_cover(os.path.splitext(os.path.basename(stream.name))[0], tdir, True) else: pml = stream.read() if extract_cover: mi.cover_data = get_cover(os.path.splitext(os.path.basename(stream.name))[0], os.path.abspath(os.path.dirname(stream.name))) for comment in re.findall(r'(?mus)\\v.*?\\v', pml): m = re.search(r'TITLE="(.*?)"', comment) if m: mi.title = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'AUTHOR="(.*?)"', comment) if m: if mi.authors == [_('Unknown')]: mi.authors = [] mi.authors.append(m.group(1).strip().decode('cp1252', 'replace')) m = re.search(r'PUBLISHER="(.*?)"', comment) if m: mi.publisher = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'COPYRIGHT="(.*?)"', comment) if m: mi.rights = m.group(1).strip().decode('cp1252', 'replace') m = re.search(r'ISBN="(.*?)"', comment) if m: mi.isbn = m.group(1).strip().decode('cp1252', 'replace') return mi
default = 'My Catalog',
default = 'My Books',
def run(self, path_to_output, opts, db, notification=DummyReporter()): from calibre.utils.logging import Log
thousandsString = self.stringFromInt(thousandsNumber)
if number > 1099 and number < 2000: resultString = '%s %s' % (self.lessThanTwenty[number/100], self.stringFromInt(number % 100)) self.text = resultString.strip().capitalize() return else: thousandsString = self.stringFromInt(thousandsNumber)
def numberTranslate(self): hundredsNumber = 0 thousandsNumber = 0 hundredsString = "" thousandsString = "" resultString = ""
catalog.cleanUp()
def numberTranslate(self): hundredsNumber = 0 thousandsNumber = 0 hundredsString = "" thousandsString = "" resultString = ""
NOT_READ_SYMBOL = '<font style="color:white">& READ_SYMBOL = '<font style="color:black">&
def numberTranslate(self): hundredsNumber = 0 thousandsNumber = 0 hundredsString = "" thousandsString = "" resultString = ""
self.__dbs_fname = opts.dbs_fname self.__databaseSnapshot = self.fetchDatabaseSnapshot(self.__dbs_fname)
def __init__(self, db, opts, plugin, notification=DummyReporter(), stylesheet="content/stylesheet.css"): self.__opts = opts self.__authors = None self.__basename = opts.basename self.__booksByAuthor = None self.__booksByTitle = None self.__catalogPath = PersistentTemporaryDirectory("_epub_mobi_catalog", prefix='') self.__contentDir = os.path.join(self.catalogPath, "content") self.__creator = opts.creator self.__db = db self.__dbs_fname = opts.dbs_fname self.__databaseSnapshot = self.fetchDatabaseSnapshot(self.__dbs_fname) self.__descriptionClip = opts.descriptionClip self.__error = None self.__genres = None self.__htmlFileList = [] self.__libraryPath = self.fetchLibraryPath() self.__markerTags = self.getMarkerTags() self.__ncxSoup = None self.__playOrder = 1 self.__plugin = plugin self.__plugin_path = opts.plugin_path self.__progressInt = 0.0 self.__progressString = '' self.__reporter = notification self.__stylesheet = stylesheet self.__thumbs = None self.__title = opts.catalog_title self.__verbose = opts.verbose
if self.verbose: print "CatalogBuilder(): Generating %s for %s" % (self.opts.fmt, self.opts.output_profile)
def __init__(self, db, opts, plugin, notification=DummyReporter(), stylesheet="content/stylesheet.css"): self.__opts = opts self.__authors = None self.__basename = opts.basename self.__booksByAuthor = None self.__booksByTitle = None self.__catalogPath = PersistentTemporaryDirectory("_epub_mobi_catalog", prefix='') self.__contentDir = os.path.join(self.catalogPath, "content") self.__creator = opts.creator self.__db = db self.__dbs_fname = opts.dbs_fname self.__databaseSnapshot = self.fetchDatabaseSnapshot(self.__dbs_fname) self.__descriptionClip = opts.descriptionClip self.__error = None self.__genres = None self.__htmlFileList = [] self.__libraryPath = self.fetchLibraryPath() self.__markerTags = self.getMarkerTags() self.__ncxSoup = None self.__playOrder = 1 self.__plugin = plugin self.__plugin_path = opts.plugin_path self.__progressInt = 0.0 self.__progressString = '' self.__reporter = notification self.__stylesheet = stylesheet self.__thumbs = None self.__title = opts.catalog_title self.__verbose = opts.verbose
def databaseSnapshot(self): def fget(self): return self.__databaseSnapshot def fset(self, val): self.__databaseSnapshot = val return property(fget=fget, fset=fset) @dynamic_property
def databaseSnapshot(self): def fget(self): return self.__databaseSnapshot def fset(self, val): self.__databaseSnapshot = val return property(fget=fget, fset=fset)
def generateForMobigen(self): def fget(self): return self.__generateForMobigen
def generateForKindle(self): def fget(self): return self.__generateForKindle
def generateForMobigen(self): def fget(self): return self.__generateForMobigen def fset(self, val): self.__generateForMobigen = val return property(fget=fget, fset=fset)
self.__generateForMobigen = val
self.__generateForKindle = val
def fset(self, val): self.__generateForMobigen = val
self.generateNCXByTitle("Titles", single_article_per_section=False)
self.generateNCXByTitle("Titles")
def buildSources(self): if getattr(self.reporter, 'cancel_requested', False): return 1 if not self.booksByTitle: self.fetchBooksByTitle()
self.generateNCXByAuthor("Authors", single_article_per_section=False)
self.generateNCXByAuthor("Authors")
def buildSources(self): if getattr(self.reporter, 'cancel_requested', False): return 1 if not self.booksByTitle: self.fetchBooksByTitle()
if True: authors = [(record['author'], record['author_sort']) for record in self.booksByAuthor] else: self.opts.sort_by = 'author_sort' data = self.plugin.search_sort_db(self.db, self.opts) print "self.booksByAuthor in sort order:" for book in self.booksByAuthor: print "%s %s" % (book['author_sort'], book['title']) print "data set in sort order:" for book in data: print "%s %s" % (book['author_sort'], book['title']) authors = [] for record in data: author_list = [] for author in record['authors']: author_list.append(author) authors_concatenated = ", ".join(author_list) authors.append((authors_concatenated, record['author_sort']))
authors = [(record['author'], record['author_sort']) for record in self.booksByAuthor]
def fetchBooksByAuthor(self): # Generate a list of titles sorted by author from the database
unique_authors.append((current_author[0], current_author[1],
unique_authors.append((current_author[0], current_author[1].title(),
def fetchBooksByAuthor(self): # Generate a list of titles sorted by author from the database
if False: print "\nget_books_by_author(): %d unique authors" % len(unique_authors) for author in unique_authors[0:3]: print "%s" % author[0] print " ... " for author in unique_authors[-3:]: print "%s" % author[0] else: print "\nget_books_by_author(): %d unique authors" % len(unique_authors) for author in unique_authors: print "%-50s %-25s %2d" % (author[0], author[1], author[2]) print
print "\nfetchBooksByauthor(): %d unique authors" % len(unique_authors) for author in unique_authors: print (u" %-50s %-25s %2d" % (author[0][0:45], author[1][0:20], author[2])).encode('utf-8') print
def fetchBooksByAuthor(self): # Generate a list of titles sorted by author from the database
star_char = "& star_string = star_char * stars empty_star_char = "& empty_stars = empty_star_char * (5 - stars)
star_string = self.FULL_RATING_SYMBOL * stars empty_stars = self.EMPTY_RATING_SYMBOL * (5 - stars)
def generateHTMLDescriptions(self): # Write each title to a separate HTML file in contentdir if self.verbose: print self.updateProgressFullStep("generateHTMLDescriptions()")
titleTag.insert(0,self.title + self.title)
titleTag.insert(0,self.title)
def generateOPF(self):
if self.opts.fmt == 'mobi' and \ self.opts.output_profile and \ self.opts.output_profile.startswith("kindle"):
if self.generateForKindle:
def generateNCXDescriptions(self, tocTitle):
def generateNCXByTitle(self, tocTitle, single_article_per_section=True):
def generateNCXByTitle(self, tocTitle):
def generateNCXByTitle(self, tocTitle, single_article_per_section=True):
if single_article_per_section: single_list = [] for book in self.booksByTitle: single_list.append(book) if len(single_list) > 1: short_description = '%s -\n%s' % (single_list[0]['title'], single_list[-1]['title'])
current_letter = self.booksByTitle[0]['title_sort'][0].upper() title_letters = [current_letter] current_book_list = [] current_book = "" for book in self.booksByTitle: if book['title_sort'][0].upper() != current_letter: book_list = " &bull; ".join(current_book_list) short_description = self.generateShortDescription(self.formatNCXText(book_list)) books_by_letter.append(short_description) current_letter = book['title_sort'][0].upper() title_letters.append(current_letter) current_book = book['title'] current_book_list = [book['title']]
def generateNCXByTitle(self, tocTitle, single_article_per_section=True):
short_description = '%s' % (single_list[0]['title']) books_by_letter.append(short_description) else: current_letter = self.booksByTitle[0]['title_sort'][0].upper() title_letters = [current_letter] current_book_list = [] current_book = "" for book in self.booksByTitle: if book['title_sort'][0].upper() != current_letter: book_list = " &bull; ".join(current_book_list) short_description = self.generateShortDescription(self.formatNCXText(book_list)) books_by_letter.append(short_description) current_letter = book['title_sort'][0].upper() title_letters.append(current_letter)
if len(current_book_list) < self.descriptionClip and \ book['title'] != current_book :
def generateNCXByTitle(self, tocTitle, single_article_per_section=True):
current_book_list = [book['title']] else: if len(current_book_list) < self.descriptionClip and \ book['title'] != current_book : current_book = book['title'] current_book_list.append(book['title']) book_list = " &bull; ".join(current_book_list) short_description = self.generateShortDescription(self.formatNCXText(book_list)) books_by_letter.append(short_description)
current_book_list.append(book['title']) book_list = " &bull; ".join(current_book_list) short_description = self.generateShortDescription(self.formatNCXText(book_list)) books_by_letter.append(short_description)
def generateNCXByTitle(self, tocTitle, single_article_per_section=True):
if not single_article_per_section: navPointByLetterTag['id'] = "%sTitles-ID" % (title_letters[i].upper())
navPointByLetterTag['id'] = "%sTitles-ID" % (title_letters[i].upper())
def generateNCXByTitle(self, tocTitle, single_article_per_section=True):
if single_article_per_section: textTag.insert(0, NavigableString("All books sorted by title")) else: textTag.insert(0, NavigableString("Books beginning with '%s'" % (title_letters[i].upper())))
textTag.insert(0, NavigableString("Books beginning with '%s'" % (title_letters[i].upper())))
def generateNCXByTitle(self, tocTitle, single_article_per_section=True):
if single_article_per_section: contentTag['src'] = "content/%s.html else: contentTag['src'] = "content/%s.html
contentTag['src'] = "content/%s.html
def generateNCXByTitle(self, tocTitle, single_article_per_section=True):
if self.opts.fmt == 'mobi' and \ self.opts.output_profile and \ self.opts.output_profile.startswith("kindle"):
if self.generateForKindle:
def generateNCXByTitle(self, tocTitle, single_article_per_section=True):
if single_article_per_section: cmTag.insert(0, NavigableString(self.formatNCXText(books_by_letter[0]))) else: cmTag.insert(0, NavigableString(self.formatNCXText(books)))
cmTag.insert(0, NavigableString(self.formatNCXText(books)))
def generateNCXByTitle(self, tocTitle, single_article_per_section=True):
def generateNCXByAuthor(self, tocTitle, single_article_per_section=True):
def generateNCXByAuthor(self, tocTitle):
def generateNCXByAuthor(self, tocTitle, single_article_per_section=True):
if single_article_per_section: file_ID = "byauthor" else: file_ID = "%s" % tocTitle.lower() file_ID = file_ID.replace(" ","")
file_ID = "%s" % tocTitle.lower() file_ID = file_ID.replace(" ","")
def generateNCXByAuthor(self, tocTitle, single_article_per_section=True):
if single_article_per_section: single_list = [] for author in self.authors: single_list.append(author[0]) if len(single_list) > 1: author_list = '%s -\n%s' % (single_list[0], single_list[-1])
master_author_list = [] current_letter = self.authors[0][1][0] current_author_list = [] for author in self.authors: if author[1][0] != current_letter: author_list = " &bull; ".join(current_author_list) if len(current_author_list) == self.descriptionClip: author_list += " &hellip;" author_list = self.formatNCXText(author_list) if self.verbose: print " adding '%s' to master_author_list" % current_letter master_author_list.append((author_list, current_letter)) current_letter = author[1][0] current_author_list = [author[0]]
def generateNCXByAuthor(self, tocTitle, single_article_per_section=True):
author_list = '%s' % (single_list[0]) master_author_list=[(author_list, self.authors[0][1][0])] else: master_author_list = [] current_letter = self.authors[0][1][0].upper() current_author_list = [] for author in self.authors: if author[1][0] != current_letter: author_list = " &bull; ".join(current_author_list) if len(current_author_list) == self.descriptionClip: author_list += " &hellip;" author_list = self.formatNCXText(author_list) master_author_list.append((author_list, current_letter)) current_letter = author[1][0].upper() current_author_list = [author[0]] else: if len(current_author_list) < self.descriptionClip: current_author_list.append(author[0]) author_list = " &bull; ".join(current_author_list) if len(current_author_list) == self.descriptionClip: author_list += " &hellip;" author_list = self.formatNCXText(author_list) master_author_list.append((author_list, current_letter))
if len(current_author_list) < self.descriptionClip: current_author_list.append(author[0]) author_list = " &bull; ".join(current_author_list) if len(current_author_list) == self.descriptionClip: author_list += " &hellip;" author_list = self.formatNCXText(author_list) if self.verbose: print " adding '%s' to master_author_list" % current_letter master_author_list.append((author_list, current_letter))
def generateNCXByAuthor(self, tocTitle, single_article_per_section=True):
for authors in master_author_list:
for authors_by_letter in master_author_list:
def generateNCXByAuthor(self, tocTitle, single_article_per_section=True):
navPointByLetterTag['id'] = "%sauthors-ID" % (authors[1].upper())
navPointByLetterTag['id'] = "%sauthors-ID" % (authors_by_letter[1])
def generateNCXByAuthor(self, tocTitle, single_article_per_section=True):
if single_article_per_section: textTag.insert(0, NavigableString("All books sorted by author")) else: textTag.insert(0, NavigableString("Authors beginning with '%s'" % (authors[1].upper())))
textTag.insert(0, NavigableString("Authors beginning with '%s'" % (authors_by_letter[1])))
def generateNCXByAuthor(self, tocTitle, single_article_per_section=True):
if single_article_per_section: contentTag['src'] = "%s else: contentTag['src'] = "%s
contentTag['src'] = "%s
def generateNCXByAuthor(self, tocTitle, single_article_per_section=True):
if self.opts.fmt == 'mobi' and \ self.opts.output_profile and \ self.opts.output_profile.startswith("kindle"):
if self.generateForKindle:
def generateNCXByAuthor(self, tocTitle, single_article_per_section=True):
cmTag.insert(0, NavigableString(authors[0]))
cmTag.insert(0, NavigableString(authors_by_letter[0]))
def generateNCXByAuthor(self, tocTitle, single_article_per_section=True):
if self.opts.fmt == 'mobi' and \ self.opts.output_profile and \ self.opts.output_profile.startswith("kindle"):
if self.generateForKindle:
def generateNCXByTags(self, tocTitle): # Create an NCX section for 'By Genre' # Add each genre as an article # 'tag', 'file', 'authors'
def writeDatabaseSnapshot(self): pickleFile = open(os.path.join(self.fetchLibraryPath(),self.__dbs_fname),'w') pickle.dump(self.databaseSnapshot,pickleFile) pickleFile.close()
def writeDatabaseSnapshot(self): # Pickle the current databaseSnapshot pickleFile = open(os.path.join(self.fetchLibraryPath(),self.__dbs_fname),'w') pickle.dump(self.databaseSnapshot,pickleFile) pickleFile.close()
def fetchDatabaseSnapshot(self,filename): fs = os.path.join(self.fetchLibraryPath(),filename) if os.path.exists(fs): return pickle.load(open(fs)) else: return {}
def createDirectoryStructure(self): catalogPath = self.catalogPath self.cleanUp()
opts.dbs_fname = "CatalogSnapshot.dat"
def run(self, path_to_output, opts, db, notification=DummyReporter()): from calibre.utils.logging import Log
print " - - - - - begin clip here - - - - - "
def run(self, path_to_output, opts, db, notification=DummyReporter()): from calibre.utils.logging import Log
print " - - - - - end clip here - - - - - "
def run(self, path_to_output, opts, db, notification=DummyReporter()): from calibre.utils.logging import Log
iPadOutput, KoboReaderOutput,
iPadOutput, KoboReaderOutput, TabletOutput,
def tags_to_string(cls, tags): return u'%s <br/><span style="color: white">%s</span>' % (', '.join(tags), 'ttt '.join(tags)+'ttt ')
metadata.timestamp = isoformat(now())
metadata.timestamp = now()
def _update_epub_metadata(self, fpath, metadata): ''' ''' self.log.info(" ITUNES._update_epub_metadata()")
def __init__(self, args, db, ids, callback):
def __init__(self, args, db, ids, cc_widgets, callback):
def __init__(self, args, db, ids, callback): Thread.__init__(self) self.args = args self.db = db self.ids = ids self.error = None self.callback = callback
for w in getattr(self, 'custom_column_widgets', []):
for w in self.cc_widgets:
def doit(self): 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 = self.args
self.worker = Worker(args, self.db, self.ids, Dispatcher(bb.accept, parent=bb))
self.worker = Worker(args, self.db, self.ids, getattr(self, 'custom_column_widgets', []), Dispatcher(bb.accept, parent=bb))
def accept(self): if len(self.ids) < 1: return QDialog.accept(self)
added = self.iTunes.add(appscript.mactypes.File(files[i]))
if isinstance(file,PersistentTemporaryFile): added = self.iTunes.add(appscript.mactypes.File(file._name)) else: added = self.iTunes.add(appscript.mactypes.File(file))
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). '''
added.rating.set(metadata[i].rating*10) added.sort_artist.set(metadata[i].author_sort)
if metadata[i].rating: added.rating.set(metadata[i].rating*10) added.sort_artist.set(metadata[i].author_sort.title())
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). '''
try: pythoncom.CoInitialize() self.iTunes = win32com.client.Dispatch("iTunes.Application") self.iTunes.sources.ItemByName(self.sources['iPod']).EjectIPod() finally: pythoncom.CoUninitialize()
if 'iPod' in self.sources: try: pythoncom.CoInitialize() self.iTunes = win32com.client.Dispatch("iTunes.Application") self.iTunes.sources.ItemByName(self.sources['iPod']).EjectIPod() finally: pythoncom.CoUninitialize()
def eject(self): ''' Un-mount / eject the device from the OS. This does not check if there are pending GUI jobs that need to communicate with the device. ''' if DEBUG: self.log.info("ITUNES:eject(): ejecting '%s'" % self.sources['iPod']) if isosx: self.iTunes.eject(self.sources['iPod']) elif iswindows: try: pythoncom.CoInitialize() self.iTunes = win32com.client.Dispatch("iTunes.Application") self.iTunes.sources.ItemByName(self.sources['iPod']).EjectIPod() finally: pythoncom.CoUninitialize()
self._update_device(msg=self.update_msg)
self._update_device(msg=self.update_msg, wait=False)
def sync_booklists(self, booklists, end_session=True): ''' Update metadata on device. @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:sync_booklists():") if self.update_needed: if DEBUG: self.log.info(' calling _update_device') self._update_device(msg=self.update_msg) self.update_needed = False
if DEBUG: self.log.info("ITUNES.upload_books():") self._dump_files(files, header='upload_books()') self._dump_cached_books('upload_books()') self._dump_update_list('upload_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). '''
lib = self.iTunes.sources.ItemByName('Library') lib_playlists = [pl.Name for pl in lib.Playlists] if not 'Books' in lib_playlists: self.log.error(" no 'Books' playlist in Library") library_books = lib.Playlists.ItemByName('Books')
for source in self.iTunes.sources: if source.Kind == self.Sources.index('Library'): lib = source if DEBUG: self.log.info(" Library source: '%s' kind: %s" % (lib.Name, self.Sources[lib.Kind])) break else: if DEBUG: self.log.info(" Library source not found") if lib is not None: lib_books = None for pl in lib.Playlists: if self.PlaylistKind[pl.Kind] == 'User' and self.PlaylistSpecialKind[pl.SpecialKind] == 'Books': if DEBUG: self.log.info(" Books playlist: '%s' special_kind: '%s'" % (pl.Name, self.PlaylistSpecialKind[pl.SpecialKind])) lib_books = pl break else: if DEBUG: self.log.error(" no Books playlist found")
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). '''
op_status = library_books.AddFile(file._name)
op_status = lib_books.AddFile(file._name)
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). '''
op_status = library_books.AddFile(file)
op_status = lib_books.AddFile(file)
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). '''
def _find_device_book(self, cached_book): ''' Windows-only method to get a handle to a device book in the current pythoncom session ''' SearchField = ['All','Visible','Artists','Titles','Composers','SongNames'] if iswindows: dev_books = self.iTunes.sources.ItemByName(self.sources['iPod']).Playlists.ItemByName('Books') hits = dev_books.Search(cached_book['title'],SearchField.index('Titles')) if hits: for hit in hits: if hit.Artist == cached_book['author']: return hit return None
def _find_device_book(self, cached_book): ''' Windows-only method to get a handle to a device book in the current pythoncom session ''' SearchField = ['All','Visible','Artists','Titles','Composers','SongNames'] if iswindows: dev_books = self.iTunes.sources.ItemByName(self.sources['iPod']).Playlists.ItemByName('Books') hits = dev_books.Search(cached_book['title'],SearchField.index('Titles')) if hits: for hit in hits: if hit.Artist == cached_book['author']: return hit return None
lib_books = self.iTunes.sources.ItemByName('Library').Playlists.ItemByName('Books')
for source in self.iTunes.sources: if source.Kind == self.Sources.index('Library'): lib = source if DEBUG: self.log.info(" Library source: '%s' kind: %s" % (lib.Name, self.Sources[lib.Kind])) break else: if DEBUG: self.log.info(" Library source not found") if lib is not None: lib_books = None for pl in lib.Playlists: if self.PlaylistKind[pl.Kind] == 'User' and self.PlaylistSpecialKind[pl.SpecialKind] == 'Books': if DEBUG: self.log.info(" Books playlist: '%s' special_kind: '%s'" % (pl.Name, self.PlaylistSpecialKind[pl.SpecialKind])) lib_books = pl break else: if DEBUG: self.log.error(" no Books playlist found")
def _find_library_book(self, cached_book): ''' Windows-only method to get a handle to a library book in the current pythoncom session ''' SearchField = ['All','Visible','Artists','Titles','Composers','SongNames'] if iswindows: if DEBUG: self.log.info("ITUNES._find_library_book()") self.log.info(" looking for '%s' by %s" % (cached_book['title'], cached_book['author'])) lib_books = self.iTunes.sources.ItemByName('Library').Playlists.ItemByName('Books')
tmp_thumb = os.path.join(tempfile.gettempdir(), "thumb.%s" % ArtworkFormat[book.Artwork.Item(1).Format])
tmp_thumb = os.path.join(tempfile.gettempdir(), "thumb.%s" % self.ArtworkFormat[book.Artwork.Item(1).Format])
def _generate_thumbnail(self, book_path, book): ''' Convert iTunes artwork to thumbnail Cache generated thumbnails cache_dir = os.path.join(config_dir, 'caches', 'itunes') '''
Windows: If sync-in-progress, this call blocked until sync completes
def _get_device_book_size(self, title, author): ''' Fetch the size of a book stored on the device
Assumes pythoncom wrapper '''
Assumes pythoncom wrapper for Windows ''' if DEBUG: self.log.info("\nITUNES._get_device_books()") device_books = []
def _get_device_books(self): ''' Assumes pythoncom wrapper ''' if isosx: if 'iPod' in self.sources: connected_device = self.sources['iPod'] if 'Books' in self.iTunes.sources[connected_device].playlists.name(): return self.iTunes.sources[connected_device].playlists['Books'].file_tracks() return []
if 'Books' in self.iTunes.sources[connected_device].playlists.name(): return self.iTunes.sources[connected_device].playlists['Books'].file_tracks() return []
device = self.iTunes.sources[connected_device] for pl in device.playlists(): if pl.special_kind() == appscript.k.Books: if DEBUG: self.log.info(" Book playlist: '%s' special_kind: '%s'" % (pl.name(), pl.special_kind())) books = pl.file_tracks() break else: self.log.error(" book_playlist not found") for book in books: if book.kind() in ['Book','Protected book']: device_books.append(book) else: if DEBUG: self.log.info(" ignoring '%s' of type '%s'" % (book.name(), book.kind()))
def _get_device_books(self): ''' Assumes pythoncom wrapper ''' if isosx: if 'iPod' in self.sources: connected_device = self.sources['iPod'] if 'Books' in self.iTunes.sources[connected_device].playlists.name(): return self.iTunes.sources[connected_device].playlists['Books'].file_tracks() return []
connected_device = self.sources['iPod'] dev = self.iTunes.sources.ItemByName(connected_device) dev_playlists = [pl.Name for pl in dev.Playlists] if 'Books' in dev_playlists: return self.iTunes.sources.ItemByName(connected_device).Playlists.ItemByName('Books').Tracks else: return [] if DEBUG: self.log.warning('ITUNES._get_device_book(): No iPod device connected') return []
try: pythoncom.CoInitialize() connected_device = self.sources['iPod'] device = self.iTunes.sources.ItemByName(connected_device) dev_books = None for pl in device.Playlists: if self.PlaylistKind[pl.Kind] == 'User' and self.PlaylistSpecialKind[pl.SpecialKind] == 'Books': if DEBUG: self.log.info(" Books playlist: '%s' special_kind: '%s'" % (pl.Name, self.PlaylistSpecialKind[pl.SpecialKind])) dev_books = pl.Tracks break else: if DEBUG: self.log.info(" no Books playlist found") for book in dev_books: if book.KindAsString in ['Book','Protected book']: device_books.append(book) else: self.log.info(" ignoring '%s' of type %s" % (book.Name, book.KindAsString)) finally: pythoncom.CoUninitialize() return device_books
def _get_device_books(self): ''' Assumes pythoncom wrapper ''' if isosx: if 'iPod' in self.sources: connected_device = self.sources['iPod'] if 'Books' in self.iTunes.sources[connected_device].playlists.name(): return self.iTunes.sources[connected_device].playlists['Books'].file_tracks() return []
lib = self.iTunes.sources['library'] if 'Books' in lib.playlists.name(): lib_books = lib.playlists['Books'].file_tracks()
for source in self.iTunes.sources(): if source.kind() == appscript.k.library: lib = source if DEBUG: self.log.info(" Library source: '%s' kind: %s" % (lib.name(), lib.kind())) break else: if DEBUG: self.log.error(' Library source not found') if lib is not None: lib_books = None for pl in lib.playlists(): if pl.special_kind() == appscript.k.Books: if DEBUG: self.log.info(" Books playlist: '%s' special_kind: '%s'" % (pl.name(), pl.special_kind())) break lib_books = pl.file_tracks()
def _get_library_books(self): ''' Populate a dict of paths from iTunes Library|Books ''' library_books = {}
path = self.path_template % (book.name(), book.artist()) library_books[path] = book
if book.kind() in ['Book','Protected book']: path = self.path_template % (book.name(), book.artist()) library_books[path] = book else: if DEBUG: self.log.info(" ignoring library book of type '%s'" % book.kind()) else: if DEBUG: self.log.info('ITUNES._get_library_books():\n No Books playlist')
def _get_library_books(self): ''' Populate a dict of paths from iTunes Library|Books ''' library_books = {}
lib = self.iTunes.sources.ItemByName('Library') lib_playlists = [pl.Name for pl in lib.Playlists] if 'Books' in lib_playlists: lib_books = lib.Playlists.ItemByName('Books').Tracks
for source in self.iTunes.sources: if source.Kind == self.Sources.index('Library'): lib = source self.log.info(" Library source: '%s' kind: %s" % (lib.Name, self.Sources[lib.Kind])) break else: self.log.error(" Library source not found") if lib is not None: lib_books = None for pl in lib.Playlists: if self.PlaylistKind[pl.Kind] == 'User' and self.PlaylistSpecialKind[pl.SpecialKind] == 'Books': if DEBUG: self.log.info(" Books playlist: '%s' special_kind: '%s'" % (pl.Name, self.PlaylistSpecialKind[pl.SpecialKind])) lib_books = pl.Tracks break else: if DEBUG: self.log.error(" no Books playlist found")
def _get_library_books(self): ''' Populate a dict of paths from iTunes Library|Books ''' library_books = {}
path = self.path_template % (book.Name, book.Artist) library_books[path] = book
if book.KindAsString in ['Book','Protected book']: path = self.path_template % (book.Name, book.Artist) library_books[path] = book else: if DEBUG: self.log.info(" ignoring '%s' of type %s" % (book.Name, book.KindAsString))
def _get_library_books(self): ''' Populate a dict of paths from iTunes Library|Books ''' library_books = {}
self._formatted_date = val
if isinstance(val, unicode): self._formatted_date = val
def fset(self, val): self._formatted_date = val
for c in self.children(): painter.setBrush(c.brush) painter.drawRect(c.boundingRect())
if hasattr(self, 'children'): for c in self.children(): painter.setBrush(c.brush) painter.drawRect(c.boundingRect())
def paint(self, painter, option, widget): x, y = 0, 0+self.height-self.descent if self.vdebug: painter.save() painter.setPen(QPen(Qt.yellow, 1, Qt.DotLine)) painter.drawRect(self.boundingRect()) painter.restore() painter.save() painter.setPen(QPen(Qt.NoPen)) for c in self.children(): painter.setBrush(c.brush) painter.drawRect(c.boundingRect()) painter.restore() painter.save() for tok in self.tokens: if isinstance(tok, (int, float)): x += tok elif isinstance(tok, Word): painter.setFont(tok.font) if tok.highlight: painter.save() painter.setPen(QPen(Qt.NoPen)) painter.setBrush(QBrush(Qt.yellow)) painter.drawRect(x, 0, tok.width, tok.height) painter.restore() painter.setPen(QPen(tok.text_color)) if tok.valign is None: painter.drawText(x, y, tok.string) elif tok.valign == 'Sub': painter.drawText(x+1, y+self.descent/1.5, tok.string) elif tok.valign == 'Sup': painter.drawText(x+1, y-2.*self.descent, tok.string) x += tok.width else: painter.drawPixmap(x, 0, tok.pixmap()) x += tok.width painter.restore()
screen_size = (1024, 768) comic_screen_size = (1024, 768)
screen_size = (768, 1024) comic_screen_size = (768, 1024)
def tags_to_string(cls, tags): return ', '.join(tags)
self.timer.start(int(self.INTERVAL * 60000))
self.timer.start(int(self.INTERVAL * 60 * 1000))
def __init__(self, parent, db): QObject.__init__(self, parent) self.internet_connection_failed = False self._parent = parent self.recipe_model = RecipeModel(db) self.lock = QMutex(QMutex.Recursive) self.download_queue = set([])
self.oldest_timer.start(int(60 * 60000)) self.oldest_check()
self.oldest_timer.start(int(60 * 60 * 1000)) QTimer.singleShot(10 * 1000, self.oldest_check)
def __init__(self, parent, db): QObject.__init__(self, parent) self.internet_connection_failed = False self._parent = parent self.recipe_model = RecipeModel(db) self.lock = QMutex(QMutex.Recursive) self.download_queue = set([])
self.delete_old_news.emit(ids)
ids = list(ids) if ids: self.delete_old_news.emit(ids)
def oldest_check(self): if self.oldest > 0: delta = timedelta(days=self.oldest) ids = self.recipe_model.db.tags_older_than(_('News'), delta) if ids: self.delete_old_news.emit(ids)
with open('%s_6090.t2b' % os.path.join(path, filename), 'wb') as t2bfile: t2b.write_t2b(t2bfile, coverdata[2])
coverdata = coverdata[2] else: coverdata = None with open('%s_6090.t2b' % os.path.join(path, filename), 'wb') as t2bfile: t2b.write_t2b(t2bfile, coverdata)
def upload_cover(self, path, filename, metadata): coverdata = getattr(metadata, 'thumbnail', None) if coverdata and coverdata[2]: with open('%s_6090.t2b' % os.path.join(path, filename), 'wb') as t2bfile: t2b.write_t2b(t2bfile, coverdata[2])
text = '<span id="%s"></span>%s' % (id, t)
text = '%s<span id="%s"></span>' % (t, id)
def parse_pml(self, pml, file_name=''): pml = self.prepare_pml(pml) output = []
'epub', 'fb2', 'djvu', 'lrx', 'cbr', 'cbz', 'oebzip',
'epub', 'fb2', 'djvu', 'lrx', 'cbr', 'cbz', 'cbc', 'oebzip',
def __init__(self, msg, only_msg=False): Exception.__init__(self, msg) self.only_msg = only_msg
if attr == 'name':
if attr in ('name', '__enter__', '__str__', '__unicode__', '__repr__'):
def __getattribute__(self, attr): if attr == 'name': return object.__getattribute__(self, attr) fobject = object.__getattribute__(self, 'fobject') return getattr(fobject, attr)
open(dest, 'wb').write(serialize_builtin_recipes())
xml = serialize_builtin_recipes() with open(dest, 'wb') as f: f.write(xml)
def run(self, opts): scripts = {} for x in ('console', 'gui'): for name in basenames[x]: if name in ('calibre-complete', 'calibre_postinstall'): continue scripts[name] = x