Esempio n. 1
0
def make_mobi(book_id):
    kindlegen = os.path.join(config.MAIN_DIR, "vendor", "kindlegen")
    if not os.path.exists(kindlegen):
        app.logger.error("make_mobi: kindlegen binary not found in: %s" %
                         kindlegen)
        return None
    book = db.session.query(db.Books).filter(db.Books.id == book_id).first()
    data = db.session.query(db.Data).filter(db.Data.book == book.id).filter(
        db.Data.format == 'EPUB').first()
    if not data:
        app.logger.error("make_mobi: epub format not found for book id: %d" %
                         book_id)
        return None

    file_path = os.path.join(config.DB_ROOT, book.path, data.name)

    if os.path.exists(file_path + ".epub"):
        check = subprocess.call([kindlegen, file_path + ".epub"],
                                stdout=subprocess.PIPE)
        if not check or check < 2:
            book.data.append(
                db.Data(name=book.data[0].name,
                        format="MOBI",
                        book=book.id,
                        uncompressed_size=os.path.getsize(file_path +
                                                          ".mobi")))
            db.session.commit()
            return file_path + ".mobi"
        else:
            app.logger.error(
                "make_mobi: kindlegen failed with error while converting book")
            return None
    else:
        app.logger.error("make_mobie: epub not found: %s.epub" % file_path)
        return None
Esempio n. 2
0
def make_mobi(book_id):
    kindlegen = os.path.join(config.MAIN_DIR, "kindlegen")
    if not os.path.exists(kindlegen):
        return False
    book = db.session.query(db.Books).filter(db.Books.id == book_id).first()

    file_path = os.path.join(config.DB_ROOT, book.path, book.data[0].name)
    # print os.path.getsize(file_path + ".epub")
    if os.path.exists(file_path +
                      ".epub") and not os.path.exists(file_path + ".mobi"):
        # print u"conversion started for %s" % book.title
        check = subprocess.call([kindlegen, file_path + ".epub"],
                                stdout=subprocess.PIPE)
        if not check or check < 2:
            book.data.append(
                db.Data(name=book.data[0].name,
                        format="MOBI",
                        book=book.id,
                        uncompressed_size=os.path.getsize(file_path +
                                                          ".mobi")))
            db.session.commit()
            return file_path + ".mobi"
        else:
            return False
    else:
        return file_path + ".mobi"
Esempio n. 3
0
def upload():
    if not config.UPLOADING:
        abort(404)
    ## create the function for sorting...
    db.session.connection().connection.connection.create_function("title_sort",1,db.title_sort)
    db.session.connection().connection.connection.create_function('uuid4', 0, lambda : str(uuid4()))
    if request.method == 'POST' and 'btn-upload' in request.files:
        file = request.files['btn-upload']
        filename = file.filename
        filename_root, fileextension = os.path.splitext(filename)
        if fileextension.upper() == ".PDF":
            title = filename_root
            author = "Unknown"
        else: 
            flash("Upload is only available for PDF files", category="error")
            return redirect(url_for('index'))
        
        title_dir = helper.get_valid_filename(title, False)
        author_dir = helper.get_valid_filename(author.decode('utf-8'), False)
        data_name = title_dir
        filepath = config.DB_ROOT + "/" + author_dir + "/" + title_dir
        saved_filename = filepath + "/" + data_name + fileextension
        if not os.path.exists(filepath):
            try:
                os.makedirs(filepath)
            except OSError:
                flash("Failed to create path %s (Permission denied)." % filepath, category="error")
                return redirect(url_for('index'))
        try:
            file.save(saved_filename)
        except OSError:
            flash("Failed to store file %s (Permission denied)." % saved_filename, category="error")
            return redirect(url_for('index'))
        file_size = os.path.getsize(saved_filename)
        has_cover = 0
        if fileextension.upper() == ".PDF":
            if use_generic_pdf_cover:
                basedir = os.path.dirname(__file__)
                print basedir
                copyfile(os.path.join(basedir, "static/generic_cover.jpg"), os.path.join(filepath, "cover.jpg"))
            else:
                with Image(filename=saved_filename + "[0]", resolution=150) as img:
                    img.compression_quality = 88
                    img.save(filename=os.path.join(filepath, "cover.jpg"))
                    has_cover = 1
        is_author = db.session.query(db.Authors).filter(db.Authors.name == author).first()
        if is_author:
            db_author = is_author
        else:
            db_author = db.Authors(author, "", "")
            db.session.add(db_author)
        db_book = db.Books(title, "", "", datetime.datetime.now(), datetime.datetime(101, 01,01), 1, datetime.datetime.now(), author_dir + "/" + title_dir, has_cover, db_author, [])
        db_book.authors.append(db_author)
        db_data = db.Data(db_book, fileextension.upper()[1:], file_size, data_name)
        db_book.data.append(db_data)
        
        db.session.add(db_book)
        db.session.commit()
    return render_template('edit_book.html', book=db_book)
