Beispiel #1
0
    def add_empty(self, *args):
        '''
        Add an empty book item to the library. This does not import any formats
        from a book file.
        '''
        author = series = title = None
        index = self.gui.library_view.currentIndex()
        if index.isValid():
            raw = index.model().db.authors(index.row())
            if raw:
                authors = [a.strip().replace('|', ',') for a in raw.split(',')]
                if authors:
                    author = authors[0]
            series = index.model().db.series(index.row())
            title = index.model().db.title(index.row())
        dlg = AddEmptyBookDialog(self.gui, self.gui.library_view.model().db,
                                 author, series, dup_title=title)
        if dlg.exec_() == dlg.Accepted:
            temp_files = []
            num = dlg.qty_to_add
            series = dlg.selected_series
            title = dlg.selected_title or _('Unknown')
            db = self.gui.library_view.model().db
            ids, orig_fmts = [], []
            if dlg.duplicate_current_book:
                origmi = db.get_metadata(index.row(), get_cover=True, cover_as_data=True)
                if dlg.copy_formats.isChecked():
                    book_id = db.id(index.row())
                    orig_fmts = tuple(db.new_api.format(book_id, fmt, as_path=True) for fmt in db.new_api.formats(book_id))

            for x in xrange(num):
                if dlg.duplicate_current_book:
                    mi = origmi
                else:
                    mi = MetaInformation(title, dlg.selected_authors)
                    if series:
                        mi.series = series
                        mi.series_index = db.get_next_series_num_for(series)
                fmts = []
                empty_format = gprefs.get('create_empty_format_file', '')
                if dlg.duplicate_current_book and dlg.copy_formats.isChecked():
                    fmts = orig_fmts
                elif empty_format:
                    from calibre.ebooks.oeb.polish.create import create_book
                    pt = PersistentTemporaryFile(suffix='.' + empty_format)
                    pt.close()
                    temp_files.append(pt.name)
                    create_book(mi, pt.name, fmt=empty_format)
                    fmts = [pt.name]
                ids.append(db.import_book(mi, fmts))
            tuple(map(os.remove, orig_fmts))
            self.gui.library_view.model().books_added(num)
            self.gui.refresh_cover_browser()
            self.gui.tags_view.recount()
            if ids:
                ids.reverse()
                self.gui.library_view.select_rows(ids)
            for path in temp_files:
                os.remove(path)
Beispiel #2
0
    def add_empty(self, *args):
        '''
        Add an empty book item to the library. This does not import any formats
        from a book file.
        '''
        author = series = title = None
        index = self.gui.library_view.currentIndex()
        if index.isValid():
            raw = index.model().db.authors(index.row())
            if raw:
                authors = [a.strip().replace('|', ',') for a in raw.split(',')]
                if authors:
                    author = authors[0]
            series = index.model().db.series(index.row())
            title = index.model().db.title(index.row())
        dlg = AddEmptyBookDialog(self.gui, self.gui.library_view.model().db,
                                 author, series, dup_title=title)
        if dlg.exec_() == dlg.Accepted:
            temp_files = []
            num = dlg.qty_to_add
            series = dlg.selected_series
            title = dlg.selected_title or _('Unknown')
            db = self.gui.library_view.model().db
            ids, orig_fmts = [], []
            if dlg.duplicate_current_book:
                origmi = db.get_metadata(index.row(), get_cover=True, cover_as_data=True)
                if dlg.copy_formats.isChecked():
                    book_id = db.id(index.row())
                    orig_fmts = tuple(db.new_api.format(book_id, fmt, as_path=True) for fmt in db.new_api.formats(book_id))

            for x in xrange(num):
                if dlg.duplicate_current_book:
                    mi = origmi
                else:
                    mi = MetaInformation(title, dlg.selected_authors)
                    if series:
                        mi.series = series
                        mi.series_index = db.get_next_series_num_for(series)
                fmts = []
                empty_format = gprefs.get('create_empty_format_file', '')
                if dlg.duplicate_current_book and dlg.copy_formats.isChecked():
                    fmts = orig_fmts
                elif empty_format:
                    from calibre.ebooks.oeb.polish.create import create_book
                    pt = PersistentTemporaryFile(suffix='.' + empty_format)
                    pt.close()
                    temp_files.append(pt.name)
                    create_book(mi, pt.name, fmt=empty_format)
                    fmts = [pt.name]
                ids.append(db.import_book(mi, fmts))
            tuple(map(os.remove, orig_fmts))
            self.gui.library_view.model().books_added(num)
            self.gui.refresh_cover_browser()
            self.gui.tags_view.recount()
            if ids:
                ids.reverse()
                self.gui.library_view.select_rows(ids)
            for path in temp_files:
                os.remove(path)
