2021-10-04 16:26:46 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
|
|
|
# Copyright (C) 2020 pwr
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
2020-08-22 20:31:00 +00:00
|
|
|
import os
|
|
|
|
import re
|
|
|
|
from glob import glob
|
|
|
|
from shutil import copyfile
|
2021-08-28 09:32:13 +00:00
|
|
|
from markupsafe import escape
|
2020-08-22 20:31:00 +00:00
|
|
|
|
2020-08-23 17:07:24 +00:00
|
|
|
from sqlalchemy.exc import SQLAlchemyError
|
2022-04-24 16:40:50 +00:00
|
|
|
from flask_babel import lazy_gettext as N_
|
2020-08-23 17:07:24 +00:00
|
|
|
|
2020-10-27 10:06:43 +00:00
|
|
|
from cps.services.worker import CalibreTask
|
2020-12-08 07:01:42 +00:00
|
|
|
from cps import db
|
2020-08-22 20:31:00 +00:00
|
|
|
from cps import logger, config
|
|
|
|
from cps.subproc_wrapper import process_open
|
|
|
|
from flask_babel import gettext as _
|
2022-01-23 12:11:02 +00:00
|
|
|
from cps.kobo_sync_status import remove_synced_book
|
2022-02-06 13:22:55 +00:00
|
|
|
from cps.ub import init_db_thread
|
2020-08-22 20:31:00 +00:00
|
|
|
|
2020-08-30 06:49:53 +00:00
|
|
|
from cps.tasks.mail import TaskEmail
|
2020-08-24 01:21:55 +00:00
|
|
|
from cps import gdriveutils
|
2022-02-08 18:35:00 +00:00
|
|
|
|
|
|
|
|
2020-08-22 20:31:00 +00:00
|
|
|
log = logger.create()
|
|
|
|
|
|
|
|
|
|
|
|
class TaskConvert(CalibreTask):
|
2022-05-08 10:55:54 +00:00
|
|
|
def __init__(self, file_path, book_id, task_message, settings, ereader_mail, user=None):
|
2022-04-24 16:40:50 +00:00
|
|
|
super(TaskConvert, self).__init__(task_message)
|
2020-08-22 20:31:00 +00:00
|
|
|
self.file_path = file_path
|
2022-04-24 16:40:50 +00:00
|
|
|
self.book_id = book_id
|
2021-08-28 09:32:13 +00:00
|
|
|
self.title = ""
|
2020-08-22 20:31:00 +00:00
|
|
|
self.settings = settings
|
2022-05-08 10:55:54 +00:00
|
|
|
self.ereader_mail = ereader_mail
|
2020-10-03 19:43:48 +00:00
|
|
|
self.user = user
|
2020-08-22 20:31:00 +00:00
|
|
|
|
|
|
|
self.results = dict()
|
|
|
|
|
|
|
|
def run(self, worker_thread):
|
|
|
|
self.worker_thread = worker_thread
|
2020-10-04 10:09:52 +00:00
|
|
|
if config.config_use_google_drive:
|
2022-04-30 06:26:00 +00:00
|
|
|
worker_db = db.CalibreDB(expire_on_commit=False, init=True)
|
2022-04-24 16:40:50 +00:00
|
|
|
cur_book = worker_db.get_book(self.book_id)
|
2021-08-28 09:32:13 +00:00
|
|
|
self.title = cur_book.title
|
2022-04-24 16:40:50 +00:00
|
|
|
data = worker_db.get_book_format(self.book_id, self.settings['old_book_format'])
|
2020-10-04 10:09:52 +00:00
|
|
|
df = gdriveutils.getFileFromEbooksFolder(cur_book.path,
|
|
|
|
data.name + "." + self.settings['old_book_format'].lower())
|
|
|
|
if df:
|
|
|
|
datafile = os.path.join(config.config_calibre_dir,
|
|
|
|
cur_book.path,
|
|
|
|
data.name + u"." + self.settings['old_book_format'].lower())
|
|
|
|
if not os.path.exists(os.path.join(config.config_calibre_dir, cur_book.path)):
|
|
|
|
os.makedirs(os.path.join(config.config_calibre_dir, cur_book.path))
|
|
|
|
df.GetContentFile(datafile)
|
2020-12-08 07:04:46 +00:00
|
|
|
worker_db.session.close()
|
2020-10-04 10:09:52 +00:00
|
|
|
else:
|
|
|
|
error_message = _(u"%(format)s not found on Google Drive: %(fn)s",
|
|
|
|
format=self.settings['old_book_format'],
|
|
|
|
fn=data.name + "." + self.settings['old_book_format'].lower())
|
2020-12-08 07:04:46 +00:00
|
|
|
worker_db.session.close()
|
2020-10-04 10:09:52 +00:00
|
|
|
return error_message
|
|
|
|
|
2020-08-22 20:31:00 +00:00
|
|
|
filename = self._convert_ebook_format()
|
2020-10-04 11:59:33 +00:00
|
|
|
if config.config_use_google_drive:
|
|
|
|
os.remove(self.file_path + u'.' + self.settings['old_book_format'].lower())
|
2020-08-24 01:35:05 +00:00
|
|
|
|
2020-08-24 01:21:55 +00:00
|
|
|
if filename:
|
|
|
|
if config.config_use_google_drive:
|
2020-10-04 10:09:52 +00:00
|
|
|
# Upload files to gdrive
|
2020-08-24 01:21:55 +00:00
|
|
|
gdriveutils.updateGdriveCalibreFromLocal()
|
2020-10-04 10:09:52 +00:00
|
|
|
self._handleSuccess()
|
2022-05-08 10:55:54 +00:00
|
|
|
if self.ereader_mail:
|
|
|
|
# if we're sending to E-Reader after converting, create a one-off task and run it immediately
|
2020-08-24 01:21:55 +00:00
|
|
|
# todo: figure out how to incorporate this into the progress
|
2020-08-24 01:35:05 +00:00
|
|
|
try:
|
2022-05-08 10:55:54 +00:00
|
|
|
EmailText = N_(u"%(book)s send to E-Reader", book=escape(self.title))
|
2021-01-03 18:27:24 +00:00
|
|
|
worker_thread.add(self.user, TaskEmail(self.settings['subject'],
|
|
|
|
self.results["path"],
|
|
|
|
filename,
|
|
|
|
self.settings,
|
2022-05-08 10:55:54 +00:00
|
|
|
self.ereader_mail,
|
2021-08-28 09:32:13 +00:00
|
|
|
EmailText,
|
2021-01-03 18:27:24 +00:00
|
|
|
self.settings['body'],
|
|
|
|
internal=True)
|
|
|
|
)
|
2021-04-04 17:40:34 +00:00
|
|
|
except Exception as ex:
|
|
|
|
return self._handleError(str(ex))
|
2020-08-22 20:31:00 +00:00
|
|
|
|
|
|
|
def _convert_ebook_format(self):
|
|
|
|
error_message = None
|
2022-04-30 06:26:00 +00:00
|
|
|
local_db = db.CalibreDB(expire_on_commit=False, init=True)
|
2020-08-22 20:31:00 +00:00
|
|
|
file_path = self.file_path
|
2022-04-24 16:40:50 +00:00
|
|
|
book_id = self.book_id
|
2020-08-22 20:31:00 +00:00
|
|
|
format_old_ext = u'.' + self.settings['old_book_format'].lower()
|
|
|
|
format_new_ext = u'.' + self.settings['new_book_format'].lower()
|
|
|
|
|
2020-12-08 12:34:15 +00:00
|
|
|
# check to see if destination format already exists - or if book is in database
|
2020-08-22 20:31:00 +00:00
|
|
|
# if it does - mark the conversion task as complete and return a success
|
2022-05-08 10:55:54 +00:00
|
|
|
# this will allow send to E-Reader workflow to continue to work
|
2020-12-08 12:34:15 +00:00
|
|
|
if os.path.isfile(file_path + format_new_ext) or\
|
2022-04-24 16:40:50 +00:00
|
|
|
local_db.get_book_format(self.book_id, self.settings['new_book_format']):
|
2020-08-22 20:31:00 +00:00
|
|
|
log.info("Book id %d already converted to %s", book_id, format_new_ext)
|
2020-12-08 10:39:23 +00:00
|
|
|
cur_book = local_db.get_book(book_id)
|
2021-08-28 09:32:13 +00:00
|
|
|
self.title = cur_book.title
|
2022-02-06 17:57:58 +00:00
|
|
|
self.results['path'] = cur_book.path
|
2021-08-28 09:32:13 +00:00
|
|
|
self.results['title'] = self.title
|
2022-02-07 12:55:18 +00:00
|
|
|
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()
|
2022-04-24 16:40:50 +00:00
|
|
|
self._handleError(N_("Database error: %(error)s.", error=e))
|
2022-02-07 12:55:18 +00:00
|
|
|
return
|
|
|
|
self._handleSuccess()
|
2022-02-06 17:57:58 +00:00
|
|
|
local_db.session.close()
|
2022-02-07 12:55:18 +00:00
|
|
|
return os.path.basename(file_path + format_new_ext)
|
2020-08-22 20:31:00 +00:00
|
|
|
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):
|
2022-04-24 16:40:50 +00:00
|
|
|
self._handleError(N_(u"Calibre ebook-convert %(tool)s not found", tool=config.config_converterpath))
|
2020-08-22 20:31:00 +00:00
|
|
|
return
|
|
|
|
check, error_message = self._convert_calibre(file_path, format_old_ext, format_new_ext)
|
|
|
|
|
|
|
|
if check == 0:
|
2020-12-08 07:01:42 +00:00
|
|
|
cur_book = local_db.get_book(book_id)
|
2020-08-22 20:31:00 +00:00
|
|
|
if os.path.isfile(file_path + format_new_ext):
|
2022-02-07 12:55:18 +00:00
|
|
|
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,
|
2020-08-22 20:31:00 +00:00
|
|
|
book_format=self.settings['new_book_format'].upper(),
|
|
|
|
book=book_id, uncompressed_size=os.path.getsize(file_path + format_new_ext))
|
2022-02-07 12:55:18 +00:00
|
|
|
try:
|
|
|
|
local_db.session.merge(new_format)
|
|
|
|
local_db.session.commit()
|
|
|
|
if self.settings['new_book_format'].upper() in ['KEPUB', 'EPUB', 'EPUB3']:
|
2022-02-07 12:57:50 +00:00
|
|
|
ub_session = init_db_thread()
|
2022-02-07 12:55:18 +00:00
|
|
|
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
|
2020-08-22 20:31:00 +00:00
|
|
|
self.results['path'] = cur_book.path
|
2021-08-28 09:32:13 +00:00
|
|
|
self.title = cur_book.title
|
|
|
|
self.results['title'] = self.title
|
2020-10-04 11:59:33 +00:00
|
|
|
if not config.config_use_google_drive:
|
2020-10-04 10:09:52 +00:00
|
|
|
self._handleSuccess()
|
2020-09-30 17:29:57 +00:00
|
|
|
return os.path.basename(file_path + format_new_ext)
|
2020-08-22 20:31:00 +00:00
|
|
|
else:
|
2022-04-24 16:40:50 +00:00
|
|
|
error_message = N_('%(format)s format not found on disk', format=format_new_ext.upper())
|
2020-12-08 07:01:42 +00:00
|
|
|
local_db.session.close()
|
2020-08-22 20:31:00 +00:00
|
|
|
log.info("ebook converter failed with error while converting book")
|
|
|
|
if not error_message:
|
2022-04-24 16:40:50 +00:00
|
|
|
error_message = N_('Ebook converter failed with unknown error')
|
2020-08-22 20:31:00 +00:00
|
|
|
self._handleError(error_message)
|
|
|
|
return
|
|
|
|
|
|
|
|
def _convert_kepubify(self, file_path, format_old_ext, format_new_ext):
|
|
|
|
quotes = [1, 3]
|
|
|
|
command = [config.config_kepubifypath, (file_path + format_old_ext), '-o', os.path.dirname(file_path)]
|
|
|
|
try:
|
|
|
|
p = process_open(command, quotes)
|
|
|
|
except OSError as e:
|
2022-04-24 16:40:50 +00:00
|
|
|
return 1, N_(u"Kepubify-converter failed: %(error)s", error=e)
|
2020-08-22 20:31:00 +00:00
|
|
|
self.progress = 0.01
|
|
|
|
while True:
|
|
|
|
nextline = p.stdout.readlines()
|
|
|
|
nextline = [x.strip('\n') for x in nextline if x != '\n']
|
|
|
|
for line in nextline:
|
|
|
|
log.debug(line)
|
|
|
|
if p.poll() is not None:
|
|
|
|
break
|
|
|
|
|
|
|
|
# ToD Handle
|
|
|
|
# process returncode
|
|
|
|
check = p.returncode
|
|
|
|
|
|
|
|
# move file
|
|
|
|
if check == 0:
|
|
|
|
converted_file = glob(os.path.join(os.path.dirname(file_path), "*.kepub.epub"))
|
|
|
|
if len(converted_file) == 1:
|
|
|
|
copyfile(converted_file[0], (file_path + format_new_ext))
|
|
|
|
os.unlink(converted_file[0])
|
|
|
|
else:
|
2022-04-24 16:40:50 +00:00
|
|
|
return 1, N_(u"Converted file not found or more than one file in folder %(folder)s",
|
2020-08-22 20:31:00 +00:00
|
|
|
folder=os.path.dirname(file_path))
|
|
|
|
return check, None
|
|
|
|
|
|
|
|
def _convert_calibre(self, file_path, format_old_ext, format_new_ext):
|
|
|
|
try:
|
|
|
|
# Linux py2.7 encode as list without quotes no empty element for parameters
|
|
|
|
# linux py3.x no encode and as list without quotes no empty element for parameters
|
|
|
|
# windows py2.7 encode as string with quotes empty element for parameters is okay
|
|
|
|
# windows py 3.x no encode and as string with quotes empty element for parameters is okay
|
|
|
|
# separate handling for windows and linux
|
|
|
|
quotes = [1, 2]
|
|
|
|
command = [config.config_converterpath, (file_path + format_old_ext),
|
|
|
|
(file_path + format_new_ext)]
|
|
|
|
quotes_index = 3
|
|
|
|
if config.config_calibre:
|
|
|
|
parameters = config.config_calibre.split(" ")
|
|
|
|
for param in parameters:
|
|
|
|
command.append(param)
|
|
|
|
quotes.append(quotes_index)
|
|
|
|
quotes_index += 1
|
|
|
|
|
2021-12-18 16:31:33 +00:00
|
|
|
p = process_open(command, quotes, newlines=False)
|
2020-08-22 20:31:00 +00:00
|
|
|
except OSError as e:
|
2022-04-24 16:40:50 +00:00
|
|
|
return 1, N_(u"Ebook-converter failed: %(error)s", error=e)
|
2020-08-22 20:31:00 +00:00
|
|
|
|
|
|
|
while p.poll() is None:
|
|
|
|
nextline = p.stdout.readline()
|
2021-12-18 16:31:33 +00:00
|
|
|
if isinstance(nextline, bytes):
|
|
|
|
nextline = nextline.decode('utf-8', errors="ignore").strip('\r\n')
|
|
|
|
if nextline:
|
|
|
|
log.debug(nextline)
|
2020-08-22 20:31:00 +00:00
|
|
|
# parse progress string from calibre-converter
|
|
|
|
progress = re.search(r"(\d+)%\s.*", nextline)
|
|
|
|
if progress:
|
|
|
|
self.progress = int(progress.group(1)) / 100
|
2020-10-04 10:09:52 +00:00
|
|
|
if config.config_use_google_drive:
|
|
|
|
self.progress *= 0.9
|
2020-08-22 20:31:00 +00:00
|
|
|
|
|
|
|
# process returncode
|
|
|
|
check = p.returncode
|
|
|
|
calibre_traceback = p.stderr.readlines()
|
|
|
|
error_message = ""
|
|
|
|
for ele in calibre_traceback:
|
2021-12-18 17:38:17 +00:00
|
|
|
ele = ele.decode('utf-8', errors="ignore").strip('\n')
|
|
|
|
log.debug(ele)
|
2020-08-22 20:31:00 +00:00
|
|
|
if not ele.startswith('Traceback') and not ele.startswith(' File'):
|
2022-04-24 16:40:50 +00:00
|
|
|
error_message = N_("Calibre failed with error: %(error)s", error=ele)
|
2020-08-22 20:31:00 +00:00
|
|
|
return check, error_message
|
|
|
|
|
|
|
|
@property
|
|
|
|
def name(self):
|
2022-04-24 16:40:50 +00:00
|
|
|
return N_("Convert")
|
2021-12-18 16:31:33 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
2022-05-08 10:55:54 +00:00
|
|
|
return "Convert {} {}".format(self.book_id, self.ereader_mail)
|
2022-01-27 05:51:50 +00:00
|
|
|
|
2021-09-29 07:40:12 +00:00
|
|
|
@property
|
|
|
|
def is_cancellable(self):
|
|
|
|
return False
|