rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
sb = QItemDelegate.createEditor(self, parent, option, index)
sb = QStyledItemDelegate.createEditor(self, parent, option, index)
def createEditor(self, parent, option, index): sb = QItemDelegate.createEditor(self, parent, option, index) sb.setMinimum(0) sb.setMaximum(5) return sb
chapter_index = self._index_item(r'(?s)\\C(?P<val>[0-4)="(?P<text>.+?)"', pml)
chapter_index = self._index_item(r'(?s)\\C(?P<val>[0-4])="(?P<text>.+?)"', pml)
def write_content(self, oeb_book, out_stream, metadata=None): pmlmlizer = PMLMLizer(self.log) pml = unicode(pmlmlizer.extract_content(oeb_book, self.opts)).encode('cp1252', 'replace')
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).strip() elif val: if tweaks['series_index_auto_increment'] == 'next': ni = self.db.get_next_series_num_for(val) if ni != 1: self.db.set_series_index(id, ni) if val:
if not val:
def setData(self, index, value, role): if role == Qt.EditRole: row, col = index.row(), index.column() column = self.column_map[col] if self.is_custom_column(column): if not self.set_custom_column_data(row, column, value): return False else: 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).strip() elif val: if tweaks['series_index_auto_increment'] == 'next': 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 self.db.set_timestamp(id, qt_to_dt(val, as_utc=False)) elif column == 'pubdate': if val.isNull() or not val.isValid(): return False self.db.set_pubdate(id, qt_to_dt(val, as_utc=False)) else: self.db.set(row, column, val) self.refresh_ids([id], row) self.dataChanged.emit(index, index) return True
self.search.emit('')
def clear_to_help(self): self.search.emit('') self._in_a_search = False self.setEditText(self.help_text) if self.timer is not None: # Turn off any timers that got started in setEditText self.killTimer(self.timer) self.timer = None self.line_edit.home(False) self.help_state = True self.line_edit.setStyleSheet( 'QLineEdit { color: gray; background-color: %s; }' % self.normal_background) self.emit(SIGNAL('cleared()'))
row = self.formats.currentRow() fmt = self.formats.item(row) if fmt is None: if self.formats.count() == 1: fmt = self.formats.item(0)
old = prefs['read_file_metadata'] if not old: prefs['read_file_metadata'] = True try: row = self.formats.currentRow() fmt = self.formats.item(row)
def get_selected_format_metadata(self): row = self.formats.currentRow() fmt = self.formats.item(row) if fmt is None: if self.formats.count() == 1: fmt = self.formats.item(0) if fmt is None: error_dialog(self, _('No format selected'), _('No format selected')).exec_() return None, None ext = fmt.ext.lower() if fmt.path is None: stream = self.db.format(self.row, ext, as_file=True) else: stream = open(fmt.path, 'r+b') try: mi = get_metadata(stream, ext) return mi, ext except: error_dialog(self, _('Could not read metadata'), _('Could not read metadata from %s format')%ext).exec_() return None, None
error_dialog(self, _('No format selected'), _('No format selected')).exec_() return None, None ext = fmt.ext.lower() if fmt.path is None: stream = self.db.format(self.row, ext, as_file=True) else: stream = open(fmt.path, 'r+b') try: mi = get_metadata(stream, ext) return mi, ext except: error_dialog(self, _('Could not read metadata'), _('Could not read metadata from %s format')%ext).exec_() return None, None
if self.formats.count() == 1: fmt = self.formats.item(0) if fmt is None: error_dialog(self, _('No format selected'), _('No format selected')).exec_() return None, None ext = fmt.ext.lower() if fmt.path is None: stream = self.db.format(self.row, ext, as_file=True) else: stream = open(fmt.path, 'r+b') try: mi = get_metadata(stream, ext) return mi, ext except: error_dialog(self, _('Could not read metadata'), _('Could not read metadata from %s format')%ext).exec_() return None, None finally: if old != prefs['read_file_metadata']: prefs['read_file_metadata'] = old
def get_selected_format_metadata(self): row = self.formats.currentRow() fmt = self.formats.item(row) if fmt is None: if self.formats.count() == 1: fmt = self.formats.item(0) if fmt is None: error_dialog(self, _('No format selected'), _('No format selected')).exec_() return None, None ext = fmt.ext.lower() if fmt.path is None: stream = self.db.format(self.row, ext, as_file=True) else: stream = open(fmt.path, 'r+b') try: mi = get_metadata(stream, ext) return mi, ext except: error_dialog(self, _('Could not read metadata'), _('Could not read metadata from %s format')%ext).exec_() return None, None
link = os.path.abspath(link)
try: link = os.path.abspath(link) except: return link_
def resource_adder(self, link_, base=None): link = self.urlnormalize(link_) link, frag = self.urldefrag(link) link = unquote(link).replace('/', os.sep) if not link.strip(): return link_ if base and not os.path.isabs(link): link = os.path.join(base, link) link = os.path.abspath(link) if not os.access(link, os.R_OK): return link_ if os.path.isdir(link): self.log.warn(link_, 'is a link to a directory. Ignoring.') return link_ if not islinux: link = link.lower() if link not in self.added_resources: bhref = os.path.basename(link) id, href = self.oeb.manifest.generate(id='added', href=bhref) self.oeb.log.debug('Added', link) self.oeb.container = self.DirContainer(os.path.dirname(link), self.oeb.log) # Load into memory guessed = self.guess_type(href)[0] media_type = guessed or self.BINARY_MIME
if isinstance(x, (unicode, str)): c = strcmp(unicode(force_unicode(x)), unicode(force_unicode(y)))
if isinstance(x, basestring) and isinstance(y, basestring): c = strcmp(force_unicode(x), force_unicode(y))
def none_cmp(xx, yy): x = xx[1] y = yy[1] if x is None and y is None: # No sort_key needed here, because defaults are ascii return cmp(xx[2], yy[2]) if x is None: return 1 if y is None: return -1 if isinstance(x, (unicode, str)): c = strcmp(unicode(force_unicode(x)), unicode(force_unicode(y))) else: c = cmp(x, y) if c != 0: return c # same as above -- no sort_key needed here return cmp(xx[2], yy[2])
if not os.path.exists(prefix): os.makedirs(prefix) with open(prefix + self.__class__.CACHE_XML, 'wb') as f:
tgt = os.path.join(prefix, *(self.CACHE_XML.split('/'))) base = os.path.dirname(tgt) if not os.path.exists(base): os.makedirs(base) with open(tgt, 'wb') as f:
def write_card_prefix(prefix, listid): if prefix is not None and hasattr(booklists[listid], 'write'): if not os.path.exists(prefix): os.makedirs(prefix) with open(prefix + self.__class__.CACHE_XML, 'wb') as f: booklists[listid].write(f)
db = getattr(self.model(), 'db', None) name = unicode(self.objectName()) if name and db is not None: db.prefs.set(name + ' books view state', state)
self.write_state(state)
def save_state(self): # Only save if we have been initialized (set_database called) if len(self.column_map) > 0 and self.was_restored: state = self.get_state() db = getattr(self.model(), 'db', None) name = unicode(self.objectName()) if name and db is not None: db.prefs.set(name + ' books view state', state)
if cmeta['datatype'] == 'series':
if cmeta and cmeta['datatype'] == 'series':
def format_field_extended(self, key, series_with_index=True): from calibre.ebooks.metadata import authors_to_string ''' returns the tuple (field_name, formatted_value) '''
ac.setShortcut(Qt.AltModifier+Qt.Key_V)
ac.setShortcut((Qt.ControlModifier if isosx else Qt.AltModifier)+Qt.Key_V)
def __init__(self, listener, opts, actions, parent=None): self.preferences_action, self.quit_action = actions self.spare_servers = [] MainWindow.__init__(self, opts, parent) # Initialize fontconfig in a separate thread as this can be a lengthy # process if run for the first time on this machine from calibre.utils.fonts import fontconfig self.fc = fontconfig self.listener = Listener(listener) self.check_messages_timer = QTimer() self.connect(self.check_messages_timer, SIGNAL('timeout()'), self.another_instance_wants_to_talk) self.check_messages_timer.start(1000)
self.device_manager.sync_booklists(None, booklists)
self.device_manager.sync_booklists( Dispatcher(self.metadata_synced), booklists)
def clean_string(x): x = x.lower() if x else '' return string_pat.sub('', x)
candidates = glob.glob(os.path.join(path, '*'+format))
try: candidates = glob.glob(os.path.join(path, '*'+format)) except: candidates = []
def format_abspath(self, index, format, index_is_id=False): 'Return absolute path to the ebook file of format `format`' id = index if index_is_id else self.id(index) try: name = self.conn.get('SELECT name FROM data WHERE book=? AND format=?', (id, format), all=False) except: return None if name: path = os.path.join(self.library_path, self.path(id, index_is_id=True)) format = ('.' + format.lower()) if format else '' fmt_path = os.path.join(path, name+format) if os.path.exists(fmt_path): return fmt_path candidates = glob.glob(os.path.join(path, '*'+format)) if format and candidates and os.path.exists(candidates[0]): shutil.copyfile(candidates[0], fmt_path) return fmt_path
idx = float(idx)
try: idx = float(idx) except: idx = 1.0
def set_series_index(self, id, idx, notify=True): if idx is None: idx = 1.0 idx = float(idx) self.conn.execute('UPDATE books SET series_index=? WHERE id=?', (idx, id)) self.conn.commit() self.data.set(id, FIELD_MAP['series_index'], idx, row_is_id=True) if notify: self.notify('metadata', [id])
q = getattr(self, attr) if q is None: return True return q == val or val in q
q = getattr(self.detected_device, attr) return q == val
def test(val, attr): q = getattr(self, attr) if q is None: return True return q == val or val in q
for y in ('idProduct',):
for y in ('idProduct', 'idVendor', 'bcdDevice'):
def test(val, attr): q = getattr(self, attr) if q is None: return True return q == val or val in q
ven, prod = map(e, ('idVendor', 'idProduct')) if not (test(ven, 'VENDOR_ID') and test(prod, 'PRODUCT_ID')):
ven, prod, bcd = map(e, ('idVendor', 'idProduct', 'bcdDevice')) if not (test(ven, 'idVendor') and test(prod, 'idProduct') and test(bcd, 'bcdDevice')):
def test(val, attr): q = getattr(self, attr) if q is None: return True return q == val or val in q
if self.BCD is not None: if not os.access(j(usb_dir, 'bcdDevice'), os.R_OK) or \ not test(e('bcdDevice'), 'BCD'): usb_dir = None continue else: break
def test(val, attr): q = getattr(self, attr) if q is None: return True return q == val or val in q
b, e = os.path.splitext(x)
b, _, e = x.rpartition('.')
def shorten_components_to(length, components): filepath = os.sep.join(components) extra = len(filepath) - length if extra < 1: return components delta = int(ceil(extra/float(len(components)))) ans = [] for x in components: if delta > len(x): r = x[0] if x is components[-1] else '' else: if x is components[-1]: b, e = os.path.splitext(x) r = b[:-delta]+e if r.startswith('.'): r = x[0]+r else: r = x[:-delta] r = r.strip() if not r: r = x.strip()[0] if x.strip() else 'x' ans.append(r) if len(os.sep.join(ans)) > length: return shorten_components_to(length, ans) return ans
ans.append(self.get_text(tag))
text = self.get_text(tag) if text and text.strip(): ans.extend([x.strip() for x in text.split(',')])
def fget(self): ans = [] for tag in self.tags_path(self.metadata): ans.append(self.get_text(tag)) return ans
pt = PersistentTemporaryFile('_user_stylesheet.css') pt.write(raw.encode('utf-8')) pt.close() self.settings().setUserStyleSheetUrl(QUrl.fromLocalFile(pt.name))
data = 'data:text/css;charset=utf-8;base64,' data += b64encode(raw.encode('utf-8')) self.settings().setUserStyleSheetUrl(QUrl(data))
def set_user_stylesheet(self): raw = config().parse().user_css pt = PersistentTemporaryFile('_user_stylesheet.css') pt.write(raw.encode('utf-8')) pt.close() self.settings().setUserStyleSheetUrl(QUrl.fromLocalFile(pt.name))
def __init__(self, name, is_dc=True, formatter=None, none_is=None):
def __init__(self, name, is_dc=True, formatter=None, none_is=None, renderer=lambda x: unicode(x)):
def __init__(self, name, is_dc=True, formatter=None, none_is=None): self.name = name self.is_dc = is_dc self.formatter = formatter self.none_is = none_is
obj.set_text(elem, unicode(val))
obj.set_text(elem, self.renderer(val))
def __set__(self, obj, val): elem = obj.get_metadata_element(self.name) if val is None: if elem is not None: elem.getparent().remove(elem) return if elem is None: elem = obj.create_metadata_element(self.name, is_dc=self.is_dc) obj.set_text(elem, unicode(val))
pubdate = MetadataField('date', formatter=parse_date)
pubdate = MetadataField('date', formatter=parse_date, renderer=isoformat)
def serialize_user_metadata(metadata_elem, all_user_metadata, tail='\n'+(' '*8)): from calibre.utils.config import to_json from calibre.ebooks.metadata.book.json_codec import object_to_unicode for name, fm in all_user_metadata.items(): try: fm = object_to_unicode(fm) fm = json.dumps(fm, default=to_json, ensure_ascii=False) except: prints('Failed to write user metadata:', name) import traceback traceback.print_exc() continue meta = metadata_elem.makeelement('meta') meta.set('name', 'calibre:user_metadata:'+name) meta.set('content', fm) meta.tail = tail metadata_elem.append(meta)
formatter=parse_date)
formatter=parse_date, renderer=isoformat)
def serialize_user_metadata(metadata_elem, all_user_metadata, tail='\n'+(' '*8)): from calibre.utils.config import to_json from calibre.ebooks.metadata.book.json_codec import object_to_unicode for name, fm in all_user_metadata.items(): try: fm = object_to_unicode(fm) fm = json.dumps(fm, default=to_json, ensure_ascii=False) except: prints('Failed to write user metadata:', name) import traceback traceback.print_exc() continue meta = metadata_elem.makeelement('meta') meta.set('name', 'calibre:user_metadata:'+name) meta.set('content', fm) meta.tail = tail metadata_elem.append(meta)
if val is None: if matches: for x in matches: x.getparent().remove(x) return
if not val: for x in matches: x.getparent().remove(x) return
def fset(self, val): matches = self.isbn_path(self.metadata) if val is None: if matches: for x in matches: x.getparent().remove(x) return if not matches: attrib = {'{%s}scheme'%self.NAMESPACES['opf']: 'ISBN'} matches = [self.create_metadata_element('identifier', attrib=attrib)] self.set_text(matches[0], unicode(val))
'isbn', 'language', 'tags', 'category', 'comments',
'isbn', 'tags', 'category', 'comments',
def smart_update(self, mi, replace_metadata=False): for attr in ('title', 'authors', 'author_sort', 'title_sort', 'publisher', 'series', 'series_index', 'rating', 'isbn', 'language', 'tags', 'category', 'comments', 'pubdate'): val = getattr(mi, attr, None) if val is not None and val != [] and val != (None, None): setattr(self, attr, val) temp = self.to_book_metadata() temp.smart_update(mi, replace_metadata=replace_metadata) self._user_metadata_ = temp.get_all_user_metadata(True)
self.db[idx].title_sorter = val
def setData(self, index, value, role): done = False if role == Qt.EditRole: row, col = index.row(), index.column() cname = self.column_map[col] if cname in ('size', 'timestamp', 'inlibrary'): return False val = unicode(value.toString()).strip() idx = self.map[row] if cname == 'title' : self.db[idx].title = val self.db[idx].title_sorter = val elif cname == 'authors': self.db[idx].authors = string_to_authors(val) elif cname == 'collections': tags = [i.strip() for i in val.split(',')] tags = [t for t in tags if t] self.db[idx].device_collections = tags self.dataChanged.emit(index, index) self.booklist_dirtied.emit() done = True return done
x, y = ','.join(self.db[x].tags), ','.join(self.db[y].tags)
x = ','.join(self.db[x].device_collections) y = ','.join(self.db[y].device_collections)
def tagscmp(x, y): x, y = ','.join(self.db[x].tags), ','.join(self.db[y].tags) return cmp(x, y)
data[_('Tags')] = ', '.join(item.tags)
data[_('Collections')] = ', '.join(item.device_collections)
def current_changed(self, current, previous): data = {} item = self.db[self.map[current.row()]] cdata = item.thumbnail if cdata is not None: img = QImage() if hasattr(cdata, 'image_path'): img.load(cdata.image_path) else: img.loadFromData(cdata) if img.isNull(): img = self.default_image data['cover'] = img type = _('Unknown') ext = os.path.splitext(item.path)[1] if ext: type = ext[1:].lower() data[_('Format')] = type data[_('Path')] = item.path dt = dt_factory(item.datetime, assume_utc=True) data[_('Timestamp')] = isoformat(dt, sep=' ', as_utc=False) data[_('Tags')] = ', '.join(item.tags) self.new_bookdisplay_data.emit(data)
url = QUrl.fromLocalFile(path) open_url(url)
if iswindows: os.startfile(os.path.normpath(path)) else: url = QUrl.fromLocalFile(path) open_url(url)
def open_local_file(path): url = QUrl.fromLocalFile(path) open_url(url)
__version__))
__version__), dir=os.environ.get('CALIBRE_TEMP_DIR', None))
def base_dir(): global _base_dir if _base_dir is None: td = os.environ.get('CALIBRE_WORKER_TEMP_DIR', None) if td is not None: try: td = cPickle.loads(binascii.unhexlify(td)) except: td = None if td and os.path.exists(td): _base_dir = td else: _base_dir = tempfile.mkdtemp(prefix='%s_%s_tmp_'%(__appname__, __version__)) atexit.register(remove_dir, _base_dir) return _base_dir
if rating_query: if (loc == MAP['rating'] and rating_query == int(item[loc])): matches.add(item[0]) continue
def get_matches(self, location, query): matches = set([]) if query and query.strip(): location = location.lower().strip()
self._model = TagsModel(db, parent=self, hidden_columns=self.hidden_categories)
self._model = TagsModel(db, parent=self, hidden_categories=self.hidden_categories)
def set_database(self, db, tag_match, popularity, restriction): self.hidden_categories = config['tag_browser_hidden_categories'] self._model = TagsModel(db, parent=self, hidden_columns=self.hidden_categories) self.popularity = popularity self.restriction = restriction self.tag_match = tag_match self.db = db self.setModel(self._model) self.setContextMenuPolicy(Qt.CustomContextMenu) self.clicked.connect(self.toggle) self.customContextMenuRequested.connect(self.show_context_menu) self.popularity.setChecked(config['sort_by_popularity']) self.popularity.stateChanged.connect(self.sort_changed) self.restriction.activated[str].connect(self.search_restriction_set) self.need_refresh.connect(self.recount, type=Qt.QueuedConnection) db.add_listener(self.database_changed) self.saved_searches_changed(recount=False)
cfile = os.path.join(os.path.dirname(self.spine[0]), 'calibre_iterator_cover.html') chtml = (TITLEPAGE%cover).encode('utf-8')
cfile = os.path.join(self.base, 'calibre_iterator_cover.html') chtml = (TITLEPAGE%os.path.relpath(cover, self.base).replace(os.sep, '/')).encode('utf-8')
def __enter__(self, processed=False): self.delete_on_exit = [] self._tdir = TemporaryDirectory('_ebook_iter') self.base = self._tdir.__enter__() from calibre.ebooks.conversion.plumber import Plumber, create_oebbook plumber = Plumber(self.pathtoebook, self.base, self.log) plumber.setup_options() if self.pathtoebook.lower().endswith('.opf'): plumber.opts.dont_package = True if hasattr(plumber.opts, 'no_process'): plumber.opts.no_process = True
self.spine[0:0] = [SpineItem(cfile)]
self.spine[0:0] = [SpineItem(cfile, mime_type='application/xhtml+xml')]
def __enter__(self, processed=False): self.delete_on_exit = [] self._tdir = TemporaryDirectory('_ebook_iter') self.base = self._tdir.__enter__() from calibre.ebooks.conversion.plumber import Plumber, create_oebbook plumber = Plumber(self.pathtoebook, self.base, self.log) plumber.setup_options() if self.pathtoebook.lower().endswith('.opf'): plumber.opts.dont_package = True if hasattr(plumber.opts, 'no_process'): plumber.opts.no_process = True
if attr == 'series' or getattr(book, 'series', None) == category:
if attr == 'series' or \ ('series' in collection_attributes and getattr(book, 'series', None) == category):
def get_collections(self, collection_attributes): from calibre.devices.usbms.driver import debug_print debug_print('Starting get_collections:', prefs['manage_device_metadata']) collections = {} series_categories = set([]) # This map of sets is used to avoid linear searches when testing for # book equality collections_lpaths = {} for book in self: # Make sure we can identify this book via the lpath lpath = getattr(book, 'lpath', None) if lpath is None: continue # Decide how we will build the collections. The default: leave the # book in all existing collections. Do not add any new ones. attrs = ['device_collections'] if getattr(book, '_new_book', False): if prefs['manage_device_metadata'] == 'manual': # Ensure that the book is in all the book's existing # collections plus all metadata collections attrs += collection_attributes else: # For new books, both 'on_send' and 'on_connect' do the same # thing. The book's existing collections are ignored. Put # the book in collections defined by its metadata. attrs = collection_attributes elif prefs['manage_device_metadata'] == 'on_connect': # For existing books, modify the collections only if the user # specified 'on_connect' attrs = collection_attributes for attr in attrs: attr = attr.strip() val = getattr(book, attr, None) if not val: continue if isbytestring(val): val = val.decode(preferred_encoding, 'replace') if isinstance(val, (list, tuple)): val = list(val) elif isinstance(val, unicode): val = [val] for category in val: if attr == 'tags' and len(category) > 1 and \ category[0] == '[' and category[-1] == ']': continue if category not in collections: collections[category] = [] collections_lpaths[category] = set() if lpath not in collections_lpaths[category]: collections_lpaths[category].add(lpath) collections[category].append(book) if attr == 'series' or getattr(book, 'series', None) == category: series_categories.add(category) # Sort collections for category, books in collections.items(): def tgetter(x): return getattr(x, 'title_sort', 'zzzz') books.sort(cmp=lambda x,y:cmp(tgetter(x), tgetter(y))) if category in series_categories: # Ensures books are sub sorted by title def getter(x): return getattr(x, 'series_index', sys.maxint) books.sort(cmp=lambda x,y:cmp(getter(x), getter(y))) return collections
im = Image.open(cStringIO.StringIO(data)) data = cStringIO.StringIO() im.convert('RGB').save(data, 'JPEG') data = data.getvalue()
data = save_cover_data_to(data, 'cover.jpg', return_data=True) width, height = identify_data(data)[:2]
def image_to_hexstring(self, data): im = Image.open(cStringIO.StringIO(data)) data = cStringIO.StringIO() im.convert('RGB').save(data, 'JPEG') data = data.getvalue()
return (hex_string, im.size[0], im.size[1])
return (hex_string, width, height)
def image_to_hexstring(self, data): im = Image.open(cStringIO.StringIO(data)) data = cStringIO.StringIO() im.convert('RGB').save(data, 'JPEG') data = data.getvalue()
if 'main' not in drives and 'carda' in drives:
if drives.get('carda', None) is not None and \ drives.get('main', None) is None:
def matches_q(drive, attr): q = getattr(self, attr) if q is None: return False if isinstance(q, basestring): q = [q] pnp = str(drive.PNPDeviceID) for x in q: if x in pnp: return True return False
self.current_tweaks.setPlainText(curt) self.default_tweaks.setPlainText(deft)
self.current_tweaks.setPlainText(curt.decode('utf-8')) self.default_tweaks.setPlainText(deft.decode('utf-8'))
def __init__(self, parent, library_view, server=None, initial_category='general'): ResizableDialog.__init__(self, parent) self._category_model = CategoryModel()
self.current_tweaks.setPlainText(deft)
self.current_tweaks.setPlainText(deft.decode('utf-8'))
def restore_tweaks_to_default(self, *args): deft, curt = read_raw_tweaks() self.current_tweaks.setPlainText(deft)
raw = unicode(self.current_tweaks.toPlainText()) raw = re.sub(r'(?m)^
raw = unicode(self.current_tweaks.toPlainText()).encode('utf-8')
def set_tweaks(self): raw = unicode(self.current_tweaks.toPlainText()) raw = re.sub(r'(?m)^#.*fileencoding.*', '# ', raw) try: exec raw except: import traceback error_dialog(self, _('Invalid tweaks'), _('The tweaks you entered are invalid, try resetting the' ' tweaks to default and changing them one by one until' ' you find the invalid setting.'), det_msg=traceback.format_exc(), show=True) return False write_tweaks(raw) return True
manifest.append((os.path.join(bp, 'images/', i), 'image/jpeg'))
path = os.path.join(bp, 'images', i) added.add(path) manifest.append((path, 'image/jpeg')) if cover_copied is not None: manifest.append((cover_copied, 'image/jpeg'))
def create_opf(self, htmlfile, guide=None, root=None): mi = getattr(self.book_header.exth, 'mi', self.embedded_mi) if mi is None: mi = MetaInformation(self.book_header.title, [_('Unknown')]) opf = OPFCreator(os.path.dirname(htmlfile), mi) if hasattr(self.book_header.exth, 'cover_offset'): opf.cover = 'images/%05d.jpg' % (self.book_header.exth.cover_offset + 1) elif mi.cover is not None: opf.cover = mi.cover else: opf.cover = 'images/%05d.jpg' % 1 if not os.path.exists(os.path.join(os.path.dirname(htmlfile), * opf.cover.split('/'))): opf.cover = None
return
from calibre.ebooks.oeb.base import urlnormalize href = urlnormalize(oeb.guide['toc'].href) if href in oeb.manifest.hrefs: item = oeb.manifest.hrefs[href] if oeb.spine.index(item) < 0: oeb.spine.add(item, linear=False) return else: oeb.guide.remove('toc')
def __call__(self, oeb, context): if 'toc' in oeb.guide: return if not getattr(getattr(oeb, 'toc', False), 'nodes', False): return oeb.logger.info('Generating in-line TOC...') title = self.title or oeb.translate(DEFAULT_TITLE) style = self.style if style not in STYLE_CSS: oeb.logger.error('Unknown TOC style %r' % style) style = 'nested' id, css_href = oeb.manifest.generate('tocstyle', 'tocstyle.css') oeb.manifest.add(id, css_href, CSS_MIME, data=STYLE_CSS[style]) language = str(oeb.metadata.language[0]) contents = element(None, XHTML('html'), nsmap={None: XHTML_NS}, attrib={XML('lang'): language}) head = element(contents, XHTML('head')) htitle = element(head, XHTML('title')) htitle.text = title element(head, XHTML('link'), rel='stylesheet', type=CSS_MIME, href=css_href) body = element(contents, XHTML('body'), attrib={'class': 'calibre_toc'}) h1 = element(body, XHTML('h1'), attrib={'class': 'calibre_toc_header'}) h1.text = title self.add_toc_level(body, oeb.toc) id, href = oeb.manifest.generate('contents', 'contents.xhtml') item = oeb.manifest.add(id, href, XHTML_MIME, data=contents) oeb.spine.add(item, linear=False) oeb.guide.add('toc', 'Table of Contents', href)
id="${r[0]}" title="${r[1]}" sort="${r[11]}" author_sort="${r[12]}"
id="${r[FM['id']]}" title="${r[FM['title']]}" sort="${r[FM['sort']]}" author_sort="${r[FM['author_sort']]}"
def do(self, *args, **kwargs): dict.update(cherrypy.response.headers, {'Server':self.server_name}) if not self.embedded: self.db.check_if_modified() return func(self, *args, **kwargs)
rating="${r[4]}"
rating="${r[FM['rating']]}"
def do(self, *args, **kwargs): dict.update(cherrypy.response.headers, {'Server':self.server_name}) if not self.embedded: self.db.check_if_modified() return func(self, *args, **kwargs)
size="${r[6]}" isbn="${r[14] if r[14] else ''}" formats="${r[13] if r[13] else ''}" series = "${r[9] if r[9] else ''}" series_index="${r[10]}" tags="${r[7] if r[7] else ''}" publisher="${r[3] if r[3] else ''}">${r[8] if r[8] else ''}
size="${r[FM['size']]}" isbn="${r[FM['isbn']] if r[FM['isbn']] else ''}" formats="${r[FM['formats']] if r[FM['formats']] else ''}" series = "${r[FM['series']] if r[FM['series']] else ''}" series_index="${r[FM['series_index']]}" tags="${r[FM['tags']] if r[FM['tags']] else ''}" publisher="${r[FM['publisher']] if r[FM['publisher']] else ''}">${r[FM['comments']] if r[FM['comments']] else ''}
def do(self, *args, **kwargs): dict.update(cherrypy.response.headers, {'Server':self.server_name}) if not self.embedded: self.db.check_if_modified() return func(self, *args, **kwargs)
<img type="image/jpeg" src="/get/thumb/${r[0]}" border="0"/>
<img type="image/jpeg" src="/get/thumb/${r[FM['id']]}" border="0"/>
def do(self, *args, **kwargs): dict.update(cherrypy.response.headers, {'Server':self.server_name}) if not self.embedded: self.db.check_if_modified() return func(self, *args, **kwargs)
<py:for each="format in r[13].split(',')"> <span class="button"><a href="/get/${format}/${authors}-${r[1]}_${r[0]}.${format}">${format.lower()}</a></span>&nbsp;
<py:for each="format in r[FM['formats']].split(',')"> <span class="button"><a href="/get/${format}/${authors}-${r[FM['title']]}_${r[FM['id']]}.${format}">${format.lower()}</a></span>&nbsp;
def do(self, *args, **kwargs): dict.update(cherrypy.response.headers, {'Server':self.server_name}) if not self.embedded: self.db.check_if_modified() return func(self, *args, **kwargs)
${r[1]}${(' ['+r[9]+'-'+r[10]+']') if r[9] else ''} by ${authors} - ${r[6]/1024}k - ${r[3] if r[3] else ''} ${pubdate} ${'['+r[7]+']' if r[7] else ''}
${r[FM['title']]}${(' ['+r[FM['series']]+'-'+r[FM['series_index']]+']') if r[FM['series']] else ''} by ${authors} - ${r[FM['size']]/1024}k - ${r[FM['publisher']] if r[FM['publisher']] else ''} ${pubdate} ${'['+r[FM['tags']]+']' if r[FM['tags']] else ''}
def do(self, *args, **kwargs): dict.update(cherrypy.response.headers, {'Server':self.server_name}) if not self.embedded: self.db.check_if_modified() return func(self, *args, **kwargs)
cmp(title_sort(x[self.db.FIELD_MAP['title']]), title_sort(y[self.db.FIELD_MAP['title']])))
cmp(title_sort(x[FM['title']]), title_sort(y[FM['title']])))
def stanza(self, search=None, sortby=None, authorid=None, tagid=None, seriesid=None, offset=0): 'Feeds to read calibre books on a ipod with stanza.' books = [] updated = self.db.last_modified() offset = int(offset) cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' # Main feed if not sortby and not search and not authorid and not tagid and not seriesid: return self.stanza_main(updated) if sortby in ('byseries', 'byauthor', 'bytag'): return self.stanza_sortby_subcategory(updated, sortby, offset)
cmp(x[self.db.FIELD_MAP['series_index']], y[self.db.FIELD_MAP['series_index']]))
cmp(x[FM['series_index']], y[FM['series_index']]))
def stanza(self, search=None, sortby=None, authorid=None, tagid=None, seriesid=None, offset=0): 'Feeds to read calibre books on a ipod with stanza.' books = [] updated = self.db.last_modified() offset = int(offset) cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' # Main feed if not sortby and not search and not authorid and not tagid and not seriesid: return self.stanza_main(updated) if sortby in ('byseries', 'byauthor', 'bytag'): return self.stanza_sortby_subcategory(updated, sortby, offset)
fmts = self.db.FIELD_MAP['formats']
fmts = FM['formats']
def stanza(self, search=None, sortby=None, authorid=None, tagid=None, seriesid=None, offset=0): 'Feeds to read calibre books on a ipod with stanza.' books = [] updated = self.db.last_modified() offset = int(offset) cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' # Main feed if not sortby and not search and not authorid and not tagid and not seriesid: return self.stanza_main(updated) if sortby in ('byseries', 'byauthor', 'bytag'): return self.stanza_sortby_subcategory(updated, sortby, offset)
record_list = [x for x in record_list if x[0] in ids and
record_list = [x for x in record_list if x[FM['id']] in ids and
def stanza(self, search=None, sortby=None, authorid=None, tagid=None, seriesid=None, offset=0): 'Feeds to read calibre books on a ipod with stanza.' books = [] updated = self.db.last_modified() offset = int(offset) cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' # Main feed if not sortby and not search and not authorid and not tagid and not seriesid: return self.stanza_main(updated) if sortby in ('byseries', 'byauthor', 'bytag'): return self.stanza_sortby_subcategory(updated, sortby, offset)
r = record[self.db.FIELD_MAP['formats']]
r = record[FM['formats']]
def stanza(self, search=None, sortby=None, authorid=None, tagid=None, seriesid=None, offset=0): 'Feeds to read calibre books on a ipod with stanza.' books = [] updated = self.db.last_modified() offset = int(offset) cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' # Main feed if not sortby and not search and not authorid and not tagid and not seriesid: return self.stanza_main(updated) if sortby in ('byseries', 'byauthor', 'bytag'): return self.stanza_sortby_subcategory(updated, sortby, offset)
z = record[self.db.FIELD_MAP['authors']]
z = record[FM['authors']]
def stanza(self, search=None, sortby=None, authorid=None, tagid=None, seriesid=None, offset=0): 'Feeds to read calibre books on a ipod with stanza.' books = [] updated = self.db.last_modified() offset = int(offset) cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' # Main feed if not sortby and not search and not authorid and not tagid and not seriesid: return self.stanza_main(updated) if sortby in ('byseries', 'byauthor', 'bytag'): return self.stanza_sortby_subcategory(updated, sortby, offset)
rating = record[self.db.FIELD_MAP['rating']]
rating = record[FM['rating']]
def stanza(self, search=None, sortby=None, authorid=None, tagid=None, seriesid=None, offset=0): 'Feeds to read calibre books on a ipod with stanza.' books = [] updated = self.db.last_modified() offset = int(offset) cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' # Main feed if not sortby and not search and not authorid and not tagid and not seriesid: return self.stanza_main(updated) if sortby in ('byseries', 'byauthor', 'bytag'): return self.stanza_sortby_subcategory(updated, sortby, offset)
tags = record[self.db.FIELD_MAP['tags']]
tags = record[FM['tags']]
def stanza(self, search=None, sortby=None, authorid=None, tagid=None, seriesid=None, offset=0): 'Feeds to read calibre books on a ipod with stanza.' books = [] updated = self.db.last_modified() offset = int(offset) cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' # Main feed if not sortby and not search and not authorid and not tagid and not seriesid: return self.stanza_main(updated) if sortby in ('byseries', 'byauthor', 'bytag'): return self.stanza_sortby_subcategory(updated, sortby, offset)
series = record[self.db.FIELD_MAP['series']]
series = record[FM['series']]
def stanza(self, search=None, sortby=None, authorid=None, tagid=None, seriesid=None, offset=0): 'Feeds to read calibre books on a ipod with stanza.' books = [] updated = self.db.last_modified() offset = int(offset) cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' # Main feed if not sortby and not search and not authorid and not tagid and not seriesid: return self.stanza_main(updated) if sortby in ('byseries', 'byauthor', 'bytag'): return self.stanza_sortby_subcategory(updated, sortby, offset)
fmt_sidx(float(record[self.db.FIELD_MAP['series_index']]))))
fmt_sidx(float(record[FM['series_index']]))))
def stanza(self, search=None, sortby=None, authorid=None, tagid=None, seriesid=None, offset=0): 'Feeds to read calibre books on a ipod with stanza.' books = [] updated = self.db.last_modified() offset = int(offset) cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' # Main feed if not sortby and not search and not authorid and not tagid and not seriesid: return self.stanza_main(updated) if sortby in ('byseries', 'byauthor', 'bytag'): return self.stanza_sortby_subcategory(updated, sortby, offset)
FM=self.db.FIELD_MAP,
FM=FM,
def stanza(self, search=None, sortby=None, authorid=None, tagid=None, seriesid=None, offset=0): 'Feeds to read calibre books on a ipod with stanza.' books = [] updated = self.db.last_modified() offset = int(offset) cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' # Main feed if not sortby and not search and not authorid and not tagid and not seriesid: return self.stanza_main(updated) if sortby in ('byseries', 'byauthor', 'bytag'): return self.stanza_sortby_subcategory(updated, sortby, offset)
urn=record[self.db.FIELD_MAP['uuid']], timestamp=strftime('%Y-%m-%dT%H:%M:%S+00:00', record[5])
urn=record[FM['uuid']], timestamp=strftime('%Y-%m-%dT%H:%M:%S+00:00', record[FM['timestamp']])
def stanza(self, search=None, sortby=None, authorid=None, tagid=None, seriesid=None, offset=0): 'Feeds to read calibre books on a ipod with stanza.' books = [] updated = self.db.last_modified() offset = int(offset) cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' # Main feed if not sortby and not search and not authorid and not tagid and not seriesid: return self.stanza_main(updated) if sortby in ('byseries', 'byauthor', 'bytag'): return self.stanza_sortby_subcategory(updated, sortby, offset)
return self.STANZA.generate(subtitle='', data=books, FM=self.db.FIELD_MAP,
return self.STANZA.generate(subtitle='', data=books, FM=FM,
def stanza(self, search=None, sortby=None, authorid=None, tagid=None, seriesid=None, offset=0): 'Feeds to read calibre books on a ipod with stanza.' books = [] updated = self.db.last_modified() offset = int(offset) cherrypy.response.headers['Last-Modified'] = self.last_modified(updated) cherrypy.response.headers['Content-Type'] = 'text/xml' # Main feed if not sortby and not search and not authorid and not tagid and not seriesid: return self.stanza_main(updated) if sortby in ('byseries', 'byauthor', 'bytag'): return self.stanza_sortby_subcategory(updated, sortby, offset)
items = [r for r in iter(self.db) if r[0] in ids]
FM = self.db.FIELD_MAP items = copy.deepcopy([r for r in iter(self.db) if r[FM['id']] in ids])
def mobile(self, start='1', num='25', sort='date', search='', _=None, order='descending'): ''' Serves metadata from the calibre database as XML.
if record[13] is None: record[13] = '' if record[6] is None: record[6] = 0 aus = record[2] if record[2] else __builtin__._('Unknown')
if record[FM['formats']] is None: record[FM['formats']] = '' if record[FM['size']] is None: record[FM['size']] = 0 aus = record[FM['authors']] if record[FM['authors']] else __builtin__._('Unknown')
def mobile(self, start='1', num='25', sort='date', search='', _=None, order='descending'): ''' Serves metadata from the calibre database as XML.
record[10] = fmt_sidx(float(record[10])) ts, pd = strftime('%Y/%m/%d %H:%M:%S', record[5]), \ strftime('%Y/%m/%d %H:%M:%S', record[self.db.FIELD_MAP['pubdate']])
record[FM['series_index']] = \ fmt_sidx(float(record[FM['series_index']])) ts, pd = strftime('%Y/%m/%d %H:%M:%S', record[FM['timestamp']]), \ strftime('%Y/%m/%d %H:%M:%S', record[FM['pubdate']])
def mobile(self, start='1', num='25', sort='date', search='', _=None, order='descending'): ''' Serves metadata from the calibre database as XML.
pubdate=pd).render('xml').decode('utf-8'))
pubdate=pd, FM=FM).render('xml').decode('utf-8'))
def mobile(self, start='1', num='25', sort='date', search='', _=None, order='descending'): ''' Serves metadata from the calibre database as XML.
return self.MOBILE.generate(books=books, start=start, updated=updated, search=search, sort=sort, order=order, num=num, total=len(ids), url_base=url_base).render('html')
return self.MOBILE.generate(books=books, start=start, updated=updated, search=search, sort=sort, order=order, num=num, FM=FM, total=len(ids), url_base=url_base).render('html')
def mobile(self, start='1', num='25', sort='date', search='', _=None, order='descending'): ''' Serves metadata from the calibre database as XML.
items = [r for r in iter(self.db) if r[0] in ids]
FM = self.db.FIELD_MAP items = copy.deepcopy([r for r in iter(self.db) if r[FM['id']] in ids])
def library(self, start='0', num='50', sort=None, search=None, _=None, order='ascending'): ''' Serves metadata from the calibre database as XML.
aus = record[2] if record[2] else __builtin__._('Unknown')
aus = record[FM['authors']] if record[FM['authors']] else __builtin__._('Unknown')
def library(self, start='0', num='50', sort=None, search=None, _=None, order='ascending'): ''' Serves metadata from the calibre database as XML.
record[10] = fmt_sidx(float(record[10])) ts, pd = strftime('%Y/%m/%d %H:%M:%S', record[5]), \ strftime('%Y/%m/%d %H:%M:%S', record[self.db.FIELD_MAP['pubdate']])
record[FM['series_index']] = \ fmt_sidx(float(record[FM['series_index']])) ts, pd = strftime('%Y/%m/%d %H:%M:%S', record[FM['timestamp']]), \ strftime('%Y/%m/%d %H:%M:%S', record[FM['pubdate']])
def library(self, start='0', num='50', sort=None, search=None, _=None, order='ascending'): ''' Serves metadata from the calibre database as XML.
pubdate=pd).render('xml').decode('utf-8'))
pubdate=pd, FM=FM).render('xml').decode('utf-8'))
def library(self, start='0', num='50', sort=None, search=None, _=None, order='ascending'): ''' Serves metadata from the calibre database as XML.
total=len(ids)).render('xml')
total=len(ids), FM=FM).render('xml')
def library(self, start='0', num='50', sort=None, search=None, _=None, order='ascending'): ''' Serves metadata from the calibre database as XML.
for fmt in all_input_formats():
for fmt in all_input_formats().union(set(['ZIP', 'RAR'])):
def __init__(self, parent, library_view, server=None, initial_category='general'): ResizableDialog.__init__(self, parent) self._category_model = CategoryModel()
soup = BeautifulSoup(xml_to_unicode(src, self.verbose, strip_encoding_pats=True)[0], markupMassage=nmassage)
soup = BeautifulSoup(xml_to_unicode(replace, self.verbose, strip_encoding_pats=True)[0], markupMassage=nmassage)
def get_soup(self, src): nmassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE) nmassage.extend(self.preprocess_regexps) nmassage += [(re.compile(r'<!DOCTYPE .+?>', re.DOTALL), lambda m: '')] # Some websites have buggy doctype declarations that mess up beautifulsoup # Remove comments as they can leave detritus when extracting tags leaves # multiple nested comments nmassage.append((re.compile(r'<!--.*?-->', re.DOTALL), lambda m: '')) soup = BeautifulSoup(xml_to_unicode(src, self.verbose, strip_encoding_pats=True)[0], markupMassage=nmassage)
def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID, readstatus):
def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID, readstatus, MimeType):
def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID, readstatus): 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('\\', '/') # debug_print("LPATH: ", lpath, " - Title: " , title)
if (ContentType != '6'and self.has_kepubs == False) or (self.has_kepubs == True):
if (ContentType != '6' and MimeType != 'Shortcover'):
def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID, readstatus): 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('\\', '/') # debug_print("LPATH: ", lpath, " - Title: " , title)
if ContentType == '6' and self.has_kepubs == False:
if ContentType == '6' and MimeType == 'Shortcover':
def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID, readstatus): 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('\\', '/') # debug_print("LPATH: ", lpath, " - Title: " , title)
path = self.path_from_contentid(row[3], row[5], oncard)
path = self.path_from_contentid(row[3], row[5], row[4], oncard)
def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID, readstatus): 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('\\', '/') # debug_print("LPATH: ", lpath, " - Title: " , title)
changed = update_booklist(self._main_prefix, path, row[0], row[1], mime, row[2], row[5], row[6], row[7])
changed = update_booklist(self._main_prefix, path, row[0], row[1], mime, row[2], row[5], row[6], row[7], row[4])
def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID, readstatus): 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('\\', '/') # debug_print("LPATH: ", lpath, " - Title: " , title)
changed = update_booklist(self._card_a_prefix, path, row[0], row[1], mime, row[2], row[5], row[6], row[7])
changed = update_booklist(self._card_a_prefix, path, row[0], row[1], mime, row[2], row[5], row[6], row[7], row[4])
def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID, readstatus): 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('\\', '/') # debug_print("LPATH: ", lpath, " - Title: " , title)
if self.has_kepubs == False:
extension = os.path.splitext(path)[1] if extension == '.kobo':
def contentid_from_path(self, path, ContentType): if ContentType == 6: if self.has_kepubs == False: ContentID = os.path.splitext(path)[0] # Remove the prefix on the file. it could be either ContentID = ContentID.replace(self._main_prefix, '') else: ContentID = path ContentID = ContentID.replace(self._main_prefix + self.normalize_path('.kobo/kepub/'), '')
def path_from_contentid(self, ContentID, ContentType, oncard):
def path_from_contentid(self, ContentID, ContentType, MimeType, oncard):
def path_from_contentid(self, ContentID, ContentType, oncard): path = ContentID
if ContentType == "6" and self.has_kepubs == False:
if ContentType == "6" and MimeType == 'Shortcover':
def path_from_contentid(self, ContentID, ContentType, oncard): path = ContentID
elif (ContentType == "6" or ContentType == "10") and self.has_kepubs == True:
elif (ContentType == "6" or ContentType == "10") and MimeType == 'application/x-kobo-epub+zip':
def path_from_contentid(self, ContentID, ContentType, oncard): path = ContentID
if set(val) != new_val or True:
if set(val) != new_val:
def commit(self, book_ids, notify=False): if self.process_each_book(): for book_id in book_ids: val = self.db.get_custom(book_id, num=self.col_id, index_is_id=True) new_val = self.getter(val) if set(val) != new_val or True: self.db.set_custom(book_id, new_val, num=self.col_id, notify=notify) else: val = self.getter() val = self.normalize_ui_val(val) if val != self.initial_val: for book_id in book_ids: self.db.set_custom(book_id, val, num=self.col_id, notify=notify)
QThread.__init__(self)
Thread.__init__(self) self.daemon = True
def __init__(self, title, author, publisher, isbn, key): QThread.__init__(self) self.title = title self.author = author self.publisher = publisher self.isbn = isbn self.key = key
if not (self.fetcher.isFinished() or time.time() - self.start_time > 75):
if self.fetcher.is_alive() and \ time.time() - self.start_time < self.HANG_TIME:
def hangcheck(self): if not (self.fetcher.isFinished() or time.time() - self.start_time > 75): return self._hangcheck.stop() try: if self.fetcher.isRunning(): error_dialog(self, _('Could not find metadata'), _('The metadata download seems to have stalled. ' 'Try again later.')).exec_() self.fetcher.terminate() return 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
if self.fetcher.isRunning():
if self.fetcher.is_alive():
def hangcheck(self): if not (self.fetcher.isFinished() or time.time() - self.start_time > 75): return self._hangcheck.stop() try: if self.fetcher.isRunning(): error_dialog(self, _('Could not find metadata'), _('The metadata download seems to have stalled. ' 'Try again later.')).exec_() self.fetcher.terminate() return 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
self.fetcher.terminate() return
self.terminate() return self.queue_reject.emit()
def hangcheck(self): if not (self.fetcher.isFinished() or time.time() - self.start_time > 75): return self._hangcheck.stop() try: if self.fetcher.isRunning(): error_dialog(self, _('Could not find metadata'), _('The metadata download seems to have stalled. ' 'Try again later.')).exec_() self.fetcher.terminate() return 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
if hasattr(self, 'fetcher') and self.fetcher.isRunning(): self.fetcher.terminate()
if hasattr(self, 'fetcher') and self.fetcher.is_alive(): _hung_fetchers.add(self.fetcher)
def terminate(self): if hasattr(self, 'fetcher') and self.fetcher.isRunning(): self.fetcher.terminate() if hasattr(self, '_hangcheck') and self._hangcheck.isActive(): self._hangcheck.stop()
self.clicked.connect(self.toggle)
def set_database(self, db, tag_match, sort_by): self.hidden_categories = config['tag_browser_hidden_categories'] self._model = TagsModel(db, parent=self, hidden_categories=self.hidden_categories, search_restriction=None) self.sort_by = sort_by self.tag_match = tag_match self.db = db self.search_restriction = None self.setModel(self._model) self.setContextMenuPolicy(Qt.CustomContextMenu) self.clicked.connect(self.toggle) self.customContextMenuRequested.connect(self.show_context_menu) pop = config['sort_tags_by'] self.sort_by.setCurrentIndex(self.db.CATEGORY_SORTS.index(pop)) self.sort_by.currentIndexChanged.connect(self.sort_changed) self.refresh_required.connect(self.recount, type=Qt.QueuedConnection) db.add_listener(self.database_changed)
self.results = search(self.title, self.book_author, self.publisher,
lang = get_lang() lang = lang[:2] if re.match(r'(fr.*|de.*)', lang) else 'all' if lang == 'all': self.results = search(self.title, self.book_author, self.publisher,
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()
tmploc = ThreadwithResults(AmazonError, self.verbose, get_social_metadata, self.title, self.book_author, self.publisher,self.isbn, verbose=self.verbose, lang=lang) tmpnoloc = ThreadwithResults(AmazonError, self.verbose, get_social_metadata, self.title, self.book_author, self.publisher, self.isbn, verbose=self.verbose, lang='all')
tmploc = ThreadwithResults(get_social_metadata, self.title, self.book_author, self.publisher,self.isbn, verbose=self.verbose, lang=lang) tmpnoloc = ThreadwithResults(get_social_metadata, self.title, self.book_author, self.publisher, self.isbn, verbose=self.verbose, lang='all')
def fetch(self): if not self.isbn: return try: lang = get_lang() lang = lang[:2] if re.match(r'(fr.*|de.*)', lang) else 'all' if lang == 'all': self.results = get_social_metadata(self.title, self.book_author, self.publisher, self.isbn, verbose=self.verbose, lang='all')[0] else: tmploc = ThreadwithResults(AmazonError, self.verbose, get_social_metadata, self.title, self.book_author, self.publisher,self.isbn, verbose=self.verbose, lang=lang) tmpnoloc = ThreadwithResults(AmazonError, self.verbose, get_social_metadata, self.title, self.book_author, self.publisher, self.isbn, verbose=self.verbose, lang='all') tmploc.start() tmpnoloc.start() tmploc.join() tmpnoloc.join() tmploc= tmploc.get_result() if tmploc is not None: tmploc = tmploc[0] tmpnoloc= tmpnoloc.get_result() if tmpnoloc is not None: tmpnoloc = tmpnoloc[0] print tmpnoloc if tmploc is not None and tmpnoloc is not None: if tmploc.rating is None: tmploc.rating = tmpnoloc.rating if tmploc.comments is not None: tmploc.comments = tmpnoloc.comments if tmploc.tags is None: tmploc.tags = tmpnoloc.tags self.results = tmploc except Exception, e: self.exception = e self.tb = traceback.format_exc()
print tmpnoloc if tmploc is not None and tmpnoloc is not None: if tmploc.rating is None: tmploc.rating = tmpnoloc.rating if tmploc.comments is not None: tmploc.comments = tmpnoloc.comments if tmploc.tags is None: tmploc.tags = tmpnoloc.tags
if tmpnoloc is not None: if tmploc.rating is None: tmploc.rating = tmpnoloc.rating if tmploc.comments is not None: tmploc.comments = tmpnoloc.comments if tmploc.tags is None: tmploc.tags = tmpnoloc.tags
def fetch(self): if not self.isbn: return try: lang = get_lang() lang = lang[:2] if re.match(r'(fr.*|de.*)', lang) else 'all' if lang == 'all': self.results = get_social_metadata(self.title, self.book_author, self.publisher, self.isbn, verbose=self.verbose, lang='all')[0] else: tmploc = ThreadwithResults(AmazonError, self.verbose, get_social_metadata, self.title, self.book_author, self.publisher,self.isbn, verbose=self.verbose, lang=lang) tmpnoloc = ThreadwithResults(AmazonError, self.verbose, get_social_metadata, self.title, self.book_author, self.publisher, self.isbn, verbose=self.verbose, lang='all') tmploc.start() tmpnoloc.start() tmploc.join() tmpnoloc.join() tmploc= tmploc.get_result() if tmploc is not None: tmploc = tmploc[0] tmpnoloc= tmpnoloc.get_result() if tmpnoloc is not None: tmpnoloc = tmpnoloc[0] print tmpnoloc if tmploc is not None and tmpnoloc is not None: if tmploc.rating is None: tmploc.rating = tmpnoloc.rating if tmploc.comments is not None: tmploc.comments = tmpnoloc.comments if tmploc.tags is None: tmploc.tags = tmpnoloc.tags self.results = tmploc except Exception, e: self.exception = e self.tb = traceback.format_exc()
def __init__(self, error, verb, func, *args, **kargs):
def __init__(self, func, *args, **kargs):
def __init__(self, error, verb, func, *args, **kargs): self.func = func self.args = args self.kargs = kargs self.verbose = verb self.ex = error self.result = None Thread.__init__(self)
self.verbose = verb self.ex = error
def __init__(self, error, verb, func, *args, **kargs): self.func = func self.args = args self.kargs = kargs self.verbose = verb self.ex = error self.result = None Thread.__init__(self)
try: self.result = self.func(*self.args, **self.kargs) except Exception, e: report(self.verbose) raise self.ex(_('An error was encountered in the function threading'))
self.result = self.func(*self.args, **self.kargs)
def run(self): try: self.result = self.func(*self.args, **self.kargs) except Exception, e: report(self.verbose) raise self.ex(_('An error was encountered in the function threading'))