Beispiel #3
0
    def add_empty_format(self, format_):
        if self.gui.stack.currentIndex() != 0:
            return
        view = self.gui.library_view
        rows = view.selectionModel().selectedRows()
        if not rows:
            return error_dialog(self.gui,
                                _('No books selected'),
                                _('Cannot add files as no books are selected'),
                                show=True)

        ids = [view.model().id(r) for r in rows]

        if len(ids) > 1 and not question_dialog(
                self.gui, _('Are you sure?'),
                _('Are you sure you want to add the same'
                  ' empty file to all %d books? If the format'
                  ' already exists for a book, it will be replaced.') %
                len(ids)):
            return

        db = self.gui.library_view.model().db
        if len(ids) == 1:
            formats = db.formats(ids[0], index_is_id=True)
            if formats:
                formats = {x.lower() for x in formats.split(',')}
                if format_ in formats:
                    title = db.title(ids[0], index_is_id=True)
                    msg = _(
                        'The {0} format will be replaced in the book {1}. Are you sure?'
                    ).format(format_, title)
                    if not confirm(msg,
                                   'confirm_format_override_on_add',
                                   title=_('Are you sure?'),
                                   parent=self.gui):
                        return

        for id_ in ids:
            from calibre.ebooks.oeb.polish.create import create_book
            pt = PersistentTemporaryFile(suffix='.' + format_)
            pt.close()
            try:
                mi = db.new_api.get_metadata(id_,
                                             get_cover=False,
                                             get_user_categories=False,
                                             cover_as_data=False)
                create_book(mi, pt.name, fmt=format_)
                db.add_format_with_hooks(id_,
                                         format_,
                                         pt.name,
                                         index_is_id=True,
                                         notify=True)
            finally:
                os.remove(pt.name)

        current_idx = self.gui.library_view.currentIndex()
        if current_idx.isValid():
            view.model().current_changed(current_idx, current_idx)
Beispiel #4
0
 def new_book(self):
     if not self._check_before_open():
         return
     d = NewBook(self.gui)
     if d.exec_() == d.Accepted:
         fmt = d.fmt
         path = choose_save_file(self.gui, 'edit-book-new-book', _('Choose file location'),
                                 filters=[(fmt.upper(), (fmt,))], all_files=False)
         if path is not None:
             from calibre.ebooks.oeb.polish.create import create_book
             create_book(d.mi, path, fmt=fmt)
             self.open_book(path=path)
Beispiel #5
0
 def add_empty_format_to_book(self, book_id, fmt):
     from calibre.ebooks.oeb.polish.create import create_book
     db = self.gui.current_db
     pt = PersistentTemporaryFile(suffix='.' + fmt.lower())
     pt.close()
     try:
         mi = db.new_api.get_metadata(book_id, get_cover=False,
                             get_user_categories=False, cover_as_data=False)
         create_book(mi, pt.name, fmt=fmt.lower())
         db.add_format_with_hooks(book_id, fmt, pt.name, index_is_id=True, notify=True)
     finally:
         os.remove(pt.name)