Esempio n. 4
0
    def _convert_ebook_format(self):
        error_message = None
        local_session = db.CalibreDB().session
        file_path = self.file_path
        book_id = self.bookid
        format_old_ext = u'.' + self.settings['old_book_format'].lower()
        format_new_ext = u'.' + self.settings['new_book_format'].lower()

        # check to see if destination format already exists -
        # if it does - mark the conversion task as complete and return a success
        # this will allow send to kindle workflow to continue to work
        if os.path.isfile(file_path + format_new_ext):
            log.info("Book id %d already converted to %s", book_id, format_new_ext)
            cur_book = calibre_db.get_book(book_id)
            self.results['path'] = file_path
            self.results['title'] = cur_book.title
            self._handleSuccess()
            return os.path.basename(file_path + format_new_ext)
        else:
            log.info("Book id %d - target format of %s does not exist. Moving forward with convert.",
                     book_id,
                     format_new_ext)

        if config.config_kepubifypath and format_old_ext == '.epub' and format_new_ext == '.kepub':
            check, error_message = self._convert_kepubify(file_path,
                                                          format_old_ext,
                                                          format_new_ext)
        else:
            # check if calibre converter-executable is existing
            if not os.path.exists(config.config_converterpath):
                # ToDo Text is not translated
                self._handleError(_(u"Calibre ebook-convert %(tool)s not found", tool=config.config_converterpath))
                return
            check, error_message = self._convert_calibre(file_path, format_old_ext, format_new_ext)

        if check == 0:
            cur_book = calibre_db.get_book(book_id)
            if os.path.isfile(file_path + format_new_ext):
                # self.db_queue.join()
                new_format = db.Data(name=cur_book.data[0].name,
                                         book_format=self.settings['new_book_format'].upper(),
                                         book=book_id, uncompressed_size=os.path.getsize(file_path + format_new_ext))
                try:
                    local_session.merge(new_format)
                    local_session.commit()
                except SQLAlchemyError as e:
                    local_session.rollback()
                    log.error("Database error: %s", e)
                    return
                self.results['path'] = cur_book.path
                self.results['title'] = cur_book.title
                if not config.config_use_google_drive:
                    self._handleSuccess()
                return os.path.basename(file_path + format_new_ext)
            else:
                error_message = _('%(format)s format not found on disk', format=format_new_ext.upper())
        log.info("ebook converter failed with error while converting book")
        if not error_message:
            error_message = _('Ebook converter failed with unknown error')
        self._handleError(error_message)
        return
Esempio n. 5
0
def upload():
    if not config.UPLOADING:
        abort(404)
    ## create the function for sorting...
    db.session.connection().connection.connection.create_function("title_sort",1,db.title_sort)
    db.session.connection().connection.connection.create_function('uuid4', 0, lambda : str(uuid4()))
    if request.method == 'POST' and 'btn-upload' in request.files:
        file = request.files['btn-upload']
        meta = uploader.upload(file)

        title = meta.title
        author = meta.author


        title_dir = helper.get_valid_filename(title, False)
        author_dir = helper.get_valid_filename(author.decode('utf-8'), False)
        data_name = title_dir
        filepath = config.DB_ROOT + "/" + author_dir + "/" + title_dir
        saved_filename = filepath + "/" + data_name + meta.extension
        if not os.path.exists(filepath):
            try:
                os.makedirs(filepath)
            except OSError:
                flash("Failed to create path %s (Permission denied)." % filepath, category="error")
                return redirect(url_for('index'))
        try:
            move(meta.file_path, saved_filename)
        except OSError:
            flash("Failed to store file %s (Permission denied)." % saved_filename, category="error")
            return redirect(url_for('index'))

        file_size = os.path.getsize(saved_filename)
        if meta.cover is None:
            has_cover = 0
            basedir = os.path.dirname(__file__)
            copyfile(os.path.join(basedir, "static/generic_cover.jpg"), os.path.join(filepath, "cover.jpg"))
        else:
            has_cover = 1
            move(meta.cover, os.path.join(filepath, "cover.jpg"))

        is_author = db.session.query(db.Authors).filter(db.Authors.name == author).first()
        if is_author:
            db_author = is_author
        else:
            db_author = db.Authors(author, "", "")
            db.session.add(db_author)
        path = os.path.join(author_dir, title_dir)
        db_book = db.Books(title, "", "", datetime.datetime.now(), datetime.datetime(101, 01,01), 1, datetime.datetime.now(), path, has_cover, db_author, [])
        db_book.authors.append(db_author)
        db_data = db.Data(db_book, meta.extension.upper()[1:], file_size, data_name)
        db_book.data.append(db_data)
        
        db.session.add(db_book)
        db.session.commit()
        author_names = []
        for author in db_book.authors:
            author_names.append(author.name)
    cc = db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()
    if current_user.role_edit() or current_user.role_admin():
        return render_template('edit_book.html', book=db_book, authors=author_names, cc=cc)
    book_in_shelfs = []
    return render_template('detail.html', entry=db_book,  cc=cc, title=db_book.title, books_shelfs=book_in_shelfs)