Beispiel #6
0
 def add_empty(self, *args):
     '''
     Add an empty book item to the library. This does not import any formats
     from a book file.
     '''
     author = series = None
     index = self.gui.library_view.currentIndex()
     if index.isValid():
         raw = index.model().db.authors(index.row())
         if raw:
             authors = [a.strip().replace('|', ',') for a in raw.split(',')]
             if authors:
                 author = authors[0]
         series = index.model().db.series(index.row())
     dlg = AddEmptyBookDialog(self.gui,
                              self.gui.library_view.model().db, author,
                              series)
     if dlg.exec_() == dlg.Accepted:
         temp_files = []
         num = dlg.qty_to_add
         series = dlg.selected_series
         title = dlg.selected_title or _('Unknown')
         db = self.gui.library_view.model().db
         ids = []
         for x in xrange(num):
             mi = MetaInformation(title, dlg.selected_authors)
             if series:
                 mi.series = series
                 mi.series_index = db.get_next_series_num_for(series)
             fmts = []
             empty_format = gprefs.get('create_empty_format_file', '')
             if empty_format:
                 from calibre.ebooks.oeb.polish.create import create_book
                 pt = PersistentTemporaryFile(suffix='.' + empty_format)
                 pt.close()
                 temp_files.append(pt.name)
                 create_book(mi, pt.name, fmt=empty_format)
                 fmts = [pt.name]
             ids.append(db.import_book(mi, fmts))
         self.gui.library_view.model().books_added(num)
         if hasattr(self.gui, 'db_images'):
             self.gui.db_images.beginResetModel(
             ), self.gui.db_images.endResetModel()
         self.gui.tags_view.recount()
         if ids:
             ids.reverse()
             self.gui.library_view.select_rows(ids)
         for path in temp_files:
             os.remove(path)
Beispiel #7
0
 def test_toc_detection(self):
     ep = os.path.join(self.tdir, 'book.epub')
     create_book(Metadata('Test ToC'), ep)
     c = get_container(ep, tdir=os.path.join(self.tdir, 'container'), tweak_mode=True)
     self.assertEqual(2, c.opf_version_parsed.major)
     self.assertTrue(len(get_toc(c)))
     c.opf.set('version', '3.0')
     self.assertEqual(3, c.opf_version_parsed.major)
     self.assertTrue(len(get_toc(c)))  # detect NCX toc even in epub 3 files
     c.add_file('nav.html', b'<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">'
                '<body><nav epub:type="toc"><ol><li><a href="start.xhtml">EPUB 3 nav</a></li></ol></nav></body></html>',
                process_manifest_item=lambda item:item.set('properties', 'nav'))
     toc = get_toc(c)
     self.assertTrue(len(toc))
     self.assertEqual(toc.as_dict['children'][0]['title'], 'EPUB 3 nav')
Beispiel #8
0
    def add_empty_format(self, format_):
        if self.gui.stack.currentIndex() != 0:
            return
        view = self.gui.library_view
        rows = view.selectionModel().selectedRows()
        if not rows:
            return error_dialog(self.gui, _('No books selected'),
                    _('Cannot add files as no books are selected'), show=True)

        ids = [view.model().id(r) for r in rows]

        if len(ids) > 1 and not question_dialog(
                self.gui,
                _('Are you sure?'),
                _('Are you sure you want to add the same'
                  ' empty file to all %d books? If the format'
                  ' already exists for a book, it will be replaced.')%len(ids)):
            return

        db = self.gui.library_view.model().db
        if len(ids) == 1:
            formats = db.formats(ids[0], index_is_id=True)
            if formats:
                formats = {x.lower() for x in formats.split(',')}
                if format_ in formats:
                    title = db.title(ids[0], index_is_id=True)
                    msg = _('The {0} format will be replaced in the book {1}. Are you sure?').format(
                        format_, title)
                    if not confirm(msg, 'confirm_format_override_on_add', title=_('Are you sure?'),
                                   parent=self.gui):
                        return

        for id_ in ids:
            from calibre.ebooks.oeb.polish.create import create_book
            pt = PersistentTemporaryFile(suffix='.' + format_)
            pt.close()
            try:
                mi = db.new_api.get_metadata(id_, get_cover=False,
                                    get_user_categories=False, cover_as_data=False)
                create_book(mi, pt.name, fmt=format_)
                db.add_format_with_hooks(id_, format_, pt.name, index_is_id=True, notify=True)
            finally:
                os.remove(pt.name)

        current_idx = self.gui.library_view.currentIndex()
        if current_idx.isValid():
            view.model().current_changed(current_idx, current_idx)