Esempio n. 6
0
    def _convert_ebook_format(self):
        error_message = None
        local_db = db.CalibreDB(expire_on_commit=False, init=True)
        file_path = self.file_path
        book_id = self.book_id
        format_old_ext = u'.' + self.settings['old_book_format'].lower()
        format_new_ext = u'.' + self.settings['new_book_format'].lower()

        # check to see if destination format already exists - or if book is in database
        # if it does - mark the conversion task as complete and return a success
        # this will allow send to E-Reader workflow to continue to work
        if os.path.isfile(file_path + format_new_ext) or\
                local_db.get_book_format(self.book_id, self.settings['new_book_format']):
            log.info("Book id %d already converted to %s", book_id,
                     format_new_ext)
            cur_book = local_db.get_book(book_id)
            self.title = cur_book.title
            self.results['path'] = cur_book.path
            self.results['title'] = self.title
            new_format = local_db.session.query(db.Data).filter(db.Data.book == book_id)\
                .filter(db.Data.format == self.settings['new_book_format'].upper()).one_or_none()
            if not new_format:
                new_format = db.Data(
                    name=os.path.basename(file_path),
                    book_format=self.settings['new_book_format'].upper(),
                    book=book_id,
                    uncompressed_size=os.path.getsize(file_path +
                                                      format_new_ext))
                try:
                    local_db.session.merge(new_format)
                    local_db.session.commit()
                except SQLAlchemyError as e:
                    local_db.session.rollback()
                    log.error("Database error: %s", e)
                    local_db.session.close()
                    self._handleError(N_("Database error: %(error)s.",
                                         error=e))
                    return
                self._handleSuccess()
                local_db.session.close()
                return os.path.basename(file_path + format_new_ext)
        else:
            log.info(
                "Book id %d - target format of %s does not exist. Moving forward with convert.",
                book_id, format_new_ext)

        if config.config_kepubifypath and format_old_ext == '.epub' and format_new_ext == '.kepub':
            check, error_message = self._convert_kepubify(
                file_path, format_old_ext, format_new_ext)
        else:
            # check if calibre converter-executable is existing
            if not os.path.exists(config.config_converterpath):
                self._handleError(
                    N_(u"Calibre ebook-convert %(tool)s not found",
                       tool=config.config_converterpath))
                return
            check, error_message = self._convert_calibre(
                file_path, format_old_ext, format_new_ext)

        if check == 0:
            cur_book = local_db.get_book(book_id)
            if os.path.isfile(file_path + format_new_ext):
                new_format = local_db.session.query(db.Data).filter(db.Data.book == book_id) \
                    .filter(db.Data.format == self.settings['new_book_format'].upper()).one_or_none()
                if not new_format:
                    new_format = db.Data(
                        name=cur_book.data[0].name,
                        book_format=self.settings['new_book_format'].upper(),
                        book=book_id,
                        uncompressed_size=os.path.getsize(file_path +
                                                          format_new_ext))
                    try:
                        local_db.session.merge(new_format)
                        local_db.session.commit()
                        if self.settings['new_book_format'].upper() in [
                                'KEPUB', 'EPUB', 'EPUB3'
                        ]:
                            ub_session = init_db_thread()
                            remove_synced_book(book_id, True, ub_session)
                            ub_session.close()
                    except SQLAlchemyError as e:
                        local_db.session.rollback()
                        log.error("Database error: %s", e)
                        local_db.session.close()
                        self._handleError(error_message)
                        return
                self.results['path'] = cur_book.path
                self.title = cur_book.title
                self.results['title'] = self.title
                if not config.config_use_google_drive:
                    self._handleSuccess()
                return os.path.basename(file_path + format_new_ext)
            else:
                error_message = N_('%(format)s format not found on disk',
                                   format=format_new_ext.upper())
        local_db.session.close()
        log.info("ebook converter failed with error while converting book")
        if not error_message:
            error_message = N_('Ebook converter failed with unknown error')
        self._handleError(error_message)
        return