Beispiel #9
0
 def add_empty(self, *args):
     '''
     Add an empty book item to the library. This does not import any formats
     from a book file.
     '''
     author = series = None
     index = self.gui.library_view.currentIndex()
     if index.isValid():
         raw = index.model().db.authors(index.row())
         if raw:
             authors = [a.strip().replace('|', ',') for a in raw.split(',')]
             if authors:
                 author = authors[0]
         series = index.model().db.series(index.row())
     dlg = AddEmptyBookDialog(self.gui, self.gui.library_view.model().db,
                              author, series)
     if dlg.exec_() == dlg.Accepted:
         temp_files = []
         num = dlg.qty_to_add
         series = dlg.selected_series
         title = dlg.selected_title or _('Unknown')
         db = self.gui.library_view.model().db
         ids = []
         for x in xrange(num):
             mi = MetaInformation(title, dlg.selected_authors)
             if series:
                 mi.series = series
                 mi.series_index = db.get_next_series_num_for(series)
             fmts = []
             empty_format = gprefs.get('create_empty_format_file', '')
             if empty_format:
                 from calibre.ebooks.oeb.polish.create import create_book
                 pt = PersistentTemporaryFile(suffix='.' + empty_format)
                 pt.close()
                 temp_files.append(pt.name)
                 create_book(mi, pt.name, fmt=empty_format)
                 fmts = [pt.name]
             ids.append(db.import_book(mi, fmts))
         self.gui.library_view.model().books_added(num)
         if hasattr(self.gui, 'db_images'):
             self.gui.db_images.beginResetModel(), self.gui.db_images.endResetModel()
         self.gui.tags_view.recount()
         if ids:
             ids.reverse()
             self.gui.library_view.select_rows(ids)
         for path in temp_files:
             os.remove(path)
Beispiel #10
0
    def test_toc_detection(self):
        ep = os.path.join(self.tdir, 'book.epub')
        create_book(Metadata('Test ToC'), ep)
        c = get_container(ep,
                          tdir=os.path.join(self.tdir, 'container'),
                          tweak_mode=True)
        self.assertEqual(2, c.opf_version_parsed.major)
        self.assertTrue(len(get_toc(c)))
        c.opf.set('version', '3.0')
        self.assertEqual(3, c.opf_version_parsed.major)
        self.assertTrue(len(get_toc(c)))  # detect NCX toc even in epub 3 files
        c.add_file(
            'nav.html',
            b'<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">'
            b'<body><nav epub:type="toc"><ol><li><a href="start.xhtml">EPUB 3 nav</a></li></ol></nav></body></html>',
            process_manifest_item=lambda item: item.set('properties', 'nav'))
        toc = get_toc(c)
        self.assertTrue(len(toc))
        self.assertEqual(toc.as_dict['children'][0]['title'], 'EPUB 3 nav')

        def tfx(linear, expected):
            items = ['<t{0}>{0}</t{0}>'.format(x) for x in linear]
            html = '<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">'
            html += '<body>%s</body></html>' % '\n'.join(items)
            with c.open('nav.html', 'wb') as f:
                f.write(html.encode('utf-8'))
            toc = toc_from_xpaths(c,
                                  ['//h:t' + x for x in sorted(set(linear))])

            def p(node):
                ans = ''
                if node.children:
                    ans += '['
                    for c in node.children:
                        ans += c.title + p(c)
                    ans += ']'
                return ans

            self.assertEqual('[%s]' % expected, p(toc))

        tfx('121333', '1[2]1[333]')
        tfx('1223424', '1[22[3[4]]2[4]]')
        tfx('32123', '321[2[3]]')
        tfx('123123', '1[2[3]]1[2[3]]')
Beispiel #11
0
 def test_toc_detection(self):
     ep = os.path.join(self.tdir, 'book.epub')
     create_book(Metadata('Test ToC'), ep)
     c = get_container(ep,
                       tdir=os.path.join(self.tdir, 'container'),
                       tweak_mode=True)
     self.assertEqual(2, c.opf_version_parsed.major)
     self.assertTrue(len(get_toc(c)))
     c.opf.set('version', '3.0')
     self.assertEqual(3, c.opf_version_parsed.major)
     self.assertTrue(len(get_toc(c)))  # detect NCX toc even in epub 3 files
     c.add_file(
         'nav.html',
         b'<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">'
         '<body><nav epub:type="toc"><ol><li><a href="start.xhtml">EPUB 3 nav</a></li></ol></nav></body></html>',
         process_manifest_item=lambda item: item.set('properties', 'nav'))
     toc = get_toc(c)
     self.assertTrue(len(toc))
     self.assertEqual(toc.as_dict['children'][0]['title'], 'EPUB 3 nav')
Beispiel #12
0
    def _add_empty_format(self, format_):
        view = self.gui.library_view
        rows = view.selectionModel().selectedRows()
        ids = [view.model().id(r) for r in rows]
        db = self.gui.library_view.model().db
        if len(ids) == 1:
            formats = db.formats(ids[0], index_is_id=True)
            if formats:
                formats = {x.lower() for x in formats.split(',')}
                if format_ in formats:
                    title = db.title(ids[0], index_is_id=True)
                    msg = _(
                        'The {0} format will be replaced in the book {1}. Are you sure?'
                    ).format(format_, title)
                    if not confirm(msg,
                                   'confirm_format_override_on_add',
                                   title=_('Are you sure?'),
                                   parent=self.gui):
                        return

        for id_ in ids:
            from calibre.ebooks.oeb.polish.create import create_book
            pt = PersistentTemporaryFile(suffix='.' + format_)
            pt.close()
            try:
                mi = db.new_api.get_metadata(id_,
                                             get_cover=False,
                                             get_user_categories=False,
                                             cover_as_data=False)
                create_book(mi, pt.name, fmt=format_)
                db.add_format_with_hooks(id_,
                                         format_,
                                         pt.name,
                                         index_is_id=True,
                                         notify=True)
            finally:
                os.remove(pt.name)

        current_idx = self.gui.library_view.currentIndex()
        if current_idx.isValid():
            view.model().current_changed(current_idx, current_idx)
Beispiel #13
0
    def test_toc_detection(self):
        ep = os.path.join(self.tdir, 'book.epub')
        create_book(Metadata('Test ToC'), ep)
        c = get_container(ep, tdir=os.path.join(self.tdir, 'container'), tweak_mode=True)
        self.assertEqual(2, c.opf_version_parsed.major)
        self.assertTrue(len(get_toc(c)))
        c.opf.set('version', '3.0')
        self.assertEqual(3, c.opf_version_parsed.major)
        self.assertTrue(len(get_toc(c)))  # detect NCX toc even in epub 3 files
        c.add_file('nav.html', b'<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">'
                   '<body><nav epub:type="toc"><ol><li><a href="start.xhtml">EPUB 3 nav</a></li></ol></nav></body></html>',
                   process_manifest_item=lambda item:item.set('properties', 'nav'))
        toc = get_toc(c)
        self.assertTrue(len(toc))
        self.assertEqual(toc.as_dict['children'][0]['title'], 'EPUB 3 nav')

        def tfx(linear, expected):
            items = ['<t{0}>{0}</t{0}>'.format(x) for x in linear]
            html = '<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">'
            html += '<body>%s</body></html>' % '\n'.join(items)
            with c.open('nav.html', 'wb') as f:
                f.write(html.encode('utf-8'))
            toc = toc_from_xpaths(c, ['//h:t'+x for x in sorted(set(linear))])

            def p(node):
                ans = ''
                if node.children:
                    ans += '['
                    for c in node.children:
                        ans += c.title + p(c)
                    ans += ']'
                return ans
            self.assertEqual('[%s]'%expected, p(toc))

        tfx('121333', '1[2]1[333]')
        tfx('1223424', '1[22[3[4]]2[4]]')
        tfx('32123', '321[2[3]]')
        tfx('123123', '1[2[3]]1[2[3]]')